diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/java/org/lwjgl/opengl/BaseReferences.java b/src/java/org/lwjgl/opengl/BaseReferences.java
index 6db1238d..a3a202bc 100644
--- a/src/java/org/lwjgl/opengl/BaseReferences.java
+++ b/src/java/org/lwjgl/opengl/BaseReferences.java
@@ -1,94 +1,94 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opengl;
import java.nio.Buffer;
import java.nio.IntBuffer;
import java.util.Arrays;
class BaseReferences {
int elementArrayBuffer;
int arrayBuffer;
Buffer[] glVertexAttribPointer_buffer;
Buffer[] glTexCoordPointer_buffer;
int glClientActiveTexture;
int pixelPackBuffer;
int pixelUnpackBuffer;
BaseReferences(ContextCapabilities caps) {
IntBuffer temp = caps.scratch_int_buffer;
int max_vertex_attribs;
if (caps.OpenGL20 || caps.GL_ARB_vertex_shader) {
GL11.glGetInteger(ARBVertexShader.GL_MAX_VERTEX_ATTRIBS_ARB, temp);
max_vertex_attribs = temp.get(0);
} else
max_vertex_attribs = 0;
glVertexAttribPointer_buffer = new Buffer[max_vertex_attribs];
int max_texture_units;
if (caps.OpenGL13 || caps.GL_ARB_multitexture) {
GL11.glGetInteger(GL13.GL_MAX_TEXTURE_UNITS, temp);
max_texture_units = temp.get(0);
} else
- max_texture_units = 0;
+ max_texture_units = 1;
glTexCoordPointer_buffer = new Buffer[max_texture_units];
}
void clear() {
this.elementArrayBuffer = 0;
this.arrayBuffer = 0;
this.glClientActiveTexture = 0;
Arrays.fill(glVertexAttribPointer_buffer, null);
Arrays.fill(glTexCoordPointer_buffer, null);
this.pixelPackBuffer = 0;
this.pixelUnpackBuffer = 0;
}
void copy(BaseReferences references, int mask) {
if ( (mask & GL11.GL_CLIENT_VERTEX_ARRAY_BIT) != 0 ) {
this.elementArrayBuffer = references.elementArrayBuffer;
this.arrayBuffer = references.arrayBuffer;
this.glClientActiveTexture = references.glClientActiveTexture;
System.arraycopy(references.glVertexAttribPointer_buffer, 0, glVertexAttribPointer_buffer, 0, glVertexAttribPointer_buffer.length);
System.arraycopy(references.glTexCoordPointer_buffer, 0, glTexCoordPointer_buffer, 0, glTexCoordPointer_buffer.length);
}
if ( (mask & GL11.GL_CLIENT_PIXEL_STORE_BIT) != 0 ) {
this.pixelPackBuffer = references.pixelPackBuffer;
this.pixelUnpackBuffer = references.pixelUnpackBuffer;
}
}
}
| true | true |
BaseReferences(ContextCapabilities caps) {
IntBuffer temp = caps.scratch_int_buffer;
int max_vertex_attribs;
if (caps.OpenGL20 || caps.GL_ARB_vertex_shader) {
GL11.glGetInteger(ARBVertexShader.GL_MAX_VERTEX_ATTRIBS_ARB, temp);
max_vertex_attribs = temp.get(0);
} else
max_vertex_attribs = 0;
glVertexAttribPointer_buffer = new Buffer[max_vertex_attribs];
int max_texture_units;
if (caps.OpenGL13 || caps.GL_ARB_multitexture) {
GL11.glGetInteger(GL13.GL_MAX_TEXTURE_UNITS, temp);
max_texture_units = temp.get(0);
} else
max_texture_units = 0;
glTexCoordPointer_buffer = new Buffer[max_texture_units];
}
|
BaseReferences(ContextCapabilities caps) {
IntBuffer temp = caps.scratch_int_buffer;
int max_vertex_attribs;
if (caps.OpenGL20 || caps.GL_ARB_vertex_shader) {
GL11.glGetInteger(ARBVertexShader.GL_MAX_VERTEX_ATTRIBS_ARB, temp);
max_vertex_attribs = temp.get(0);
} else
max_vertex_attribs = 0;
glVertexAttribPointer_buffer = new Buffer[max_vertex_attribs];
int max_texture_units;
if (caps.OpenGL13 || caps.GL_ARB_multitexture) {
GL11.glGetInteger(GL13.GL_MAX_TEXTURE_UNITS, temp);
max_texture_units = temp.get(0);
} else
max_texture_units = 1;
glTexCoordPointer_buffer = new Buffer[max_texture_units];
}
|
diff --git a/update/org.eclipse.update.core/src/org/eclipse/update/core/Utilities.java b/update/org.eclipse.update.core/src/org/eclipse/update/core/Utilities.java
index 0649c4a59..f35f255ad 100644
--- a/update/org.eclipse.update.core/src/org/eclipse/update/core/Utilities.java
+++ b/update/org.eclipse.update.core/src/org/eclipse/update/core/Utilities.java
@@ -1,344 +1,345 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.update.core;
import java.io.*;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.eclipse.core.runtime.*;
import org.eclipse.update.core.model.*;
import org.eclipse.update.internal.core.*;
/**
* This class is a collection of utility functions that can be
* used for install processing
* <p>
* <b>Note:</b> This class/interface is part of an interim API that is still under development and expected to
* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
* (repeatedly) as the API evolves.
* </p>
*/
public class Utilities {
private static Map entryMap;
private static final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.getDefault());
private static long tmpseed = (new Date()).getTime();
private static String dirRoot = null;
/**
* Returns a new working directory (in temporary space). Ensures
* the directory exists. Any directory levels that had to be created
* are marked for deletion on exit.
*
* @return working directory
* @exception IOException
* @since 2.0
*/
public static synchronized File createWorkingDirectory() throws IOException {
if (dirRoot == null) {
dirRoot = System.getProperty("java.io.tmpdir"); //$NON-NLS-1$
// in Linux, returns '/tmp', we must add '/'
if (!dirRoot.endsWith(File.separator))
dirRoot += File.separator;
// on Unix/Linux, the temp dir is shared by many users, so we need to ensure
// that the top working directory is different for each user
if (!Platform.getOS().equals("win32")) { //$NON-NLS-1$
String home = System.getProperty("user.home"); //$NON-NLS-1$
home = Integer.toString(home.hashCode());
dirRoot += home + File.separator;
}
dirRoot += "eclipse" + File.separator + ".update" + File.separator + Long.toString(tmpseed) + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
}
String tmpName = dirRoot + Long.toString(++tmpseed) + File.separator;
File tmpDir = new File(tmpName);
verifyPath(tmpDir, false);
if (!tmpDir.exists())
throw new FileNotFoundException(tmpName);
return tmpDir;
}
/**
* Create a new working file. The file is marked for deletion on exit.
*
* @see #lookupLocalFile(String)
* @param tmpDir directory location for new file. Any missing directory
* levels are created (and marked for deletion on exit)
* @param name optional file name, or <code>null</code>. If name is not
* specified, a temporary name is generated.
* @return created working file
* @exception IOException
* @since 2.0
*/
public static synchronized File createLocalFile(File tmpDir, String name) throws IOException {
// create the local file
File temp;
String filePath;
if (name != null) {
// create file with specified name
filePath = name.replace('/', File.separatorChar);
if (filePath.startsWith(File.separator))
filePath = filePath.substring(1);
temp = new File(tmpDir, filePath);
} else {
// create file with temp name
temp = File.createTempFile("eclipse", null, tmpDir); //$NON-NLS-1$
}
temp.deleteOnExit();
verifyPath(temp, true);
return temp;
}
/**
* The file is associated with a lookup key.
* @param key optional lookup key, or <code>null</code>.
* @param temp the local working file
* @since 2.0.2
*/
public synchronized static void mapLocalFile(String key, File temp) {
// create file association
if (key != null) {
if (entryMap == null)
entryMap = new HashMap();
entryMap.put(key, temp);
}
}
/**
* Returns a previously cached local file (in temporary area) matching the
* specified key.
*
* @param key lookup key
* @return cached file, or <code>null</code>.
* @since 2.0
*/
public static synchronized File lookupLocalFile(String key) {
if (entryMap == null)
return null;
return (File) entryMap.get(key);
}
/**
* Flushes all the keys from the local file map.
* Reinitialize the cache.
*
* @since 2.1
*/
public synchronized static void flushLocalFile() {
entryMap = null;
}
/**
* Removes the specified key from the local file map. The file is
* not actually deleted until VM termination.
*
* @param key lookup key
* @since 2.0
*/
public static synchronized void removeLocalFile(String key) {
if (entryMap != null)
entryMap.remove(key);
}
/**
* Copies specified input stream to the output stream. Neither stream
* is closed as part of this operation.
*
* @param is input stream
* @param os output stream
* @param monitor progress monitor
* @exception IOException
* @exception InstallAbortedException
* @since 2.0
*/
public static void copy(InputStream is, OutputStream os, InstallMonitor monitor) throws IOException, InstallAbortedException {
long offset = UpdateManagerUtils.copy(is, os, monitor, 0);
if (offset != -1) {
if (monitor.isCanceled()) {
String msg = Messages.Feature_InstallationCancelled;
throw new InstallAbortedException(msg, null);
} else {
throw new IOException();
}
}
}
/**
* Creates a CoreException from some other exception.
* The type of the CoreException is <code>IStatus.ERROR</code>
* If the exception passed as a parameter is also a CoreException,
* the new CoreException will contain all the status of the passed
* CoreException.
*
* @see IStatus#ERROR
* @param s exception string
* @param code the code reported
* @param e actual exception being reported
* @return a CoreException
* @since 2.0
*/
public static CoreException newCoreException(String s, int code, Throwable e) {
String id = UpdateCore.getPlugin().getBundle().getSymbolicName();
// check the case of a multistatus
IStatus status;
if (e instanceof FeatureDownloadException)
return (FeatureDownloadException)e;
else if (e instanceof CoreException) {
if (s == null)
s = ""; //$NON-NLS-1$
status = new MultiStatus(id, code, s, e);
IStatus childrenStatus = ((CoreException) e).getStatus();
((MultiStatus) status).add(childrenStatus);
((MultiStatus) status).addAll(childrenStatus);
} else {
StringBuffer completeString = new StringBuffer(""); //$NON-NLS-1$
if (s != null)
completeString.append(s);
if (e != null) {
completeString.append(" ["); //$NON-NLS-1$
String msg = e.getLocalizedMessage();
completeString.append(msg!=null?msg:e.toString());
completeString.append("]"); //$NON-NLS-1$
}
status = new Status(IStatus.ERROR, id, code, completeString.toString(), e);
}
CoreException ce = new CoreException(status);
if ( e instanceof CoreException) {
ce.initCause(e.getCause());
} else {
ce.initCause(e);
}
- e.setStackTrace(e.getStackTrace());
+ if (e != null)
+ ce.setStackTrace(e.getStackTrace());
return ce;
}
/**
* Creates a CoreException from some other exception.
* The type of the CoreException is <code>IStatus.ERROR</code>
* If the exceptionpassed as a parameter is also a CoreException,
* the new CoreException will contain all the status of the passed
* CoreException.
*
* @see IStatus#ERROR
* @param s exception string
* @param e actual exception being reported
* @return a CoreException
* @since 2.0
*/
public static CoreException newCoreException(String s, Throwable e) {
return newCoreException(s, IStatus.OK, e);
}
/**
* Creates a CoreException from two other CoreException
*
* @param s overall exception string
* @param s1 string for first detailed exception
* @param s2 string for second detailed exception
* @param e1 first detailed exception
* @param e2 second detailed exception
* @return a CoreException with multi-status
* @since 2.0
*/
public static CoreException newCoreException(String s, String s1, String s2, CoreException e1, CoreException e2) {
String id = UpdateCore.getPlugin().getBundle().getSymbolicName();
if (s == null)
s = ""; //$NON-NLS-1$
IStatus childStatus1 = e1.getStatus();
IStatus childStatus2 = e2.getStatus();
int code = (childStatus1.getCode() == childStatus2.getCode()) ? childStatus1.getCode() : IStatus.OK;
MultiStatus multi = new MultiStatus(id, code, s, null);
multi.add(childStatus1);
multi.addAll(childStatus1);
multi.add(childStatus2);
multi.addAll(childStatus2);
return new CoreException(multi);
}
/**
* Formats a Date based on the default Locale
* If teh Date is <code>null</code> returns an empty String
*
* @param date the Date to format
* @return the formatted Date as a String
* @since 2.0
*/
public static String format(Date date) {
if (date == null)
return ""; //$NON-NLS-1$
return dateFormat.format(date);
}
/**
* Perform shutdown processing for temporary file handling.
* This method is called when platform is shutting down.
* It is not intended to be called at any other time under
* normal circumstances. A side-effect of calling this method
* is that the contents of the temporary directory managed
* by this class are deleted.
*
* @since 2.0
*/
public static void shutdown() {
if (dirRoot == null)
return;
File temp = new File(dirRoot); // temp directory root for this run
cleanupTemp(temp);
temp.delete();
}
private static void cleanupTemp(File root) {
File[] files = root.listFiles();
for (int i = 0; files != null && i < files.length; i++) {
if (files[i].isDirectory())
cleanupTemp(files[i]);
files[i].delete();
}
}
private static void verifyPath(File path, boolean isFile) {
// if we are expecting a file back off 1 path element
if (isFile) {
if (path.getAbsolutePath().endsWith(File.separator)) {
// make sure this is a file
path = path.getParentFile();
isFile = false;
}
}
// already exists ... just return
if (path.exists())
return;
// does not exist ... ensure parent exists
File parent = path.getParentFile();
verifyPath(parent, false);
// ensure directories are made. Mark files or directories for deletion
if (!isFile)
path.mkdir();
path.deleteOnExit();
}
}
| true | true |
public static CoreException newCoreException(String s, int code, Throwable e) {
String id = UpdateCore.getPlugin().getBundle().getSymbolicName();
// check the case of a multistatus
IStatus status;
if (e instanceof FeatureDownloadException)
return (FeatureDownloadException)e;
else if (e instanceof CoreException) {
if (s == null)
s = ""; //$NON-NLS-1$
status = new MultiStatus(id, code, s, e);
IStatus childrenStatus = ((CoreException) e).getStatus();
((MultiStatus) status).add(childrenStatus);
((MultiStatus) status).addAll(childrenStatus);
} else {
StringBuffer completeString = new StringBuffer(""); //$NON-NLS-1$
if (s != null)
completeString.append(s);
if (e != null) {
completeString.append(" ["); //$NON-NLS-1$
String msg = e.getLocalizedMessage();
completeString.append(msg!=null?msg:e.toString());
completeString.append("]"); //$NON-NLS-1$
}
status = new Status(IStatus.ERROR, id, code, completeString.toString(), e);
}
CoreException ce = new CoreException(status);
if ( e instanceof CoreException) {
ce.initCause(e.getCause());
} else {
ce.initCause(e);
}
e.setStackTrace(e.getStackTrace());
return ce;
}
|
public static CoreException newCoreException(String s, int code, Throwable e) {
String id = UpdateCore.getPlugin().getBundle().getSymbolicName();
// check the case of a multistatus
IStatus status;
if (e instanceof FeatureDownloadException)
return (FeatureDownloadException)e;
else if (e instanceof CoreException) {
if (s == null)
s = ""; //$NON-NLS-1$
status = new MultiStatus(id, code, s, e);
IStatus childrenStatus = ((CoreException) e).getStatus();
((MultiStatus) status).add(childrenStatus);
((MultiStatus) status).addAll(childrenStatus);
} else {
StringBuffer completeString = new StringBuffer(""); //$NON-NLS-1$
if (s != null)
completeString.append(s);
if (e != null) {
completeString.append(" ["); //$NON-NLS-1$
String msg = e.getLocalizedMessage();
completeString.append(msg!=null?msg:e.toString());
completeString.append("]"); //$NON-NLS-1$
}
status = new Status(IStatus.ERROR, id, code, completeString.toString(), e);
}
CoreException ce = new CoreException(status);
if ( e instanceof CoreException) {
ce.initCause(e.getCause());
} else {
ce.initCause(e);
}
if (e != null)
ce.setStackTrace(e.getStackTrace());
return ce;
}
|
diff --git a/src/se/tidensavtryck/gateway/RouteGateway.java b/src/se/tidensavtryck/gateway/RouteGateway.java
index dab1d24..fcbc5a0 100644
--- a/src/se/tidensavtryck/gateway/RouteGateway.java
+++ b/src/se/tidensavtryck/gateway/RouteGateway.java
@@ -1,108 +1,108 @@
package se.tidensavtryck.gateway;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import android.content.res.AssetManager;
import android.location.Location;
import com.google.android.maps.GeoPoint;
import se.tidensavtryck.model.User;
import se.tidensavtryck.model.Place;
import se.tidensavtryck.model.Record;
import se.tidensavtryck.model.Route;
public class RouteGateway {
private AssetManager mAssetManager;
public RouteGateway(AssetManager assetManager) {
this.mAssetManager = assetManager;
}
public List<Route> list() {
List<Route> routeList = new LinkedList<Route>();
Route route = new Route();
route.setTitle("En kort rundtur i Sundsvall");
User user = new User("Me");
route.setCreator(user);
route.setDescription("Information hämtad från K-samsök.");
Place place1 = new Place();
place1.setTitle("Place 1");
place1.setDescription("Runsten");
Place place2 = new Place();
place2.setTitle("Place 2");
place2.setDescription("Båt");
Place place3 = new Place();
place3.setTitle("Place 3");
place3.setDescription("Hedbergska");
Place place4 = new Place();
place4.setTitle("Place 4");
place4.setDescription("Stenstaden");
Location loc1 = new Location("se.tidensavtryck");
loc1.setLatitude(62.4007043202567);
loc1.setLongitude(17.2577392061653);
place1.setGeoLocation(loc1);
Location loc2 = new Location("se.tidensavtryck");
loc2.setLatitude(62.394369903217);
loc2.setLongitude(17.2816450479837);
place2.setGeoLocation(loc2);
Location loc3 = new Location("se.tidensavtryck");
loc3.setLatitude(62.3897829867526);
loc3.setLongitude(17.2995418371631);
place3.setGeoLocation(loc3);
Location loc4 = new Location("se.tidensavtryck");
loc4.setLatitude(62.391178326117);
loc4.setLongitude(17.3004228024664);
place4.setGeoLocation(loc4);
/*
Location loc5 = new Location("se.tidensavtryck");
loc5.setLatitude(62.3900820918969);
loc5.setLongitude(17.3091424714359);
place2.setGeoLocation(loc5);
*/
Map<Integer, Place> placeRecordMap = new HashMap<Integer, Place>();
placeRecordMap.put(1, place1);
placeRecordMap.put(2, place2);
placeRecordMap.put(3, place3);
placeRecordMap.put(4, place4);
List<Record> placeRecords = new ArrayList<Record>();
try {
for (Integer i : placeRecordMap.keySet()) {
String filename = String.format("place%d.xml", i);
- InputStream is = this.mAssetManager.open("place1.xml");
+ InputStream is = this.mAssetManager.open(filename);
XMLPull pull = new XMLPull(is);
placeRecordMap.get(i).setRecords(pull.parse());
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
List<Place> places = new LinkedList<Place>();
places.add(place1);
places.add(place2);
places.add(place3);
places.add(place4);
route.setPlaces(places);
routeList.add(route);
return routeList;
}
}
| true | true |
public List<Route> list() {
List<Route> routeList = new LinkedList<Route>();
Route route = new Route();
route.setTitle("En kort rundtur i Sundsvall");
User user = new User("Me");
route.setCreator(user);
route.setDescription("Information hämtad från K-samsök.");
Place place1 = new Place();
place1.setTitle("Place 1");
place1.setDescription("Runsten");
Place place2 = new Place();
place2.setTitle("Place 2");
place2.setDescription("Båt");
Place place3 = new Place();
place3.setTitle("Place 3");
place3.setDescription("Hedbergska");
Place place4 = new Place();
place4.setTitle("Place 4");
place4.setDescription("Stenstaden");
Location loc1 = new Location("se.tidensavtryck");
loc1.setLatitude(62.4007043202567);
loc1.setLongitude(17.2577392061653);
place1.setGeoLocation(loc1);
Location loc2 = new Location("se.tidensavtryck");
loc2.setLatitude(62.394369903217);
loc2.setLongitude(17.2816450479837);
place2.setGeoLocation(loc2);
Location loc3 = new Location("se.tidensavtryck");
loc3.setLatitude(62.3897829867526);
loc3.setLongitude(17.2995418371631);
place3.setGeoLocation(loc3);
Location loc4 = new Location("se.tidensavtryck");
loc4.setLatitude(62.391178326117);
loc4.setLongitude(17.3004228024664);
place4.setGeoLocation(loc4);
/*
Location loc5 = new Location("se.tidensavtryck");
loc5.setLatitude(62.3900820918969);
loc5.setLongitude(17.3091424714359);
place2.setGeoLocation(loc5);
*/
Map<Integer, Place> placeRecordMap = new HashMap<Integer, Place>();
placeRecordMap.put(1, place1);
placeRecordMap.put(2, place2);
placeRecordMap.put(3, place3);
placeRecordMap.put(4, place4);
List<Record> placeRecords = new ArrayList<Record>();
try {
for (Integer i : placeRecordMap.keySet()) {
String filename = String.format("place%d.xml", i);
InputStream is = this.mAssetManager.open("place1.xml");
XMLPull pull = new XMLPull(is);
placeRecordMap.get(i).setRecords(pull.parse());
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
List<Place> places = new LinkedList<Place>();
places.add(place1);
places.add(place2);
places.add(place3);
places.add(place4);
route.setPlaces(places);
routeList.add(route);
return routeList;
}
|
public List<Route> list() {
List<Route> routeList = new LinkedList<Route>();
Route route = new Route();
route.setTitle("En kort rundtur i Sundsvall");
User user = new User("Me");
route.setCreator(user);
route.setDescription("Information hämtad från K-samsök.");
Place place1 = new Place();
place1.setTitle("Place 1");
place1.setDescription("Runsten");
Place place2 = new Place();
place2.setTitle("Place 2");
place2.setDescription("Båt");
Place place3 = new Place();
place3.setTitle("Place 3");
place3.setDescription("Hedbergska");
Place place4 = new Place();
place4.setTitle("Place 4");
place4.setDescription("Stenstaden");
Location loc1 = new Location("se.tidensavtryck");
loc1.setLatitude(62.4007043202567);
loc1.setLongitude(17.2577392061653);
place1.setGeoLocation(loc1);
Location loc2 = new Location("se.tidensavtryck");
loc2.setLatitude(62.394369903217);
loc2.setLongitude(17.2816450479837);
place2.setGeoLocation(loc2);
Location loc3 = new Location("se.tidensavtryck");
loc3.setLatitude(62.3897829867526);
loc3.setLongitude(17.2995418371631);
place3.setGeoLocation(loc3);
Location loc4 = new Location("se.tidensavtryck");
loc4.setLatitude(62.391178326117);
loc4.setLongitude(17.3004228024664);
place4.setGeoLocation(loc4);
/*
Location loc5 = new Location("se.tidensavtryck");
loc5.setLatitude(62.3900820918969);
loc5.setLongitude(17.3091424714359);
place2.setGeoLocation(loc5);
*/
Map<Integer, Place> placeRecordMap = new HashMap<Integer, Place>();
placeRecordMap.put(1, place1);
placeRecordMap.put(2, place2);
placeRecordMap.put(3, place3);
placeRecordMap.put(4, place4);
List<Record> placeRecords = new ArrayList<Record>();
try {
for (Integer i : placeRecordMap.keySet()) {
String filename = String.format("place%d.xml", i);
InputStream is = this.mAssetManager.open(filename);
XMLPull pull = new XMLPull(is);
placeRecordMap.get(i).setRecords(pull.parse());
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
List<Place> places = new LinkedList<Place>();
places.add(place1);
places.add(place2);
places.add(place3);
places.add(place4);
route.setPlaces(places);
routeList.add(route);
return routeList;
}
|
diff --git a/atlas-web/src/main/java/ae3/dao/NetCDFReader.java b/atlas-web/src/main/java/ae3/dao/NetCDFReader.java
index 14518be86..67e1cb793 100644
--- a/atlas-web/src/main/java/ae3/dao/NetCDFReader.java
+++ b/atlas-web/src/main/java/ae3/dao/NetCDFReader.java
@@ -1,231 +1,232 @@
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 sc = i.next().substring("bs_".length());
+ 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);
}
}
| true | true |
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 sc = i.next().substring("bs_".length());
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);
}
|
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);
}
|
diff --git a/framework/src/play/Invoker.java b/framework/src/play/Invoker.java
index a0e23d43..dfabc6df 100644
--- a/framework/src/play/Invoker.java
+++ b/framework/src/play/Invoker.java
@@ -1,62 +1,62 @@
package play;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer;
import play.db.DB;
import play.db.jpa.JPA;
import play.exceptions.PlayException;
import play.exceptions.UnexpectedException;
public class Invoker {
public static Executor executor =null;
public static void invoke(Invocation invocation) {
if (executor==null) {
executor=Invoker.startExecutor();
}
executor.execute(invocation);
}
public static void invokeInThread(Invocation invocation) {
invocation.run();
}
public static abstract class Invocation extends Thread {
public abstract void execute() throws Exception;
@Override
public void run() {
try {
Play.detectChanges();
setContextClassLoader(Play.classloader);
LocalVariablesNamesTracer.enterMethod();
JPA.startTx(false);
execute();
+ JPA.closeTx(false);
} catch (Throwable e) {
JPA.closeTx(true);
if(e instanceof PlayException) {
throw (PlayException)e;
}
throw new UnexpectedException(e);
} finally {
- JPA.closeTx(false);
DB.close();
}
}
}
private static Executor startExecutor () {
Properties p = Play.configuration;
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable> ();
int core = Integer.parseInt(p.getProperty("play.pool.core", "2"));
int max = Integer.parseInt(p.getProperty("play.pool.max", "50"));
int keepalive = Integer.parseInt(p.getProperty("play.pool.keepalive", "5"));
return new ThreadPoolExecutor (core,max,keepalive*60,TimeUnit.SECONDS,queue,new ThreadPoolExecutor.AbortPolicy());
}
}
| false | true |
public void run() {
try {
Play.detectChanges();
setContextClassLoader(Play.classloader);
LocalVariablesNamesTracer.enterMethod();
JPA.startTx(false);
execute();
} catch (Throwable e) {
JPA.closeTx(true);
if(e instanceof PlayException) {
throw (PlayException)e;
}
throw new UnexpectedException(e);
} finally {
JPA.closeTx(false);
DB.close();
}
}
|
public void run() {
try {
Play.detectChanges();
setContextClassLoader(Play.classloader);
LocalVariablesNamesTracer.enterMethod();
JPA.startTx(false);
execute();
JPA.closeTx(false);
} catch (Throwable e) {
JPA.closeTx(true);
if(e instanceof PlayException) {
throw (PlayException)e;
}
throw new UnexpectedException(e);
} finally {
DB.close();
}
}
|
diff --git a/Stores/src/at/edu/hti/concurrency/prodcon/ThreadProducerConsumerStarter.java b/Stores/src/at/edu/hti/concurrency/prodcon/ThreadProducerConsumerStarter.java
index a29d868..86f9c9c 100644
--- a/Stores/src/at/edu/hti/concurrency/prodcon/ThreadProducerConsumerStarter.java
+++ b/Stores/src/at/edu/hti/concurrency/prodcon/ThreadProducerConsumerStarter.java
@@ -1,112 +1,112 @@
package at.edu.hti.concurrency.prodcon;
import at.edu.hti.concurrency.stores.LinkedListStore;
public class ThreadProducerConsumerStarter implements ProducerConsumerStarter {
Configuration config = null;
LinkedListStore store = null;
final Object locker = new Object();
long numberObjectsProduced = 0;
long numberObjectsConsumed = 0;
@Override
public void setUpTest(Configuration configuration) {
this.config = configuration;
}
@Override
public long runProducerConsumerTest() {
store = new LinkedListStore();
store.initMaxSize(config.getBufferSize());
numberObjectsConsumed = 0;
numberObjectsProduced = 0;
long startTime = System.currentTimeMillis();
for (int i = 0; i < config.getNumberOfConsumers(); i++) {
Consumer c = new Consumer();
Thread t = new Thread(c, "Consumer-" + i);
t.start();
}
for (int i = 0; i < config.getNumberOfProcuders(); i++) {
Producer p = new Producer();
Thread t = new Thread(p, "Producer-" + i);
t.start();
}
- while (numberObjectsConsumed < numberObjectsProduced) {
+ while (numberObjectsConsumed < config.getNumberOfItems()) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
return System.currentTimeMillis() - startTime;
}
class Producer implements Runnable {
@Override
public void run() {
while (numberObjectsProduced < config.getNumberOfItems()) {
synchronized (locker) {
if (store.size() < config.getBufferSize()) {
String produced = "String-" + numberObjectsProduced++;
System.out.println("Produced at "+Thread.currentThread().getName()+": " + produced);
store.addFirst(produced);
locker.notifyAll();
} else {
try {
locker.wait();
} catch (InterruptedException e) {
}
}
}
}
}
}
class Consumer implements Runnable {
@Override
public void run() {
while (numberObjectsConsumed < config.getNumberOfItems()) {
synchronized (locker) {
if (store.size() > 0) {
String consumed = store.removeLast();
numberObjectsConsumed++;
System.out.println("Consumed at "+Thread.currentThread().getName()+": " + consumed);
locker.notifyAll();
} else {
try {
locker.wait();
} catch (InterruptedException e) {
}
}
}
}
}
}
public static void main(String[] args) {
ProducerConsumerStarter test = new ThreadProducerConsumerStarter();
Configuration config = new Configuration(10, 10, 5, 1000);
test.setUpTest(config);
long time = test.runProducerConsumerTest();
System.out.println("Result: " + time + " : " + config);
}
}
| true | true |
public long runProducerConsumerTest() {
store = new LinkedListStore();
store.initMaxSize(config.getBufferSize());
numberObjectsConsumed = 0;
numberObjectsProduced = 0;
long startTime = System.currentTimeMillis();
for (int i = 0; i < config.getNumberOfConsumers(); i++) {
Consumer c = new Consumer();
Thread t = new Thread(c, "Consumer-" + i);
t.start();
}
for (int i = 0; i < config.getNumberOfProcuders(); i++) {
Producer p = new Producer();
Thread t = new Thread(p, "Producer-" + i);
t.start();
}
while (numberObjectsConsumed < numberObjectsProduced) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
return System.currentTimeMillis() - startTime;
}
|
public long runProducerConsumerTest() {
store = new LinkedListStore();
store.initMaxSize(config.getBufferSize());
numberObjectsConsumed = 0;
numberObjectsProduced = 0;
long startTime = System.currentTimeMillis();
for (int i = 0; i < config.getNumberOfConsumers(); i++) {
Consumer c = new Consumer();
Thread t = new Thread(c, "Consumer-" + i);
t.start();
}
for (int i = 0; i < config.getNumberOfProcuders(); i++) {
Producer p = new Producer();
Thread t = new Thread(p, "Producer-" + i);
t.start();
}
while (numberObjectsConsumed < config.getNumberOfItems()) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
return System.currentTimeMillis() - startTime;
}
|
diff --git a/src/test/java/net/praqma/hudson/test/integration/sibling/BaselinesFound.java b/src/test/java/net/praqma/hudson/test/integration/sibling/BaselinesFound.java
index 581d544..f5c02e7 100644
--- a/src/test/java/net/praqma/hudson/test/integration/sibling/BaselinesFound.java
+++ b/src/test/java/net/praqma/hudson/test/integration/sibling/BaselinesFound.java
@@ -1,51 +1,54 @@
package net.praqma.hudson.test.integration.sibling;
import net.praqma.hudson.test.BaseTestClass;
import net.praqma.util.test.junit.LoggingRule;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import hudson.model.AbstractBuild;
import net.praqma.clearcase.ucm.entities.Baseline;
import net.praqma.clearcase.ucm.entities.Stream;
import net.praqma.clearcase.ucm.entities.Project.PromotionLevel;
import net.praqma.hudson.test.CCUCMRule;
import net.praqma.hudson.test.SystemValidator;
import net.praqma.util.debug.Logger;
import net.praqma.clearcase.test.junit.ClearCaseRule;
import java.util.logging.Level;
public class BaselinesFound extends BaseTestClass {
@Rule
public static ClearCaseRule ccenv = new ClearCaseRule( "ccucm", "setup-interproject.xml" );
private static Logger logger = Logger.getLogger();
public AbstractBuild<?, ?> initiateBuild( String projectName, boolean recommend, boolean tag, boolean description, boolean fail ) throws Exception {
return jenkins.initiateBuild( projectName, "sibling", "_System@" + ccenv.getPVob(), "two_int@" + ccenv.getPVob(), recommend, tag, description, fail, true );
}
@Test
public void basicSibling() throws Exception {
Stream one = ccenv.context.streams.get( "one_int" );
Stream two = ccenv.context.streams.get( "two_int" );
one.setDefaultTarget( two );
/* The baseline that should be built */
Baseline baseline = ccenv.context.baselines.get( "model-1" );
AbstractBuild<?, ?> build = initiateBuild( "no-options-" + ccenv.getUniqueName(), false, false, false, false );
/* Validate */
- SystemValidator validator = new SystemValidator( build ).validateBuild( build.getResult() ).validateBuiltBaseline( PromotionLevel.BUILT, baseline, false ).validateCreatedBaseline( true );
+ SystemValidator validator = new SystemValidator( build ).
+ validateBuild( build.getResult() ).
+ validateBuiltBaseline( PromotionLevel.BUILT, baseline, false ).
+ validateCreatedBaseline( true );
validator.validate();
}
}
| true | true |
public void basicSibling() throws Exception {
Stream one = ccenv.context.streams.get( "one_int" );
Stream two = ccenv.context.streams.get( "two_int" );
one.setDefaultTarget( two );
/* The baseline that should be built */
Baseline baseline = ccenv.context.baselines.get( "model-1" );
AbstractBuild<?, ?> build = initiateBuild( "no-options-" + ccenv.getUniqueName(), false, false, false, false );
/* Validate */
SystemValidator validator = new SystemValidator( build ).validateBuild( build.getResult() ).validateBuiltBaseline( PromotionLevel.BUILT, baseline, false ).validateCreatedBaseline( true );
validator.validate();
}
|
public void basicSibling() throws Exception {
Stream one = ccenv.context.streams.get( "one_int" );
Stream two = ccenv.context.streams.get( "two_int" );
one.setDefaultTarget( two );
/* The baseline that should be built */
Baseline baseline = ccenv.context.baselines.get( "model-1" );
AbstractBuild<?, ?> build = initiateBuild( "no-options-" + ccenv.getUniqueName(), false, false, false, false );
/* Validate */
SystemValidator validator = new SystemValidator( build ).
validateBuild( build.getResult() ).
validateBuiltBaseline( PromotionLevel.BUILT, baseline, false ).
validateCreatedBaseline( true );
validator.validate();
}
|
diff --git a/android_4.x/src/com/vipercn/viper4android_v2/activity/ViPER4Android.java b/android_4.x/src/com/vipercn/viper4android_v2/activity/ViPER4Android.java
index c7fee95..2bde28e 100755
--- a/android_4.x/src/com/vipercn/viper4android_v2/activity/ViPER4Android.java
+++ b/android_4.x/src/com/vipercn/viper4android_v2/activity/ViPER4Android.java
@@ -1,1675 +1,1679 @@
package com.vipercn.viper4android_v2.activity;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.vipercn.viper4android_v2.R;
import com.vipercn.viper4android_v2.service.ViPER4AndroidService;
import com.vipercn.viper4android_v2.widgets.CustomDrawerLayout;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Random;
public final class ViPER4Android extends Activity {
//==================================
// Static Fields
//==================================
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String PREF_IS_TABBED = "pref_is_tabbed";
//==================================
public static final String SHARED_PREFERENCES_BASENAME = "com.vipercn.viper4android_v2";
public static final String ACTION_UPDATE_PREFERENCES = "com.vipercn.viper4android_v2.UPDATE";
public static final String ACTION_SHOW_NOTIFY = "com.vipercn.viper4android_v2.SHOWNOTIFY";
public static final String ACTION_CANCEL_NOTIFY = "com.vipercn.viper4android_v2.CANCELNOTIFY";
public static final int NOTIFY_FOREGROUND_ID = 1;
//==================================
private static String[] mEntries;
private static List<HashMap<String, String>> mTitles;
//==================================
// Drawer
//==================================
private ActionBarDrawerToggle mDrawerToggle;
private CustomDrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
//==================================
// ViewPager
//==================================
protected MyAdapter pagerAdapter;
protected ViewPager viewPager;
protected PagerTabStrip pagerTabStrip;
//==================================
// Fields
//==================================
private SharedPreferences mPreferences;
private boolean mIsTabbed = true;
private CharSequence mTitle;
private boolean checkFirstRun() {
PackageManager packageMgr = getPackageManager();
PackageInfo packageInfo;
String mVersion;
try {
packageInfo = packageMgr.getPackageInfo(getPackageName(), 0);
mVersion = packageInfo.versionName;
} catch (NameNotFoundException e) {
return false;
}
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings", 0);
String mLastVersion = prefSettings.getString("viper4android.settings.lastversion", "");
return mLastVersion == null || mLastVersion.equals("")
|| !mLastVersion.equalsIgnoreCase(mVersion);
}
private boolean checkDDCDBVer() {
PackageManager packageMgr = getPackageManager();
PackageInfo packageInfo;
String mVersion;
try {
packageInfo = packageMgr.getPackageInfo(getPackageName(), 0);
mVersion = packageInfo.versionName;
} catch (NameNotFoundException e) {
return false;
}
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings", 0);
String mDBVersion = prefSettings.getString("viper4android.settings.ddc_db_compatible", "");
return mDBVersion == null || mDBVersion.equals("")
|| !mDBVersion.equalsIgnoreCase(mVersion);
}
private void setFirstRun() {
PackageManager packageMgr = getPackageManager();
PackageInfo packageInfo;
String mVersion;
try {
packageInfo = packageMgr.getPackageInfo(getPackageName(), 0);
mVersion = packageInfo.versionName;
} catch (NameNotFoundException e) {
return;
}
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings", 0);
Editor editSettings = prefSettings.edit();
if (editSettings != null) {
editSettings.putString("viper4android.settings.lastversion", mVersion);
editSettings.commit();
}
}
private void setDDCDBVer() {
PackageManager packageMgr = getPackageManager();
PackageInfo packageInfo;
String mVersion;
try {
packageInfo = packageMgr.getPackageInfo(getPackageName(), 0);
mVersion = packageInfo.versionName;
} catch (NameNotFoundException e) {
return;
}
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings", 0);
Editor editSettings = prefSettings.edit();
if (editSettings != null) {
editSettings.putString("viper4android.settings.ddc_db_compatible", mVersion);
editSettings.commit();
}
}
private boolean checkSoftwareActive() {
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings", 0);
boolean mActived = prefSettings.getBoolean("viper4android.settings.onlineactive", false);
return !mActived;
}
private void setSoftwareActive() {
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings", 0);
Editor editSettings = prefSettings.edit();
if (editSettings != null) {
editSettings.putBoolean("viper4android.settings.onlineactive", true);
editSettings.commit();
}
}
private boolean submitInformation() {
String mCode = "";
Random rndMachine = new Random();
for (int i = 0; i < 8; i++) {
int oneByte = (int) rndMachine.nextInt(256);
String byteHexString = Integer.toHexString(oneByte);
if (byteHexString.length() < 2) {
byteHexString = "0" + byteHexString;
}
mCode = mCode + byteHexString;
}
mCode = mCode + "-";
for (int i = 0; i < 4; i++) {
int oneByte = (int) rndMachine.nextInt(256);
String byteHexString = Integer.toHexString(oneByte);
if (byteHexString.length() < 2) {
byteHexString = "0" + byteHexString;
}
mCode = mCode + byteHexString;
}
mCode = mCode + "-" + Build.VERSION.SDK_INT;
String mURL = "http://vipersaudio.com/stat/v4a_stat.php?code=" + mCode
+ "&ver=viper4android-fx";
try {
HttpGet httpRequest = new HttpGet(mURL);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpRequest);
return httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
} catch (Exception e) {
Log.i("ViPER4Android", "Submit failed, error = " + e.getMessage());
return false;
}
}
private void processDriverCheck() {
boolean isDriverUsable;
Utils.AudioEffectUtils aeuUtils = new Utils().new AudioEffectUtils();
if (!aeuUtils.isViPER4AndroidEngineFound()) {
isDriverUsable = false;
} else {
int[] iaDrvVer = aeuUtils.getViper4AndroidEngineVersion();
String mDriverVersion = iaDrvVer[0] + "." + iaDrvVer[1] + "." + iaDrvVer[2] + "."
+ iaDrvVer[3];
isDriverUsable = isDriverCompatible(mDriverVersion);
}
if (!isDriverUsable) {
Log.i("ViPER4Android",
"Android audio effect engine reports the v4a driver is not usable");
Message message = new Message();
message.what = 0xA00A;
message.obj = this;
mDriverHandler.sendMessage(message);
}
}
public static boolean isDriverCompatible(String szDrvVersion){
List<String> lstCompatibleList = new ArrayList<String>();
// TODO: <DO NOT REMOVE> add compatible driver version to lstCompatibleList
if (lstCompatibleList.contains(szDrvVersion)) {
lstCompatibleList.clear();
lstCompatibleList = null;
return true;
} else {
lstCompatibleList.clear();
lstCompatibleList = null;
// Since we cant use getPackageManager in static method, we need to type the current version here
// TODO: <DO NOT REMOVE> please make sure this string equals to current apk's version
if (szDrvVersion.equals("2.3.3.0")) {
return true;
}
return false;
}
}
private static boolean cpuHasQualitySelection() {
Utils.CpuInfo mCPUInfo = new Utils.CpuInfo();
boolean bCPUHasNEON = mCPUInfo.hasNEON();
mCPUInfo = null;
return bCPUHasNEON;
}
private static String determineCPUWithDriver(String mQual) {
String mDriverFile = "libv4a_fx_";
if (Build.VERSION.SDK_INT >= 18) {
mDriverFile = mDriverFile + "jb_";
} else {
mDriverFile = mDriverFile + "ics_";
}
if (Build.CPU_ABI.contains("x86") ||
Build.CPU_ABI.contains("X86")) {
// x86 architecture
mDriverFile = mDriverFile + "X86.so";
Log.i("ViPER4Android", "Driver selection = " + mDriverFile);
return mDriverFile;
}
Utils.CpuInfo mCPUInfo = new Utils.CpuInfo();
if (mCPUInfo.hasNEON()) {
if (mQual == null) {
mDriverFile = mDriverFile + "NEON";
} else if (mQual.equals("")) {
mDriverFile = mDriverFile + "NEON";
} else if (mQual.equalsIgnoreCase("sq")) {
mDriverFile = mDriverFile + "NEON_SQ";
} else if (mQual.equalsIgnoreCase("hq")) {
mDriverFile = mDriverFile + "NEON_HQ";
} else {
mDriverFile = mDriverFile + "NEON";
}
} else if (mCPUInfo.hasVFP()) {
mDriverFile = mDriverFile + "VFP";
} else {
mDriverFile = mDriverFile + "NOVFP";
}
mCPUInfo = null;
mDriverFile = mDriverFile + ".so";
Log.i("ViPER4Android", "Driver selection = " + mDriverFile);
return mDriverFile;
}
private static String readTextFile(InputStream inputStream) {
InputStreamReader inputStreamReader;
try {
inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
} catch (UnsupportedEncodingException e1) {
return "";
}
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuilder build = new StringBuilder("");
String line;
try {
while ((line = reader.readLine()) != null) {
build.append(line);
build.append("\n");
}
reader.close();
inputStreamReader.close();
reader = null;
inputStreamReader = null;
} catch (IOException e) {
return "";
}
return build.toString();
}
private ViPER4AndroidService mAudioServiceInstance;
// Driver install handler
private static final Handler mDriverHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
if (msg.what == 0xA00A) {
if (msg.obj == null) {
super.handleMessage(msg);
return;
}
final Context ctxInstance = (Context) msg.obj;
AlertDialog.Builder mUpdateDrv = new AlertDialog.Builder(ctxInstance);
mUpdateDrv.setTitle("ViPER4Android");
mUpdateDrv.setMessage(ctxInstance.getResources().getString(
R.string.text_drvvernotmatch));
mUpdateDrv.setPositiveButton(
ctxInstance.getResources().getString(R.string.text_yes),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Install/Update driver
boolean canChooseQuality = cpuHasQualitySelection();
if (canChooseQuality) {
new AlertDialog.Builder(ctxInstance)
.setTitle(R.string.text_drvinst_prefer)
.setIcon(R.drawable.icon)
.setItems(R.array.drvinst_prefer, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String[] mQual = ctxInstance.getResources().getStringArray(
R.array.drvinst_prefer_values);
final String result = mQual[which];
if (result.equalsIgnoreCase("sq")) {
AlertDialog.Builder mSQWarn = new AlertDialog.Builder(ctxInstance);
mSQWarn.setTitle("ViPER4Android");
mSQWarn.setMessage(ctxInstance.getResources().getString(R.string.text_drvinst_sqdrv));
mSQWarn.setPositiveButton(ctxInstance.getResources().getString(R.string.text_ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!Utils.isBusyBoxInstalled(ctxInstance)) {
AlertDialog.Builder mResult = new AlertDialog.Builder(ctxInstance);
mResult.setTitle("ViPER4Android");
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_busybox_not_installed));
mResult.setNegativeButton(ctxInstance.getResources().getString(
R.string.text_ok), null);
mResult.show();
} else {
int drvInstResult = Utils.installDrv_FX(ctxInstance, determineCPUWithDriver(result));
if (drvInstResult == 0) {
Utils.proceedBuildProp(ctxInstance);
AlertDialog.Builder mResult = new AlertDialog.Builder(ctxInstance);
mResult.setTitle("ViPER4Android");
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_ok));
mResult.setNegativeButton(ctxInstance.getResources()
.getString(R.string.text_ok), null);
mResult.show();
} else {
AlertDialog.Builder mResult = new AlertDialog.Builder(ctxInstance);
mResult.setTitle("ViPER4Android");
switch (drvInstResult) {
case 1:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_acquireroot));
break;
case 2:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_sdnotmounted));
break;
case 3:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_dataioerr));
break;
case 4:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_cfg_unsup));
break;
case 5:
case 6:
default:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_failed));
break;
}
mResult.setNegativeButton(ctxInstance.getResources().getString(
R.string.text_ok), null);
mResult.show();
}
}
dialog.dismiss();
}
});
mSQWarn.setNegativeButton(ctxInstance.getResources().getString(R.string.text_cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
mSQWarn.show();
} else {
if (!Utils.isBusyBoxInstalled(ctxInstance)) {
AlertDialog.Builder mResult = new AlertDialog.Builder(ctxInstance);
mResult.setTitle("ViPER4Android");
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_busybox_not_installed));
mResult.setNegativeButton(ctxInstance.getResources().getString(
R.string.text_ok), null);
mResult.show();
} else {
int drvInstResult = Utils.installDrv_FX(ctxInstance, determineCPUWithDriver(result));
if (drvInstResult == 0) {
Utils.proceedBuildProp(ctxInstance);
AlertDialog.Builder mResult = new AlertDialog.Builder(ctxInstance);
mResult.setTitle("ViPER4Android");
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_ok));
mResult.setNegativeButton(ctxInstance.getResources()
.getString(R.string.text_ok), null);
mResult.show();
} else {
AlertDialog.Builder mResult = new AlertDialog.Builder(ctxInstance);
mResult.setTitle("ViPER4Android");
switch (drvInstResult) {
case 1:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_acquireroot));
break;
case 2:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_sdnotmounted));
break;
case 3:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_dataioerr));
break;
case 4:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_cfg_unsup));
break;
case 5:
case 6:
default:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_failed));
break;
}
mResult.setNegativeButton(ctxInstance.getResources().getString(
R.string.text_ok), null);
mResult.show();
}
}
}
}
})
.setNegativeButton(R.string.text_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).create().show();
} else {
String mDriverFileName = determineCPUWithDriver("");
if (!Utils.isBusyBoxInstalled(ctxInstance)) {
AlertDialog.Builder mResult = new AlertDialog.Builder(ctxInstance);
mResult.setTitle("ViPER4Android");
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_busybox_not_installed));
mResult.setNegativeButton(ctxInstance.getResources().getString(
R.string.text_ok), null);
mResult.show();
} else {
int drvInstResult = Utils.installDrv_FX(ctxInstance, mDriverFileName);
if (drvInstResult == 0) {
Utils.proceedBuildProp(ctxInstance);
AlertDialog.Builder mResult = new AlertDialog.Builder(ctxInstance);
mResult.setTitle("ViPER4Android");
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_ok));
mResult.setNegativeButton(ctxInstance.getResources()
.getString(R.string.text_ok), null);
mResult.show();
} else {
AlertDialog.Builder mResult = new AlertDialog.Builder(ctxInstance);
mResult.setTitle("ViPER4Android");
switch (drvInstResult) {
case 1:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_acquireroot));
break;
case 2:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_sdnotmounted));
break;
case 3:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_dataioerr));
break;
case 4:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_cfg_unsup));
break;
case 5:
case 6:
default:
mResult.setMessage(ctxInstance.getResources().getString(
R.string.text_drvinst_failed));
break;
}
mResult.setNegativeButton(ctxInstance.getResources().getString(
R.string.text_ok), null);
mResult.show();
}
}
}
}
});
mUpdateDrv.setNegativeButton(ctxInstance.getResources().getString(R.string.text_no),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
mUpdateDrv.show();
mUpdateDrv = null;
}
super.handleMessage(msg);
} catch (Exception e) {
super.handleMessage(msg);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load jni first
boolean jniLoaded = V4AJniInterface.CheckLibrary();
Log.i("ViPER4Android", "Jni library status = " + jniLoaded);
// Welcome window
if (checkFirstRun()) {
// TODO: Welcome window
}
// Prepare ViPER-DDC database
if (checkDDCDBVer()) {
if (DDCDatabase.initializeDatabase(this))
setDDCDBVer();
}
// We should start the background service first
Log.i("ViPER4Android", "Starting service, reason = ViPER4Android::onCreate");
Intent serviceIntent = new Intent(this, ViPER4AndroidService.class);
startService(serviceIntent);
// Setup ui
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mUserLearnedDrawer = mPreferences.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (getResources().getBoolean(R.bool.config_allow_toggle_tabbed)) {
mIsTabbed = mPreferences.getBoolean(PREF_IS_TABBED,
getResources().getBoolean(R.bool.config_use_tabbed));
} else {
mIsTabbed = getResources().getBoolean(R.bool.config_use_tabbed);
}
mTitle = getTitle();
// Setup action bar
ActionBar mActionBar = getActionBar();
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setHomeButtonEnabled(true);
mActionBar.setDisplayShowTitleEnabled(true);
// Setup effect setting page
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Show changelog
if (checkFirstRun()) {
String mLocale = Locale.getDefault().getLanguage() + "_"
+ Locale.getDefault().getCountry();
String mChangelog_AssetsName = "Changelog_";
if (mLocale.equalsIgnoreCase("zh_CN")) {
mChangelog_AssetsName = mChangelog_AssetsName + "zh_CN";
} else {
mChangelog_AssetsName = mLocale.equalsIgnoreCase("zh_TW") ? mChangelog_AssetsName
+ "zh_TW" : mChangelog_AssetsName + "en_US";
}
mChangelog_AssetsName = mChangelog_AssetsName + ".txt";
String mChangeLog = "";
InputStream isChglogHandle;
try {
isChglogHandle = getAssets().open(mChangelog_AssetsName);
mChangeLog = readTextFile(isChglogHandle);
isChglogHandle.close();
} catch (IOException e) {
Log.i("ViPER4Android", "Can not read changelog");
}
setFirstRun();
if (!mChangeLog.equalsIgnoreCase("")) {
AlertDialog.Builder mChglog = new AlertDialog.Builder(this);
mChglog.setTitle(R.string.text_changelog);
mChglog.setMessage(mChangeLog);
mChglog.setNegativeButton(getResources().getString(R.string.text_ok), null);
mChglog.show();
} else {
Log.i("ViPER4Android", "Changelog is empty");
}
}
// Start active thread
Thread activeThread = new Thread(new Runnable() {
@Override
public void run() {
if (checkSoftwareActive()) {
if (submitInformation()) {
setSoftwareActive();
}
}
}
});
activeThread.start();
// Start post init thread
Thread postInitThread = new Thread(new Runnable() {
@Override
public void run() {
// Init environment
Log.i("ViPER4Android", "Init environment");
StaticEnvironment.initEnvironment();
// Driver check loop
Log.i("ViPER4Android", "Check driver");
processDriverCheck();
}
});
postInitThread.start();
setUpUi();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (!mIsTabbed) {
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (!mIsTabbed) {
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
}
@Override
public void onResume() {
Log.i("ViPER4Android", "Main activity onResume()");
super.onResume();
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
Log.i("ViPER4Android", "ViPER4Android service connected");
ViPER4AndroidService service = ((ViPER4AndroidService.LocalBinder)binder).getService();
mAudioServiceInstance = service;
String routing = ViPER4AndroidService.getAudioOutputRouting(getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings", MODE_PRIVATE));
if (mIsTabbed && viewPager != null) {
String[] entries = getEntries();
for (int i = 0; i < entries.length; i++) {
if (routing.equals(entries[i])) {
viewPager.setCurrentItem(i);
break;
}
}
} else if (!mIsTabbed) {
String[] entries = getEntries();
for (int i = 0; i < entries.length; i++) {
if (routing.equals(entries[i])) {
selectItem(i);
break;
}
}
}
Log.i("ViPER4Android", "Unbinding service ...");
unbindService(this);
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e("ViPER4Android", "ViPER4Android service disconnected");
}
};
Log.i("ViPER4Android", "onResume(), Binding service ...");
Intent serviceIntent = new Intent(this, ViPER4AndroidService.class);
bindService(serviceIntent, connection, Context.BIND_IMPORTANT);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!isDrawerOpen()) {
getMenuInflater().inflate(mIsTabbed ? R.menu.menu_tabbed : R.menu.menu, menu);
if (!getResources().getBoolean(R.bool.config_allow_toggle_tabbed)) {
menu.removeItem(R.id.v4a_action_tabbed);
}
getActionBar().setTitle(mTitle);
return true;
} else {
getActionBar().setTitle(getString(R.string.app_name));
return super.onCreateOptionsMenu(menu);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
SharedPreferences preferences = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings", MODE_PRIVATE);
boolean mEnableNotify = preferences.getBoolean("viper4android.settings.show_notify_icon", false);
String mDriverMode = preferences.getString("viper4android.settings.compatiblemode", "global");
if (!isDrawerOpen()) {
// Notification icon menu
if (mEnableNotify) {
MenuItem mNotify = menu.findItem(R.id.notify);
String mNotifyTitle = getResources().getString(R.string.text_hidetrayicon);
mNotify.setTitle(mNotifyTitle);
} else {
MenuItem mNotify = menu.findItem(R.id.notify);
String mNotifyTitle = getResources().getString(R.string.text_showtrayicon);
mNotify.setTitle(mNotifyTitle);
}
// Driver mode menu
boolean isDriverInGlobalMode = true;
if (!mDriverMode.equalsIgnoreCase("global")) {
isDriverInGlobalMode = false;
}
if (!isDriverInGlobalMode) {
/* If the driver is in compatible mode, driver status is invalid */
MenuItem mDrvStatus = menu.findItem(R.id.drvstatus);
mDrvStatus.setEnabled(false);
} else {
MenuItem mDrvStatus = menu.findItem(R.id.drvstatus);
mDrvStatus.setEnabled(true);
}
// Driver install/uninstall menu
if (mAudioServiceInstance == null) {
MenuItem drvInstItem = menu.findItem(R.id.drvinst);
String menuTitle = getResources().getString(R.string.text_install);
drvInstItem.setTitle(menuTitle);
if (!StaticEnvironment.isEnvironmentInitialized()) {
drvInstItem.setEnabled(false);
} else {
drvInstItem.setEnabled(true);
}
} else {
boolean mDriverIsReady = mAudioServiceInstance.getDriverIsReady();
if (mDriverIsReady) {
MenuItem drvInstItem = menu.findItem(R.id.drvinst);
String menuTitle = getResources().getString(R.string.text_uninstall);
drvInstItem.setTitle(menuTitle);
if (!StaticEnvironment.isEnvironmentInitialized())
drvInstItem.setEnabled(false);
else drvInstItem.setEnabled(true);
} else {
MenuItem drvInstItem = menu.findItem(R.id.drvinst);
String menuTitle = getResources().getString(R.string.text_install);
drvInstItem.setTitle(menuTitle);
if (!StaticEnvironment.isEnvironmentInitialized())
drvInstItem.setEnabled(false);
else drvInstItem.setEnabled(true);
}
}
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
/* item == null in Monkey test */
if (item == null) return true;
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings", MODE_PRIVATE);
if (!mIsTabbed) {
+ if (mDrawerToggle == null) {
+ /* mDrawerToggle == null in Monkey test */
+ return true;
+ }
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
}
int choice = item.getItemId();
switch (choice) {
case R.id.about: {
PackageManager packageMgr = getPackageManager();
PackageInfo packageInfo;
String mVersion;
try {
packageInfo = packageMgr.getPackageInfo(getPackageName(), 0);
mVersion = packageInfo.versionName;
} catch (NameNotFoundException e) {
mVersion = "N/A";
}
String mAbout = getResources().getString(R.string.about_text);
mAbout = String.format(mAbout, mVersion) + "\n";
mAbout = mAbout + getResources().getString(R.string.text_help_content);
AlertDialog.Builder mHelp = new AlertDialog.Builder(this);
mHelp.setTitle(getResources().getString(R.string.about_title));
mHelp.setMessage(mAbout);
mHelp.setPositiveButton(getResources().getString(R.string.text_ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
mHelp.setNegativeButton(getResources().getString(R.string.text_view_forum),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Uri uri = Uri.parse(getResources().getString(
R.string.text_forum_link));
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
mHelp.show();
return true;
}
case R.id.checkupdate: {
Uri uri = Uri.parse(getResources().getString(R.string.text_updatelink));
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
return true;
}
case R.id.drvstatus: {
DialogFragment df = new DialogFragment() {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle state) {
if (mAudioServiceInstance == null) {
View v = inflater.inflate(R.layout.drvstatus, null);
TextView tv = (TextView) v.findViewById(R.id.drv_status);
tv.setText(R.string.text_service_error);
return v;
} else {
mAudioServiceInstance.startStatusUpdating();
SystemClock.sleep(500);
mAudioServiceInstance.stopStatusUpdating();
String mDrvNEONEnabled = getResources().getString(R.string.text_yes);
if (!mAudioServiceInstance.getDriverNEON()) {
mDrvNEONEnabled = getResources().getString(R.string.text_no);
}
String mDrvEnabled = getResources().getString(R.string.text_yes);
if (!mAudioServiceInstance.getDriverEnabled()) {
mDrvEnabled = getResources().getString(R.string.text_no);
}
String mDrvUsable = getResources().getString(R.string.text_normal);
if (!mAudioServiceInstance.getDriverCanWork()) {
mDrvUsable = getResources().getString(R.string.text_abnormal);
}
String mDrvSupportFmt = getResources().getString(R.string.text_supported);
if (!mAudioServiceInstance.getDriverSupportFormat()) {
mDrvSupportFmt = getResources().getString(R.string.text_unsupported);
}
String mDrvProcess = getResources().getString(R.string.text_yes);
if (!mAudioServiceInstance.getDriverProcess()) {
mDrvProcess = getResources().getString(R.string.text_no);
}
Utils.AudioEffectUtils aeuUtils = new Utils().new AudioEffectUtils();
int[] iaDrvVer = aeuUtils.getViper4AndroidEngineVersion();
String mDriverVersion = iaDrvVer[0] + "." + iaDrvVer[1] + "."
+ iaDrvVer[2] + "." + iaDrvVer[3];
String mDrvStatus;
mDrvStatus = getResources().getString(R.string.text_drv_status_view);
mDrvStatus = String.format(mDrvStatus,
mDriverVersion, mDrvNEONEnabled,
mDrvEnabled, mDrvUsable, mDrvSupportFmt, mDrvProcess,
mAudioServiceInstance.getDriverSamplingRate());
View v = inflater.inflate(R.layout.drvstatus, null);
TextView tv = (TextView) v.findViewById(R.id.drv_status);
tv.setText(mDrvStatus);
return v;
}
}
};
df.setStyle(DialogFragment.STYLE_NO_TITLE, 0);
df.show(getFragmentManager(), "v4astatus");
return true;
}
case R.id.changelog: {
// Deal with changelog file name
String mLocale = Locale.getDefault().getLanguage() + "_"
+ Locale.getDefault().getCountry();
String mChangelog_AssetsName = "Changelog_";
if (mLocale.equalsIgnoreCase("zh_CN")) {
mChangelog_AssetsName = mChangelog_AssetsName + "zh_CN";
} else {
mChangelog_AssetsName = mLocale.equalsIgnoreCase("zh_TW") ?
mChangelog_AssetsName + "zh_TW" : mChangelog_AssetsName + "en_US";
}
mChangelog_AssetsName = mChangelog_AssetsName + ".txt";
String mChangeLog = "";
InputStream isChglogHandle;
try {
isChglogHandle = getAssets().open(mChangelog_AssetsName);
mChangeLog = readTextFile(isChglogHandle);
isChglogHandle.close();
} catch (IOException e) {
Log.i("ViPER4Android", "Can not read changelog");
}
if (mChangeLog.equalsIgnoreCase("")) return true;
AlertDialog.Builder mChglog = new AlertDialog.Builder(this);
mChglog.setTitle(R.string.text_changelog);
mChglog.setMessage(mChangeLog);
mChglog.setNegativeButton(getResources().getString(R.string.text_ok), null);
mChglog.show();
return true;
}
case R.id.loadprofile: {
loadProfileDialog();
return true;
}
case R.id.saveprofile: {
saveProfileDialog();
return true;
}
case R.id.drvinst: {
String menuText = item.getTitle().toString();
if (getResources().getString(R.string.text_uninstall).equals(menuText)) {
// Please confirm the process
AlertDialog.Builder mConfirm = new AlertDialog.Builder(this);
mConfirm.setTitle("ViPER4Android");
mConfirm.setMessage(getResources().getString(R.string.text_drvuninst_confim));
mConfirm.setPositiveButton(getResources().getString(R.string.text_yes),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Uninstall driver
Utils.uninstallDrv_FX();
AlertDialog.Builder mResult = new AlertDialog.Builder(ViPER4Android.this);
mResult.setTitle("ViPER4Android");
mResult.setMessage(getResources().getString(R.string.text_drvuninst_ok));
mResult.setNegativeButton(getResources().getString(R.string.text_ok), null);
mResult.show();
}
});
mConfirm.setNegativeButton(getResources().getString(R.string.text_no), null);
mConfirm.show();
} else if (getResources().getString(R.string.text_install).equals(menuText)) {
Message message = new Message();
message.what = 0xA00A;
message.obj = this;
mDriverHandler.sendMessage(message);
} else {
String szTip = getResources().getString(R.string.text_service_error);
Toast.makeText(this, szTip, Toast.LENGTH_LONG).show();
}
return true;
}
case R.id.uiprefer: {
int nUIPrefer = prefSettings.getInt("viper4android.settings.uiprefer", 0);
if (nUIPrefer < 0 || nUIPrefer > 2) {
nUIPrefer = 0;
}
Dialog selectDialog = new AlertDialog.Builder(this)
.setTitle(R.string.text_uiprefer_dialog)
.setIcon(R.drawable.icon)
.setSingleChoiceItems(R.array.ui_prefer, nUIPrefer,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which < 0 || which > 2) which = 0;
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings", MODE_PRIVATE);
int nOldSelIdx = prefSettings.getInt(
"viper4android.settings.uiprefer", 0);
if (nOldSelIdx == which) {
dialog.dismiss();
return;
}
Editor edit = prefSettings.edit();
edit.putInt("viper4android.settings.uiprefer", which);
edit.commit();
sendBroadcast(new Intent(ACTION_UPDATE_PREFERENCES));
dialog.dismiss();
Utils.restartActivity(ViPER4Android.this);
}
}).setCancelable(false).create();
selectDialog.show();
return true;
}
case R.id.compatible: {
String mCompatibleMode = prefSettings.getString(
"viper4android.settings.compatiblemode", "global");
int mSelectIndex;
mSelectIndex = mCompatibleMode.equals("global") ? 0 : 1;
Dialog selectDialog = new AlertDialog.Builder(this)
.setTitle(R.string.text_commode)
.setIcon(R.drawable.icon)
.setSingleChoiceItems(R.array.compatible_mode, mSelectIndex,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings",
MODE_PRIVATE);
Editor edit = prefSettings.edit();
switch (which) {
case 0:
edit.putString(
"viper4android.settings.compatiblemode",
"global");
break;
case 1:
edit.putString(
"viper4android.settings.compatiblemode",
"local");
break;
}
edit.commit();
dialog.dismiss();
}
}).setCancelable(false).create();
selectDialog.show();
return true;
}
case R.id.notify: {
boolean enableNotify = prefSettings.getBoolean(
"viper4android.settings.show_notify_icon", false);
enableNotify = !enableNotify;
if (enableNotify) {
item.setTitle(getResources().getString(R.string.text_hidetrayicon));
} else {
item.setTitle(getResources().getString(R.string.text_showtrayicon));
}
Editor edit = prefSettings.edit();
edit.putBoolean("viper4android.settings.show_notify_icon", enableNotify);
edit.commit();
// Tell background service to deal with the notification icon
if (enableNotify) {
sendBroadcast(new Intent(ACTION_SHOW_NOTIFY));
} else {
sendBroadcast(new Intent(ACTION_CANCEL_NOTIFY));
}
return true;
}
case R.id.lockeffect: {
String mLockedEffect = prefSettings.getString(
"viper4android.settings.lock_effect", "none");
int mLockIndex;
if (mLockedEffect.equalsIgnoreCase("none")) {
mLockIndex = 0;
} else if (mLockedEffect.equalsIgnoreCase("headset")) {
mLockIndex = 1;
} else if (mLockedEffect.equalsIgnoreCase("speaker")) {
mLockIndex = 2;
} else if (mLockedEffect.equalsIgnoreCase("bluetooth")) {
mLockIndex = 3;
} else if (mLockedEffect.equalsIgnoreCase("usb")) {
mLockIndex = 4;
} else {
mLockIndex = 5;
}
String[] modeList = {
getResources().getString(R.string.text_disabled),
getResources().getString(R.string.text_headset),
getResources().getString(R.string.text_speaker),
getResources().getString(R.string.text_bluetooth),
getResources().getString(R.string.text_usb)
};
Dialog selectDialog = new AlertDialog.Builder(this)
.setTitle(R.string.text_lockeffect)
.setIcon(R.drawable.icon)
.setSingleChoiceItems(modeList, mLockIndex,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings",
MODE_PRIVATE);
Editor edit = prefSettings.edit();
switch (which) {
case 0:
edit.putString("viper4android.settings.lock_effect",
"none");
break;
case 1:
edit.putString("viper4android.settings.lock_effect",
"headset");
break;
case 2:
edit.putString("viper4android.settings.lock_effect",
"speaker");
break;
case 3:
edit.putString("viper4android.settings.lock_effect",
"bluetooth");
break;
case 4:
edit.putString("viper4android.settings.lock_effect",
"usb");
break;
}
edit.commit();
// Tell background service to change the mode
sendBroadcast(new Intent(ACTION_UPDATE_PREFERENCES));
dialog.dismiss();
}
}).setCancelable(false).create();
selectDialog.show();
return true;
}
case R.id.v4a_action_tabbed: {
mIsTabbed = !mIsTabbed;
mPreferences.edit().putBoolean(PREF_IS_TABBED, mIsTabbed).commit();
Utils.restartActivity(this);
return true;
}
default:
return false;
}
}
//==================================
// Methods
//==================================
private void setUpUi() {
mTitles = getTitles();
mEntries = getEntries();
if (!mIsTabbed) {
setContentView(R.layout.activity_main);
mDrawerListView = (ListView) findViewById(R.id.v4a_navigation_drawer);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new SimpleAdapter(
getActionBar().getThemedContext(),
mTitles,
R.layout.drawer_item,
new String[]{"ICON", "TITLE"},
new int[]{R.id.drawer_icon, R.id.drawer_title}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
setUpNavigationDrawer(
findViewById(R.id.v4a_navigation_drawer),
findViewById(R.id.v4a_drawer_layout));
} else {
setContentView(R.layout.activity_main_tabbed);
pagerAdapter = new MyAdapter(getFragmentManager());
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0);
pagerTabStrip = (PagerTabStrip) findViewById(R.id.pagerTabStrip);
pagerTabStrip.setDrawFullUnderline(true);
pagerTabStrip.setTabIndicatorColor(
getResources().getColor(R.color.action_bar_divider));
}
}
public void saveProfileDialog() {
// We first list existing profiles
File profileDir = new File(StaticEnvironment.getV4aProfilePath());
profileDir.mkdirs();
Log.i("ViPER4Android", "Saving preset to " + profileDir.getAbsolutePath());
// The first entry is "New profile", so we offset
File[] profiles = profileDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory())
return true;
return false;
}
});
final String[] names = new String[profiles != null ? profiles.length + 1 : 1];
names[0] = getString(R.string.text_newfxprofile);
if (profiles != null) {
for (int i = 0; i < profiles.length; i++) {
names[i + 1] = profiles[i].getName();
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.text_savefxprofile)
.setItems(names, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
// New profile, we ask for the name
AlertDialog.Builder inputBuilder =
new AlertDialog.Builder(ViPER4Android.this);
inputBuilder.setTitle(R.string.text_newfxprofile);
// Set an EditText view to get user input
final EditText input = new EditText(ViPER4Android.this);
inputBuilder.setView(input);
inputBuilder.setPositiveButton(
getResources().getString(R.string.text_ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
saveProfile(value);
}
});
inputBuilder.setNegativeButton(
getResources().getString(R.string.text_cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
inputBuilder.show();
} else {
// Overwrite exist profile?
final String profileName = names[which];
AlertDialog.Builder mOverwriteProfile = new AlertDialog.Builder(ViPER4Android.this);
mOverwriteProfile.setTitle("ViPER4Android");
mOverwriteProfile.setMessage(getResources().getString(R.string.text_profilesaved_overwrite));
mOverwriteProfile.setPositiveButton(getResources().getString(R.string.text_ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
saveProfile(profileName);
}
}).setNegativeButton(getResources().getString(R.string.text_cancel), null);
mOverwriteProfile.show();
}
}
});
Dialog dlg = builder.create();
dlg.show();
}
public void loadProfileDialog() {
File profileDir = new File(StaticEnvironment.getV4aProfilePath());
profileDir.mkdirs();
/* Scan version 1 profiles */
final ArrayList<String> profilenames = Utils.getProfileList(
StaticEnvironment.getV4aProfilePath());
/* Scan version 2 profiles */
File[] profiles = profileDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory())
return true;
return false;
}
});
if (profiles != null) {
for (int i = 0; i < profiles.length; i++) {
profilenames.add(profiles[i].getName());
}
}
/* Write all profiles to a new array */
final String[] names = new String[profilenames.size()];
for (int i = 0; i < profilenames.size(); i++) {
names[i] = profilenames.get(i);
}
/* Show profile list box */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.text_loadfxprofile)
.setItems(names, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
loadProfile(names[which]);
}
});
builder.create().show();
}
public void saveProfile(String name) {
final String spDir = getApplicationInfo().dataDir + "/shared_prefs/";
// Copy the SharedPreference to our output directory
File profileDir = new File(StaticEnvironment.getV4aProfilePath() + "/" + name);
profileDir.mkdirs();
Log.i("ViPER4Android", "Saving profile to " + profileDir.getAbsolutePath());
final String packageName = SHARED_PREFERENCES_BASENAME + ".";
try {
copy(new File(spDir + packageName + "bluetooth.xml"),
new File(profileDir, packageName + "bluetooth.xml"));
copy(new File(spDir + packageName + "headset.xml"),
new File(profileDir, packageName + "headset.xml"));
copy(new File(spDir + packageName + "speaker.xml"),
new File(profileDir, packageName + "speaker.xml"));
copy(new File(spDir + packageName + "usb.xml"),
new File(profileDir, packageName + "usb.xml"));
} catch (IOException e) {
Log.e("ViPER4Android", "Cannot save preset");
}
}
public void loadProfile(String name) {
// Copy the SharedPreference to our local directory
File profileDir = new File(StaticEnvironment.getV4aProfilePath() + "/" + name);
if (!profileDir.exists()) {
/* If the profile directory does not exist, we load it as version 1 profile */
final String[] audioDevices = new String[4];
audioDevices[0] = getResources().getString(R.string.text_headset);
audioDevices[1] = getResources().getString(R.string.text_speaker);
audioDevices[2] = getResources().getString(R.string.text_bluetooth);
audioDevices[3] = getResources().getString(R.string.text_usb);
/* Which mode you want to apply the profile? */
final String profilename = name;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.text_profileload_tip)
.setItems(audioDevices, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String applyPreference = "";
switch (which) {
case 0:
applyPreference = SHARED_PREFERENCES_BASENAME + ".headset";
break;
case 1:
applyPreference = SHARED_PREFERENCES_BASENAME + ".speaker";
break;
case 2:
applyPreference = SHARED_PREFERENCES_BASENAME + ".bluetooth";
break;
case 3:
applyPreference = SHARED_PREFERENCES_BASENAME + ".usb";
break;
}
if (applyPreference.isEmpty()) {
return;
}
Utils.loadProfileV1(profilename, StaticEnvironment.getV4aProfilePath(), applyPreference, ViPER4Android.this);
// Reload preferences
startActivity(new Intent(ViPER4Android.this, ViPER4Android.class));
finish();
}
}).setNegativeButton(getResources().getString(R.string.text_cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.i("ViPER4Android", "Load profile canceled");
}
});
builder.create().show();
return;
}
final String packageName = SHARED_PREFERENCES_BASENAME + ".";
final String spDir = getApplicationInfo().dataDir + "/shared_prefs/";
try {
copy(new File(profileDir, packageName + "bluetooth.xml"),
new File(spDir + packageName + "bluetooth.xml"));
copy(new File(profileDir, packageName + "headset.xml"),
new File(spDir + packageName + "headset.xml"));
copy(new File(profileDir, packageName + "speaker.xml"),
new File(spDir + packageName + "speaker.xml"));
copy(new File(profileDir, packageName + "usb.xml"),
new File(spDir + packageName + "usb.xml"));
} catch (IOException e) {
Log.e("ViPER4Android", "Cannot load preset");
}
// Update effects
sendBroadcast(new Intent(ViPER4Android.ACTION_UPDATE_PREFERENCES));
// Reload preferences
startActivity(new Intent(this, ViPER4Android.class));
finish();
}
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
Log.i("ViPER4Android", "Copying " + src.getAbsolutePath() + " to " + dst.getAbsolutePath());
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
/**
* Users of this fragment must call this method to set up the
* navigation menu_drawer interactions.
*
* @param fragmentContainerView The view of this fragment in its activity's layout.
* @param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUpNavigationDrawer(View fragmentContainerView, View drawerLayout) {
mFragmentContainerView = fragmentContainerView;
mDrawerLayout = (CustomDrawerLayout) drawerLayout;
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
mPreferences.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).commit();
}
invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
mDrawerLayout.post(new Runnable() {
@Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
selectItem(mCurrentSelectedPosition);
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.v4a_container, PlaceholderFragment.newInstance(position))
.commit();
mTitle = mTitles.get(position).get("TITLE");
getActionBar().setTitle(mTitle);
}
/**
* @return String[] containing titles
*/
private List<HashMap<String, String>> getTitles() {
// TODO: use real drawables
ArrayList<HashMap<String, String>> tmpList = new ArrayList<HashMap<String, String>>();
// Headset
HashMap<String, String> mTitleMap = new HashMap<String, String>();
mTitleMap.put("ICON", R.drawable.empty_icon + "");
mTitleMap.put("TITLE", getString(R.string.headset_title));
tmpList.add(mTitleMap);
// Speaker
mTitleMap = new HashMap<String, String>();
mTitleMap.put("ICON", R.drawable.empty_icon + "");
mTitleMap.put("TITLE", getString(R.string.speaker_title));
tmpList.add(mTitleMap);
// Bluetooth
mTitleMap = new HashMap<String, String>();
mTitleMap.put("ICON", R.drawable.empty_icon + "");
mTitleMap.put("TITLE", getString(R.string.bluetooth_title));
tmpList.add(mTitleMap);
// Usb
mTitleMap = new HashMap<String, String>();
mTitleMap.put("ICON", R.drawable.empty_icon + "");
mTitleMap.put("TITLE", getString(R.string.usb_title));
tmpList.add(mTitleMap);
return tmpList;
}
/**
* @return String[] containing titles
*/
private String[] getEntries() {
ArrayList<String> entryString = new ArrayList<String>();
entryString.add("headset");
entryString.add("speaker");
entryString.add("bluetooth");
entryString.add("usb");
return entryString.toArray(new String[entryString.size()]);
}
//==================================
// Internal Classes
//==================================
/**
* Loads our Fragments.
*/
public static class PlaceholderFragment extends Fragment {
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static Fragment newInstance(int fragmentId) {
final MainDSPScreen dspFragment = new MainDSPScreen();
Bundle bundle = new Bundle();
bundle.putString("config", mEntries[fragmentId]);
dspFragment.setArguments(bundle);
return dspFragment;
}
public PlaceholderFragment() {
// intentionally left blank
}
}
public class MyAdapter extends FragmentPagerAdapter {
private final String[] entries;
private final List<HashMap<String, String>> titles;
public MyAdapter(FragmentManager fm) {
super(fm);
entries = mEntries;
titles = mTitles;
}
@Override
public CharSequence getPageTitle(int position) {
return titles.get(position).get("TITLE");
}
public String[] getEntries() {
return entries;
}
@Override
public int getCount() {
return entries.length;
}
@Override
public Fragment getItem(int position) {
final MainDSPScreen dspFragment = new MainDSPScreen();
Bundle bundle = new Bundle();
bundle.putString("config", entries[position]);
dspFragment.setArguments(bundle);
return dspFragment;
}
}
}
| true | true |
public boolean onOptionsItemSelected(MenuItem item) {
/* item == null in Monkey test */
if (item == null) return true;
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings", MODE_PRIVATE);
if (!mIsTabbed) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
}
int choice = item.getItemId();
switch (choice) {
case R.id.about: {
PackageManager packageMgr = getPackageManager();
PackageInfo packageInfo;
String mVersion;
try {
packageInfo = packageMgr.getPackageInfo(getPackageName(), 0);
mVersion = packageInfo.versionName;
} catch (NameNotFoundException e) {
mVersion = "N/A";
}
String mAbout = getResources().getString(R.string.about_text);
mAbout = String.format(mAbout, mVersion) + "\n";
mAbout = mAbout + getResources().getString(R.string.text_help_content);
AlertDialog.Builder mHelp = new AlertDialog.Builder(this);
mHelp.setTitle(getResources().getString(R.string.about_title));
mHelp.setMessage(mAbout);
mHelp.setPositiveButton(getResources().getString(R.string.text_ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
mHelp.setNegativeButton(getResources().getString(R.string.text_view_forum),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Uri uri = Uri.parse(getResources().getString(
R.string.text_forum_link));
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
mHelp.show();
return true;
}
case R.id.checkupdate: {
Uri uri = Uri.parse(getResources().getString(R.string.text_updatelink));
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
return true;
}
case R.id.drvstatus: {
DialogFragment df = new DialogFragment() {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle state) {
if (mAudioServiceInstance == null) {
View v = inflater.inflate(R.layout.drvstatus, null);
TextView tv = (TextView) v.findViewById(R.id.drv_status);
tv.setText(R.string.text_service_error);
return v;
} else {
mAudioServiceInstance.startStatusUpdating();
SystemClock.sleep(500);
mAudioServiceInstance.stopStatusUpdating();
String mDrvNEONEnabled = getResources().getString(R.string.text_yes);
if (!mAudioServiceInstance.getDriverNEON()) {
mDrvNEONEnabled = getResources().getString(R.string.text_no);
}
String mDrvEnabled = getResources().getString(R.string.text_yes);
if (!mAudioServiceInstance.getDriverEnabled()) {
mDrvEnabled = getResources().getString(R.string.text_no);
}
String mDrvUsable = getResources().getString(R.string.text_normal);
if (!mAudioServiceInstance.getDriverCanWork()) {
mDrvUsable = getResources().getString(R.string.text_abnormal);
}
String mDrvSupportFmt = getResources().getString(R.string.text_supported);
if (!mAudioServiceInstance.getDriverSupportFormat()) {
mDrvSupportFmt = getResources().getString(R.string.text_unsupported);
}
String mDrvProcess = getResources().getString(R.string.text_yes);
if (!mAudioServiceInstance.getDriverProcess()) {
mDrvProcess = getResources().getString(R.string.text_no);
}
Utils.AudioEffectUtils aeuUtils = new Utils().new AudioEffectUtils();
int[] iaDrvVer = aeuUtils.getViper4AndroidEngineVersion();
String mDriverVersion = iaDrvVer[0] + "." + iaDrvVer[1] + "."
+ iaDrvVer[2] + "." + iaDrvVer[3];
String mDrvStatus;
mDrvStatus = getResources().getString(R.string.text_drv_status_view);
mDrvStatus = String.format(mDrvStatus,
mDriverVersion, mDrvNEONEnabled,
mDrvEnabled, mDrvUsable, mDrvSupportFmt, mDrvProcess,
mAudioServiceInstance.getDriverSamplingRate());
View v = inflater.inflate(R.layout.drvstatus, null);
TextView tv = (TextView) v.findViewById(R.id.drv_status);
tv.setText(mDrvStatus);
return v;
}
}
};
df.setStyle(DialogFragment.STYLE_NO_TITLE, 0);
df.show(getFragmentManager(), "v4astatus");
return true;
}
case R.id.changelog: {
// Deal with changelog file name
String mLocale = Locale.getDefault().getLanguage() + "_"
+ Locale.getDefault().getCountry();
String mChangelog_AssetsName = "Changelog_";
if (mLocale.equalsIgnoreCase("zh_CN")) {
mChangelog_AssetsName = mChangelog_AssetsName + "zh_CN";
} else {
mChangelog_AssetsName = mLocale.equalsIgnoreCase("zh_TW") ?
mChangelog_AssetsName + "zh_TW" : mChangelog_AssetsName + "en_US";
}
mChangelog_AssetsName = mChangelog_AssetsName + ".txt";
String mChangeLog = "";
InputStream isChglogHandle;
try {
isChglogHandle = getAssets().open(mChangelog_AssetsName);
mChangeLog = readTextFile(isChglogHandle);
isChglogHandle.close();
} catch (IOException e) {
Log.i("ViPER4Android", "Can not read changelog");
}
if (mChangeLog.equalsIgnoreCase("")) return true;
AlertDialog.Builder mChglog = new AlertDialog.Builder(this);
mChglog.setTitle(R.string.text_changelog);
mChglog.setMessage(mChangeLog);
mChglog.setNegativeButton(getResources().getString(R.string.text_ok), null);
mChglog.show();
return true;
}
case R.id.loadprofile: {
loadProfileDialog();
return true;
}
case R.id.saveprofile: {
saveProfileDialog();
return true;
}
case R.id.drvinst: {
String menuText = item.getTitle().toString();
if (getResources().getString(R.string.text_uninstall).equals(menuText)) {
// Please confirm the process
AlertDialog.Builder mConfirm = new AlertDialog.Builder(this);
mConfirm.setTitle("ViPER4Android");
mConfirm.setMessage(getResources().getString(R.string.text_drvuninst_confim));
mConfirm.setPositiveButton(getResources().getString(R.string.text_yes),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Uninstall driver
Utils.uninstallDrv_FX();
AlertDialog.Builder mResult = new AlertDialog.Builder(ViPER4Android.this);
mResult.setTitle("ViPER4Android");
mResult.setMessage(getResources().getString(R.string.text_drvuninst_ok));
mResult.setNegativeButton(getResources().getString(R.string.text_ok), null);
mResult.show();
}
});
mConfirm.setNegativeButton(getResources().getString(R.string.text_no), null);
mConfirm.show();
} else if (getResources().getString(R.string.text_install).equals(menuText)) {
Message message = new Message();
message.what = 0xA00A;
message.obj = this;
mDriverHandler.sendMessage(message);
} else {
String szTip = getResources().getString(R.string.text_service_error);
Toast.makeText(this, szTip, Toast.LENGTH_LONG).show();
}
return true;
}
case R.id.uiprefer: {
int nUIPrefer = prefSettings.getInt("viper4android.settings.uiprefer", 0);
if (nUIPrefer < 0 || nUIPrefer > 2) {
nUIPrefer = 0;
}
Dialog selectDialog = new AlertDialog.Builder(this)
.setTitle(R.string.text_uiprefer_dialog)
.setIcon(R.drawable.icon)
.setSingleChoiceItems(R.array.ui_prefer, nUIPrefer,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which < 0 || which > 2) which = 0;
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings", MODE_PRIVATE);
int nOldSelIdx = prefSettings.getInt(
"viper4android.settings.uiprefer", 0);
if (nOldSelIdx == which) {
dialog.dismiss();
return;
}
Editor edit = prefSettings.edit();
edit.putInt("viper4android.settings.uiprefer", which);
edit.commit();
sendBroadcast(new Intent(ACTION_UPDATE_PREFERENCES));
dialog.dismiss();
Utils.restartActivity(ViPER4Android.this);
}
}).setCancelable(false).create();
selectDialog.show();
return true;
}
case R.id.compatible: {
String mCompatibleMode = prefSettings.getString(
"viper4android.settings.compatiblemode", "global");
int mSelectIndex;
mSelectIndex = mCompatibleMode.equals("global") ? 0 : 1;
Dialog selectDialog = new AlertDialog.Builder(this)
.setTitle(R.string.text_commode)
.setIcon(R.drawable.icon)
.setSingleChoiceItems(R.array.compatible_mode, mSelectIndex,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings",
MODE_PRIVATE);
Editor edit = prefSettings.edit();
switch (which) {
case 0:
edit.putString(
"viper4android.settings.compatiblemode",
"global");
break;
case 1:
edit.putString(
"viper4android.settings.compatiblemode",
"local");
break;
}
edit.commit();
dialog.dismiss();
}
}).setCancelable(false).create();
selectDialog.show();
return true;
}
case R.id.notify: {
boolean enableNotify = prefSettings.getBoolean(
"viper4android.settings.show_notify_icon", false);
enableNotify = !enableNotify;
if (enableNotify) {
item.setTitle(getResources().getString(R.string.text_hidetrayicon));
} else {
item.setTitle(getResources().getString(R.string.text_showtrayicon));
}
Editor edit = prefSettings.edit();
edit.putBoolean("viper4android.settings.show_notify_icon", enableNotify);
edit.commit();
// Tell background service to deal with the notification icon
if (enableNotify) {
sendBroadcast(new Intent(ACTION_SHOW_NOTIFY));
} else {
sendBroadcast(new Intent(ACTION_CANCEL_NOTIFY));
}
return true;
}
case R.id.lockeffect: {
String mLockedEffect = prefSettings.getString(
"viper4android.settings.lock_effect", "none");
int mLockIndex;
if (mLockedEffect.equalsIgnoreCase("none")) {
mLockIndex = 0;
} else if (mLockedEffect.equalsIgnoreCase("headset")) {
mLockIndex = 1;
} else if (mLockedEffect.equalsIgnoreCase("speaker")) {
mLockIndex = 2;
} else if (mLockedEffect.equalsIgnoreCase("bluetooth")) {
mLockIndex = 3;
} else if (mLockedEffect.equalsIgnoreCase("usb")) {
mLockIndex = 4;
} else {
mLockIndex = 5;
}
String[] modeList = {
getResources().getString(R.string.text_disabled),
getResources().getString(R.string.text_headset),
getResources().getString(R.string.text_speaker),
getResources().getString(R.string.text_bluetooth),
getResources().getString(R.string.text_usb)
};
Dialog selectDialog = new AlertDialog.Builder(this)
.setTitle(R.string.text_lockeffect)
.setIcon(R.drawable.icon)
.setSingleChoiceItems(modeList, mLockIndex,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings",
MODE_PRIVATE);
Editor edit = prefSettings.edit();
switch (which) {
case 0:
edit.putString("viper4android.settings.lock_effect",
"none");
break;
case 1:
edit.putString("viper4android.settings.lock_effect",
"headset");
break;
case 2:
edit.putString("viper4android.settings.lock_effect",
"speaker");
break;
case 3:
edit.putString("viper4android.settings.lock_effect",
"bluetooth");
break;
case 4:
edit.putString("viper4android.settings.lock_effect",
"usb");
break;
}
edit.commit();
// Tell background service to change the mode
sendBroadcast(new Intent(ACTION_UPDATE_PREFERENCES));
dialog.dismiss();
}
}).setCancelable(false).create();
selectDialog.show();
return true;
}
case R.id.v4a_action_tabbed: {
mIsTabbed = !mIsTabbed;
mPreferences.edit().putBoolean(PREF_IS_TABBED, mIsTabbed).commit();
Utils.restartActivity(this);
return true;
}
default:
return false;
}
}
|
public boolean onOptionsItemSelected(MenuItem item) {
/* item == null in Monkey test */
if (item == null) return true;
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings", MODE_PRIVATE);
if (!mIsTabbed) {
if (mDrawerToggle == null) {
/* mDrawerToggle == null in Monkey test */
return true;
}
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
}
int choice = item.getItemId();
switch (choice) {
case R.id.about: {
PackageManager packageMgr = getPackageManager();
PackageInfo packageInfo;
String mVersion;
try {
packageInfo = packageMgr.getPackageInfo(getPackageName(), 0);
mVersion = packageInfo.versionName;
} catch (NameNotFoundException e) {
mVersion = "N/A";
}
String mAbout = getResources().getString(R.string.about_text);
mAbout = String.format(mAbout, mVersion) + "\n";
mAbout = mAbout + getResources().getString(R.string.text_help_content);
AlertDialog.Builder mHelp = new AlertDialog.Builder(this);
mHelp.setTitle(getResources().getString(R.string.about_title));
mHelp.setMessage(mAbout);
mHelp.setPositiveButton(getResources().getString(R.string.text_ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
mHelp.setNegativeButton(getResources().getString(R.string.text_view_forum),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Uri uri = Uri.parse(getResources().getString(
R.string.text_forum_link));
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
mHelp.show();
return true;
}
case R.id.checkupdate: {
Uri uri = Uri.parse(getResources().getString(R.string.text_updatelink));
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
return true;
}
case R.id.drvstatus: {
DialogFragment df = new DialogFragment() {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle state) {
if (mAudioServiceInstance == null) {
View v = inflater.inflate(R.layout.drvstatus, null);
TextView tv = (TextView) v.findViewById(R.id.drv_status);
tv.setText(R.string.text_service_error);
return v;
} else {
mAudioServiceInstance.startStatusUpdating();
SystemClock.sleep(500);
mAudioServiceInstance.stopStatusUpdating();
String mDrvNEONEnabled = getResources().getString(R.string.text_yes);
if (!mAudioServiceInstance.getDriverNEON()) {
mDrvNEONEnabled = getResources().getString(R.string.text_no);
}
String mDrvEnabled = getResources().getString(R.string.text_yes);
if (!mAudioServiceInstance.getDriverEnabled()) {
mDrvEnabled = getResources().getString(R.string.text_no);
}
String mDrvUsable = getResources().getString(R.string.text_normal);
if (!mAudioServiceInstance.getDriverCanWork()) {
mDrvUsable = getResources().getString(R.string.text_abnormal);
}
String mDrvSupportFmt = getResources().getString(R.string.text_supported);
if (!mAudioServiceInstance.getDriverSupportFormat()) {
mDrvSupportFmt = getResources().getString(R.string.text_unsupported);
}
String mDrvProcess = getResources().getString(R.string.text_yes);
if (!mAudioServiceInstance.getDriverProcess()) {
mDrvProcess = getResources().getString(R.string.text_no);
}
Utils.AudioEffectUtils aeuUtils = new Utils().new AudioEffectUtils();
int[] iaDrvVer = aeuUtils.getViper4AndroidEngineVersion();
String mDriverVersion = iaDrvVer[0] + "." + iaDrvVer[1] + "."
+ iaDrvVer[2] + "." + iaDrvVer[3];
String mDrvStatus;
mDrvStatus = getResources().getString(R.string.text_drv_status_view);
mDrvStatus = String.format(mDrvStatus,
mDriverVersion, mDrvNEONEnabled,
mDrvEnabled, mDrvUsable, mDrvSupportFmt, mDrvProcess,
mAudioServiceInstance.getDriverSamplingRate());
View v = inflater.inflate(R.layout.drvstatus, null);
TextView tv = (TextView) v.findViewById(R.id.drv_status);
tv.setText(mDrvStatus);
return v;
}
}
};
df.setStyle(DialogFragment.STYLE_NO_TITLE, 0);
df.show(getFragmentManager(), "v4astatus");
return true;
}
case R.id.changelog: {
// Deal with changelog file name
String mLocale = Locale.getDefault().getLanguage() + "_"
+ Locale.getDefault().getCountry();
String mChangelog_AssetsName = "Changelog_";
if (mLocale.equalsIgnoreCase("zh_CN")) {
mChangelog_AssetsName = mChangelog_AssetsName + "zh_CN";
} else {
mChangelog_AssetsName = mLocale.equalsIgnoreCase("zh_TW") ?
mChangelog_AssetsName + "zh_TW" : mChangelog_AssetsName + "en_US";
}
mChangelog_AssetsName = mChangelog_AssetsName + ".txt";
String mChangeLog = "";
InputStream isChglogHandle;
try {
isChglogHandle = getAssets().open(mChangelog_AssetsName);
mChangeLog = readTextFile(isChglogHandle);
isChglogHandle.close();
} catch (IOException e) {
Log.i("ViPER4Android", "Can not read changelog");
}
if (mChangeLog.equalsIgnoreCase("")) return true;
AlertDialog.Builder mChglog = new AlertDialog.Builder(this);
mChglog.setTitle(R.string.text_changelog);
mChglog.setMessage(mChangeLog);
mChglog.setNegativeButton(getResources().getString(R.string.text_ok), null);
mChglog.show();
return true;
}
case R.id.loadprofile: {
loadProfileDialog();
return true;
}
case R.id.saveprofile: {
saveProfileDialog();
return true;
}
case R.id.drvinst: {
String menuText = item.getTitle().toString();
if (getResources().getString(R.string.text_uninstall).equals(menuText)) {
// Please confirm the process
AlertDialog.Builder mConfirm = new AlertDialog.Builder(this);
mConfirm.setTitle("ViPER4Android");
mConfirm.setMessage(getResources().getString(R.string.text_drvuninst_confim));
mConfirm.setPositiveButton(getResources().getString(R.string.text_yes),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Uninstall driver
Utils.uninstallDrv_FX();
AlertDialog.Builder mResult = new AlertDialog.Builder(ViPER4Android.this);
mResult.setTitle("ViPER4Android");
mResult.setMessage(getResources().getString(R.string.text_drvuninst_ok));
mResult.setNegativeButton(getResources().getString(R.string.text_ok), null);
mResult.show();
}
});
mConfirm.setNegativeButton(getResources().getString(R.string.text_no), null);
mConfirm.show();
} else if (getResources().getString(R.string.text_install).equals(menuText)) {
Message message = new Message();
message.what = 0xA00A;
message.obj = this;
mDriverHandler.sendMessage(message);
} else {
String szTip = getResources().getString(R.string.text_service_error);
Toast.makeText(this, szTip, Toast.LENGTH_LONG).show();
}
return true;
}
case R.id.uiprefer: {
int nUIPrefer = prefSettings.getInt("viper4android.settings.uiprefer", 0);
if (nUIPrefer < 0 || nUIPrefer > 2) {
nUIPrefer = 0;
}
Dialog selectDialog = new AlertDialog.Builder(this)
.setTitle(R.string.text_uiprefer_dialog)
.setIcon(R.drawable.icon)
.setSingleChoiceItems(R.array.ui_prefer, nUIPrefer,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which < 0 || which > 2) which = 0;
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings", MODE_PRIVATE);
int nOldSelIdx = prefSettings.getInt(
"viper4android.settings.uiprefer", 0);
if (nOldSelIdx == which) {
dialog.dismiss();
return;
}
Editor edit = prefSettings.edit();
edit.putInt("viper4android.settings.uiprefer", which);
edit.commit();
sendBroadcast(new Intent(ACTION_UPDATE_PREFERENCES));
dialog.dismiss();
Utils.restartActivity(ViPER4Android.this);
}
}).setCancelable(false).create();
selectDialog.show();
return true;
}
case R.id.compatible: {
String mCompatibleMode = prefSettings.getString(
"viper4android.settings.compatiblemode", "global");
int mSelectIndex;
mSelectIndex = mCompatibleMode.equals("global") ? 0 : 1;
Dialog selectDialog = new AlertDialog.Builder(this)
.setTitle(R.string.text_commode)
.setIcon(R.drawable.icon)
.setSingleChoiceItems(R.array.compatible_mode, mSelectIndex,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings",
MODE_PRIVATE);
Editor edit = prefSettings.edit();
switch (which) {
case 0:
edit.putString(
"viper4android.settings.compatiblemode",
"global");
break;
case 1:
edit.putString(
"viper4android.settings.compatiblemode",
"local");
break;
}
edit.commit();
dialog.dismiss();
}
}).setCancelable(false).create();
selectDialog.show();
return true;
}
case R.id.notify: {
boolean enableNotify = prefSettings.getBoolean(
"viper4android.settings.show_notify_icon", false);
enableNotify = !enableNotify;
if (enableNotify) {
item.setTitle(getResources().getString(R.string.text_hidetrayicon));
} else {
item.setTitle(getResources().getString(R.string.text_showtrayicon));
}
Editor edit = prefSettings.edit();
edit.putBoolean("viper4android.settings.show_notify_icon", enableNotify);
edit.commit();
// Tell background service to deal with the notification icon
if (enableNotify) {
sendBroadcast(new Intent(ACTION_SHOW_NOTIFY));
} else {
sendBroadcast(new Intent(ACTION_CANCEL_NOTIFY));
}
return true;
}
case R.id.lockeffect: {
String mLockedEffect = prefSettings.getString(
"viper4android.settings.lock_effect", "none");
int mLockIndex;
if (mLockedEffect.equalsIgnoreCase("none")) {
mLockIndex = 0;
} else if (mLockedEffect.equalsIgnoreCase("headset")) {
mLockIndex = 1;
} else if (mLockedEffect.equalsIgnoreCase("speaker")) {
mLockIndex = 2;
} else if (mLockedEffect.equalsIgnoreCase("bluetooth")) {
mLockIndex = 3;
} else if (mLockedEffect.equalsIgnoreCase("usb")) {
mLockIndex = 4;
} else {
mLockIndex = 5;
}
String[] modeList = {
getResources().getString(R.string.text_disabled),
getResources().getString(R.string.text_headset),
getResources().getString(R.string.text_speaker),
getResources().getString(R.string.text_bluetooth),
getResources().getString(R.string.text_usb)
};
Dialog selectDialog = new AlertDialog.Builder(this)
.setTitle(R.string.text_lockeffect)
.setIcon(R.drawable.icon)
.setSingleChoiceItems(modeList, mLockIndex,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences prefSettings = getSharedPreferences(
SHARED_PREFERENCES_BASENAME + ".settings",
MODE_PRIVATE);
Editor edit = prefSettings.edit();
switch (which) {
case 0:
edit.putString("viper4android.settings.lock_effect",
"none");
break;
case 1:
edit.putString("viper4android.settings.lock_effect",
"headset");
break;
case 2:
edit.putString("viper4android.settings.lock_effect",
"speaker");
break;
case 3:
edit.putString("viper4android.settings.lock_effect",
"bluetooth");
break;
case 4:
edit.putString("viper4android.settings.lock_effect",
"usb");
break;
}
edit.commit();
// Tell background service to change the mode
sendBroadcast(new Intent(ACTION_UPDATE_PREFERENCES));
dialog.dismiss();
}
}).setCancelable(false).create();
selectDialog.show();
return true;
}
case R.id.v4a_action_tabbed: {
mIsTabbed = !mIsTabbed;
mPreferences.edit().putBoolean(PREF_IS_TABBED, mIsTabbed).commit();
Utils.restartActivity(this);
return true;
}
default:
return false;
}
}
|
diff --git a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Expression.java b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Expression.java
index dadf98c5..c69807b7 100644
--- a/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Expression.java
+++ b/libraries/jnaerator/jnaerator-parser/src/main/java/com/ochafik/lang/jnaerator/parser/Expression.java
@@ -1,1571 +1,1571 @@
/*
Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved
This file is part of JNAerator (http://jnaerator.googlecode.com/).
JNAerator is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
JNAerator is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with JNAerator. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ochafik.lang.jnaerator.parser;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier;
import com.ochafik.util.listenable.Pair;
import java.math.BigInteger;
public abstract class Expression extends Element {
private static final long MAX_UINT_VALUE = 2L * Integer.MAX_VALUE;
public static class ExpressionsBlock extends ExpressionSequence {
@Override
public void accept(Visitor visitor) {
visitor.visitExpressionsBlock(this);
}
}
public static class ExpressionSequence extends Expression {
final List<Expression> expressions = new ArrayList<Expression>();
public ExpressionSequence() {
}
public ExpressionSequence(Expression... expressions) {
this(Arrays.asList(expressions));
}
public ExpressionSequence(List<Expression> expressions) {
setExpressions(expressions);
}
public void addExpression(Expression e) {
if (e != null) {
expressions.add(e);
e.setParentElement(this);
}
}
public List<Expression> getExpressions() {
return expressions;
}
public void setExpressions(List<Expression> sequence) {
changeValue(this, this.expressions, sequence);
}
@Override
public void accept(Visitor visitor) {
visitor.visitExpressionSequence(this);
}
@Override
public Element getNextChild(Element child) {
return getNextSibling(getExpressions(), child);
}
@Override
public Element getPreviousChild(Element child) {
return getPreviousSibling(getExpressions(), child);
}
@Override
public boolean replaceChild(Element child, Element by) {
return replaceChild(getExpressions(), Expression.class, this, child, by);
}
}
public static class OpaqueExpression extends Expression {
String opaqueString;
public void setOpaqueString(String opaqueString) {
this.opaqueString = opaqueString;
}
public String getOpaqueString() {
return opaqueString;
}
public OpaqueExpression() {
}
public OpaqueExpression(String opaqueString) {
setOpaqueString(opaqueString);
}
@Override
public void accept(Visitor visitor) {
visitor.visitOpaqueExpression(this);
}
@Override
public Element getNextChild(Element child) {
return null;
}
@Override
public Element getPreviousChild(Element child) {
return null;
}
@Override
public boolean replaceChild(Element child, Element by) {
return false;
}
}
boolean parenthesis;
public Expression setParenthesis(boolean parenthesis) {
this.parenthesis = parenthesis;
return this;
}
public Expression setParenthesisIfNeeded() {
setParenthesis(!(
this instanceof VariableRef ||
this instanceof FunctionCall ||
this instanceof MemberRef ||
this instanceof ArrayAccess
));
return this;
}
public boolean getParenthesis() {
return parenthesis;
}
public boolean isParenthesis() {
return parenthesis;
}
@Override
public Expression clone() {
return (Expression)super.clone();
}
public enum MemberRefStyle {
Dot, SquareBrackets, Arrow, Colons
}
public static MemberRefStyle parseMemberRefStyle(String s) {
if (s.equals("->"))
return MemberRefStyle.Arrow;
if (s.equals("."))
return MemberRefStyle.Dot;
if (s.equals("::"))
return MemberRefStyle.Colons;
return null;
}
public static class TypeRefExpression extends Expression {
TypeRef type;
public TypeRefExpression(TypeRef type) {
setType(type);
}
public TypeRefExpression() {}
public TypeRef getType() {
return type;
}
public void setType(TypeRef type) {
this.type = changeValue(this, this.type, type);
}
@Override
public void accept(Visitor visitor) {
visitor.visitTypeRefExpression(this);
}
@Override
public Element getNextChild(Element child) {
return null;
}
@Override
public Element getPreviousChild(Element child) {
return null;
}
@Override
public boolean replaceChild(Element child, Element by) {
if (child == getType()) {
setType((TypeRef) by);
return true;
}
return false;
}
}
public static class EmptyArraySize extends Expression {
@Override
public void accept(Visitor visitor) {
visitor.visitEmptyArraySize(this);
}
@Override
public Element getNextChild(Element child) {
return null;
}
@Override
public Element getPreviousChild(Element child) {
return null;
}
@Override
public boolean replaceChild(Element child, Element by) {
return false;
}
}
public static class MemberRef extends Expression {
MemberRefStyle memberRefStyle;
Expression target;
Identifier name;
public MemberRef(SimpleIdentifier name) {
setName(name);
}
public MemberRef(Expression target, MemberRefStyle memberRefStyle, Identifier name) {
setTarget(target);
setName(name);
setMemberRefStyle(memberRefStyle);
}
public MemberRef() {
}
public void setName(Identifier name) {
this.name = changeValue(this, this.name, name);
}
public Identifier getName() {
return name;
}
public void setTarget(Expression target) {
this.target = changeValue(this, this.target, target);
}
public Expression getTarget() {
return target;
}
public void setMemberRefStyle(MemberRefStyle memberRefStyle) {
this.memberRefStyle = memberRefStyle;
}
public MemberRefStyle getMemberRefStyle() {
return memberRefStyle;
}
@Override
public boolean replaceChild(Element child, Element by) {
if (child == getTarget())
setTarget((Expression)by);
if (child == getName())
setName((Identifier)by);
return false;
}
@Override
public void accept(Visitor visitor) {
visitor.visitMemberRef(this);
}
@Override
public Element getNextChild(Element child) {
// TODO Auto-generated method stub
return null;
}
@Override
public Element getPreviousChild(Element child) {
// TODO Auto-generated method stub
return null;
}
}
public static class NewArray extends Expression {
TypeRef type;
List<Expression> dimensions = new ArrayList<Expression>();
List<Expression> initialValues = new ArrayList<Expression>();
public NewArray() {}
public NewArray(TypeRef type, Expression[] dimensions, Expression[] initialValues) {
setType(type);
setDimensions(Arrays.asList(dimensions));
setInitialValues(Arrays.asList(initialValues));
}
public List<Expression> getDimensions() {
return unmodifiableList(dimensions);
}
public void addDimension(Expression dimension) {
if (dimension == null)
return;
dimension.setParentElement(this);
dimensions.add(dimension);
}
public void setDimensions(List<Expression> dimensions) {
changeValue(this, this.dimensions, dimensions);
}
public List<Expression> getInitialValues() {
return unmodifiableList(initialValues);
}
public void setInitialValues(List<Expression> initialValues) {
changeValue(this, this.initialValues, initialValues);
}
public TypeRef getType() {
return type;
}
public void setType(TypeRef type) {
this.type = changeValue(this, this.type, type);
}
@Override
public void accept(Visitor visitor) {
visitor.visitNewArray(this);
}
@Override
public Element getNextChild(Element child) {
Element e = getNextSibling(dimensions, child);
if (e == null)
e = getNextSibling(initialValues, child);
return e;
}
@Override
public Element getPreviousChild(Element child) {
Element e = getPreviousSibling(dimensions, child);
if (e == null)
e = getPreviousSibling(initialValues, child);
return e;
}
@Override
public boolean replaceChild(Element child, Element by) {
if (child == getType()) {
setType((TypeRef)by);
return true;
}
return
replaceChild(initialValues, Expression.class, this, child, by) ||
replaceChild(dimensions, Expression.class, this, child, by);
}
}
public static class New extends Expression {
TypeRef type;
FunctionCall construction;
public New(TypeRef type) {
setType(type);
}
public New(TypeRef type, FunctionCall construction) {
setType(type);
setConstruction(construction);
}
public New(TypeRef type, Expression... arguments) {
setType(type);
setConstruction(new FunctionCall(null, arguments));
}
public New(TypeRef type, List<Expression> arguments) {
this(type, arguments.toArray(new Expression[arguments.size()]));
}
public New() {}
public void setType(TypeRef type) {
this.type = changeValue(this, this.type, type);
}
public TypeRef getType() {
return type;
}
public void setConstruction(FunctionCall construction) {
this.construction = changeValue(this, this.construction, construction);
}
public FunctionCall getConstruction() {
return construction;
}
@Override
public void accept(Visitor visitor) {
visitor.visitNew(this);
}
@Override
public Element getNextChild(Element child) {
return null;
}
@Override
public Element getPreviousChild(Element child) {
return null;
}
@Override
public boolean replaceChild(Element child, Element by) {
if (child == getType()) {
setType((TypeRef) by);
return true;
}
if (child == getConstruction()) {
setConstruction((FunctionCall) by);
return true;
}
return false;
}
}
public static class FunctionCall extends MemberRef {
Expression function;
//String functionName;
List<Pair<String, Expression>> arguments = new ArrayList<Pair<String, Expression>>();
public List<Pair<String, Expression>> getArguments() {
return unmodifiableList(arguments);
}
public void setArguments(List<Pair<String, Expression>> arguments) {
for (Pair<String, Expression> p : this.arguments)
p.getSecond().setParentElement(null);
this.arguments.clear();
for (Pair<String, Expression> p : arguments)
addArgument(p.getFirst(), p.getSecond());
}
public FunctionCall(Expression function) {
setFunction(function);
}
public FunctionCall(Expression function, Expression... unnamedArgs) {
setFunction(function);
for (Expression x : unnamedArgs)
if (x != null)
addArgument(x);
}
public FunctionCall(Expression target, Expression function, MemberRefStyle memberRefStyle, Expression... unnamedArgs) {
setTarget(target);
setFunction(function);
setMemberRefStyle(memberRefStyle);
for (Expression x : unnamedArgs)
addArgument(x);
}
public FunctionCall() {
}
public void addArgument(Expression ex) {
addArgument(null, ex);
}
public void addArguments(List<Expression> ex) {
for (Expression x : ex)
addArgument(null, x);
}
public void addArgument(String argumentSelector, Expression ex) {
if (ex == null)
return;
ex.setParentElement(this);
arguments.add(new Pair<String, Expression>(argumentSelector, ex));
}
public Expression getFunction() {
return function;
}
public void setFunction(Expression function) {
this.function = changeValue(this, this.function, function);
}
@Override
public void accept(Visitor visitor) {
visitor.visitFunctionCall(this);
}
protected int indexOf(Element x, List<Pair<String, Expression>> list) {
int i = 0;
for (Pair<String, Expression> p : list) {
if (p.getValue() == x)
return i;
i++;
}
return -1;
}
@Override
public Element getNextChild(Element child) {
int i = indexOf(child, arguments);
if (i >= 0) {
return i < arguments.size() - 1 ? arguments.get(i + 1).getValue() : null;
}
return null;
}
@Override
public Element getPreviousChild(Element child) {
int i = indexOf(child, arguments);
if (i >= 0) {
return i > 0 ? arguments.get(i - 1).getValue() : null;
}
return null;
}
@Override
public boolean replaceChild(Element child, Element by) {
if (child == getTarget()) {
setTarget((Expression) by);
return true;
}
if (child == getFunction()) {
setFunction((Expression) by);
return true;
}
//return replaceChild(arguments, Expression.class, this, child, by);
int i = indexOf(child, arguments);
if (i >= 0) {
Expression old;
if (by == null)
old = arguments.remove(i).getValue();
else
old = arguments.get(i).setValue((Expression)by);
if (old != by) {
if (old != null)
old.setParentElement(null);
if (by != null)
by.setParentElement(this);
}
return true;
}
return super.replaceChild(child, by);
}
}
public static class ArrayAccess extends Expression {
Expression target, index;
public ArrayAccess() {}
public ArrayAccess(Expression target, Expression index) {
setTarget(target);
setIndex(index);
}
public Expression getTarget() {
return target;
}
public void setTarget(Expression target) {
this.target = changeValue(this, this.target, target);
}
public void setIndex(Expression index) {
this.index = changeValue(this, this.index, index);
}
public Expression getIndex() {
return index;
}
@Override
public void accept(Visitor visitor) {
visitor.visitArrayAccess(this);
}
@Override
public Element getNextChild(Element child) {
return null;
}
@Override
public Element getPreviousChild(Element child) {
return null;
}
@Override
public boolean replaceChild(Element child, Element by) {
if (child == getTarget()) {
setTarget((Expression)by);
return true;
}
if (child == getIndex()) {
setIndex((Expression)by);
return true;
}
return false;
}
}
public static class VariableRef extends Expression {
Identifier name;
public VariableRef(Identifier name) {
setName(name);
}
public VariableRef() {
}
public Identifier getName() {
return name;
}
public void setName(Identifier name) {
this.name = changeValue(this, this.name, name);
}
@Override
public void accept(Visitor visitor) {
visitor.visitVariableRef(this);
}
@Override
public Element getNextChild(Element child) {
return null;
}
@Override
public Element getPreviousChild(Element child) {
return null;
}
@Override
public boolean replaceChild(Element child, Element by) {
if (child == getName()) {
setName((Identifier) by);
return true;
}
return false;
}
}
public enum BinaryOperator implements Operator {
Assign("="),
Arrow("->"),
ArrowStar("->*"),
SquareBrackets("[]"),
Comma(","),
Plus("+"), Minus("-"), Divide("/"), Multiply("*"), Modulo("%"), LeftShift("<<"), RightShift(">>"), SignedRightShift(">>>"), XOR("^"),
LessEqual("<=", true), GreaterEqual(">=", true), Less("<", true), Greater(">", true), IsEqual("==", true), IsDifferent("!=", true),
BitOr("|"), Or("||", true), BitAnd("&"), And("&&", true);
final String s;
public final boolean givesBool;
BinaryOperator(String s) {
this(s, false);
}
BinaryOperator(String s, boolean givesBool) {
this.s = s;
this.givesBool = givesBool;
}
@Override
public String toString() {
return s;
}
};
public interface Operator {
}
public enum AssignmentOperator implements Operator {
Equal("=", null),
MultiplyEqual("*=", BinaryOperator.Multiply),
DivideEqual("/=", BinaryOperator.Divide),
ModuloEqual("%=", BinaryOperator.Modulo),
PlusEqual("+=", BinaryOperator.Plus),
MinusEqual("-=", BinaryOperator.Minus),
LeftShiftEqual("<<=", BinaryOperator.LeftShift),
RightShiftEqual(">>=", BinaryOperator.RightShift),
SignedRightShiftEqual(">>>=", BinaryOperator.SignedRightShift),
BitAndEqual("&=", BinaryOperator.BitAnd),
XOREqual("^=", BinaryOperator.XOR),
//ComplementEqual("~=", BinaryOperator.C),
BitOrEqual("|=", BinaryOperator.BitOr);
String s;
AssignmentOperator(String s, BinaryOperator correspondingBinaryOp) {
this.s = s;
this.correspondingBinaryOp = correspondingBinaryOp;
}
@Override
public String toString() {
return s;
}
BinaryOperator correspondingBinaryOp;
public BinaryOperator getCorrespondingBinaryOp() {
return correspondingBinaryOp;
}
}
public enum UnaryOperator implements Operator {
Not("!"),
Minus("-"),
Parenthesis("()"),
Complement("~"),
Reference("&"),
Dereference("*"),
PreIncr("++"),
PreDecr("--"),
PostIncr("++"),
PostDecr("--");
String s;
UnaryOperator(String s) {
this.s = s;
}
@Override
public String toString() {
return s;
}
};
static final Map<String, AssignmentOperator> assignOps = new HashMap<String, AssignmentOperator>();
static final Map<String, BinaryOperator> binOps = new HashMap<String, BinaryOperator>();
static final Map<String, UnaryOperator> unOps = new HashMap<String, UnaryOperator>();
static final Map<AssignmentOperator, String> assignOpsRev = new HashMap<AssignmentOperator, String>();
static final Map<BinaryOperator, String> binOpsRev = new HashMap<BinaryOperator, String>();
static final Map<UnaryOperator, String> unOpsRev = new HashMap<UnaryOperator, String>();
//public static final Expression EMPTY_EXPRESSION = new Constant(null, null, "");
static {
for (AssignmentOperator op : AssignmentOperator.values())
map(assignOps, assignOpsRev, op.toString(), op);
for (UnaryOperator op : UnaryOperator.values())
map(unOps, unOpsRev, op.toString(), op);
for (BinaryOperator op : BinaryOperator.values())
map(binOps, binOpsRev, op.toString(), op);
}
static <K, V> void map(Map<K, V> m, Map<V, K> r, K k, V v) {
m.put(k, v);
r.put(v, k);
}
public static BinaryOperator getBinaryOperator(String s) {
return binOps.get(s);
}
public static AssignmentOperator getAssignmentOperator(String s) {
AssignmentOperator op = assignOps.get(s);
if (op == null)
throw new RuntimeException("Failed to parse op " + s);
return op;
}
public static UnaryOperator getUnaryOperator(String s) {
UnaryOperator op = unOps.get(s);
if (op == null)
throw new RuntimeException("Failed to parse op " + s);
return op;
}
public static java.lang.Enum<?> getAnyOperator(String s) {
java.lang.Enum<?> e = binOps.get(s);//Expression.getBinaryOperator(s);
if (e != null)
return e;
e = unOps.get(s);//Expression.getUnaryOperator(s);
if (e != null)
return e;
return Expression.getAssignmentOperator(s);
}
public static class NullExpression extends Expression {
@Override
public void accept(Visitor visitor) {
visitor.visitNullExpression(this);
}
@Override
public Element getNextChild(Element child) {
return null;
}
@Override
public Element getPreviousChild(Element child) {
return null;
}
@Override
public boolean replaceChild(Element child, Element by) {
return false;
}
}
public static class ConditionalExpression extends Expression {
Expression test, thenValue, elseValue;
public ConditionalExpression() {}
public ConditionalExpression(Expression test, Expression thenValue, Expression elseValue) {
setTest(test);
setThenValue(thenValue);
setElseValue(elseValue);
}
public Expression getTest() {
return test;
}
public void setTest(Expression test) {
this.test = changeValue(this, this.test, test);
}
public Expression getThenValue() {
return thenValue;
}
public void setThenValue(Expression thenValue) {
this.thenValue = changeValue(this, this.thenValue, thenValue);
}
public Expression getElseValue() {
return elseValue;
}
public void setElseValue(Expression elseValue) {
this.elseValue = changeValue(this, this.elseValue, elseValue);
}
@Override
public void accept(Visitor visitor) {
visitor.visitConditionalExpression(this);
}
@Override
public Element getNextChild(Element child) {
return null;
}
@Override
public Element getPreviousChild(Element child) {
return null;
}
@Override
public boolean replaceChild(Element child, Element by) {
if (child == getTest()) {
setTest((Expression)by);
return true;
}
if (child == getThenValue()) {
setThenValue((Expression)by);
return true;
}
if (child == getElseValue()) {
setElseValue((Expression)by);
return true;
}
return false;
}
}
public static class Cast extends Expression {
TypeRef type;
Expression target;
public Cast(TypeRef type, Expression target) {
setTarget(target);
setType(type);
}
public Cast() {
}
public void setTarget(Expression target) {
this.target = changeValue(this, this.target, target);
}
public void setType(TypeRef type) {
this.type = changeValue(this, this.type, type);
}
public Expression getTarget() {
return target;
}
public TypeRef getType() {
return type;
}
@Override
public void accept(Visitor visitor) {
visitor.visitCast(this);
}
@Override
public Element getNextChild(Element child) {
return null;
}
@Override
public Element getPreviousChild(Element child) {
return null;
}
@Override
public boolean replaceChild(Element child, Element by) {
if (child == getTarget()) {
setTarget((Expression)by);
return true;
}
if (child == getType()) {
setType((TypeRef)by);
return true;
}
return false;
}
}
public static class AssignmentOp extends Expression {
Expression target, value;
AssignmentOperator operator;
public AssignmentOp() {
}
public AssignmentOp(Expression target, AssignmentOperator operator, Expression value) {
if (operator == null)
throw new NullPointerException();
setValue(value);
setTarget(target);
setOperator(operator);
}
public AssignmentOperator getOperator() {
return operator;
}
public void setOperator(AssignmentOperator operator) {
this.operator = operator;
}
public Expression getValue() {
return value;
}
public Expression getTarget() {
return target;
}
public void setValue(Expression value) {
this.value = changeValue(this, this.value, value);
}
public void setTarget(Expression target) {
this.target = changeValue(this, this.target, target);
}
@Override
public void accept(Visitor visitor) {
visitor.visitAssignmentOp(this);
}
@Override
public Element getNextChild(Element child) {
if (child == getTarget())
return getValue();
return null;
}
@Override
public Element getPreviousChild(Element child) {
if (child == getValue())
return getTarget();
return null;
}
@Override
public boolean replaceChild(Element child, Element by) {
if (child == getTarget()) {
setTarget((Expression) by);
return true;
}
if (child == getValue()) {
setValue((Expression) by);
return true;
}
return false;
}
}
public static class BinaryOp extends Expression {
BinaryOperator operator;
Expression firstOperand, secondOperand;
public BinaryOp(Expression firstOperand, BinaryOperator operator, Expression secondOperand) {
if (operator == null)
throw new NullPointerException();
setOperator(operator);
setFirstOperand(firstOperand);
setSecondOperand(secondOperand);
}
public BinaryOp() {
}
public void setOperator(BinaryOperator operator) {
this.operator = operator;
}
public Expression getSecondOperand() {
return secondOperand;
}
public Expression getFirstOperand() {
return firstOperand;
}
public void setSecondOperand(Expression secondOperand) {
this.secondOperand = changeValue(this, this.secondOperand, secondOperand);
}
public void setFirstOperand(Expression firstOperand) {
this.firstOperand = changeValue(this, this.firstOperand, firstOperand);
}
public BinaryOperator getOperator() {
return operator;
}
@Override
public void accept(Visitor visitor) {
visitor.visitBinaryOp(this);
}
@Override
public Element getNextChild(Element child) {
if (child == getFirstOperand())
return getSecondOperand();
return null;
}
@Override
public Element getPreviousChild(Element child) {
if (child == getSecondOperand())
return getFirstOperand();
return null;
}
@Override
public boolean replaceChild(Element child, Element by) {
if (child == getFirstOperand()) {
setFirstOperand((Expression) by);
return true;
}
if (child == getSecondOperand()) {
setSecondOperand((Expression) by);
return true;
}
return false;
}
}
public static class UnaryOp extends Expression {
UnaryOperator operator;
Expression operand;
public UnaryOp(Expression operand, UnaryOperator operator) {
setOperand(operand);
setOperator(operator);
}
public UnaryOp() {
}
public Expression getOperand() {
return operand;
}
public void setOperator(UnaryOperator operator) {
this.operator = operator;
}
public void setOperand(Expression operand) {
this.operand = changeValue(this, this.operand, operand);
}
public UnaryOperator getOperator() {
return operator;
}
@Override
public void accept(Visitor visitor) {
visitor.visitUnaryOp(this);
}
@Override
public Element getNextChild(Element child) {
return null;
}
@Override
public Element getPreviousChild(Element child) {
return null;
}
@Override
public boolean replaceChild(Element child, Element by) {
if (child == getOperand()) {
setOperand((Expression) by);
return true;
}
return false;
}
}
public static class Constant extends Expression {
public enum Type {
Int, String, Char, IntegerString, Float, Short, Byte, Long, UInt, Double, LongString, ULong, Bool, Null
}
public enum IntForm {
Hex, Octal, String, Decimal
}
Type type;
IntForm intForm;
Object value;
String originalTextualRepresentation;
public Constant(Type type, IntForm intForm, Object value, String originalTextualRepresentation) {
if (value == null)
throw new NullPointerException();
setType(type);
setIntForm(intForm);
setValue(value);
setOriginalTextualRepresentation(originalTextualRepresentation);
checkType();
}
public Constant(Type type, Object value, String originalTextualRepresentation) {
setType(type);
setValue(value);
setOriginalTextualRepresentation(originalTextualRepresentation);
checkType();
}
public void setOriginalTextualRepresentation(String originalTextualRepresentation) {
this.originalTextualRepresentation = originalTextualRepresentation;
}
public String getOriginalTextualRepresentation() {
return originalTextualRepresentation;
}
void checkType() {
if (type == null)
return;
Object value = getValue();
switch (type) {
case Int:
case UInt:
case IntegerString:
value = (Integer)value;
break;
case ULong:
case Long:
case LongString:
value = (Long)value;
break;
case Char:
value = (Character)value;
break;
case Double:
value = (Double)value;
break;
case Float:
value = (Float)value;
break;
case String:
value = (String)value;
break;
case Bool:
value = (Boolean)value;
}
}
public static Constant newNull() {
return new Constant(Constant.Type.Null, null, null);
}
public void setIntForm(IntForm intForm) {
this.intForm = intForm;
}
public IntForm getIntForm() {
return intForm;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Constant() {
}
/*
public Constant fromString(String s) {
String v = s.toUpperCase();
Type type = null;
if (v.startsWith("\""))
type = Type.String;
else if (v.startsWith("'"))
type = v.length()Type.String;
else if (v.contains(".")) {
if (v.endsWith("L"))
c = Float.TYPE;
else
c = Double.TYPE;
} else if (v.endsWith("L"))
c = Long.TYPE;
else if (v.endsWith("F"))
c = Float.TYPE;
else if (v.endsWith("D"))
c = Double.TYPE;
else {
//TODO try to parse as long and if it fails as integer, use Long.TYPE
c = Integer.TYPE;
}
}*/
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
static String intStr(int intVal) {
return String.valueOf((char)(0xff & (intVal >> 24))) +
((char)(0xff & (intVal >> 16)))+
((char)(0xff & (intVal >> 8)))+
((char)(0xff & (intVal)))
;
}
public void accept(Visitor visitor) {
visitor.visitConstant(this);
}
@Override
public Element getNextChild(Element child) {
return null;
}
@Override
public Element getPreviousChild(Element child) {
return null;
}
@Override
public boolean replaceChild(Element child, Element by) {
return false;
}
public Integer asInteger() {
switch (getType()) {
case Int:
case IntegerString:
return (Integer)value;
}
throw new ClassCastException("Constant " + getValue() + " is not an integer, but a " + getType());
}
public static Constant parseCharOrStringInteger(final String orig) {
String string = orig;
int len = string.length();
if (len <= 2 || string.charAt(0) != '\'' || string.charAt(len - 1) != '\'')
throw new IllegalArgumentException("Expecting char or integer string, got " + string);
string = string.substring(1, len - 1);
len -= 2;
if (len == 4) {
boolean isIntegerString = true;
for (int i = len; i-- != 0;) {
if (string.charAt(i) == '\\') {
isIntegerString = false;
break;
}
}
if (isIntegerString) {
long result = 0;
for (int i = 0; i < len; i++) {
result = result << 8 | (int)string.charAt(i);
}
if (len == 4)
return new Constant(Type.IntegerString, IntForm.String, (int)result, orig);
else
return new Constant(Type.LongString, IntForm.String, result, orig);
}
}
return new Constant(Type.Char, parseNakedString(string).charAt(0), orig);
}
public static Constant parseChar(final String orig) {
String string = orig;
int len = string.length();
if (len <= 2 || string.charAt(0) != '\'' || string.charAt(len - 1) != '\'')
throw new IllegalArgumentException("Expecting char, got " + string);
string = string.substring(1, len - 1);
return new Constant(Type.Char, parseNakedString(string).charAt(0), orig);
}
private static String parseNakedString(String string) {
//return StringUtils.javaUnEscape(string)
int len = string.length();
StringBuffer b = new StringBuffer(len);
for (int i = 0; i < len;) {
char c = string.charAt(i++);
if (c == '\\') {
c = string.charAt(i++);
switch (c) {
case 't':
b.append('\t');
break;
case 'n':
b.append('\n');
break;
case 'r':
b.append('\r');
break;
case 'f':
b.append('\f');
break;
case 'b':
b.append('\b');
break;
case '\\':
b.append('\\');
break;
case '"':
b.append('"');
break;
case '\'':
b.append('\'');
break;
case 'u':
if (i < (len - 3)) {
b.append((char)Integer.parseInt(string.substring(i, i + 4), 16));
i += 4;
}
break;
case '0':
b.append('\0');
break;
default:
if (Character.isDigit(c)) {
int start = i - 1;
int end = i;
while (Character.isDigit(string.charAt(end))) {
end++;
}
b.append((char)Integer.parseInt(string.substring(start, end), 8));
i = end;
}
}
} else {
b.append(c);
}
}
return b.toString();
}
public static Constant parseStringInteger(final String orig) {
String string = orig;
int len = string.length();
if (len <= 2 || string.charAt(0) != '\'' || string.charAt(len - 1) != '\'' || ((len -= 2) != 4 && len != 8))
throw new IllegalArgumentException("Expecting 'xxxx' or 'xxxxxxxx', got " + string);
string = string.substring(1, len - 1);
long result = 0;
for (int i = len; i-- != 0;) {
result = result << 8 | (int)string.charAt(i);
}
if (len == 4)
return new Constant(Type.Int, IntForm.String, (int)result, orig);
else
return new Constant(Type.Long, IntForm.String, result, orig);
}
public static Constant parseString(final String orig) {
String string = orig;
int len = string.length();
if (len < 2 || string.charAt(0) != '"' || string.charAt(len - 1) != '"')
throw new IllegalArgumentException("Expecting string, got " + string);
string = string.substring(1, len - 1);
return new Constant(Type.String, parseNakedString(string), orig);
}
public static Constant parseDecimal(String string) {
return parseInteger(string, 10, IntForm.Decimal, false);
}
public static Constant parseInteger(final String string, int radix, IntForm form, boolean negate) {
return parseInteger(string, radix, form, negate, string);
}
public static Constant parseInteger(String string, int radix, IntForm form, boolean negate, final String orig) {
string = string.trim().toLowerCase();
if (string.startsWith("+"))
string = string.substring(1);
Type tpe = Type.Int;
boolean unsigned = false;
char c;
while (string.length() > 0 &&
((c = string.charAt(string.length() - 1)) == 'u' || c == 'i' || c == 'l' || c == 's')) {
if (string.endsWith("ll") || string.endsWith("li")) {
tpe = Type.Long;
string = string.substring(0, string.length() - 2);
} else if (string.endsWith("l") /*) {
tpe = Type.Long;
string = string.substring(0, string.length() - 1);
} else if (*/ || string.endsWith("i")) {
string = string.substring(0, string.length() - 1);
} else if (string.endsWith("s")) {
tpe = Type.Short;
string = string.substring(0, string.length() - 1);
} else if (string.endsWith("u")) {
unsigned = true;
string = string.substring(0, string.length() - 1);
}
}
Object value;
if (string.equals("ffffffffffffffff")) {
tpe = Type.Long;
value = 0xffffffffffffffffL;
} else {
long longValue;
if (tpe == Type.Long && unsigned || string.length() == 16) {
longValue = new BigInteger(string, radix).longValue();
} else {
longValue = Long.parseLong(string, radix);
}
switch (tpe) {
case Bool:
assert !negate;
value = (boolean)(longValue != 0);
break;
case Byte:
- if (longValue > Byte.MAX_VALUE) {
+ if (longValue > Byte.MAX_VALUE || longValue < 2 * Byte.MIN_VALUE) {
tpe = Type.Short;
value = (short)(negate ? -longValue : longValue);
} else {
byte v = (byte)(longValue & 0xff);
value = negate ? -v : v;
}
break;
case Char:
assert !negate;
value = (char)(longValue & 0xffff);
break;
case Short:
- if (longValue > 2 * Short.MAX_VALUE) {
+ if (longValue > 2 * Short.MAX_VALUE || longValue < 2 * Short.MIN_VALUE) {
tpe = Type.Int;
value = (int)(negate ? -longValue : longValue);
} else {
short v = (short)(longValue & 0xffff);
value = negate ? -v : v;
}
break;
case Int:
- if (longValue > 2L * Integer.MAX_VALUE) {
+ if (longValue > 2L * Integer.MAX_VALUE || longValue < 2L * Integer.MIN_VALUE) {
tpe = Type.Long;
value = negate ? -longValue : longValue;
} else {
- if (longValue > Integer.MAX_VALUE)
+ if (longValue > Integer.MAX_VALUE || longValue < Integer.MIN_VALUE)
tpe = Type.UInt;
int v = (int)(longValue & 0xffffffff);
value = negate ? -v : v;
}
break;
case Long:
value = negate ? -longValue : longValue;
break;
default:
throw new UnsupportedOperationException("Can't parse decimal of type " + tpe);
}
}
if (unsigned || form == IntForm.Hex) {
switch (tpe) {
case Int:
tpe = Type.UInt;
break;
case Long:
tpe = Type.ULong;
break;
// TODO: handle UShort, UByte
}
}
return new Constant(tpe, form, value, orig);
}
public static Constant parseHex(final String orig, boolean negate) {
String string = orig;
string = string.trim().toLowerCase();
if (!string.startsWith("0x"))
throw new IllegalArgumentException("Expected hex literal, got " + string);
try {
return parseInteger(string.substring(2), 16, IntForm.Hex, negate, orig);
} catch (NumberFormatException ex) {
throw new NumberFormatException("Parsing hex : \"" + string +"\"");
}
}
public static Constant parseOctal(String string, boolean negate) {
string = string.trim().toLowerCase();
if (!string.startsWith("0"))
throw new IllegalArgumentException("Expected octal literal, got " + string);
return parseInteger(string.substring(1), 8, IntForm.Octal, negate);
}
public static Constant parseFloat(final String orig) {
String string = orig;
string = string.trim().toLowerCase();
if (string.length() > 0) {
int lm1 = string.length() - 1;
char c = string.charAt(lm1);
if (Character.isLetter(c)) {
String beg = string.substring(0, lm1);
if (c == 'f')
return new Constant(Type.Float, Float.parseFloat(beg), orig);
}
}
return new Constant(Type.Double, Double.parseDouble(string), orig);
}
static final String[] trailingTypeInfos = new String[] { "ll", "li", "l", "s", "u" };
static String trimTrailingTypeInfo(String s) {
if (s == null)
return null;
while (s.length() > 0) {
switch (Character.toLowerCase(s.charAt(s.length() - 1))) {
case 'u':
case 'l':
case 'i':
case 's':
s = s.substring(0, s.length() - 1);
break;
default:
return s;
}
}
return s;
}
public Constant asJava() {
Type type = getType();
String txt = originalTextualRepresentation;
switch (type) {
case Byte:
case Int:
case Long:
case LongString:
case Short:
txt = trimTrailingTypeInfo(txt);
break;
case UInt:
if (intForm != IntForm.Hex && (getValue() instanceof Long) && ((Long)getValue()) > Integer.MAX_VALUE) {
txt = null;
break;
}
case ULong:
if (intForm == IntForm.Hex) {
txt = trimTrailingTypeInfo(txt);
break;
}
case IntegerString:
txt = null;
break;
}
switch (type) {
case Long:
case ULong:
if (txt != null)
txt += "L";
case LongString:
type = Type.Long;
break;
case UInt:
case IntegerString:
type = Type.Int;
break;
}
return new Constant(type, getValue(), txt);
}
}
}
| false | true |
public static Constant parseInteger(String string, int radix, IntForm form, boolean negate, final String orig) {
string = string.trim().toLowerCase();
if (string.startsWith("+"))
string = string.substring(1);
Type tpe = Type.Int;
boolean unsigned = false;
char c;
while (string.length() > 0 &&
((c = string.charAt(string.length() - 1)) == 'u' || c == 'i' || c == 'l' || c == 's')) {
if (string.endsWith("ll") || string.endsWith("li")) {
tpe = Type.Long;
string = string.substring(0, string.length() - 2);
} else if (string.endsWith("l") /*) {
tpe = Type.Long;
string = string.substring(0, string.length() - 1);
} else if (*/ || string.endsWith("i")) {
string = string.substring(0, string.length() - 1);
} else if (string.endsWith("s")) {
tpe = Type.Short;
string = string.substring(0, string.length() - 1);
} else if (string.endsWith("u")) {
unsigned = true;
string = string.substring(0, string.length() - 1);
}
}
Object value;
if (string.equals("ffffffffffffffff")) {
tpe = Type.Long;
value = 0xffffffffffffffffL;
} else {
long longValue;
if (tpe == Type.Long && unsigned || string.length() == 16) {
longValue = new BigInteger(string, radix).longValue();
} else {
longValue = Long.parseLong(string, radix);
}
switch (tpe) {
case Bool:
assert !negate;
value = (boolean)(longValue != 0);
break;
case Byte:
if (longValue > Byte.MAX_VALUE) {
tpe = Type.Short;
value = (short)(negate ? -longValue : longValue);
} else {
byte v = (byte)(longValue & 0xff);
value = negate ? -v : v;
}
break;
case Char:
assert !negate;
value = (char)(longValue & 0xffff);
break;
case Short:
if (longValue > 2 * Short.MAX_VALUE) {
tpe = Type.Int;
value = (int)(negate ? -longValue : longValue);
} else {
short v = (short)(longValue & 0xffff);
value = negate ? -v : v;
}
break;
case Int:
if (longValue > 2L * Integer.MAX_VALUE) {
tpe = Type.Long;
value = negate ? -longValue : longValue;
} else {
if (longValue > Integer.MAX_VALUE)
tpe = Type.UInt;
int v = (int)(longValue & 0xffffffff);
value = negate ? -v : v;
}
break;
case Long:
value = negate ? -longValue : longValue;
break;
default:
throw new UnsupportedOperationException("Can't parse decimal of type " + tpe);
}
}
if (unsigned || form == IntForm.Hex) {
switch (tpe) {
case Int:
tpe = Type.UInt;
break;
case Long:
tpe = Type.ULong;
break;
// TODO: handle UShort, UByte
}
}
return new Constant(tpe, form, value, orig);
}
|
public static Constant parseInteger(String string, int radix, IntForm form, boolean negate, final String orig) {
string = string.trim().toLowerCase();
if (string.startsWith("+"))
string = string.substring(1);
Type tpe = Type.Int;
boolean unsigned = false;
char c;
while (string.length() > 0 &&
((c = string.charAt(string.length() - 1)) == 'u' || c == 'i' || c == 'l' || c == 's')) {
if (string.endsWith("ll") || string.endsWith("li")) {
tpe = Type.Long;
string = string.substring(0, string.length() - 2);
} else if (string.endsWith("l") /*) {
tpe = Type.Long;
string = string.substring(0, string.length() - 1);
} else if (*/ || string.endsWith("i")) {
string = string.substring(0, string.length() - 1);
} else if (string.endsWith("s")) {
tpe = Type.Short;
string = string.substring(0, string.length() - 1);
} else if (string.endsWith("u")) {
unsigned = true;
string = string.substring(0, string.length() - 1);
}
}
Object value;
if (string.equals("ffffffffffffffff")) {
tpe = Type.Long;
value = 0xffffffffffffffffL;
} else {
long longValue;
if (tpe == Type.Long && unsigned || string.length() == 16) {
longValue = new BigInteger(string, radix).longValue();
} else {
longValue = Long.parseLong(string, radix);
}
switch (tpe) {
case Bool:
assert !negate;
value = (boolean)(longValue != 0);
break;
case Byte:
if (longValue > Byte.MAX_VALUE || longValue < 2 * Byte.MIN_VALUE) {
tpe = Type.Short;
value = (short)(negate ? -longValue : longValue);
} else {
byte v = (byte)(longValue & 0xff);
value = negate ? -v : v;
}
break;
case Char:
assert !negate;
value = (char)(longValue & 0xffff);
break;
case Short:
if (longValue > 2 * Short.MAX_VALUE || longValue < 2 * Short.MIN_VALUE) {
tpe = Type.Int;
value = (int)(negate ? -longValue : longValue);
} else {
short v = (short)(longValue & 0xffff);
value = negate ? -v : v;
}
break;
case Int:
if (longValue > 2L * Integer.MAX_VALUE || longValue < 2L * Integer.MIN_VALUE) {
tpe = Type.Long;
value = negate ? -longValue : longValue;
} else {
if (longValue > Integer.MAX_VALUE || longValue < Integer.MIN_VALUE)
tpe = Type.UInt;
int v = (int)(longValue & 0xffffffff);
value = negate ? -v : v;
}
break;
case Long:
value = negate ? -longValue : longValue;
break;
default:
throw new UnsupportedOperationException("Can't parse decimal of type " + tpe);
}
}
if (unsigned || form == IntForm.Hex) {
switch (tpe) {
case Int:
tpe = Type.UInt;
break;
case Long:
tpe = Type.ULong;
break;
// TODO: handle UShort, UByte
}
}
return new Constant(tpe, form, value, orig);
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/MylarTaskEditor.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/MylarTaskEditor.java
index ac7dbda5e..c9a220bde 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/MylarTaskEditor.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/MylarTaskEditor.java
@@ -1,554 +1,553 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.internal.tasks.ui.editors;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.mylar.context.core.MylarStatusHandler;
import org.eclipse.mylar.internal.tasks.ui.ITaskEditorFactory;
import org.eclipse.mylar.internal.tasks.ui.TaskListImages;
import org.eclipse.mylar.internal.tasks.ui.TaskListPreferenceConstants;
import org.eclipse.mylar.internal.tasks.ui.views.TaskListView;
import org.eclipse.mylar.tasks.core.AbstractRepositoryTask;
import org.eclipse.mylar.tasks.core.ITask;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.editor.IFormPage;
import org.eclipse.ui.forms.widgets.FormToolkit;
/**
* @author Mik Kersten
* @author Eric Booth (initial prototype)
*/
public class MylarTaskEditor extends FormEditor {
// private static final String TASK_INFO_PAGE_LABEL = "Planning";
private static final String ISSUE_WEB_PAGE_LABEL = "Browser";
protected ITask task;
private TaskPlanningEditor taskPlanningEditor;
private Browser webBrowser;
private TaskEditorInput taskEditorInput;
private TaskEditorListener partListener;
private List<IEditorPart> editors = new ArrayList<IEditorPart>();
private Menu contextMenu;
private IEditorPart contentOutlineProvider = null;
// private TaskEditorSelectionProvider selectionProvider;
//
// private static class TaskEditorSelectionProvider extends
// MultiPageSelectionProvider {
// private ISelection globalSelection;
//
// public TaskEditorSelectionProvider(MylarTaskEditor taskEditor) {
// super(taskEditor);
// }
//
// public ISelection getSelection() {
// IEditorPart activeEditor = ((MylarTaskEditor)
// getMultiPageEditor()).getActiveEditor();
// if (activeEditor != null && activeEditor.getSite() != null) {
// ISelectionProvider selectionProvider =
// activeEditor.getSite().getSelectionProvider();
// if (selectionProvider != null)
// return selectionProvider.getSelection();
// }
//
// return globalSelection;
// }
//
// public void setSelection(ISelection selection) {
// IEditorPart activeEditor = ((MylarTaskEditor)
// getMultiPageEditor()).getActiveEditor();
// if (activeEditor != null && activeEditor.getSite() != null) {
// ISelectionProvider selectionProvider =
// activeEditor.getSite().getSelectionProvider();
// if (selectionProvider != null)
// selectionProvider.setSelection(selection);
// } else {
// this.globalSelection = selection;
// fireSelectionChanged(new SelectionChangedEvent(this, globalSelection));
// }
// }
// }
public MylarTaskEditor() {
super();
taskPlanningEditor = new TaskPlanningEditor(this);
taskPlanningEditor.setParentEditor(this);
}
// @Override
// protected void createPages() {
// try {
// MenuManager manager = new MenuManager();
// IMenuListener listener = new IMenuListener() {
// public void menuAboutToShow(IMenuManager manager) {
// contextMenuAboutToShow(manager);
// }
// };
// manager.setRemoveAllWhenShown(true);
// manager.addMenuListener(listener);
// contextMenu = manager.createContextMenu(getContainer());
// getContainer().setMenu(contextMenu);
//
// int index = 0;
// index = createTaskSummaryPage();
// int selectedIndex = index;
// for (ITaskEditorFactory factory :
// TasksUiPlugin.getDefault().getTaskEditorFactories()) {
// if (factory.canCreateEditorFor(task)) {
// try {
// IEditorPart editor = factory.createEditor(this);
// IEditorInput input = factory.createEditorInput(task);
// if (editor != null && input != null) {
// editors.add(editor);
// if (editor instanceof AbstractRepositoryTaskEditor) {
// AbstractRepositoryTaskEditor repositoryTaskEditor =
// (AbstractRepositoryTaskEditor)editor;
// repositoryTaskEditor.setParentEditor(this);
// editor.init(getEditorSite(), input);
// repositoryTaskEditor.createPartControl(getContainer());
// index = addPage(repositoryTaskEditor.getControl());
// } else {
// index = addPage(editor, input);
// }
// selectedIndex = index;
// setPageText(index++, factory.getTitle());
// }
// // HACK: overwrites if multiple present
// if (factory.providesOutline()) {
// contentOutlineProvider = editor;
// }
// } catch (Exception e) {
// MylarStatusHandler.fail(e, "Could not create editor via factory: " +
// factory, true);
// }
// }
// }
// if (hasValidUrl()) {
// int browserIndex = createBrowserPage();
// if (selectedIndex == 0 && !taskEditorInput.isNewTask()) {
// selectedIndex = browserIndex;
// }
// }
// setActivePage(selectedIndex);
//
// if (task instanceof AbstractRepositoryTask) {
// setTitleImage(TaskListImages.getImage(TaskListImages.TASK_REPOSITORY));
// } else if (hasValidUrl()) {
// setTitleImage(TaskListImages.getImage(TaskListImages.TASK_WEB));
// }
// } catch (PartInitException e) {
// MylarStatusHandler.fail(e, "failed to create task editor pages", false);
// }
// }
protected void contextMenuAboutToShow(IMenuManager manager) {
TaskEditorActionContributor contributor = getContributor();
// IFormPage page = getActivePageInstance();
if (contributor != null)
contributor.contextMenuAboutToShow(manager);
}
public TaskEditorActionContributor getContributor() {
return (TaskEditorActionContributor) getEditorSite().getActionBarContributor();
}
@Override
public Object getAdapter(Class adapter) {
// TODO: consider adding: IContentOutlinePage.class.equals(adapter) &&
if (contentOutlineProvider != null) {
return contentOutlineProvider.getAdapter(adapter);
} else {
return super.getAdapter(adapter);
}
}
public IEditorPart getActiveEditor() {
return super.getActiveEditor();
}
private int createBrowserPage() {
if (!TasksUiPlugin.getDefault().getPreferenceStore().getBoolean(
TaskListPreferenceConstants.REPORT_DISABLE_INTERNAL)) {
try {
webBrowser = new Browser(getContainer(), SWT.NONE);
int index = addPage(webBrowser);
setPageText(index, ISSUE_WEB_PAGE_LABEL);
webBrowser.setUrl(task.getUrl());
boolean openWithBrowser = TasksUiPlugin.getDefault().getPreferenceStore().getBoolean(
TaskListPreferenceConstants.REPORT_OPEN_INTERNAL);
// if (!(task instanceof AbstractRepositoryTask) ||
// openWithBrowser) {
if (openWithBrowser) {
setActivePage(index);
}
return index;
} catch (SWTError e) {
MylarStatusHandler.fail(e, "Could not create Browser page: " + e.getMessage(), true);
} catch (RuntimeException e) {
MylarStatusHandler.fail(e, "could not create issue report page", false);
}
}
return 0;
}
@Override
public void doSave(IProgressMonitor monitor) {
// commitFormPages(true);
// editorDirtyStateChanged();
for (IFormPage page : getPages()) {
if (page.isDirty()) {
page.doSave(monitor);
}
}
editorDirtyStateChanged();
// for (IEditorPart editor : editors) {
// if (editor.isDirty())
// editor.doSave(monitor);
// }
//
// if (webBrowser != null) {
// webBrowser.setUrl(task.getUrl());
// } else if (hasValidUrl()) {
// createBrowserPage();
// }
}
// // see PDEFormEditor
// private void commitFormPages(boolean onSave) {
// IFormPage[] pages = getPages();
// for (int i = 0; i < pages.length; i++) {
// IFormPage page = pages[i];
// IManagedForm mform = page.getManagedForm();
// if (mform != null && mform.isDirty()) {
// mform.commit(true);
// }
// }
// }
// see PDEFormEditor
/* package */@SuppressWarnings("unchecked")
IFormPage[] getPages() {
ArrayList formPages = new ArrayList();
for (int i = 0; i < pages.size(); i++) {
Object page = pages.get(i);
if (page instanceof IFormPage)
formPages.add(page);
}
return (IFormPage[]) formPages.toArray(new IFormPage[formPages.size()]);
}
/**
* HACK: perform real check
*/
private boolean hasValidUrl() {
return task != null && task.getUrl().length() > 9;
}
/**
* Saves the multi-page editor's document as another file. Also updates the
* text for page 0's tab, and updates this multi-page editor's input to
* correspond to the nested editor's.
*
* @see org.eclipse.ui.ISaveablePart#doSaveAs()
*/
@Override
public void doSaveAs() {
IEditorPart editor = getEditor(0);
if (editor != null) {
editor.doSaveAs();
setPageText(0, editor.getTitle());
setInput(editor.getEditorInput());
}
}
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
partListener = new TaskEditorListener();
site.getPage().addPartListener(partListener);
super.init(site, input);
// taskEditorInput = (TaskEditorInput) input;
setSite(site);
// // selectionProvider = new TaskEditorSelectionProvider(this);
// // site.setSelectionProvider(selectionProvider);
//
// /*
// * The task data is saved only once, at the initialization of the
// * editor. This is then passed to each of the child editors. This way,
// * only one instance of the task data is stored for each editor
// opened.
// */
// task = taskEditorInput.getTask();
//
// try {
// // taskPlanningEditor.init(this.getEditorSite(),
// // this.getEditorInput());
// // taskPlanningEditor.setTask(task);
// // Set the title on the editor's tab
// this.setPartName(taskEditorInput.getLabel());
// } catch (Exception e) {
// throw new PartInitException(e.getMessage());
// }
}
public void notifyTaskChanged() {
TasksUiPlugin.getTaskListManager().getTaskList().notifyLocalInfoChanged(task);
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
// public boolean isDirty() {
// fLastDirtyState = computeDirtyState();
// return fLastDirtyState;
// }
// private boolean computeDirtyState() {
// IFormPage page = getActivePageInstance();
// if (page != null && page.isDirty())
// return true;
// return super.isDirty();
// }
@Override
public boolean isDirty() {
for (IFormPage page : getPages()) {
if (page.isDirty()) {
return true;
}
}
return false;
}
private class TaskEditorListener implements IPartListener {
public void partActivated(IWorkbenchPart part) {
if (part.equals(MylarTaskEditor.this)) {
if (taskEditorInput != null) {
ITask task = taskEditorInput.getTask();
if (TaskListView.getFromActivePerspective() != null) {
TaskListView.getFromActivePerspective().selectedAndFocusTask(task);
}
}
}
}
/**
* @see org.eclipse.ui.IPartListener#partBroughtToTop(org.eclipse.ui.IWorkbenchPart)
*/
public void partBroughtToTop(IWorkbenchPart part) {
// don't care about this event
}
/**
* @see org.eclipse.ui.IPartListener#partClosed(org.eclipse.ui.IWorkbenchPart)
*/
public void partClosed(IWorkbenchPart part) {
// don't care about this event
}
/**
* @see org.eclipse.ui.IPartListener#partDeactivated(org.eclipse.ui.IWorkbenchPart)
*/
public void partDeactivated(IWorkbenchPart part) {
// don't care about this event
}
/**
* @see org.eclipse.ui.IPartListener#partOpened(org.eclipse.ui.IWorkbenchPart)
*/
public void partOpened(IWorkbenchPart part) {
// don't care about this event
}
}
/**
* Updates the tab titile
*/
public void changeTitle() {
this.setPartName(taskEditorInput.getLabel());
}
public void markDirty() {
firePropertyChange(PROP_DIRTY);
return;
}
@Override
public void setFocus() {
// taskInfoEditor.setFocus();
}
public Browser getWebBrowser() {
return webBrowser;
}
@Override
protected void pageChange(int newPageIndex) {
for (ITaskEditorFactory factory : TasksUiPlugin.getDefault().getTaskEditorFactories()) {
for (IEditorPart editor : editors) {
factory.notifyEditorActivationChange(editor);
}
}
super.pageChange(newPageIndex);
}
public void dispose() {
for (IEditorPart part : editors) {
part.dispose();
}
if (taskPlanningEditor != null)
taskPlanningEditor.dispose();
if (webBrowser != null) {
webBrowser.dispose();
}
IWorkbench workbench = TasksUiPlugin.getDefault().getWorkbench();
if (workbench != null && partListener != null) {
for (IWorkbenchWindow window : workbench.getWorkbenchWindows()) {
IWorkbenchPage activePage = window.getActivePage();
if (activePage != null) {
activePage.removePartListener(partListener);
}
}
}
super.dispose();
}
public TaskEditorInput getTaskEditorInput() {
return taskEditorInput;
}
@Override
protected void addPages() {
try {
MenuManager manager = new MenuManager();
IMenuListener listener = new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
contextMenuAboutToShow(manager);
}
};
manager.setRemoveAllWhenShown(true);
manager.addMenuListener(listener);
contextMenu = manager.createContextMenu(getContainer());
getContainer().setMenu(contextMenu);
int index = -1;
if (getEditorInput() instanceof TaskEditorInput) {
addPage(taskPlanningEditor);
index++;
taskEditorInput = (TaskEditorInput) getEditorInput();
task = taskEditorInput.getTask();
setPartName(taskEditorInput.getLabel());
+ } else {
+ this.setTitleImage(TaskListImages.getImage(TaskListImages.TASK_REMOTE));
}
-// else {
-// this.setTitleImage(TaskListImages.getImage(TaskListImages.O));
-// }
int selectedIndex = index;
for (ITaskEditorFactory factory : TasksUiPlugin.getDefault().getTaskEditorFactories()) {
if ((task != null && factory.canCreateEditorFor(task)) || factory.canCreateEditorFor(getEditorInput())) {
try {
IEditorPart editor = factory.createEditor(this);
IEditorInput input = task != null ? factory.createEditorInput(task) : getEditorInput();
if (editor != null && input != null) {
if (editor instanceof AbstractRepositoryTaskEditor) {
TaskFormPage repositoryTaskEditor = (TaskFormPage) editor;
// repositoryTaskEditor.setParentEditor(this);
editor.init(getEditorSite(), input);
repositoryTaskEditor.createPartControl(getContainer());
index = addPage(repositoryTaskEditor);
if(getEditorInput() instanceof ExistingBugEditorInput) {
setPartName(((ExistingBugEditorInput)getEditorInput()).getToolTipText());
}
} else {
index = addPage(editor, input);
}
selectedIndex = index;
setPageText(index++, factory.getTitle());
}
// HACK: overwrites if multiple present
if (factory.providesOutline()) {
contentOutlineProvider = editor;
}
} catch (Exception e) {
MylarStatusHandler.fail(e, "Could not create editor via factory: " + factory, true);
}
}
}
if (hasValidUrl()) {
int browserIndex = createBrowserPage();
if (selectedIndex == 0 && !taskEditorInput.isNewTask()) {
selectedIndex = browserIndex;
}
}
setActivePage(selectedIndex);
if (task instanceof AbstractRepositoryTask) {
setTitleImage(TaskListImages.getImage(TaskListImages.TASK_REPOSITORY));
} else if (hasValidUrl()) {
setTitleImage(TaskListImages.getImage(TaskListImages.TASK_WEB));
}
} catch (PartInitException e) {
MylarStatusHandler.fail(e, "failed to create task editor pages", false);
}
}
protected FormToolkit createToolkit(Display display) {
// Create a toolkit that shares colors between editors.
return new FormToolkit(PlatformUI.getWorkbench().getDisplay());
}
public ISelection getSelection() {
return getSite().getSelectionProvider().getSelection();
}
}
| false | true |
protected void addPages() {
try {
MenuManager manager = new MenuManager();
IMenuListener listener = new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
contextMenuAboutToShow(manager);
}
};
manager.setRemoveAllWhenShown(true);
manager.addMenuListener(listener);
contextMenu = manager.createContextMenu(getContainer());
getContainer().setMenu(contextMenu);
int index = -1;
if (getEditorInput() instanceof TaskEditorInput) {
addPage(taskPlanningEditor);
index++;
taskEditorInput = (TaskEditorInput) getEditorInput();
task = taskEditorInput.getTask();
setPartName(taskEditorInput.getLabel());
}
// else {
// this.setTitleImage(TaskListImages.getImage(TaskListImages.O));
// }
int selectedIndex = index;
for (ITaskEditorFactory factory : TasksUiPlugin.getDefault().getTaskEditorFactories()) {
if ((task != null && factory.canCreateEditorFor(task)) || factory.canCreateEditorFor(getEditorInput())) {
try {
IEditorPart editor = factory.createEditor(this);
IEditorInput input = task != null ? factory.createEditorInput(task) : getEditorInput();
if (editor != null && input != null) {
if (editor instanceof AbstractRepositoryTaskEditor) {
TaskFormPage repositoryTaskEditor = (TaskFormPage) editor;
// repositoryTaskEditor.setParentEditor(this);
editor.init(getEditorSite(), input);
repositoryTaskEditor.createPartControl(getContainer());
index = addPage(repositoryTaskEditor);
if(getEditorInput() instanceof ExistingBugEditorInput) {
setPartName(((ExistingBugEditorInput)getEditorInput()).getToolTipText());
}
} else {
index = addPage(editor, input);
}
selectedIndex = index;
setPageText(index++, factory.getTitle());
}
// HACK: overwrites if multiple present
if (factory.providesOutline()) {
contentOutlineProvider = editor;
}
} catch (Exception e) {
MylarStatusHandler.fail(e, "Could not create editor via factory: " + factory, true);
}
}
}
if (hasValidUrl()) {
int browserIndex = createBrowserPage();
if (selectedIndex == 0 && !taskEditorInput.isNewTask()) {
selectedIndex = browserIndex;
}
}
setActivePage(selectedIndex);
if (task instanceof AbstractRepositoryTask) {
setTitleImage(TaskListImages.getImage(TaskListImages.TASK_REPOSITORY));
} else if (hasValidUrl()) {
setTitleImage(TaskListImages.getImage(TaskListImages.TASK_WEB));
}
} catch (PartInitException e) {
MylarStatusHandler.fail(e, "failed to create task editor pages", false);
}
}
|
protected void addPages() {
try {
MenuManager manager = new MenuManager();
IMenuListener listener = new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
contextMenuAboutToShow(manager);
}
};
manager.setRemoveAllWhenShown(true);
manager.addMenuListener(listener);
contextMenu = manager.createContextMenu(getContainer());
getContainer().setMenu(contextMenu);
int index = -1;
if (getEditorInput() instanceof TaskEditorInput) {
addPage(taskPlanningEditor);
index++;
taskEditorInput = (TaskEditorInput) getEditorInput();
task = taskEditorInput.getTask();
setPartName(taskEditorInput.getLabel());
} else {
this.setTitleImage(TaskListImages.getImage(TaskListImages.TASK_REMOTE));
}
int selectedIndex = index;
for (ITaskEditorFactory factory : TasksUiPlugin.getDefault().getTaskEditorFactories()) {
if ((task != null && factory.canCreateEditorFor(task)) || factory.canCreateEditorFor(getEditorInput())) {
try {
IEditorPart editor = factory.createEditor(this);
IEditorInput input = task != null ? factory.createEditorInput(task) : getEditorInput();
if (editor != null && input != null) {
if (editor instanceof AbstractRepositoryTaskEditor) {
TaskFormPage repositoryTaskEditor = (TaskFormPage) editor;
// repositoryTaskEditor.setParentEditor(this);
editor.init(getEditorSite(), input);
repositoryTaskEditor.createPartControl(getContainer());
index = addPage(repositoryTaskEditor);
if(getEditorInput() instanceof ExistingBugEditorInput) {
setPartName(((ExistingBugEditorInput)getEditorInput()).getToolTipText());
}
} else {
index = addPage(editor, input);
}
selectedIndex = index;
setPageText(index++, factory.getTitle());
}
// HACK: overwrites if multiple present
if (factory.providesOutline()) {
contentOutlineProvider = editor;
}
} catch (Exception e) {
MylarStatusHandler.fail(e, "Could not create editor via factory: " + factory, true);
}
}
}
if (hasValidUrl()) {
int browserIndex = createBrowserPage();
if (selectedIndex == 0 && !taskEditorInput.isNewTask()) {
selectedIndex = browserIndex;
}
}
setActivePage(selectedIndex);
if (task instanceof AbstractRepositoryTask) {
setTitleImage(TaskListImages.getImage(TaskListImages.TASK_REPOSITORY));
} else if (hasValidUrl()) {
setTitleImage(TaskListImages.getImage(TaskListImages.TASK_WEB));
}
} catch (PartInitException e) {
MylarStatusHandler.fail(e, "failed to create task editor pages", false);
}
}
|
diff --git a/src/de/uni_koblenz/jgralab/greql2/funlib/NthElement.java b/src/de/uni_koblenz/jgralab/greql2/funlib/NthElement.java
index 8111a14b6..edbc6c3d2 100644
--- a/src/de/uni_koblenz/jgralab/greql2/funlib/NthElement.java
+++ b/src/de/uni_koblenz/jgralab/greql2/funlib/NthElement.java
@@ -1,99 +1,99 @@
/*
* JGraLab - The Java graph laboratory
* (c) 2006-2009 Institute for Software Technology
* University of Koblenz-Landau, Germany
*
* [email protected]
*
* Please report bugs to http://serres.uni-koblenz.de/bugzilla
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package de.uni_koblenz.jgralab.greql2.funlib;
import java.util.ArrayList;
import de.uni_koblenz.jgralab.Graph;
import de.uni_koblenz.jgralab.graphmarker.BooleanGraphMarker;
import de.uni_koblenz.jgralab.greql2.exception.EvaluateException;
import de.uni_koblenz.jgralab.greql2.exception.WrongFunctionParameterException;
import de.uni_koblenz.jgralab.greql2.jvalue.JValue;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueCollection;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueType;
/**
* Returns the n-th element of the given list or tuple.
*
* <dl>
* <dt><b>GReQL-signature</b></dt>
* <dd><code>OBJECT nthElement(list:LIST<OBJECT>, n:INTEGER)</code></dd>
* <dd><code>OBJECT nthElement(list:SET<OBJECT>, n:INTEGER)</code></dd>
* <dd><code>OBJECT nthElement(tuple:TUPLE<OBJECT>, n:INTEGER)</code></dd>
* <dd> </dd>
* </dl>
* <dl>
* <dt></dt>
* <dd>
* <dl>
* <dt><b>Parameters:</b></dt>
* <dd><code>list</code> - list to return n-th element for</dd>
* <dd><code>set</code> - sorted set to return n-th element for</dd>
* <dd><code>tuple</code> - tuple to return n-th element for</dd>
* <dd><code>n</code> - index of the element to return</dd>
* <dt><b>Returns:</b></dt>
* <dd>the n-th element of the given list or tuple</dd>
* <dd><code>Null</code> if one of the parameters is <code>Null</code></dd>
* </dl>
* </dd>
* </dl>
*
* @author [email protected]
*
*/
public class NthElement extends AbstractGreql2Function {
{
JValueType[][] x = { { JValueType.COLLECTION, JValueType.INTEGER } };
signatures = x;
}
public JValue evaluate(Graph graph, BooleanGraphMarker subgraph,
JValue[] arguments) throws EvaluateException {
if (checkArguments(arguments) == -1) {
throw new WrongFunctionParameterException(this, arguments);
}
int index = arguments[1].toInteger();
JValueCollection col = arguments[0].toCollection();
if (index >= col.size()) {
throw new EvaluateException("The given collection has fewer than "
- + (index) + " elements.");
+ + (index + 1) + " elements.");
}
return col.toJValueList().get(index);
}
public long getEstimatedCosts(ArrayList<Long> inElements) {
return 2;
}
public double getSelectivity() {
return 1;
}
public long getEstimatedCardinality(int inElements) {
return 1;
}
}
| true | true |
public JValue evaluate(Graph graph, BooleanGraphMarker subgraph,
JValue[] arguments) throws EvaluateException {
if (checkArguments(arguments) == -1) {
throw new WrongFunctionParameterException(this, arguments);
}
int index = arguments[1].toInteger();
JValueCollection col = arguments[0].toCollection();
if (index >= col.size()) {
throw new EvaluateException("The given collection has fewer than "
+ (index) + " elements.");
}
return col.toJValueList().get(index);
}
|
public JValue evaluate(Graph graph, BooleanGraphMarker subgraph,
JValue[] arguments) throws EvaluateException {
if (checkArguments(arguments) == -1) {
throw new WrongFunctionParameterException(this, arguments);
}
int index = arguments[1].toInteger();
JValueCollection col = arguments[0].toCollection();
if (index >= col.size()) {
throw new EvaluateException("The given collection has fewer than "
+ (index + 1) + " elements.");
}
return col.toJValueList().get(index);
}
|
diff --git a/testsuite/load/container/src/main/java/org/mobicents/diameter/server/bootstrap/Main.java b/testsuite/load/container/src/main/java/org/mobicents/diameter/server/bootstrap/Main.java
index 28d4e852..7d852294 100644
--- a/testsuite/load/container/src/main/java/org/mobicents/diameter/server/bootstrap/Main.java
+++ b/testsuite/load/container/src/main/java/org/mobicents/diameter/server/bootstrap/Main.java
@@ -1,254 +1,255 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.diameter.server.bootstrap;
import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;
import org.jboss.dependency.spi.Controller;
import org.jboss.dependency.spi.ControllerContext;
import org.jboss.kernel.Kernel;
import org.jboss.kernel.plugins.bootstrap.basic.BasicBootstrap;
import org.jboss.kernel.plugins.deployment.xml.BasicXMLDeployer;
import org.jboss.util.StringPropertyReplacer;
/**
* @author <a href="mailto:[email protected]">Ales Justin</a>
* @author <a href="mailto:[email protected]">amit bhayani</a>
* @author baranowb
*/
public class Main {
private final static String HOME_DIR = "DIA_HOME";
private final static String BOOT_URL = "/conf/bootstrap-beans.xml";
private final static String LOG4J_URL = "/conf/log4j.properties";
private final static String LOG4J_URL_XML = "/conf/log4j.xml";
public static final String DIA_HOME = "dia.home.dir";
public static final String DIA_BIND_ADDRESS = "dia.bind.address";
private static int index = 0;
private Kernel kernel;
private BasicXMLDeployer kernelDeployer;
private Controller controller;
private static Logger logger = Logger.getLogger(Main.class);
public static void main(String[] args) throws Throwable {
String homeDir = getHomeDir(args);
System.setProperty(DIA_HOME, homeDir);
if (!initLOG4JProperties(homeDir) && !initLOG4JXml(homeDir)) {
//logger.error("Failed to initialize loggin, no configuration. Defaults are used.");
System.err.println("Failed to initialize loggin, no configuration. Defaults are used.");
}else
{
logger.info("log4j configured");
}
URL bootURL = getBootURL(args);
Main main = new Main();
main.processCommandLine(args);
logger.info("Booting from " + bootURL);
main.boot(bootURL);
}
private void processCommandLine(String[] args) {
String programName = System.getProperty("program.name", "Mobicents Diameter Test Server");
int c;
String arg;
- LongOpt[] longopts = new LongOpt[2];
- longopts[0] = new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h');
- longopts[1] = new LongOpt("host", LongOpt.REQUIRED_ARGUMENT, null, 'b');
+ LongOpt[] longopts =
+ { new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'),
+ new LongOpt("host", LongOpt.REQUIRED_ARGUMENT, null, 'b')
+ };
Getopt g = new Getopt("MMS", args, "-:b:h", longopts);
g.setOpterr(false); // We'll do our own error handling
//
while ((c = g.getopt()) != -1) {
switch (c) {
//
case 'b':
arg = g.getOptarg();
System.setProperty(DIA_BIND_ADDRESS, arg);
break;
//
case 'h':
System.out.println("usage: " + programName + " [options]");
System.out.println();
System.out.println("options:");
System.out.println(" -h, --help Show this help message");
System.out.println(" -b, --host=<host or ip> Bind address for all Mobicents Media Server services");
System.out.println();
System.exit(0);
break;
case ':':
System.out.println("You need an argument for option " + (char) g.getOptopt());
System.exit(0);
break;
//
case '?':
System.out.println("The option '" + (char) g.getOptopt() + "' is not valid");
System.exit(0);
break;
//
default:
System.out.println("getopt() returned " + c);
break;
}
}
if (System.getProperty(DIA_BIND_ADDRESS) == null) {
System.setProperty(DIA_BIND_ADDRESS, "127.0.0.1");
}
}
private static boolean initLOG4JProperties(String homeDir) {
String Log4jURL = homeDir + LOG4J_URL;
try {
URL log4jurl = getURL(Log4jURL);
InputStream inStreamLog4j = log4jurl.openStream();
Properties propertiesLog4j = new Properties();
try {
propertiesLog4j.load(inStreamLog4j);
PropertyConfigurator.configure(propertiesLog4j);
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
// e.printStackTrace();
logger.info("Failed to initialize LOG4J with properties file.");
return false;
}
return true;
}
private static boolean initLOG4JXml(String homeDir) {
String Log4jURL = homeDir + LOG4J_URL_XML;
try {
URL log4jurl = getURL(Log4jURL);
DOMConfigurator.configure(log4jurl);
} catch (Exception e) {
// e.printStackTrace();
logger.info("Failed to initialize LOG4J with xml file.");
return false;
}
return true;
}
/**
* Gets the Media Server Home directory.
*
* @param args
* the command line arguments
* @return the path to the home directory.
*/
private static String getHomeDir(String args[]) {
if (System.getenv(HOME_DIR) == null) {
if (args.length > index) {
return args[index++];
} else {
return ".";
}
} else {
return System.getenv(HOME_DIR);
}
}
/**
* Gets the URL which points to the boot descriptor.
*
* @param args
* command line arguments.
* @return URL of the boot descriptor.
*/
private static URL getBootURL(String args[]) throws Exception {
String bootURL = "${" + DIA_HOME + "}" + BOOT_URL;
return getURL(bootURL);
}
protected void boot(URL bootURL) throws Throwable {
BasicBootstrap bootstrap = new BasicBootstrap();
bootstrap.run();
registerShutdownThread();
kernel = bootstrap.getKernel();
kernelDeployer = new BasicXMLDeployer(kernel);
kernelDeployer.deploy(bootURL);
kernelDeployer.validate();
controller = kernel.getController();
start(kernel, kernelDeployer);
}
public void start(Kernel kernel, BasicXMLDeployer kernelDeployer) {
ControllerContext context = controller.getInstalledContext("MainDeployer");
if (context != null) {
MainDeployer deployer = (MainDeployer) context.getTarget();
deployer.start(kernel, kernelDeployer);
}
}
public static URL getURL(String url) throws Exception {
// replace ${} inputs
url = StringPropertyReplacer.replaceProperties(url, System.getProperties());
File file = new File(url);
if (file.exists() == false) {
throw new IllegalArgumentException("No such file: " + url);
}
return file.toURI().toURL();
}
protected void registerShutdownThread() {
Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownThread()));
}
private class ShutdownThread implements Runnable {
public void run() {
System.out.println("Shutting down");
kernelDeployer.shutdown();
kernelDeployer = null;
kernel.getController().shutdown();
kernel = null;
}
}
}
| true | true |
private void processCommandLine(String[] args) {
String programName = System.getProperty("program.name", "Mobicents Diameter Test Server");
int c;
String arg;
LongOpt[] longopts = new LongOpt[2];
longopts[0] = new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h');
longopts[1] = new LongOpt("host", LongOpt.REQUIRED_ARGUMENT, null, 'b');
Getopt g = new Getopt("MMS", args, "-:b:h", longopts);
g.setOpterr(false); // We'll do our own error handling
//
while ((c = g.getopt()) != -1) {
switch (c) {
//
case 'b':
arg = g.getOptarg();
System.setProperty(DIA_BIND_ADDRESS, arg);
break;
//
case 'h':
System.out.println("usage: " + programName + " [options]");
System.out.println();
System.out.println("options:");
System.out.println(" -h, --help Show this help message");
System.out.println(" -b, --host=<host or ip> Bind address for all Mobicents Media Server services");
System.out.println();
System.exit(0);
break;
case ':':
System.out.println("You need an argument for option " + (char) g.getOptopt());
System.exit(0);
break;
//
case '?':
System.out.println("The option '" + (char) g.getOptopt() + "' is not valid");
System.exit(0);
break;
//
default:
System.out.println("getopt() returned " + c);
break;
}
}
if (System.getProperty(DIA_BIND_ADDRESS) == null) {
System.setProperty(DIA_BIND_ADDRESS, "127.0.0.1");
}
}
|
private void processCommandLine(String[] args) {
String programName = System.getProperty("program.name", "Mobicents Diameter Test Server");
int c;
String arg;
LongOpt[] longopts =
{ new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'),
new LongOpt("host", LongOpt.REQUIRED_ARGUMENT, null, 'b')
};
Getopt g = new Getopt("MMS", args, "-:b:h", longopts);
g.setOpterr(false); // We'll do our own error handling
//
while ((c = g.getopt()) != -1) {
switch (c) {
//
case 'b':
arg = g.getOptarg();
System.setProperty(DIA_BIND_ADDRESS, arg);
break;
//
case 'h':
System.out.println("usage: " + programName + " [options]");
System.out.println();
System.out.println("options:");
System.out.println(" -h, --help Show this help message");
System.out.println(" -b, --host=<host or ip> Bind address for all Mobicents Media Server services");
System.out.println();
System.exit(0);
break;
case ':':
System.out.println("You need an argument for option " + (char) g.getOptopt());
System.exit(0);
break;
//
case '?':
System.out.println("The option '" + (char) g.getOptopt() + "' is not valid");
System.exit(0);
break;
//
default:
System.out.println("getopt() returned " + c);
break;
}
}
if (System.getProperty(DIA_BIND_ADDRESS) == null) {
System.setProperty(DIA_BIND_ADDRESS, "127.0.0.1");
}
}
|
diff --git a/src/main/java/com/couchbase/client/CouchbaseConnectionFactory.java b/src/main/java/com/couchbase/client/CouchbaseConnectionFactory.java
index d147a38e..b8bdc58a 100644
--- a/src/main/java/com/couchbase/client/CouchbaseConnectionFactory.java
+++ b/src/main/java/com/couchbase/client/CouchbaseConnectionFactory.java
@@ -1,148 +1,148 @@
/**
* Copyright (C) 2009-2011 Couchbase, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
* IN THE SOFTWARE.
*/
package com.couchbase.client;
import com.couchbase.client.vbucket.ConfigurationException;
import com.couchbase.client.vbucket.ConfigurationProvider;
import com.couchbase.client.vbucket.ConfigurationProviderHTTP;
import com.couchbase.client.vbucket.VBucketNodeLocator;
import com.couchbase.client.vbucket.config.Config;
import com.couchbase.client.vbucket.config.ConfigType;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.List;
import net.spy.memcached.BinaryConnectionFactory;
import net.spy.memcached.DefaultHashAlgorithm;
import net.spy.memcached.FailureMode;
import net.spy.memcached.HashAlgorithm;
import net.spy.memcached.KetamaNodeLocator;
import net.spy.memcached.MemcachedConnection;
import net.spy.memcached.MemcachedNode;
import net.spy.memcached.NodeLocator;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.auth.PlainCallbackHandler;
/**
* Couchbase implementation of ConnectionFactory.
*
* <p>
* This implementation creates connections where the operation queue is an
* ArrayBlockingQueue and the read and write queues are unbounded
* LinkedBlockingQueues. The <code>Retry</code> FailureMode and <code>
* KetamaHash</code> VBucket hashing mechanism are always used. If other
* configurations are needed, look at the ConnectionFactoryBuilder.
*
* </p>
*/
public class CouchbaseConnectionFactory extends BinaryConnectionFactory {
/**
* Default failure mode.
*/
public static final FailureMode DEFAULT_FAILURE_MODE = FailureMode.Retry;
/**
* Default hash algorithm.
*/
public static final HashAlgorithm DEFAULT_HASH =
DefaultHashAlgorithm.KETAMA_HASH;
/**
* Maximum length of the operation queue returned by this connection factory.
*/
public static final int DEFAULT_OP_QUEUE_LEN = 16384;
private final ConfigurationProvider configurationProvider;
private final String bucket;
private final String pass;
public CouchbaseConnectionFactory(final List<URI> baseList,
final String bucketName, final String password)
throws IOException {
// ConnectionFactoryBuilder cfb = new ConnectionFactoryBuilder(cf);
for (URI bu : baseList) {
if (!bu.isAbsolute()) {
throw new IllegalArgumentException("The base URI must be absolute");
}
}
bucket = bucketName;
pass = password;
configurationProvider =
new ConfigurationProviderHTTP(baseList, bucketName, password);
}
@Override
public MemcachedConnection createConnection(List<InetSocketAddress> addrs)
throws IOException {
return new CouchbaseConnection(getReadBufSize(), this, addrs,
getInitialObservers(), getFailureMode(), getOperationFactory());
}
@Override
public NodeLocator createLocator(List<MemcachedNode> nodes) {
Config config = getVBucketConfig();
if (config == null) {
throw new IllegalStateException("Couldn't get config");
}
- if (config.getConfigType() == ConfigType.COUCHBASE) {
+ if (config.getConfigType() == ConfigType.MEMCACHE) {
return new KetamaNodeLocator(nodes, getHashAlg());
- } else if (config.getConfigType() == ConfigType.MEMCACHE) {
+ } else if (config.getConfigType() == ConfigType.COUCHBASE) {
return new VBucketNodeLocator(nodes, getVBucketConfig());
} else {
throw new IllegalStateException("Unhandled locator type: "
+ config.getConfigType());
}
}
public AuthDescriptor getAuthDescriptor() {
if (!configurationProvider.getAnonymousAuthBucket().equals(bucket)
&& bucket != null) {
return new AuthDescriptor(new String[] { "PLAIN" },
new PlainCallbackHandler(bucket, pass));
} else {
return null;
}
}
public String getBucketName() {
return bucket;
}
public Config getVBucketConfig() {
try {
return configurationProvider.getBucketConfiguration(bucket).getConfig();
} catch (ConfigurationException e) {
return null;
}
}
public ConfigurationProvider getConfigurationProvider() {
return configurationProvider;
}
}
| false | true |
public NodeLocator createLocator(List<MemcachedNode> nodes) {
Config config = getVBucketConfig();
if (config == null) {
throw new IllegalStateException("Couldn't get config");
}
if (config.getConfigType() == ConfigType.COUCHBASE) {
return new KetamaNodeLocator(nodes, getHashAlg());
} else if (config.getConfigType() == ConfigType.MEMCACHE) {
return new VBucketNodeLocator(nodes, getVBucketConfig());
} else {
throw new IllegalStateException("Unhandled locator type: "
+ config.getConfigType());
}
}
|
public NodeLocator createLocator(List<MemcachedNode> nodes) {
Config config = getVBucketConfig();
if (config == null) {
throw new IllegalStateException("Couldn't get config");
}
if (config.getConfigType() == ConfigType.MEMCACHE) {
return new KetamaNodeLocator(nodes, getHashAlg());
} else if (config.getConfigType() == ConfigType.COUCHBASE) {
return new VBucketNodeLocator(nodes, getVBucketConfig());
} else {
throw new IllegalStateException("Unhandled locator type: "
+ config.getConfigType());
}
}
|
diff --git a/src/com/android/bluetooth/map/BluetoothMasService.java b/src/com/android/bluetooth/map/BluetoothMasService.java
index 863e0567..2bbd8f67 100644
--- a/src/com/android/bluetooth/map/BluetoothMasService.java
+++ b/src/com/android/bluetooth/map/BluetoothMasService.java
@@ -1,899 +1,902 @@
/*
* Copyright (c) 2008-2009, Motorola, Inc. All rights reserved.
* Copyright (c) 2010-2012, Code Aurora Forum. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Code Aurora nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.android.bluetooth.map;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import com.android.bluetooth.R;
import com.android.bluetooth.map.BluetoothMns.MnsClient;
import com.android.bluetooth.map.MapUtils.EmailUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.obex.ServerSession;
import static com.android.bluetooth.map.IBluetoothMasApp.MESSAGE_TYPE_EMAIL;
import static com.android.bluetooth.map.IBluetoothMasApp.MESSAGE_TYPE_MMS;
import static com.android.bluetooth.map.IBluetoothMasApp.MESSAGE_TYPE_SMS;
import static com.android.bluetooth.map.IBluetoothMasApp.MESSAGE_TYPE_SMS_MMS;
public class BluetoothMasService extends Service {
private static final String TAG = "BluetoothMasService";
/**
* To enable MAP DEBUG/VERBOSE logging - run below cmd in adb shell, and
* restart com.android.bluetooth process. only enable DEBUG log:
* "setprop log.tag.BluetoothMapService DEBUG"; enable both VERBOSE and
* DEBUG log: "setprop log.tag.BluetoothMapService VERBOSE"
*/
public static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
public static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
/**
* Intent indicating incoming connection request which is sent to
* BluetoothMasActivity
*/
public static final String ACCESS_REQUEST_ACTION = "com.android.bluetooth.map.accessrequest";
/**
* Intent indicating incoming connection request accepted by user which is
* sent from BluetoothMasActivity
*/
public static final String ACCESS_ALLOWED_ACTION = "com.android.bluetooth.map.accessallowed";
/**
* Intent indicating incoming connection request denied by user which is
* sent from BluetoothMasActivity
*/
public static final String ACCESS_DISALLOWED_ACTION = "com.android.bluetooth.map.accessdisallowed";
/**
* Intent indicating incoming obex authentication request which is from
* PCE(Carkit)
*/
public static final String AUTH_CHALL_ACTION = "com.android.bluetooth.map.authchall";
/**
* Intent indicating obex session key input complete by user which is sent
* from BluetoothMasActivity
*/
public static final String AUTH_RESPONSE_ACTION = "com.android.bluetooth.map.authresponse";
/**
* Intent indicating user canceled obex authentication session key input
* which is sent from BluetoothMasActivity
*/
public static final String AUTH_CANCELLED_ACTION = "com.android.bluetooth.map.authcancelled";
/**
* Intent indicating timeout for user confirmation, which is sent to
* BluetoothMasActivity
*/
public static final String USER_CONFIRM_TIMEOUT_ACTION = "com.android.bluetooth.map.userconfirmtimeout";
public static final String THIS_PACKAGE_NAME = "com.android.bluetooth";
/**
* Intent Extra name indicating always allowed which is sent from
* BluetoothMasActivity
*/
public static final String EXTRA_ALWAYS_ALLOWED = "com.android.bluetooth.map.alwaysallowed";
/**
* Intent Extra name indicating session key which is sent from
* BluetoothMasActivity
*/
public static final String EXTRA_SESSION_KEY = "com.android.bluetooth.map.sessionkey";
/**
* Intent Extra name indicating BluetoothDevice which is sent to
* BluetoothMasActivity
*/
public static final String EXTRA_BLUETOOTH_DEVICE = "com.android.bluetooth.map.bluetoothdevice";
private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
public static final int MSG_SERVERSESSION_CLOSE = 5004;
public static final int MSG_SESSION_ESTABLISHED = 5005;
public static final int MSG_SESSION_DISCONNECTED = 5006;
public static final int MSG_OBEX_AUTH_CHALL = 5007;
private static final int MSG_INTERNAL_START_LISTENER = 1;
private static final int MSG_INTERNAL_USER_TIMEOUT = 2;
private static final int USER_CONFIRM_TIMEOUT_VALUE = 30000;
// Ensure not conflict with Opp notification ID
private static final int NOTIFICATION_ID_ACCESS = -1000005;
private BluetoothAdapter mAdapter;
private Object mAuthSync = new Object();
private BluetoothMapAuthenticator mAuth = null;
BluetoothMasObexConnectionManager mConnectionManager = null;
BluetoothMns mnsClient;
private boolean mHasStarted = false;
private int mStartId = -1;
/**
* The flag indicating MAP request has been notified.
* This is set on when initiate notification and set off after accept/time out
*/
private volatile boolean mIsRequestBeingNotified = false;
// package and class name to which we send intent to check Message access permission
private static final String ACCESS_AUTHORITY_PACKAGE = "com.android.settings";
private static final String ACCESS_AUTHORITY_CLASS =
"com.android.settings.bluetooth.BluetoothPermissionRequest";
public static class MasInstanceInfo {
int mSupportedMessageTypes;
Class<? extends MnsClient> mMnsClientClass;
int mRfcommPort;
public MasInstanceInfo(int smt, Class<? extends MnsClient> _class, int port) {
mSupportedMessageTypes = smt;
mMnsClientClass = _class;
mRfcommPort = port;
}
}
public static final int MAX_INSTANCES = 2;
public static final int EMAIL_MAS_START = 1;
public static final int EMAIL_MAS_END = 1;
public static final MasInstanceInfo MAS_INS_INFO[] = new MasInstanceInfo[MAX_INSTANCES];
// The following information must match with corresponding
// SDP records supported message types and port number
// Please refer sdptool.c, BluetoothService.java, & init.qcom.rc
static {
MAS_INS_INFO[0] = new MasInstanceInfo(MESSAGE_TYPE_SMS_MMS, BluetoothMnsSmsMms.class, 16);
MAS_INS_INFO[1] = new MasInstanceInfo(MESSAGE_TYPE_EMAIL, BluetoothMnsEmail.class, 17);
}
private ContentObserver mEmailAccountObserver;
private void updateEmailAccount() {
if (VERBOSE) Log.v(TAG, "updateEmailAccount()");
List<Long> list = EmailUtils.getEmailAccountIdList(this);
ArrayList<Long> notAssigned = new ArrayList<Long>();
EmailUtils.removeMasIdIfNotPresent(list);
for (Long id : list) {
int masId = EmailUtils.getMasId(id);
if (masId == -1) {
notAssigned.add(id);
}
}
for (int i = EMAIL_MAS_START; i <= EMAIL_MAS_END; i ++) {
long accountId = EmailUtils.getAccountId(i);
if (accountId == -1 && notAssigned.size() > 0) {
EmailUtils.updateMapTable(notAssigned.remove(0), i);
}
}
}
public BluetoothMasService() {
mConnectionManager = new BluetoothMasObexConnectionManager();
mEmailAccountObserver = new ContentObserver(null) {
@Override
public void onChange(boolean selfChange) {
updateEmailAccount();
}
};
}
@Override
public void onCreate() {
super.onCreate();
if (VERBOSE)
Log.v(TAG, "Map Service onCreate");
mConnectionManager.init();
mAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mHasStarted) {
mHasStarted = true;
if (VERBOSE) Log.v(TAG, "Starting MAS instances");
int state = mAdapter.getState();
if (state == BluetoothAdapter.STATE_ON) {
mSessionStatusHandler.sendEmptyMessage(MSG_INTERNAL_START_LISTENER);
} else if (VERBOSE) {
Log.v(TAG, "BT is not ON, no start");
}
}
getContentResolver().registerContentObserver(
EmailUtils.EMAIL_ACCOUNT_URI, true, mEmailAccountObserver);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (VERBOSE)
Log.v(TAG, "Map Service onStartCommand");
int retCode = super.onStartCommand(intent, flags, startId);
if (retCode == START_STICKY) {
mStartId = startId;
if (mAdapter == null) {
Log.w(TAG, "Stopping BluetoothMasService: "
+ "device does not have BT or device is not ready");
// Release all resources
closeService();
} else {
// No need to handle the null intent case, because we have
// all restart work done in onCreate()
if (intent != null) {
parseIntent(intent);
}
}
}
return retCode;
}
// process the intent from receiver
private void parseIntent(final Intent intent) {
String action = intent.getStringExtra("action");
if (VERBOSE)
Log.v(TAG, "action: " + action);
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
boolean removeTimeoutMsg = true;
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
if (state == BluetoothAdapter.STATE_TURNING_OFF) {
// Release all resources
closeService();
} else {
removeTimeoutMsg = false;
}
} else if (action.equals(BluetoothDevice.ACTION_CONNECTION_ACCESS_REPLY)) {
if (intent.getIntExtra(BluetoothDevice.EXTRA_CONNECTION_ACCESS_RESULT,
BluetoothDevice.CONNECTION_ACCESS_NO) == BluetoothDevice.CONNECTION_ACCESS_YES) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (intent.getBooleanExtra(BluetoothDevice.EXTRA_ALWAYS_ALLOWED, false)) {
if (device != null) {
boolean result = device.setTrust(true);
if (VERBOSE) Log.v(TAG, "setTrust() result=" + result);
} else {
Log.e(TAG, "No BluetoothDevice from intent");
}
}
updateEmailAccount();
mConnectionManager.initiateObexServerSession(device);
} else {
mConnectionManager.stopObexServerSessionWaiting();
}
} else if (AUTH_RESPONSE_ACTION.equals(action)) {
String sessionkey = intent.getStringExtra(EXTRA_SESSION_KEY);
notifyAuthKeyInput(sessionkey);
} else if (AUTH_CANCELLED_ACTION.equals(action)) {
notifyAuthCancelled();
} else {
removeTimeoutMsg = false;
}
if (removeTimeoutMsg) {
mSessionStatusHandler.removeMessages(MSG_INTERNAL_USER_TIMEOUT);
if (VERBOSE) Log.v(TAG, "MAS access request notification flag off");
mIsRequestBeingNotified = false;
}
}
@Override
public void onDestroy() {
if (VERBOSE)
Log.v(TAG, "Map Service onDestroy");
super.onDestroy();
getContentResolver().unregisterContentObserver(mEmailAccountObserver);
EmailUtils.clearMapTable();
closeService();
}
private final void closeService() {
if (VERBOSE) Log.v(TAG, "MNS_BT: inside closeService");
try {
if(mnsClient!=null) {
if (VERBOSE) Log.v(TAG, "MNS_BT: about to send MNS_BLUETOOTH_OFF");
mnsClient.getHandler().sendEmptyMessage(BluetoothMns.MNS_BLUETOOTH_OFF);
mnsClient = null;
}
} catch (Exception e) {
Log.e(TAG, "MNS_BT: exception while sending MNS_BLUETOOTH_OFF");
} finally {
if (VERBOSE) Log.v(TAG, "MNS_BT: successfully sent MNS_BLUETOOTH_OFF");
mConnectionManager.closeAll();
mHasStarted = false;
if (stopSelfResult(mStartId)) {
if (VERBOSE) Log.v(TAG, "successfully stopped map service");
}
}
}
@Override
public IBinder onBind(Intent intent) {
if (VERBOSE) Log.v(TAG, "Map Service onBind");
return null;
}
private final Handler mSessionStatusHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (VERBOSE) Log.v(TAG, "Handler(): got msg=" + msg.what);
Context context = getApplicationContext();
if (mnsClient == null) {
mnsClient = new BluetoothMns(context);
}
switch (msg.what) {
case MSG_INTERNAL_START_LISTENER:
if (mAdapter.isEnabled()) {
mConnectionManager.startAll();
} else {
closeService();
}
break;
case MSG_INTERNAL_USER_TIMEOUT:
Intent intent = new Intent(BluetoothDevice.ACTION_CONNECTION_ACCESS_CANCEL);
intent.setClassName(ACCESS_AUTHORITY_PACKAGE, ACCESS_AUTHORITY_CLASS);
intent.putExtra(BluetoothDevice.EXTRA_ACCESS_REQUEST_TYPE,
BluetoothDevice.REQUEST_TYPE_MESSAGE_ACCESS);
sendBroadcast(intent);
removeMapNotification(NOTIFICATION_ID_ACCESS);
if (VERBOSE) Log.v(TAG, "MAS access request notification flag off");
mIsRequestBeingNotified = false;
mConnectionManager.stopObexServerSessionWaiting();
break;
case MSG_SERVERSESSION_CLOSE:
{
final int masId = msg.arg1;
mConnectionManager.stopObexServerSession(masId);
break;
}
case MSG_SESSION_ESTABLISHED:
break;
case MSG_SESSION_DISCONNECTED:
break;
default:
break;
}
}
};
private void createMapNotification(BluetoothDevice device) {
if (VERBOSE) Log.v(TAG, "Creating MAS access notification");
mIsRequestBeingNotified = true;
/*
NotificationManager nm = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
// Create an intent triggered by clicking on the status icon.
Intent clickIntent = new Intent();
clickIntent.setClass(this, BluetoothMasActivity.class);
clickIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
clickIntent.setAction(ACCESS_REQUEST_ACTION);
clickIntent.putExtra(EXTRA_BLUETOOTH_DEVICE, device);
// Create an intent triggered by clicking on the
// "Clear All Notifications" button
Intent deleteIntent = new Intent();
deleteIntent.setClass(this, BluetoothMasReceiver.class);
Notification notification = null;
String name = device.getName();
if (TextUtils.isEmpty(name)) {
name = getString(R.string.defaultname);
}
deleteIntent.setAction(ACCESS_DISALLOWED_ACTION);
notification = new Notification(android.R.drawable.stat_sys_data_bluetooth,
getString(R.string.map_notif_ticker), System.currentTimeMillis());
notification.setLatestEventInfo(this, getString(R.string.map_notif_title),
getString(R.string.map_notif_message, name), PendingIntent
.getActivity(this, 0, clickIntent, 0));
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
notification.defaults = Notification.DEFAULT_SOUND;
notification.deleteIntent = PendingIntent.getBroadcast(this, 0, deleteIntent, 0);
nm.notify(NOTIFICATION_ID_ACCESS, notification);
*/
Intent intent = new Intent(BluetoothDevice.ACTION_CONNECTION_ACCESS_REQUEST);
intent.setClassName(ACCESS_AUTHORITY_PACKAGE, ACCESS_AUTHORITY_CLASS);
intent.putExtra(BluetoothDevice.EXTRA_ACCESS_REQUEST_TYPE,
BluetoothDevice.REQUEST_TYPE_MESSAGE_ACCESS);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
intent.putExtra(BluetoothDevice.EXTRA_PACKAGE_NAME, getPackageName());
intent.putExtra(BluetoothDevice.EXTRA_CLASS_NAME,
BluetoothMasReceiver.class.getName());
sendBroadcast(intent, BLUETOOTH_ADMIN_PERM);
if (VERBOSE) Log.v(TAG, "Awaiting Authorization : MAS Connection : " + device.getName());
}
private void removeMapNotification(int id) {
Context context = getApplicationContext();
NotificationManager nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(id);
}
private void notifyAuthKeyInput(final String key) {
synchronized (mAuthSync) {
if (key != null) {
mAuth.setSessionKey(key);
}
mAuth.setChallenged(true);
mAuth.notify();
}
}
private void notifyAuthCancelled() {
synchronized (mAuthSync) {
mAuth.setCancelled(true);
mAuth.notify();
}
}
class BluetoothMasObexConnectionManager {
private ArrayList<BluetoothMasObexConnection> mConnections =
new ArrayList<BluetoothMasObexConnection>();
public BluetoothMasObexConnectionManager() {
for (int i = 0; i < MAX_INSTANCES; i ++) {
mConnections.add(new BluetoothMasObexConnection(
MAS_INS_INFO[i].mSupportedMessageTypes, i, MAS_INS_INFO[i].mRfcommPort));
}
}
public void initiateObexServerSession(BluetoothDevice device) {
try {
for (BluetoothMasObexConnection connection : mConnections) {
if (connection.mConnSocket != null && connection.mWaitingForConfirmation) {
connection.mWaitingForConfirmation = false;
connection.startObexServerSession(device, mnsClient);
}
}
} catch (IOException ex) {
Log.e(TAG, "Caught the error: " + ex.toString());
}
}
public void setWaitingForConfirmation(int masId) {
if (masId < mConnections.size()) {
final BluetoothMasObexConnection connect = mConnections.get(masId);
connect.mWaitingForConfirmation = true;
} else {
Log.e(TAG, "Attempt to set waiting for user confirmation for MAS id: " + masId);
Log.e(TAG, "out of index");
}
}
public void stopObexServerSession(int masId) {
if (masId < mConnections.size()) {
final BluetoothMasObexConnection connect = mConnections.get(masId);
if (connect.mConnSocket != null) {
connect.stopObexServerSession();
} else {
Log.w(TAG, "Attempt to stop OBEX Server session for MAS id: " + masId);
Log.w(TAG, "when there is no connected socket");
}
} else {
Log.e(TAG, "Attempt to stop OBEX Server session for MAS id: " + masId);
Log.e(TAG, "out of index");
}
}
public void stopObexServerSessionWaiting() {
for (BluetoothMasObexConnection connection : mConnections) {
if (connection.mConnSocket != null && connection.mWaitingForConfirmation) {
connection.mWaitingForConfirmation = false;
connection.stopObexServerSession();
}
}
}
public void stopObexServerSessionAll() {
for (BluetoothMasObexConnection connection : mConnections) {
if (connection.mConnSocket != null) {
connection.stopObexServerSession();
}
}
}
public void closeAll() {
for (BluetoothMasObexConnection connection : mConnections) {
// Stop the possible trying to init serverSocket
connection.mInterrupted = true;
connection.closeConnection();
}
}
public void startAll() {
for (BluetoothMasObexConnection connection : mConnections) {
connection.startRfcommSocketListener(mnsClient);
}
}
public void init() {
for (BluetoothMasObexConnection connection: mConnections) {
connection.mInterrupted = false;
}
}
public boolean isAllowedConnection(BluetoothDevice remoteDevice) {
String remoteAddress = remoteDevice.getAddress();
if (remoteAddress == null) {
if (VERBOSE) Log.v(TAG, "Connection request from unknown device");
return false;
}
final int size = mConnections.size();
for (int i = 0; i < size; i ++) {
final BluetoothMasObexConnection connection = mConnections.get(i);
BluetoothSocket socket = connection.mConnSocket;
if (socket != null) {
BluetoothDevice device = socket.getRemoteDevice();
if (device != null) {
String address = device.getAddress();
if (address != null) {
if (remoteAddress.equalsIgnoreCase(address)) {
if (VERBOSE) {
Log.v(TAG, "Connection request from " + remoteAddress);
Log.v(TAG, "when MAS id:" + i + " is connected to " + address);
}
return true;
} else {
if (VERBOSE) {
Log.v(TAG, "Connection request from " + remoteAddress);
Log.v(TAG, "when MAS id:" + i + " is connected to " + address);
}
return false;
}
} else {
// shall not happen, connected device must has address
// just for null pointer dereference
Log.w(TAG, "Connected device has no address!");
}
}
}
}
if (VERBOSE) {
Log.v(TAG, "Connection request from " + remoteAddress);
Log.v(TAG, "when no MAS instance is connected.");
}
return true;
}
}
private class BluetoothMasObexConnection {
private volatile boolean mInterrupted;
private BluetoothServerSocket mServerSocket = null;
private SocketAcceptThread mAcceptThread = null;
private BluetoothSocket mConnSocket = null;
private ServerSession mServerSession = null;
private PowerManager.WakeLock mWakeLock = null;
private BluetoothMasObexServer mMapServer = null;
private int mSupportedMessageTypes;
private int mPortNum;
private int mMasId;
boolean mWaitingForConfirmation = false;
public BluetoothMasObexConnection(int supportedMessageTypes, int masId, int portNumber) {
mSupportedMessageTypes = supportedMessageTypes;
mMasId = masId;
mPortNum = portNumber;
}
private void startRfcommSocketListener(BluetoothMns mnsClient) {
if (VERBOSE)
Log.v(TAG, "Map Service startRfcommSocketListener");
if (mServerSocket == null) {
if (!initSocket()) {
closeService();
return;
}
}
if (mAcceptThread == null) {
mAcceptThread = new SocketAcceptThread(mnsClient, mMasId);
mAcceptThread.setName("BluetoothMapAcceptThread " + mPortNum);
mAcceptThread.start();
}
}
private final boolean initSocket() {
if (VERBOSE)
Log.v(TAG, "Map Service initSocket");
boolean initSocketOK = false;
final int CREATE_RETRY_TIME = 10;
// It's possible that create will fail in some cases. retry for 10 times
for (int i = 0; i < CREATE_RETRY_TIME && !mInterrupted; i++) {
try {
mServerSocket = mAdapter.listenUsingRfcommOn(mPortNum);
initSocketOK = true;
} catch (IOException e) {
Log.e(TAG, "Error create RfcommServerSocket " + e.toString());
initSocketOK = false;
}
if (!initSocketOK) {
synchronized (this) {
try {
if (VERBOSE) Log.v(TAG, "wait 3 seconds");
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, "socketAcceptThread thread was interrupted (3)");
mInterrupted = true;
}
}
} else {
break;
}
}
if (initSocketOK) {
if (VERBOSE)
Log.v(TAG, "Succeed to create listening socket on channel "
+ mPortNum);
} else {
Log.e(TAG, "Error to create listening socket after "
+ CREATE_RETRY_TIME + " try");
}
return initSocketOK;
}
private final void closeSocket() throws IOException {
if (mConnSocket != null) {
mConnSocket.close();
mConnSocket = null;
}
}
public void closeConnection() {
if (VERBOSE) Log.v(TAG, "Mas connection closing");
// Release the wake lock if obex transaction is over
if (mWakeLock != null) {
if (mWakeLock.isHeld()) {
if (VERBOSE) Log.v(TAG,"Release full wake lock");
mWakeLock.release();
mWakeLock = null;
} else {
mWakeLock = null;
}
}
if (mAcceptThread != null) {
try {
mAcceptThread.shutdown();
mAcceptThread.join();
} catch (InterruptedException ex) {
Log.w(TAG, "mAcceptThread close error" + ex);
} finally {
mAcceptThread = null;
}
}
if (mServerSession != null) {
mServerSession.close();
mServerSession = null;
}
try {
closeSocket();
} catch (IOException ex) {
Log.e(TAG, "CloseSocket error: " + ex);
}
if (VERBOSE) Log.v(TAG, "Mas connection closed");
}
private final void startObexServerSession(BluetoothDevice device, BluetoothMns mnsClient)
throws IOException {
if (VERBOSE)
Log.v(TAG, "Map Service startObexServerSession ");
// acquire the wakeLock before start Obex transaction thread
if (mWakeLock == null) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"StartingObexMapTransaction");
mWakeLock.setReferenceCounted(false);
}
if(!mWakeLock.isHeld()) {
if (VERBOSE) Log.v(TAG,"Acquire partial wake lock");
mWakeLock.acquire();
}
Context context = getApplicationContext();
IBluetoothMasApp appIf = null;
if (((mSupportedMessageTypes & ~MESSAGE_TYPE_SMS_MMS) == 0x00) &&
((mSupportedMessageTypes & MESSAGE_TYPE_SMS) != 0x00) &&
((mSupportedMessageTypes & MESSAGE_TYPE_MMS) != 0x00)) {
// BluetoothMasAppZero if and only if both SMS and MMS
appIf = new BluetoothMasAppSmsMms(context, mSessionStatusHandler, mnsClient,
mMasId, device.getName());
} else if (((mSupportedMessageTypes & ~MESSAGE_TYPE_EMAIL) == 0x0) &&
((mSupportedMessageTypes & MESSAGE_TYPE_EMAIL) != 0x0)) {
// BluetoothMasAppOne if and only if email
appIf = new BluetoothMasAppEmail(context, mSessionStatusHandler, mnsClient,
mMasId, device.getName());
}
mMapServer = new BluetoothMasObexServer(mSessionStatusHandler,
device, context, appIf);
synchronized (mAuthSync) {
mAuth = new BluetoothMapAuthenticator(mSessionStatusHandler);
mAuth.setChallenged(false);
mAuth.setCancelled(false);
}
BluetoothMapRfcommTransport transport = new BluetoothMapRfcommTransport(
mConnSocket);
mServerSession = new ServerSession(transport, mMapServer, mAuth);
if (VERBOSE) Log.v(TAG, "startObexServerSession() success!");
}
private void stopObexServerSession() {
if (VERBOSE) Log.v(TAG, "Map Service stopObexServerSession ");
closeConnection();
// Last obex transaction is finished, we start to listen for incoming
// connection again
if (mAdapter.isEnabled()) {
startRfcommSocketListener(mnsClient);
}
}
/**
* A thread that runs in the background waiting for remote rfcomm
* connect.Once a remote socket connected, this thread shall be
* shutdown.When the remote disconnect,this thread shall run again waiting
* for next request.
*/
private class SocketAcceptThread extends Thread {
private boolean stopped = false;
private BluetoothMns mnsObj;
private int mMasId;
public SocketAcceptThread(BluetoothMns mnsClient, int masId) {
mnsObj = mnsClient;
mMasId = masId;
}
@Override
public void run() {
while (!stopped) {
try {
+ if (mServerSocket == null) {
+ break;
+ }
BluetoothSocket connSocket = mServerSocket.accept();
BluetoothDevice device = connSocket.getRemoteDevice();
if (device == null) {
Log.i(TAG, "getRemoteDevice() = null");
break;
}
String remoteDeviceName = device.getName();
// In case getRemoteName failed and return null
if (TextUtils.isEmpty(remoteDeviceName)) {
remoteDeviceName = getString(R.string.defaultname);
}
if (!mConnectionManager.isAllowedConnection(device)) {
connSocket.close();
continue;
}
mConnSocket = connSocket;
boolean trust = device.getTrustState();
if (VERBOSE) Log.v(TAG, "GetTrustState() = " + trust);
if (mIsRequestBeingNotified) {
if (VERBOSE) Log.v(TAG, "Request notification is still on going.");
mConnectionManager.setWaitingForConfirmation(mMasId);
break;
} else if (trust) {
if (VERBOSE) {
Log.v(TAG, "trust is true::");
Log.v(TAG, "incomming connection accepted from: "
+ remoteDeviceName + " automatically as trusted device");
}
try {
startObexServerSession(device, mnsObj);
} catch (IOException ex) {
Log.e(TAG, "catch exception starting obex server session"
+ ex.toString());
}
} else {
if (VERBOSE) Log.v(TAG, "trust is false.");
mConnectionManager.setWaitingForConfirmation(mMasId);
createMapNotification(device);
if (VERBOSE) Log.v(TAG, "incomming connection accepted from: "
+ remoteDeviceName);
mSessionStatusHandler.sendMessageDelayed(
mSessionStatusHandler.obtainMessage(MSG_INTERNAL_USER_TIMEOUT),
USER_CONFIRM_TIMEOUT_VALUE);
}
stopped = true; // job done ,close this thread;
} catch (IOException ex) {
if (stopped) {
break;
}
if (VERBOSE)
Log.v(TAG, "Accept exception: " + ex.toString());
}
}
}
void shutdown() {
if (VERBOSE) Log.v(TAG, "AcceptThread shutdown for MAS id: " + mMasId);
stopped = true;
interrupt();
if (mServerSocket != null) {
try {
mServerSocket.close();
mServerSocket = null;
} catch (IOException e) {
Log.e(TAG, "Failed to close socket", e);
}
}
}
}
}
};
| true | true |
public void run() {
while (!stopped) {
try {
BluetoothSocket connSocket = mServerSocket.accept();
BluetoothDevice device = connSocket.getRemoteDevice();
if (device == null) {
Log.i(TAG, "getRemoteDevice() = null");
break;
}
String remoteDeviceName = device.getName();
// In case getRemoteName failed and return null
if (TextUtils.isEmpty(remoteDeviceName)) {
remoteDeviceName = getString(R.string.defaultname);
}
if (!mConnectionManager.isAllowedConnection(device)) {
connSocket.close();
continue;
}
mConnSocket = connSocket;
boolean trust = device.getTrustState();
if (VERBOSE) Log.v(TAG, "GetTrustState() = " + trust);
if (mIsRequestBeingNotified) {
if (VERBOSE) Log.v(TAG, "Request notification is still on going.");
mConnectionManager.setWaitingForConfirmation(mMasId);
break;
} else if (trust) {
if (VERBOSE) {
Log.v(TAG, "trust is true::");
Log.v(TAG, "incomming connection accepted from: "
+ remoteDeviceName + " automatically as trusted device");
}
try {
startObexServerSession(device, mnsObj);
} catch (IOException ex) {
Log.e(TAG, "catch exception starting obex server session"
+ ex.toString());
}
} else {
if (VERBOSE) Log.v(TAG, "trust is false.");
mConnectionManager.setWaitingForConfirmation(mMasId);
createMapNotification(device);
if (VERBOSE) Log.v(TAG, "incomming connection accepted from: "
+ remoteDeviceName);
mSessionStatusHandler.sendMessageDelayed(
mSessionStatusHandler.obtainMessage(MSG_INTERNAL_USER_TIMEOUT),
USER_CONFIRM_TIMEOUT_VALUE);
}
stopped = true; // job done ,close this thread;
} catch (IOException ex) {
if (stopped) {
break;
}
if (VERBOSE)
Log.v(TAG, "Accept exception: " + ex.toString());
}
}
}
|
public void run() {
while (!stopped) {
try {
if (mServerSocket == null) {
break;
}
BluetoothSocket connSocket = mServerSocket.accept();
BluetoothDevice device = connSocket.getRemoteDevice();
if (device == null) {
Log.i(TAG, "getRemoteDevice() = null");
break;
}
String remoteDeviceName = device.getName();
// In case getRemoteName failed and return null
if (TextUtils.isEmpty(remoteDeviceName)) {
remoteDeviceName = getString(R.string.defaultname);
}
if (!mConnectionManager.isAllowedConnection(device)) {
connSocket.close();
continue;
}
mConnSocket = connSocket;
boolean trust = device.getTrustState();
if (VERBOSE) Log.v(TAG, "GetTrustState() = " + trust);
if (mIsRequestBeingNotified) {
if (VERBOSE) Log.v(TAG, "Request notification is still on going.");
mConnectionManager.setWaitingForConfirmation(mMasId);
break;
} else if (trust) {
if (VERBOSE) {
Log.v(TAG, "trust is true::");
Log.v(TAG, "incomming connection accepted from: "
+ remoteDeviceName + " automatically as trusted device");
}
try {
startObexServerSession(device, mnsObj);
} catch (IOException ex) {
Log.e(TAG, "catch exception starting obex server session"
+ ex.toString());
}
} else {
if (VERBOSE) Log.v(TAG, "trust is false.");
mConnectionManager.setWaitingForConfirmation(mMasId);
createMapNotification(device);
if (VERBOSE) Log.v(TAG, "incomming connection accepted from: "
+ remoteDeviceName);
mSessionStatusHandler.sendMessageDelayed(
mSessionStatusHandler.obtainMessage(MSG_INTERNAL_USER_TIMEOUT),
USER_CONFIRM_TIMEOUT_VALUE);
}
stopped = true; // job done ,close this thread;
} catch (IOException ex) {
if (stopped) {
break;
}
if (VERBOSE)
Log.v(TAG, "Accept exception: " + ex.toString());
}
}
}
|
diff --git a/core/src/processing/core/PApplet.java b/core/src/processing/core/PApplet.java
index 9ff9ac230..522a3e400 100644
--- a/core/src/processing/core/PApplet.java
+++ b/core/src/processing/core/PApplet.java
@@ -1,8004 +1,8013 @@
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-08 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
import java.util.zip.*;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
/**
* Base class for all sketches that use processing.core.
* <p/>
* Note that you should not use AWT or Swing components inside a Processing
* applet. The surface is made to automatically update itself, and will cause
* problems with redraw of components drawn above it. If you'd like to
* integrate other Java components, see below.
* <p/>
* As of release 0145, Processing uses active mode rendering in all cases.
* All animation tasks happen on the "Processing Animation Thread". The
* setup() and draw() methods are handled by that thread, and events (like
* mouse movement and key presses, which are fired by the event dispatch
* thread or EDT) are queued to be (safely) handled at the end of draw().
* For code that needs to run on the EDT, use SwingUtilities.invokeLater().
* When doing so, be careful to synchronize between that code (since
* invokeLater() will make your code run from the EDT) and the Processing
* animation thread. Use of a callback function or the registerXxx() methods
* in PApplet can help ensure that your code doesn't do something naughty.
* <p/>
* As of release 0136 of Processing, we have discontinued support for versions
* of Java prior to 1.5. We don't have enough people to support it, and for a
* project of our size, we should be focusing on the future, rather than
* working around legacy Java code. In addition, Java 1.5 gives us access to
* better timing facilities which will improve the steadiness of animation.
* <p/>
* This class extends Applet instead of JApplet because 1) historically,
* we supported Java 1.1, which does not include Swing (without an
* additional, sizable, download), and 2) Swing is a bloated piece of crap.
* A Processing applet is a heavyweight AWT component, and can be used the
* same as any other AWT component, with or without Swing.
* <p/>
* Similarly, Processing runs in a Frame and not a JFrame. However, there's
* nothing to prevent you from embedding a PApplet into a JFrame, it's just
* that the base version uses a regular AWT frame because there's simply
* no need for swing in that context. If people want to use Swing, they can
* embed themselves as they wish.
* <p/>
* It is possible to use PApplet, along with core.jar in other projects.
* In addition to enabling you to use Java 1.5+ features with your sketch,
* this also allows you to embed a Processing drawing area into another Java
* application. This means you can use standard GUI controls with a Processing
* sketch. Because AWT and Swing GUI components cannot be used on top of a
* PApplet, you can instead embed the PApplet inside another GUI the way you
* would any other Component.
* <p/>
* It is also possible to resize the Processing window by including
* <tt>frame.setResizable(true)</tt> inside your <tt>setup()</tt> method.
* Note that the Java method <tt>frame.setSize()</tt> will not work unless
* you first set the frame to be resizable.
* <p/>
* Because the default animation thread will run at 60 frames per second,
* an embedded PApplet can make the parent sluggish. You can use frameRate()
* to make it update less often, or you can use noLoop() and loop() to disable
* and then re-enable looping. If you want to only update the sketch
* intermittently, use noLoop() inside setup(), and redraw() whenever
* the screen needs to be updated once (or loop() to re-enable the animation
* thread). The following example embeds a sketch and also uses the noLoop()
* and redraw() methods. You need not use noLoop() and redraw() when embedding
* if you want your application to animate continuously.
* <PRE>
* public class ExampleFrame extends Frame {
*
* public ExampleFrame() {
* super("Embedded PApplet");
*
* setLayout(new BorderLayout());
* PApplet embed = new Embedded();
* add(embed, BorderLayout.CENTER);
*
* // important to call this whenever embedding a PApplet.
* // It ensures that the animation thread is started and
* // that other internal variables are properly set.
* embed.init();
* }
* }
*
* public class Embedded extends PApplet {
*
* public void setup() {
* // original setup code here ...
* size(400, 400);
*
* // prevent thread from starving everything else
* noLoop();
* }
*
* public void draw() {
* // drawing code goes here
* }
*
* public void mousePressed() {
* // do something based on mouse movement
*
* // update the screen (run draw once)
* redraw();
* }
* }
* </PRE>
*
* <H2>Processing on multiple displays</H2>
* <P>I was asked about Processing with multiple displays, and for lack of a
* better place to document it, things will go here.</P>
* <P>You can address both screens by making a window the width of both,
* and the height of the maximum of both screens. In this case, do not use
* present mode, because that's exclusive to one screen. Basically it'll
* give you a PApplet that spans both screens. If using one half to control
* and the other half for graphics, you'd just have to put the 'live' stuff
* on one half of the canvas, the control stuff on the other. This works
* better in windows because on the mac we can't get rid of the menu bar
* unless it's running in present mode.</P>
* <P>For more control, you need to write straight java code that uses p5.
* You can create two windows, that are shown on two separate screens,
* that have their own PApplet. this is just one of the tradeoffs of one of
* the things that we don't support in p5 from within the environment
* itself (we must draw the line somewhere), because of how messy it would
* get to start talking about multiple screens. It's also not that tough to
* do by hand w/ some Java code.</P>
*/
public class PApplet extends Applet
implements PConstants, Runnable,
MouseListener, MouseMotionListener, KeyListener, FocusListener
{
/**
* Full name of the Java version (i.e. 1.5.0_11).
* Prior to 0125, this was only the first three digits.
*/
public static final String javaVersionName =
System.getProperty("java.version");
/**
* Version of Java that's in use, whether 1.1 or 1.3 or whatever,
* stored as a float.
* <P>
* Note that because this is stored as a float, the values may
* not be <EM>exactly</EM> 1.3 or 1.4. Instead, make sure you're
* comparing against 1.3f or 1.4f, which will have the same amount
* of error (i.e. 1.40000001). This could just be a double, but
* since Processing only uses floats, it's safer for this to be a float
* because there's no good way to specify a double with the preproc.
*/
public static final float javaVersion =
new Float(javaVersionName.substring(0, 3)).floatValue();
/**
* Current platform in use.
* <P>
* Equivalent to System.getProperty("os.name"), just used internally.
*/
/**
* Current platform in use, one of the
* PConstants WINDOWS, MACOSX, MACOS9, LINUX or OTHER.
*/
static public int platform;
/**
* Name associated with the current 'platform' (see PConstants.platformNames)
*/
//static public String platformName;
static {
String osname = System.getProperty("os.name");
if (osname.indexOf("Mac") != -1) {
platform = MACOSX;
} else if (osname.indexOf("Windows") != -1) {
platform = WINDOWS;
} else if (osname.equals("Linux")) { // true for the ibm vm
platform = LINUX;
} else {
platform = OTHER;
}
}
/**
* Modifier flags for the shortcut key used to trigger menus.
* (Cmd on Mac OS X, Ctrl on Linux and Windows)
*/
static public final int MENU_SHORTCUT =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/** The PGraphics renderer associated with this PApplet */
public PGraphics g;
//protected Object glock = new Object(); // for sync
/** The frame containing this applet (if any) */
public Frame frame;
/**
* The screen size when the applet was started.
* <P>
* Access this via screen.width and screen.height. To make an applet
* run at full screen, use size(screen.width, screen.height).
* <P>
* If you have multiple displays, this will be the size of the main
* display. Running full screen across multiple displays isn't
* particularly supported, and requires more monkeying with the values.
* This probably can't/won't be fixed until/unless I get a dual head
* system.
* <P>
* Note that this won't update if you change the resolution
* of your screen once the the applet is running.
* <p>
* This variable is not static, because future releases need to be better
* at handling multiple displays.
*/
public Dimension screen =
Toolkit.getDefaultToolkit().getScreenSize();
/**
* A leech graphics object that is echoing all events.
*/
public PGraphics recorder;
/**
* Command line options passed in from main().
* <P>
* This does not include the arguments passed in to PApplet itself.
*/
public String args[];
/** Path to sketch folder */
public String sketchPath; //folder;
/** When debugging headaches */
static final boolean THREAD_DEBUG = false;
/** Default width and height for applet when not specified */
static public final int DEFAULT_WIDTH = 100;
static public final int DEFAULT_HEIGHT = 100;
/**
* Minimum dimensions for the window holding an applet.
* This varies between platforms, Mac OS X 10.3 can do any height
* but requires at least 128 pixels width. Windows XP has another
* set of limitations. And for all I know, Linux probably lets you
* make windows with negative sizes.
*/
static public final int MIN_WINDOW_WIDTH = 128;
static public final int MIN_WINDOW_HEIGHT = 128;
/**
* Exception thrown when size() is called the first time.
* <P>
* This is used internally so that setup() is forced to run twice
* when the renderer is changed. This is the only way for us to handle
* invoking the new renderer while also in the midst of rendering.
*/
static public class RendererChangeException extends RuntimeException { }
/**
* true if no size() command has been executed. This is used to wait until
* a size has been set before placing in the window and showing it.
*/
public boolean defaultSize;
volatile boolean resizeRequest;
volatile int resizeWidth;
volatile int resizeHeight;
/**
* Pixel buffer from this applet's PGraphics.
* <P>
* When used with OpenGL or Java2D, this value will
* be null until loadPixels() has been called.
*/
public int pixels[];
/** width of this applet's associated PGraphics */
public int width;
/** height of this applet's associated PGraphics */
public int height;
/** current x position of the mouse */
public int mouseX;
/** current y position of the mouse */
public int mouseY;
/**
* Previous x/y position of the mouse. This will be a different value
* when inside a mouse handler (like the mouseMoved() method) versus
* when inside draw(). Inside draw(), pmouseX is updated once each
* frame, but inside mousePressed() and friends, it's updated each time
* an event comes through. Be sure to use only one or the other type of
* means for tracking pmouseX and pmouseY within your sketch, otherwise
* you're gonna run into trouble.
*/
public int pmouseX, pmouseY;
/**
* previous mouseX/Y for the draw loop, separated out because this is
* separate from the pmouseX/Y when inside the mouse event handlers.
*/
protected int dmouseX, dmouseY;
/**
* pmouseX/Y for the event handlers (mousePressed(), mouseDragged() etc)
* these are different because mouse events are queued to the end of
* draw, so the previous position has to be updated on each event,
* as opposed to the pmouseX/Y that's used inside draw, which is expected
* to be updated once per trip through draw().
*/
protected int emouseX, emouseY;
/**
* Used to set pmouseX/Y to mouseX/Y the first time mouseX/Y are used,
* otherwise pmouseX/Y are always zero, causing a nasty jump.
* <P>
* Just using (frameCount == 0) won't work since mouseXxxxx()
* may not be called until a couple frames into things.
*/
public boolean firstMouse;
/**
* Last mouse button pressed, one of LEFT, CENTER, or RIGHT.
* <P>
* If running on Mac OS, a ctrl-click will be interpreted as
* the righthand mouse button (unlike Java, which reports it as
* the left mouse).
*/
public int mouseButton;
public boolean mousePressed;
public MouseEvent mouseEvent;
/**
* Last key pressed.
* <P>
* If it's a coded key, i.e. UP/DOWN/CTRL/SHIFT/ALT,
* this will be set to CODED (0xffff or 65535).
*/
public char key;
/**
* When "key" is set to CODED, this will contain a Java key code.
* <P>
* For the arrow keys, keyCode will be one of UP, DOWN, LEFT and RIGHT.
* Also available are ALT, CONTROL and SHIFT. A full set of constants
* can be obtained from java.awt.event.KeyEvent, from the VK_XXXX variables.
*/
public int keyCode;
/**
* true if the mouse is currently pressed.
*/
public boolean keyPressed;
/**
* the last KeyEvent object passed into a mouse function.
*/
public KeyEvent keyEvent;
/**
* Gets set to true/false as the applet gains/loses focus.
*/
public boolean focused = false;
/**
* true if the applet is online.
* <P>
* This can be used to test how the applet should behave
* since online situations are different (no file writing, etc).
*/
public boolean online = false;
/**
* Time in milliseconds when the applet was started.
* <P>
* Used by the millis() function.
*/
long millisOffset;
/**
* The current value of frames per second.
* <P>
* The initial value will be 10 fps, and will be updated with each
* frame thereafter. The value is not instantaneous (since that
* wouldn't be very useful since it would jump around so much),
* but is instead averaged (integrated) over several frames.
* As such, this value won't be valid until after 5-10 frames.
*/
public float frameRate = 10;
/** Last time in nanoseconds that frameRate was checked */
protected long frameRateLastNanos = 0;
/** As of release 0116, frameRate(60) is called as a default */
protected float frameRateTarget = 60;
protected long frameRatePeriod = 1000000000L / 60L;
protected boolean looping;
/** flag set to true when a redraw is asked for by the user */
protected boolean redraw;
/**
* How many frames have been displayed since the applet started.
* <P>
* This value is read-only <EM>do not</EM> attempt to set it,
* otherwise bad things will happen.
* <P>
* Inside setup(), frameCount is 0.
* For the first iteration of draw(), frameCount will equal 1.
*/
public int frameCount;
/**
* true if this applet has had it.
*/
public boolean finished;
/**
* true if exit() has been called so that things shut down
* once the main thread kicks off.
*/
protected boolean exitCalled;
Thread thread;
protected RegisteredMethods sizeMethods;
protected RegisteredMethods preMethods, drawMethods, postMethods;
protected RegisteredMethods mouseEventMethods, keyEventMethods;
protected RegisteredMethods disposeMethods;
// messages to send if attached as an external vm
/**
* Position of the upper-lefthand corner of the editor window
* that launched this applet.
*/
static public final String ARGS_EDITOR_LOCATION = "--editor-location";
/**
* Location for where to position the applet window on screen.
* <P>
* This is used by the editor to when saving the previous applet
* location, or could be used by other classes to launch at a
* specific position on-screen.
*/
static public final String ARGS_EXTERNAL = "--external";
static public final String ARGS_LOCATION = "--location";
static public final String ARGS_DISPLAY = "--display";
static public final String ARGS_BGCOLOR = "--bgcolor";
static public final String ARGS_PRESENT = "--present";
static public final String ARGS_STOP_COLOR = "--stop-color";
static public final String ARGS_HIDE_STOP = "--hide-stop";
/**
* Allows the user or PdeEditor to set a specific sketch folder path.
* <P>
* Used by PdeEditor to pass in the location where saveFrame()
* and all that stuff should write things.
*/
static public final String ARGS_SKETCH_FOLDER = "--sketch-path";
/**
* When run externally to a PdeEditor,
* this is sent by the applet when it quits.
*/
//static public final String EXTERNAL_QUIT = "__QUIT__";
static public final String EXTERNAL_STOP = "__STOP__";
/**
* When run externally to a PDE Editor, this is sent by the applet
* whenever the window is moved.
* <P>
* This is used so that the editor can re-open the sketch window
* in the same position as the user last left it.
*/
static public final String EXTERNAL_MOVE = "__MOVE__";
/** true if this sketch is being run by the PDE */
boolean external = false;
static final String ERROR_MIN_MAX =
"Cannot use min() or max() on an empty array.";
// during rev 0100 dev cycle, working on new threading model,
// but need to disable and go conservative with changes in order
// to get pdf and audio working properly first.
// for 0116, the CRUSTY_THREADS are being disabled to fix lots of bugs.
//static final boolean CRUSTY_THREADS = false; //true;
public void init() {
// println("Calling init()");
// send tab keys through to the PApplet
setFocusTraversalKeysEnabled(false);
millisOffset = System.currentTimeMillis();
finished = false; // just for clarity
// this will be cleared by draw() if it is not overridden
looping = true;
redraw = true; // draw this guy once
firstMouse = true;
// these need to be inited before setup
sizeMethods = new RegisteredMethods();
preMethods = new RegisteredMethods();
drawMethods = new RegisteredMethods();
postMethods = new RegisteredMethods();
mouseEventMethods = new RegisteredMethods();
keyEventMethods = new RegisteredMethods();
disposeMethods = new RegisteredMethods();
try {
getAppletContext();
online = true;
} catch (NullPointerException e) {
online = false;
}
try {
if (sketchPath == null) {
sketchPath = System.getProperty("user.dir");
}
} catch (Exception e) { } // may be a security problem
Dimension size = getSize();
if ((size.width != 0) && (size.height != 0)) {
// When this PApplet is embedded inside a Java application with other
// Component objects, its size() may already be set externally (perhaps
// by a LayoutManager). In this case, honor that size as the default.
// Size of the component is set, just create a renderer.
g = makeGraphics(size.width, size.height, JAVA2D, null, true);
// This doesn't call setSize() or setPreferredSize() because the fact
// that a size was already set means that someone is already doing it.
} else {
// Set the default size, until the user specifies otherwise
this.defaultSize = true;
g = makeGraphics(DEFAULT_WIDTH, DEFAULT_HEIGHT, JAVA2D, null, true);
// Fire component resize event
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
}
width = g.width;
height = g.height;
addListeners();
// this is automatically called in applets
// though it's here for applications anyway
start();
}
/**
* Called by the browser or applet viewer to inform this applet that it
* should start its execution. It is called after the init method and
* each time the applet is revisited in a Web page.
* <p/>
* Called explicitly via the first call to PApplet.paint(), because
* PAppletGL needs to have a usable screen before getting things rolling.
*/
public void start() {
// When running inside a browser, start() will be called when someone
// returns to a page containing this applet.
// http://dev.processing.org/bugs/show_bug.cgi?id=581
finished = false;
if (thread != null) return;
thread = new Thread(this, "Animation Thread");
thread.start();
}
/**
* Called by the browser or applet viewer to inform
* this applet that it should stop its execution.
* <p/>
* Unfortunately, there are no guarantees from the Java spec
* when or if stop() will be called (i.e. on browser quit,
* or when moving between web pages), and it's not always called.
*/
public void stop() {
// bringing this back for 0111, hoping it'll help opengl shutdown
finished = true; // why did i comment this out?
// don't run stop and disposers twice
if (thread == null) return;
thread = null;
// call to shut down renderer, in case it needs it (pdf does)
if (g != null) g.dispose();
// maybe this should be done earlier? might help ensure it gets called
// before the vm just craps out since 1.5 craps out so aggressively.
disposeMethods.handle();
}
/**
* Called by the browser or applet viewer to inform this applet
* that it is being reclaimed and that it should destroy
* any resources that it has allocated.
* <p/>
* This also attempts to call PApplet.stop(), in case there
* was an inadvertent override of the stop() function by a user.
* <p/>
* destroy() supposedly gets called as the applet viewer
* is shutting down the applet. stop() is called
* first, and then destroy() to really get rid of things.
* no guarantees on when they're run (on browser quit, or
* when moving between pages), though.
*/
public void destroy() {
((PApplet)this).stop();
}
/**
* This returns the last width and height specified by the user
* via the size() command.
*/
// public Dimension getPreferredSize() {
// return new Dimension(width, height);
// }
// public void addNotify() {
// super.addNotify();
// println("addNotify()");
// }
//////////////////////////////////////////////////////////////
public class RegisteredMethods {
int count;
Object objects[];
Method methods[];
// convenience version for no args
public void handle() {
handle(new Object[] { });
}
public void handle(Object oargs[]) {
for (int i = 0; i < count; i++) {
try {
//System.out.println(objects[i] + " " + args);
methods[i].invoke(objects[i], oargs);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void add(Object object, Method method) {
if (objects == null) {
objects = new Object[5];
methods = new Method[5];
}
if (count == objects.length) {
objects = (Object[]) PApplet.expand(objects);
methods = (Method[]) PApplet.expand(methods);
// Object otemp[] = new Object[count << 1];
// System.arraycopy(objects, 0, otemp, 0, count);
// objects = otemp;
// Method mtemp[] = new Method[count << 1];
// System.arraycopy(methods, 0, mtemp, 0, count);
// methods = mtemp;
}
objects[count] = object;
methods[count] = method;
count++;
}
/**
* Removes first object/method pair matched (and only the first,
* must be called multiple times if object is registered multiple times).
* Does not shrink array afterwards, silently returns if method not found.
*/
public void remove(Object object, Method method) {
int index = findIndex(object, method);
if (index != -1) {
// shift remaining methods by one to preserve ordering
count--;
for (int i = index; i < count; i++) {
objects[i] = objects[i+1];
methods[i] = methods[i+1];
}
// clean things out for the gc's sake
objects[count] = null;
methods[count] = null;
}
}
protected int findIndex(Object object, Method method) {
for (int i = 0; i < count; i++) {
if (objects[i] == object && methods[i].equals(method)) {
//objects[i].equals() might be overridden, so use == for safety
// since here we do care about actual object identity
//methods[i]==method is never true even for same method, so must use
// equals(), this should be safe because of object identity
return i;
}
}
return -1;
}
}
public void registerSize(Object o) {
Class<?> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE };
registerWithArgs(sizeMethods, "size", o, methodArgs);
}
public void registerPre(Object o) {
registerNoArgs(preMethods, "pre", o);
}
public void registerDraw(Object o) {
registerNoArgs(drawMethods, "draw", o);
}
public void registerPost(Object o) {
registerNoArgs(postMethods, "post", o);
}
public void registerMouseEvent(Object o) {
Class<?> methodArgs[] = new Class[] { MouseEvent.class };
registerWithArgs(mouseEventMethods, "mouseEvent", o, methodArgs);
}
public void registerKeyEvent(Object o) {
Class<?> methodArgs[] = new Class[] { KeyEvent.class };
registerWithArgs(keyEventMethods, "keyEvent", o, methodArgs);
}
public void registerDispose(Object o) {
registerNoArgs(disposeMethods, "dispose", o);
}
protected void registerNoArgs(RegisteredMethods meth,
String name, Object o) {
Class<?> c = o.getClass();
try {
Method method = c.getMethod(name, new Class[] {});
meth.add(o, method);
} catch (NoSuchMethodException nsme) {
die("There is no " + name + "() method in the class " +
o.getClass().getName());
} catch (Exception e) {
die("Could not register " + name + " + () for " + o, e);
}
}
protected void registerWithArgs(RegisteredMethods meth,
String name, Object o, Class<?> cargs[]) {
Class<?> c = o.getClass();
try {
Method method = c.getMethod(name, cargs);
meth.add(o, method);
} catch (NoSuchMethodException nsme) {
die("There is no " + name + "() method in the class " +
o.getClass().getName());
} catch (Exception e) {
die("Could not register " + name + " + () for " + o, e);
}
}
public void unregisterSize(Object o) {
Class<?> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE };
unregisterWithArgs(sizeMethods, "size", o, methodArgs);
}
public void unregisterPre(Object o) {
unregisterNoArgs(preMethods, "pre", o);
}
public void unregisterDraw(Object o) {
unregisterNoArgs(drawMethods, "draw", o);
}
public void unregisterPost(Object o) {
unregisterNoArgs(postMethods, "post", o);
}
public void unregisterMouseEvent(Object o) {
Class<?> methodArgs[] = new Class[] { MouseEvent.class };
unregisterWithArgs(mouseEventMethods, "mouseEvent", o, methodArgs);
}
public void unregisterKeyEvent(Object o) {
Class<?> methodArgs[] = new Class[] { KeyEvent.class };
unregisterWithArgs(keyEventMethods, "keyEvent", o, methodArgs);
}
public void unregisterDispose(Object o) {
unregisterNoArgs(disposeMethods, "dispose", o);
}
protected void unregisterNoArgs(RegisteredMethods meth,
String name, Object o) {
Class<?> c = o.getClass();
try {
Method method = c.getMethod(name, new Class[] {});
meth.remove(o, method);
} catch (Exception e) {
die("Could not unregister " + name + "() for " + o, e);
}
}
protected void unregisterWithArgs(RegisteredMethods meth,
String name, Object o, Class<?> cargs[]) {
Class<?> c = o.getClass();
try {
Method method = c.getMethod(name, cargs);
meth.remove(o, method);
} catch (Exception e) {
die("Could not unregister " + name + "() for " + o, e);
}
}
//////////////////////////////////////////////////////////////
public void setup() {
}
public void draw() {
// if no draw method, then shut things down
//System.out.println("no draw method, goodbye");
finished = true;
}
//////////////////////////////////////////////////////////////
protected void resizeRenderer(int iwidth, int iheight) {
// println("resizeRenderer request for " + iwidth + " " + iheight);
if (width != iwidth || height != iheight) {
// println(" former size was " + width + " " + height);
g.setSize(iwidth, iheight);
width = iwidth;
height = iheight;
}
}
/**
* Starts up and creates a two-dimensional drawing surface,
* or resizes the current drawing surface.
* <P>
* This should be the first thing called inside of setup().
* <P>
* If using Java 1.3 or later, this will default to using
* PGraphics2, the Java2D-based renderer. If using Java 1.1,
* or if PGraphics2 is not available, then PGraphics will be used.
* To set your own renderer, use the other version of the size()
* method that takes a renderer as its last parameter.
* <P>
* If called once a renderer has already been set, this will
* use the previous renderer and simply resize it.
*/
public void size(int iwidth, int iheight) {
size(iwidth, iheight, JAVA2D, null);
}
public void size(int iwidth, int iheight, String irenderer) {
size(iwidth, iheight, irenderer, null);
}
/**
* Creates a new PGraphics object and sets it to the specified size.
*
* Note that you cannot change the renderer once outside of setup().
* In most cases, you can call size() to give it a new size,
* but you need to always ask for the same renderer, otherwise
* you're gonna run into trouble.
*
* The size() method should *only* be called from inside the setup() or
* draw() methods, so that it is properly run on the main animation thread.
* To change the size of a PApplet externally, use setSize(), which will
* update the component size, and queue a resize of the renderer as well.
*/
public void size(final int iwidth, final int iheight,
String irenderer, String ipath) {
// Run this from the EDT, just cuz it's AWT stuff (or maybe later Swing)
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Set the preferred size so that the layout managers can handle it
setPreferredSize(new Dimension(iwidth, iheight));
setSize(iwidth, iheight);
}
});
// ensure that this is an absolute path
if (ipath != null) ipath = savePath(ipath);
String currentRenderer = g.getClass().getName();
if (currentRenderer.equals(irenderer)) {
// Avoid infinite loop of throwing exception to reset renderer
resizeRenderer(iwidth, iheight);
//redraw(); // will only be called insize draw()
} else { // renderer is being changed
// otherwise ok to fall through and create renderer below
// the renderer is changing, so need to create a new object
g = makeGraphics(iwidth, iheight, irenderer, ipath, true);
width = iwidth;
height = iheight;
// fire resize event to make sure the applet is the proper size
// setSize(iwidth, iheight);
// this is the function that will run if the user does their own
// size() command inside setup, so set defaultSize to false.
defaultSize = false;
// throw an exception so that setup() is called again
// but with a properly sized render
// this is for opengl, which needs a valid, properly sized
// display before calling anything inside setup().
throw new RendererChangeException();
}
}
/**
* Create an offscreen PGraphics object for drawing. This can be used
* for bitmap or vector images drawing or rendering.
* <UL>
* <LI>Do not use "new PGraphicsXxxx()", use this method. This method
* ensures that internal variables are set up properly that tie the
* new graphics context back to its parent PApplet.
* <LI>The basic way to create bitmap images is to use the <A
* HREF="http://processing.org/reference/saveFrame_.html">saveFrame()</A>
* function.
* <LI>If you want to create a really large scene and write that,
* first make sure that you've allocated a lot of memory in the Preferences.
* <LI>If you want to create images that are larger than the screen,
* you should create your own PGraphics object, draw to that, and use
* <A HREF="http://processing.org/reference/save_.html">save()</A>.
* For now, it's best to use <A HREF="http://dev.processing.org/reference/everything/javadoc/processing/core/PGraphics3D.html">P3D</A> in this scenario.
* P2D is currently disabled, and the JAVA2D default will give mixed
* results. An example of using P3D:
* <PRE>
*
* PGraphics big;
*
* void setup() {
* big = createGraphics(3000, 3000, P3D);
*
* big.beginDraw();
* big.background(128);
* big.line(20, 1800, 1800, 900);
* // etc..
* big.endDraw();
*
* // make sure the file is written to the sketch folder
* big.save("big.tif");
* }
*
* </PRE>
* <LI>It's important to always wrap drawing to createGraphics() with
* beginDraw() and endDraw() (beginFrame() and endFrame() prior to
* revision 0115). The reason is that the renderer needs to know when
* drawing has stopped, so that it can update itself internally.
* This also handles calling the defaults() method, for people familiar
* with that.
* <LI>It's not possible to use createGraphics() with the OPENGL renderer,
* because it doesn't allow offscreen use.
* <LI>With Processing 0115 and later, it's possible to write images in
* formats other than the default .tga and .tiff. The exact formats and
* background information can be found in the developer's reference for
* <A HREF="http://dev.processing.org/reference/core/javadoc/processing/core/PImage.html#save(java.lang.String)">PImage.save()</A>.
* </UL>
*/
public PGraphics createGraphics(int iwidth, int iheight,
String irenderer) {
PGraphics pg = makeGraphics(iwidth, iheight, irenderer, null, false);
//pg.parent = this; // make save() work
return pg;
}
/**
* Create an offscreen graphics surface for drawing, in this case
* for a renderer that writes to a file (such as PDF or DXF).
* @param ipath can be an absolute or relative path
*/
public PGraphics createGraphics(int iwidth, int iheight,
String irenderer, String ipath) {
if (ipath != null) {
ipath = savePath(ipath);
}
PGraphics pg = makeGraphics(iwidth, iheight, irenderer, ipath, false);
pg.parent = this; // make save() work
return pg;
}
/**
* Version of createGraphics() used internally.
*
* @param ipath must be an absolute path, usually set via savePath()
* @oaram applet the parent applet object, this should only be non-null
* in cases where this is the main drawing surface object.
*/
protected PGraphics makeGraphics(int iwidth, int iheight,
String irenderer, String ipath,
boolean iprimary) {
if (irenderer.equals(OPENGL)) {
if (PApplet.platform == WINDOWS) {
String s = System.getProperty("java.version");
if (s != null) {
if (s.equals("1.5.0_10")) {
System.err.println("OpenGL support is broken with Java 1.5.0_10");
System.err.println("See http://dev.processing.org" +
"/bugs/show_bug.cgi?id=513 for more info.");
throw new RuntimeException("Please update your Java " +
"installation (see bug #513)");
}
}
}
}
// if (irenderer.equals(P2D)) {
// throw new RuntimeException("The P2D renderer is currently disabled, " +
// "please use P3D or JAVA2D.");
// }
String openglError =
"Before using OpenGL, first select " +
"Import Library > opengl from the Sketch menu.";
try {
/*
Class<?> rendererClass = Class.forName(irenderer);
Class<?> constructorParams[] = null;
Object constructorValues[] = null;
if (ipath == null) {
constructorParams = new Class[] {
Integer.TYPE, Integer.TYPE, PApplet.class
};
constructorValues = new Object[] {
new Integer(iwidth), new Integer(iheight), this
};
} else {
constructorParams = new Class[] {
Integer.TYPE, Integer.TYPE, PApplet.class, String.class
};
constructorValues = new Object[] {
new Integer(iwidth), new Integer(iheight), this, ipath
};
}
Constructor<?> constructor =
rendererClass.getConstructor(constructorParams);
PGraphics pg = (PGraphics) constructor.newInstance(constructorValues);
*/
Class<?> rendererClass =
Thread.currentThread().getContextClassLoader().loadClass(irenderer);
//Class<?> params[] = null;
//PApplet.println(rendererClass.getConstructors());
Constructor<?> constructor = rendererClass.getConstructor(new Class[] { });
PGraphics pg = (PGraphics) constructor.newInstance();
pg.setParent(this);
pg.setPrimary(iprimary);
if (ipath != null) pg.setPath(ipath);
pg.setSize(iwidth, iheight);
// everything worked, return it
return pg;
} catch (InvocationTargetException ite) {
String msg = ite.getTargetException().getMessage();
if ((msg != null) &&
(msg.indexOf("no jogl in java.library.path") != -1)) {
throw new RuntimeException(openglError +
" (The native library is missing.)");
} else {
ite.getTargetException().printStackTrace();
Throwable target = ite.getTargetException();
if (platform == MACOSX) target.printStackTrace(System.out); // bug
// neither of these help, or work
//target.printStackTrace(System.err);
//System.err.flush();
//System.out.println(System.err); // and the object isn't null
throw new RuntimeException(target.getMessage());
}
} catch (ClassNotFoundException cnfe) {
if (cnfe.getMessage().indexOf("processing.opengl.PGraphicsGL") != -1) {
throw new RuntimeException(openglError +
" (The library .jar file is missing.)");
} else {
throw new RuntimeException("You need to use \"Import Library\" " +
"to add " + irenderer + " to your sketch.");
}
} catch (Exception e) {
//System.out.println("ex3");
if ((e instanceof IllegalArgumentException) ||
(e instanceof NoSuchMethodException) ||
(e instanceof IllegalAccessException)) {
e.printStackTrace();
/*
String msg = "public " +
irenderer.substring(irenderer.lastIndexOf('.') + 1) +
"(int width, int height, PApplet parent" +
((ipath == null) ? "" : ", String filename") +
") does not exist.";
*/
String msg = irenderer + " needs to be updated " +
"for the current release of Processing.";
throw new RuntimeException(msg);
} else {
if (platform == MACOSX) e.printStackTrace(System.out);
throw new RuntimeException(e.getMessage());
}
}
}
/**
* Preferred method of creating new PImage objects, ensures that a
* reference to the parent PApplet is included, which makes save() work
* without needing an absolute path.
*/
public PImage createImage(int wide, int high, int format) {
PImage image = new PImage(wide, high, format);
image.parent = this; // make save() work
return image;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
public void update(Graphics screen) {
paint(screen);
}
//synchronized public void paint(Graphics screen) { // shutting off for 0146
public void paint(Graphics screen) {
// ignore the very first call to paint, since it's coming
// from the o.s., and the applet will soon update itself anyway.
if (frameCount == 0) {
// println("Skipping frame");
// paint() may be called more than once before things
// are finally painted to the screen and the thread gets going
return;
}
// without ignoring the first call, the first several frames
// are confused because paint() gets called in the midst of
// the initial nextFrame() call, so there are multiple
// updates fighting with one another.
// g.image is synchronized so that draw/loop and paint don't
// try to fight over it. this was causing a randomized slowdown
// that would cut the frameRate into a third on macosx,
// and is probably related to the windows sluggishness bug too
// make sure the screen is visible and usable
// (also prevents over-drawing when using PGraphicsOpenGL)
if ((g != null) && (g.image != null)) {
// println("inside paint(), screen.drawImage()");
screen.drawImage(g.image, 0, 0, null);
}
}
// active paint method
protected void paint() {
try {
Graphics screen = this.getGraphics();
if (screen != null) {
if ((g != null) && (g.image != null)) {
screen.drawImage(g.image, 0, 0, null);
}
Toolkit.getDefaultToolkit().sync();
}
} catch (Exception e) {
// Seen on applet destroy, maybe can ignore?
e.printStackTrace();
} finally {
if (g != null) {
g.dispose();
}
}
}
//////////////////////////////////////////////////////////////
/**
* Main method for the primary animation thread.
*
* <A HREF="http://java.sun.com/products/jfc/tsc/articles/painting/">Painting in AWT and Swing</A>
*/
public void run() { // not good to make this synchronized, locks things up
long beforeTime = System.nanoTime();
long overSleepTime = 0L;
int noDelays = 0;
// Number of frames with a delay of 0 ms before the
// animation thread yields to other running threads.
final int NO_DELAYS_PER_YIELD = 15;
/*
// this has to be called after the exception is thrown,
// otherwise the supporting libs won't have a valid context to draw to
Object methodArgs[] =
new Object[] { new Integer(width), new Integer(height) };
sizeMethods.handle(methodArgs);
*/
while ((Thread.currentThread() == thread) && !finished) {
// Don't resize the renderer from the EDT (i.e. from a ComponentEvent),
// otherwise it may attempt a resize mid-render.
if (resizeRequest) {
resizeRenderer(resizeWidth, resizeHeight);
resizeRequest = false;
}
// render a single frame
handleDraw();
if (frameCount == 1) {
// Call the request focus event once the image is sure to be on
// screen and the component is valid. The OpenGL renderer will
// request focus for its canvas inside beginDraw().
// http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html
//println("requesting focus");
requestFocus();
}
// wait for update & paint to happen before drawing next frame
// this is necessary since the drawing is sometimes in a
// separate thread, meaning that the next frame will start
// before the update/paint is completed
long afterTime = System.nanoTime();
long timeDiff = afterTime - beforeTime;
//System.out.println("time diff is " + timeDiff);
long sleepTime = (frameRatePeriod - timeDiff) - overSleepTime;
if (sleepTime > 0) { // some time left in this cycle
try {
// Thread.sleep(sleepTime / 1000000L); // nanoseconds -> milliseconds
Thread.sleep(sleepTime / 1000000L, (int) (sleepTime % 1000000L));
noDelays = 0; // Got some sleep, not delaying anymore
} catch (InterruptedException ex) { }
overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
//System.out.println(" oversleep is " + overSleepTime);
} else { // sleepTime <= 0; the frame took longer than the period
// excess -= sleepTime; // store excess time value
overSleepTime = 0L;
if (noDelays > NO_DELAYS_PER_YIELD) {
Thread.yield(); // give another thread a chance to run
noDelays = 0;
}
}
beforeTime = System.nanoTime();
}
stop(); // call to shutdown libs?
// If the user called the exit() function, the window should close,
// rather than the sketch just halting.
if (exitCalled) {
exit2();
}
}
//synchronized public void handleDisplay() {
public void handleDraw() {
if (g != null && (looping || redraw)) {
if (!g.canDraw()) {
// Don't draw if the renderer is not yet ready.
// (e.g. OpenGL has to wait for a peer to be on screen)
return;
}
//System.out.println("handleDraw() " + frameCount);
g.beginDraw();
long now = System.nanoTime();
if (frameCount == 0) {
try {
//println("Calling setup()");
setup();
//println("Done with setup()");
} catch (RendererChangeException e) {
// Give up, instead set the new renderer and re-attempt setup()
return;
}
this.defaultSize = false;
} else { // frameCount > 0, meaning an actual draw()
// update the current frameRate
double rate = 1000000.0 / ((now - frameRateLastNanos) / 1000000.0);
float instantaneousRate = (float) rate / 1000.0f;
frameRate = (frameRate * 0.9f) + (instantaneousRate * 0.1f);
preMethods.handle();
// use dmouseX/Y as previous mouse pos, since this is the
// last position the mouse was in during the previous draw.
pmouseX = dmouseX;
pmouseY = dmouseY;
//println("Calling draw()");
draw();
//println("Done calling draw()");
// dmouseX/Y is updated only once per frame (unlike emouseX/Y)
dmouseX = mouseX;
dmouseY = mouseY;
// these are called *after* loop so that valid
// drawing commands can be run inside them. it can't
// be before, since a call to background() would wipe
// out anything that had been drawn so far.
dequeueMouseEvents();
dequeueKeyEvents();
drawMethods.handle();
redraw = false; // unset 'redraw' flag in case it was set
// (only do this once draw() has run, not just setup())
}
g.endDraw();
frameRateLastNanos = now;
frameCount++;
// Actively render the screen
paint();
// repaint();
// getToolkit().sync(); // force repaint now (proper method)
postMethods.handle();
}
}
//////////////////////////////////////////////////////////////
synchronized public void redraw() {
if (!looping) {
redraw = true;
// if (thread != null) {
// // wake from sleep (necessary otherwise it'll be
// // up to 10 seconds before update)
// if (CRUSTY_THREADS) {
// thread.interrupt();
// } else {
// synchronized (blocker) {
// blocker.notifyAll();
// }
// }
// }
}
}
synchronized public void loop() {
if (!looping) {
looping = true;
}
}
synchronized public void noLoop() {
if (looping) {
looping = false;
}
}
//////////////////////////////////////////////////////////////
public void addListeners() {
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
addFocusListener(this);
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
Component c = e.getComponent();
//System.out.println("componentResized() " + c);
Rectangle bounds = c.getBounds();
resizeRequest = true;
resizeWidth = bounds.width;
resizeHeight = bounds.height;
}
});
}
//////////////////////////////////////////////////////////////
MouseEvent mouseEventQueue[] = new MouseEvent[10];
int mouseEventCount;
protected void enqueueMouseEvent(MouseEvent e) {
synchronized (mouseEventQueue) {
if (mouseEventCount == mouseEventQueue.length) {
MouseEvent temp[] = new MouseEvent[mouseEventCount << 1];
System.arraycopy(mouseEventQueue, 0, temp, 0, mouseEventCount);
mouseEventQueue = temp;
}
mouseEventQueue[mouseEventCount++] = e;
}
}
protected void dequeueMouseEvents() {
synchronized (mouseEventQueue) {
for (int i = 0; i < mouseEventCount; i++) {
mouseEvent = mouseEventQueue[i];
handleMouseEvent(mouseEvent);
}
mouseEventCount = 0;
}
}
/**
* Actually take action based on a mouse event.
* Internally updates mouseX, mouseY, mousePressed, and mouseEvent.
* Then it calls the event type with no params,
* i.e. mousePressed() or mouseReleased() that the user may have
* overloaded to do something more useful.
*/
protected void handleMouseEvent(MouseEvent event) {
int id = event.getID();
// http://dev.processing.org/bugs/show_bug.cgi?id=170
// also prevents mouseExited() on the mac from hosing the mouse
// position, because x/y are bizarre values on the exit event.
// see also the id check below.. both of these go together
if ((id == MouseEvent.MOUSE_DRAGGED) ||
(id == MouseEvent.MOUSE_MOVED)) {
pmouseX = emouseX;
pmouseY = emouseY;
mouseX = event.getX();
mouseY = event.getY();
}
mouseEvent = event;
int modifiers = event.getModifiers();
if ((modifiers & InputEvent.BUTTON1_MASK) != 0) {
mouseButton = LEFT;
} else if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
mouseButton = CENTER;
} else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
mouseButton = RIGHT;
}
// if running on macos, allow ctrl-click as right mouse
if (platform == MACOSX) {
if (mouseEvent.isPopupTrigger()) {
mouseButton = RIGHT;
}
}
mouseEventMethods.handle(new Object[] { event });
// this used to only be called on mouseMoved and mouseDragged
// change it back if people run into trouble
if (firstMouse) {
pmouseX = mouseX;
pmouseY = mouseY;
dmouseX = mouseX;
dmouseY = mouseY;
firstMouse = false;
}
//println(event);
switch (id) {
case MouseEvent.MOUSE_PRESSED:
mousePressed = true;
mousePressed();
break;
case MouseEvent.MOUSE_RELEASED:
mousePressed = false;
mouseReleased();
break;
case MouseEvent.MOUSE_CLICKED:
mouseClicked();
break;
case MouseEvent.MOUSE_DRAGGED:
mouseDragged();
break;
case MouseEvent.MOUSE_MOVED:
mouseMoved();
break;
}
if ((id == MouseEvent.MOUSE_DRAGGED) ||
(id == MouseEvent.MOUSE_MOVED)) {
emouseX = mouseX;
emouseY = mouseY;
}
}
/**
* Figure out how to process a mouse event. When loop() has been
* called, the events will be queued up until drawing is complete.
* If noLoop() has been called, then events will happen immediately.
*/
protected void checkMouseEvent(MouseEvent event) {
if (looping) {
enqueueMouseEvent(event);
} else {
handleMouseEvent(event);
}
}
/**
* If you override this or any function that takes a "MouseEvent e"
* without calling its super.mouseXxxx() then mouseX, mouseY,
* mousePressed, and mouseEvent will no longer be set.
*/
public void mousePressed(MouseEvent e) {
checkMouseEvent(e);
}
public void mouseReleased(MouseEvent e) {
checkMouseEvent(e);
}
public void mouseClicked(MouseEvent e) {
checkMouseEvent(e);
}
public void mouseEntered(MouseEvent e) {
checkMouseEvent(e);
}
public void mouseExited(MouseEvent e) {
checkMouseEvent(e);
}
public void mouseDragged(MouseEvent e) {
checkMouseEvent(e);
}
public void mouseMoved(MouseEvent e) {
checkMouseEvent(e);
}
/**
* Mouse has been pressed, and should be considered "down"
* until mouseReleased() is called. If you must, use
* int button = mouseEvent.getButton();
* to figure out which button was clicked. It will be one of:
* MouseEvent.BUTTON1, MouseEvent.BUTTON2, MouseEvent.BUTTON3
* Note, however, that this is completely inconsistent across
* platforms.
*/
public void mousePressed() { }
/**
* Mouse button has been released.
*/
public void mouseReleased() { }
/**
* When the mouse is clicked, mousePressed() will be called,
* then mouseReleased(), then mouseClicked(). Note that
* mousePressed is already false inside of mouseClicked().
*/
public void mouseClicked() { }
/**
* Mouse button is pressed and the mouse has been dragged.
*/
public void mouseDragged() { }
/**
* Mouse button is not pressed but the mouse has changed locations.
*/
public void mouseMoved() { }
//////////////////////////////////////////////////////////////
KeyEvent keyEventQueue[] = new KeyEvent[10];
int keyEventCount;
protected void enqueueKeyEvent(KeyEvent e) {
synchronized (keyEventQueue) {
if (keyEventCount == keyEventQueue.length) {
KeyEvent temp[] = new KeyEvent[keyEventCount << 1];
System.arraycopy(keyEventQueue, 0, temp, 0, keyEventCount);
keyEventQueue = temp;
}
keyEventQueue[keyEventCount++] = e;
}
}
protected void dequeueKeyEvents() {
synchronized (keyEventQueue) {
for (int i = 0; i < keyEventCount; i++) {
keyEvent = keyEventQueue[i];
handleKeyEvent(keyEvent);
}
keyEventCount = 0;
}
}
protected void handleKeyEvent(KeyEvent event) {
keyEvent = event;
key = event.getKeyChar();
keyCode = event.getKeyCode();
keyEventMethods.handle(new Object[] { event });
switch (event.getID()) {
case KeyEvent.KEY_PRESSED:
keyPressed = true;
keyPressed();
break;
case KeyEvent.KEY_RELEASED:
keyPressed = false;
keyReleased();
break;
case KeyEvent.KEY_TYPED:
keyTyped();
break;
}
// if someone else wants to intercept the key, they should
// set key to zero (or something besides the ESC).
if (event.getID() == KeyEvent.KEY_PRESSED) {
if (key == KeyEvent.VK_ESCAPE) {
exit();
}
// When running tethered to the Processing application, respond to
// Ctrl-W (or Cmd-W) events by closing the sketch. Disable this behavior
// when running independently, because this sketch may be one component
// embedded inside an application that has its own close behavior.
if (external &&
event.getModifiers() == MENU_SHORTCUT &&
event.getKeyCode() == 'W') {
exit();
}
}
}
protected void checkKeyEvent(KeyEvent event) {
if (looping) {
enqueueKeyEvent(event);
} else {
handleKeyEvent(event);
}
}
/**
* Overriding keyXxxxx(KeyEvent e) functions will cause the 'key',
* 'keyCode', and 'keyEvent' variables to no longer work;
* key events will no longer be queued until the end of draw();
* and the keyPressed(), keyReleased() and keyTyped() methods
* will no longer be called.
*/
public void keyPressed(KeyEvent e) { checkKeyEvent(e); }
public void keyReleased(KeyEvent e) { checkKeyEvent(e); }
public void keyTyped(KeyEvent e) { checkKeyEvent(e); }
/**
* Called each time a single key on the keyboard is pressed.
* Because of how operating systems handle key repeats, holding
* down a key will cause multiple calls to keyPressed(), because
* the OS repeat takes over.
* <P>
* Examples for key handling:
* (Tested on Windows XP, please notify if different on other
* platforms, I have a feeling Mac OS and Linux may do otherwise)
* <PRE>
* 1. Pressing 'a' on the keyboard:
* keyPressed with key == 'a' and keyCode == 'A'
* keyTyped with key == 'a' and keyCode == 0
* keyReleased with key == 'a' and keyCode == 'A'
*
* 2. Pressing 'A' on the keyboard:
* keyPressed with key == 'A' and keyCode == 'A'
* keyTyped with key == 'A' and keyCode == 0
* keyReleased with key == 'A' and keyCode == 'A'
*
* 3. Pressing 'shift', then 'a' on the keyboard (caps lock is off):
* keyPressed with key == CODED and keyCode == SHIFT
* keyPressed with key == 'A' and keyCode == 'A'
* keyTyped with key == 'A' and keyCode == 0
* keyReleased with key == 'A' and keyCode == 'A'
* keyReleased with key == CODED and keyCode == SHIFT
*
* 4. Holding down the 'a' key.
* The following will happen several times,
* depending on your machine's "key repeat rate" settings:
* keyPressed with key == 'a' and keyCode == 'A'
* keyTyped with key == 'a' and keyCode == 0
* When you finally let go, you'll get:
* keyReleased with key == 'a' and keyCode == 'A'
*
* 5. Pressing and releasing the 'shift' key
* keyPressed with key == CODED and keyCode == SHIFT
* keyReleased with key == CODED and keyCode == SHIFT
* (note there is no keyTyped)
*
* 6. Pressing the tab key in an applet with Java 1.4 will
* normally do nothing, but PApplet dynamically shuts
* this behavior off if Java 1.4 is in use (tested 1.4.2_05 Windows).
* Java 1.1 (Microsoft VM) passes the TAB key through normally.
* Not tested on other platforms or for 1.3.
* </PRE>
*/
public void keyPressed() { }
/**
* See keyPressed().
*/
public void keyReleased() { }
/**
* Only called for "regular" keys like letters,
* see keyPressed() for full documentation.
*/
public void keyTyped() { }
//////////////////////////////////////////////////////////////
// i am focused man, and i'm not afraid of death.
// and i'm going all out. i circle the vultures in a van
// and i run the block.
public void focusGained() { }
public void focusGained(FocusEvent e) {
focused = true;
focusGained();
}
public void focusLost() { }
public void focusLost(FocusEvent e) {
focused = false;
focusLost();
}
//////////////////////////////////////////////////////////////
// getting the time
/**
* Get the number of milliseconds since the applet started.
* <P>
* This is a function, rather than a variable, because it may
* change multiple times per frame.
*/
public int millis() {
return (int) (System.currentTimeMillis() - millisOffset);
}
/** Seconds position of the current time. */
static public int second() {
return Calendar.getInstance().get(Calendar.SECOND);
}
/** Minutes position of the current time. */
static public int minute() {
return Calendar.getInstance().get(Calendar.MINUTE);
}
/**
* Hour position of the current time in international format (0-23).
* <P>
* To convert this value to American time: <BR>
* <PRE>int yankeeHour = (hour() % 12);
* if (yankeeHour == 0) yankeeHour = 12;</PRE>
*/
static public int hour() {
return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
}
/**
* Get the current day of the month (1 through 31).
* <P>
* If you're looking for the day of the week (M-F or whatever)
* or day of the year (1..365) then use java's Calendar.get()
*/
static public int day() {
return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
}
/**
* Get the current month in range 1 through 12.
*/
static public int month() {
// months are number 0..11 so change to colloquial 1..12
return Calendar.getInstance().get(Calendar.MONTH) + 1;
}
/**
* Get the current year.
*/
static public int year() {
return Calendar.getInstance().get(Calendar.YEAR);
}
//////////////////////////////////////////////////////////////
// controlling time (playing god)
/**
* The delay() function causes the program to halt for a specified time.
* Delay times are specified in thousandths of a second. For example,
* running delay(3000) will stop the program for three seconds and
* delay(500) will stop the program for a half-second. Remember: the
* display window is updated only at the end of draw(), so putting more
* than one delay() inside draw() will simply add them together and the new
* frame will be drawn when the total delay is over.
* <br/> <br/>
* I'm not sure if this is even helpful anymore, as the screen isn't
* updated before or after the delay, meaning which means it just
* makes the app lock up temporarily.
*/
public void delay(int napTime) {
if (frameCount != 0) {
if (napTime > 0) {
try {
Thread.sleep(napTime);
} catch (InterruptedException e) { }
}
}
}
/**
* Set a target frameRate. This will cause delay() to be called
* after each frame so that the sketch synchronizes to a particular speed.
* Note that this only sets the maximum frame rate, it cannot be used to
* make a slow sketch go faster. Sketches have no default frame rate
* setting, and will attempt to use maximum processor power to achieve
* maximum speed.
*/
public void frameRate(float newRateTarget) {
frameRateTarget = newRateTarget;
frameRatePeriod = (long) (1000000000.0 / frameRateTarget);
}
//////////////////////////////////////////////////////////////
/**
* Get a param from the web page, or (eventually)
* from a properties file.
*/
public String param(String what) {
if (online) {
return getParameter(what);
} else {
System.err.println("param() only works inside a web browser");
}
return null;
}
/**
* Show status in the status bar of a web browser, or in the
* System.out console. Eventually this might show status in the
* p5 environment itself, rather than relying on the console.
*/
public void status(String what) {
if (online) {
showStatus(what);
} else {
System.out.println(what); // something more interesting?
}
}
public void link(String here) {
link(here, null);
}
/**
* Link to an external page without all the muss.
* <P>
* When run with an applet, uses the browser to open the url,
* for applications, attempts to launch a browser with the url.
* <P>
* Works on Mac OS X and Windows. For Linux, use:
* <PRE>open(new String[] { "firefox", url });</PRE>
* or whatever you want as your browser, since Linux doesn't
* yet have a standard method for launching URLs.
*/
public void link(String url, String frameTitle) {
if (online) {
try {
if (frameTitle == null) {
getAppletContext().showDocument(new URL(url));
} else {
getAppletContext().showDocument(new URL(url), frameTitle);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Could not open " + url);
}
} else {
try {
if (platform == WINDOWS) {
// the following uses a shell execute to launch the .html file
// note that under cygwin, the .html files have to be chmodded +x
// after they're unpacked from the zip file. i don't know why,
// and don't understand what this does in terms of windows
// permissions. without the chmod, the command prompt says
// "Access is denied" in both cygwin and the "dos" prompt.
//Runtime.getRuntime().exec("cmd /c " + currentDir + "\\reference\\" +
// referenceFile + ".html");
// replace ampersands with control sequence for DOS.
// solution contributed by toxi on the bugs board.
url = url.replaceAll("&","^&");
// open dos prompt, give it 'start' command, which will
// open the url properly. start by itself won't work since
// it appears to need cmd
Runtime.getRuntime().exec("cmd /c start " + url);
} else if (platform == MACOSX) {
//com.apple.mrj.MRJFileUtils.openURL(url);
try {
Class<?> mrjFileUtils = Class.forName("com.apple.mrj.MRJFileUtils");
Method openMethod =
mrjFileUtils.getMethod("openURL", new Class[] { String.class });
openMethod.invoke(null, new Object[] { url });
} catch (Exception e) {
e.printStackTrace();
}
} else {
//throw new RuntimeException("Can't open URLs for this platform");
// Just pass it off to open() and hope for the best
open(url);
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Could not open " + url);
}
}
}
/**
* Attempt to open a file using the platform's shell.
*/
static public void open(String filename) {
open(new String[] { filename });
}
static String openLauncher;
/**
* Launch a process using a platforms shell. This version uses an array
* to make it easier to deal with spaces in the individual elements.
* (This avoids the situation of trying to put single or double quotes
* around different bits).
*/
static public Process open(String argv[]) {
String[] params = null;
if (platform == WINDOWS) {
// just launching the .html file via the shell works
// but make sure to chmod +x the .html files first
// also place quotes around it in case there's a space
// in the user.dir part of the url
params = new String[] { "cmd", "/c" };
} else if (platform == MACOSX) {
params = new String[] { "open" };
} else if (platform == LINUX) {
if (openLauncher == null) {
// Attempt to use gnome-open
try {
Process p = Runtime.getRuntime().exec(new String[] { "gnome-open" });
/*int result =*/ p.waitFor();
// Not installed will throw an IOException (JDK 1.4.2, Ubuntu 7.04)
openLauncher = "gnome-open";
} catch (Exception e) { }
}
if (openLauncher == null) {
// Attempt with kde-open
try {
Process p = Runtime.getRuntime().exec(new String[] { "kde-open" });
/*int result =*/ p.waitFor();
openLauncher = "kde-open";
} catch (Exception e) { }
}
if (openLauncher == null) {
System.err.println("Could not find gnome-open or kde-open, " +
"the open() command may not work.");
}
if (openLauncher != null) {
params = new String[] { openLauncher };
}
//} else { // give up and just pass it to Runtime.exec()
//open(new String[] { filename });
//params = new String[] { filename };
}
if (params != null) {
// If the 'open', 'gnome-open' or 'cmd' are already included
if (params[0].equals(argv[0])) {
// then don't prepend those params again
return exec(argv);
} else {
params = concat(params, argv);
return exec(params);
}
} else {
return exec(argv);
}
}
static public Process exec(String[] argv) {
try {
return Runtime.getRuntime().exec(argv);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Could not open " + join(argv, ' '));
}
}
//////////////////////////////////////////////////////////////
/**
* Function for an applet/application to kill itself and
* display an error. Mostly this is here to be improved later.
*/
public void die(String what) {
stop();
throw new RuntimeException(what);
}
/**
* Same as above but with an exception. Also needs work.
*/
public void die(String what, Exception e) {
if (e != null) e.printStackTrace();
die(what);
}
/**
* Call to safely exit the sketch when finished. For instance,
* to render a single frame, save it, and quit.
*/
public void exit() {
if (thread == null) {
// exit immediately, stop() has already been called,
// meaning that the main thread has long since exited
exit2();
} else if (looping) {
// stop() will be called as the thread exits
finished = true;
// tell the code to call exit2() to do a System.exit()
// once the next draw() has completed
exitCalled = true;
} else if (!looping) {
// if not looping, need to call stop explicitly,
// because the main thread will be sleeping
stop();
// now get out
exit2();
}
}
void exit2() {
try {
System.exit(0);
} catch (SecurityException e) {
// don't care about applet security exceptions
}
}
//////////////////////////////////////////////////////////////
// SCREEN GRABASS
/**
* Intercepts any relative paths to make them absolute (relative
* to the sketch folder) before passing to save() in PImage.
* (Changed in 0100)
*/
public void save(String filename) {
g.save(savePath(filename));
}
/**
* Grab an image of what's currently in the drawing area and save it
* as a .tif or .tga file.
* <P>
* Best used just before endDraw() at the end of your draw().
* This can only create .tif or .tga images, so if neither extension
* is specified it defaults to writing a tiff and adds a .tif suffix.
*/
public void saveFrame() {
try {
g.save(savePath("screen-" + nf(frameCount, 4) + ".tif"));
} catch (SecurityException se) {
System.err.println("Can't use saveFrame() when running in a browser, " +
"unless using a signed applet.");
}
}
/**
* Save the current frame as a .tif or .tga image.
* <P>
* The String passed in can contain a series of # signs
* that will be replaced with the screengrab number.
* <PRE>
* i.e. saveFrame("blah-####.tif");
* // saves a numbered tiff image, replacing the
* // #### signs with zeros and the frame number </PRE>
*/
public void saveFrame(String what) {
try {
g.save(savePath(insertFrame(what)));
} catch (SecurityException se) {
System.err.println("Can't use saveFrame() when running in a browser, " +
"unless using a signed applet.");
}
}
/**
* Check a string for #### signs to see if the frame number should be
* inserted. Used for functions like saveFrame() and beginRecord() to
* replace the # marks with the frame number. If only one # is used,
* it will be ignored, under the assumption that it's probably not
* intended to be the frame number.
*/
protected String insertFrame(String what) {
int first = what.indexOf('#');
int last = what.lastIndexOf('#');
if ((first != -1) && (last - first > 0)) {
String prefix = what.substring(0, first);
int count = last - first + 1;
String suffix = what.substring(last + 1);
return prefix + nf(frameCount, count) + suffix;
}
return what; // no change
}
//////////////////////////////////////////////////////////////
// CURSOR
//
int cursorType = ARROW; // cursor type
boolean cursorVisible = true; // cursor visibility flag
PImage invisibleCursor;
/**
* Set the cursor type
*/
public void cursor(int cursorType) {
setCursor(Cursor.getPredefinedCursor(cursorType));
cursorVisible = true;
this.cursorType = cursorType;
}
/**
* Replace the cursor with the specified PImage. The x- and y-
* coordinate of the center will be the center of the image.
*/
public void cursor(PImage image) {
cursor(image, image.width/2, image.height/2);
}
/**
* Set a custom cursor to an image with a specific hotspot.
* Only works with JDK 1.2 and later.
* Currently seems to be broken on Java 1.4 for Mac OS X
* <P>
* Based on code contributed by Amit Pitaru, plus additional
* code to handle Java versions via reflection by Jonathan Feinberg.
* Reflection removed for release 0128 and later.
*/
public void cursor(PImage image, int hotspotX, int hotspotY) {
// don't set this as cursor type, instead use cursor_type
// to save the last cursor used in case cursor() is called
//cursor_type = Cursor.CUSTOM_CURSOR;
Image jimage =
createImage(new MemoryImageSource(image.width, image.height,
image.pixels, 0, image.width));
Point hotspot = new Point(hotspotX, hotspotY);
Toolkit tk = Toolkit.getDefaultToolkit();
Cursor cursor = tk.createCustomCursor(jimage, hotspot, "Custom Cursor");
setCursor(cursor);
cursorVisible = true;
}
/**
* Show the cursor after noCursor() was called.
* Notice that the program remembers the last set cursor type
*/
public void cursor() {
// maybe should always set here? seems dangerous, since
// it's likely that java will set the cursor to something
// else on its own, and the applet will be stuck b/c bagel
// thinks that the cursor is set to one particular thing
if (!cursorVisible) {
cursorVisible = true;
setCursor(Cursor.getPredefinedCursor(cursorType));
}
}
/**
* Hide the cursor by creating a transparent image
* and using it as a custom cursor.
*/
public void noCursor() {
if (!cursorVisible) return; // don't hide if already hidden.
if (invisibleCursor == null) {
invisibleCursor = new PImage(16, 16, ARGB);
}
// was formerly 16x16, but the 0x0 was added by jdf as a fix
// for macosx, which wasn't honoring the invisible cursor
cursor(invisibleCursor, 8, 8);
cursorVisible = false;
}
//////////////////////////////////////////////////////////////
static public void print(byte what) {
System.out.print(what);
System.out.flush();
}
static public void print(boolean what) {
System.out.print(what);
System.out.flush();
}
static public void print(char what) {
System.out.print(what);
System.out.flush();
}
static public void print(int what) {
System.out.print(what);
System.out.flush();
}
static public void print(float what) {
System.out.print(what);
System.out.flush();
}
static public void print(String what) {
System.out.print(what);
System.out.flush();
}
static public void print(Object what) {
if (what == null) {
// special case since this does fuggly things on > 1.1
System.out.print("null");
} else {
System.out.println(what.toString());
}
}
//
static public void println() {
System.out.println();
}
//
static public void println(byte what) {
print(what); System.out.println();
}
static public void println(boolean what) {
print(what); System.out.println();
}
static public void println(char what) {
print(what); System.out.println();
}
static public void println(int what) {
print(what); System.out.println();
}
static public void println(float what) {
print(what); System.out.println();
}
static public void println(String what) {
print(what); System.out.println();
}
static public void println(Object what) {
if (what == null) {
// special case since this does fuggly things on > 1.1
System.out.println("null");
} else {
String name = what.getClass().getName();
if (name.charAt(0) == '[') {
switch (name.charAt(1)) {
case '[':
// don't even mess with multi-dimensional arrays (case '[')
// or anything else that's not int, float, boolean, char
System.out.println(what);
break;
case 'L':
// print a 1D array of objects as individual elements
Object poo[] = (Object[]) what;
for (int i = 0; i < poo.length; i++) {
if (poo[i] instanceof String) {
System.out.println("[" + i + "] \"" + poo[i] + "\"");
} else {
System.out.println("[" + i + "] " + poo[i]);
}
}
break;
case 'Z': // boolean
boolean zz[] = (boolean[]) what;
for (int i = 0; i < zz.length; i++) {
System.out.println("[" + i + "] " + zz[i]);
}
break;
case 'B': // byte
byte bb[] = (byte[]) what;
for (int i = 0; i < bb.length; i++) {
System.out.println("[" + i + "] " + bb[i]);
}
break;
case 'C': // char
char cc[] = (char[]) what;
for (int i = 0; i < cc.length; i++) {
System.out.println("[" + i + "] '" + cc[i] + "'");
}
break;
case 'I': // int
int ii[] = (int[]) what;
for (int i = 0; i < ii.length; i++) {
System.out.println("[" + i + "] " + ii[i]);
}
break;
case 'F': // float
float ff[] = (float[]) what;
for (int i = 0; i < ff.length; i++) {
System.out.println("[" + i + "] " + ff[i]);
}
break;
/*
case 'D': // double
double dd[] = (double[]) what;
for (int i = 0; i < dd.length; i++) {
System.out.println("[" + i + "] " + dd[i]);
}
break;
*/
default:
System.out.println(what);
}
} else { // not an array
System.out.println(what);
}
}
}
//
/*
// not very useful, because it only works for public (and protected?)
// fields of a class, not local variables to methods
public void printvar(String name) {
try {
Field field = getClass().getDeclaredField(name);
println(name + " = " + field.get(this));
} catch (Exception e) {
e.printStackTrace();
}
}
*/
//////////////////////////////////////////////////////////////
// MATH
// lots of convenience methods for math with floats.
// doubles are overkill for processing applets, and casting
// things all the time is annoying, thus the functions below.
static public final float abs(float n) {
return (n < 0) ? -n : n;
}
static public final int abs(int n) {
return (n < 0) ? -n : n;
}
static public final float sq(float a) {
return a*a;
}
static public final float sqrt(float a) {
return (float)Math.sqrt(a);
}
static public final float log(float a) {
return (float)Math.log(a);
}
static public final float exp(float a) {
return (float)Math.exp(a);
}
static public final float pow(float a, float b) {
return (float)Math.pow(a, b);
}
static public final int max(int a, int b) {
return (a > b) ? a : b;
}
static public final float max(float a, float b) {
return (a > b) ? a : b;
}
static public final int max(int a, int b, int c) {
return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
}
static public final float max(float a, float b, float c) {
return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
}
/**
* Find the maximum value in an array.
* Throws an ArrayIndexOutOfBoundsException if the array is length 0.
* @param list the source array
* @return The maximum value
*/
static public final int max(int[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
int max = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] > max) max = list[i];
}
return max;
}
/**
* Find the maximum value in an array.
* Throws an ArrayIndexOutOfBoundsException if the array is length 0.
* @param list the source array
* @return The maximum value
*/
static public final float max(float[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
float max = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] > max) max = list[i];
}
return max;
}
static public final int min(int a, int b) {
return (a < b) ? a : b;
}
static public final float min(float a, float b) {
return (a < b) ? a : b;
}
static public final int min(int a, int b, int c) {
return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c);
}
static public final float min(float a, float b, float c) {
return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c);
}
/**
* Find the minimum value in an array.
* Throws an ArrayIndexOutOfBoundsException if the array is length 0.
* @param list the source array
* @return The minimum value
*/
static public final int min(int[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
int min = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] < min) min = list[i];
}
return min;
}
/**
* Find the minimum value in an array.
* Throws an ArrayIndexOutOfBoundsException if the array is length 0.
* @param list the source array
* @return The minimum value
*/
static public final float min(float[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
float min = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] < min) min = list[i];
}
return min;
}
static public final int constrain(int amt, int low, int high) {
return (amt < low) ? low : ((amt > high) ? high : amt);
}
static public final float constrain(float amt, float low, float high) {
return (amt < low) ? low : ((amt > high) ? high : amt);
}
static public final float sin(float angle) {
return (float)Math.sin(angle);
}
static public final float cos(float angle) {
return (float)Math.cos(angle);
}
static public final float tan(float angle) {
return (float)Math.tan(angle);
}
static public final float asin(float value) {
return (float)Math.asin(value);
}
static public final float acos(float value) {
return (float)Math.acos(value);
}
static public final float atan(float value) {
return (float)Math.atan(value);
}
static public final float atan2(float a, float b) {
return (float)Math.atan2(a, b);
}
static public final float degrees(float radians) {
return radians * RAD_TO_DEG;
}
static public final float radians(float degrees) {
return degrees * DEG_TO_RAD;
}
static public final int ceil(float what) {
return (int) Math.ceil(what);
}
static public final int floor(float what) {
return (int) Math.floor(what);
}
static public final int round(float what) {
return (int) Math.round(what);
}
static public final float mag(float a, float b) {
return (float)Math.sqrt(a*a + b*b);
}
static public final float mag(float a, float b, float c) {
return (float)Math.sqrt(a*a + b*b + c*c);
}
static public final float dist(float x1, float y1, float x2, float y2) {
return sqrt(sq(x2-x1) + sq(y2-y1));
}
static public final float dist(float x1, float y1, float z1,
float x2, float y2, float z2) {
return sqrt(sq(x2-x1) + sq(y2-y1) + sq(z2-z1));
}
static public final float lerp(float start, float stop, float amt) {
return start + (stop-start) * amt;
}
/**
* Normalize a value to exist between 0 and 1 (inclusive).
* Mathematically the opposite of lerp(), figures out what proportion
* a particular value is relative to start and stop coordinates.
*/
static public final float norm(float value, float start, float stop) {
return (value - start) / (stop - start);
}
/**
* Convenience function to map a variable from one coordinate space
* to another. Equivalent to unlerp() followed by lerp().
*/
static public final float map(float value,
float istart, float istop,
float ostart, float ostop) {
return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
}
//////////////////////////////////////////////////////////////
// RANDOM NUMBERS
Random internalRandom;
/**
* Return a random number in the range [0, howbig).
* <P>
* The number returned will range from zero up to
* (but not including) 'howbig'.
*/
public final float random(float howbig) {
// for some reason (rounding error?) Math.random() * 3
// can sometimes return '3' (once in ~30 million tries)
// so a check was added to avoid the inclusion of 'howbig'
// avoid an infinite loop
if (howbig == 0) return 0;
// internal random number object
if (internalRandom == null) internalRandom = new Random();
float value = 0;
do {
//value = (float)Math.random() * howbig;
value = internalRandom.nextFloat() * howbig;
} while (value == howbig);
return value;
}
/**
* Return a random number in the range [howsmall, howbig).
* <P>
* The number returned will range from 'howsmall' up to
* (but not including 'howbig'.
* <P>
* If howsmall is >= howbig, howsmall will be returned,
* meaning that random(5, 5) will return 5 (useful)
* and random(7, 4) will return 7 (not useful.. better idea?)
*/
public final float random(float howsmall, float howbig) {
if (howsmall >= howbig) return howsmall;
float diff = howbig - howsmall;
return random(diff) + howsmall;
}
public final void randomSeed(long what) {
// internal random number object
if (internalRandom == null) internalRandom = new Random();
internalRandom.setSeed(what);
}
//////////////////////////////////////////////////////////////
// PERLIN NOISE
// [toxi 040903]
// octaves and amplitude amount per octave are now user controlled
// via the noiseDetail() function.
// [toxi 030902]
// cleaned up code and now using bagel's cosine table to speed up
// [toxi 030901]
// implementation by the german demo group farbrausch
// as used in their demo "art": http://www.farb-rausch.de/fr010src.zip
static final int PERLIN_YWRAPB = 4;
static final int PERLIN_YWRAP = 1<<PERLIN_YWRAPB;
static final int PERLIN_ZWRAPB = 8;
static final int PERLIN_ZWRAP = 1<<PERLIN_ZWRAPB;
static final int PERLIN_SIZE = 4095;
int perlin_octaves = 4; // default to medium smooth
float perlin_amp_falloff = 0.5f; // 50% reduction/octave
// [toxi 031112]
// new vars needed due to recent change of cos table in PGraphics
int perlin_TWOPI, perlin_PI;
float[] perlin_cosTable;
float[] perlin;
Random perlinRandom;
/**
* Computes the Perlin noise function value at point x.
*/
public float noise(float x) {
// is this legit? it's a dumb way to do it (but repair it later)
return noise(x, 0f, 0f);
}
/**
* Computes the Perlin noise function value at the point x, y.
*/
public float noise(float x, float y) {
return noise(x, y, 0f);
}
/**
* Computes the Perlin noise function value at x, y, z.
*/
public float noise(float x, float y, float z) {
if (perlin == null) {
if (perlinRandom == null) {
perlinRandom = new Random();
}
perlin = new float[PERLIN_SIZE + 1];
for (int i = 0; i < PERLIN_SIZE + 1; i++) {
perlin[i] = perlinRandom.nextFloat(); //(float)Math.random();
}
// [toxi 031112]
// noise broke due to recent change of cos table in PGraphics
// this will take care of it
perlin_cosTable = PGraphics.cosLUT;
perlin_TWOPI = perlin_PI = PGraphics.SINCOS_LENGTH;
perlin_PI >>= 1;
}
if (x<0) x=-x;
if (y<0) y=-y;
if (z<0) z=-z;
int xi=(int)x, yi=(int)y, zi=(int)z;
float xf = (float)(x-xi);
float yf = (float)(y-yi);
float zf = (float)(z-zi);
float rxf, ryf;
float r=0;
float ampl=0.5f;
float n1,n2,n3;
for (int i=0; i<perlin_octaves; i++) {
int of=xi+(yi<<PERLIN_YWRAPB)+(zi<<PERLIN_ZWRAPB);
rxf=noise_fsc(xf);
ryf=noise_fsc(yf);
n1 = perlin[of&PERLIN_SIZE];
n1 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n1);
n2 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE];
n2 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n2);
n1 += ryf*(n2-n1);
of += PERLIN_ZWRAP;
n2 = perlin[of&PERLIN_SIZE];
n2 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n2);
n3 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE];
n3 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n3);
n2 += ryf*(n3-n2);
n1 += noise_fsc(zf)*(n2-n1);
r += n1*ampl;
ampl *= perlin_amp_falloff;
xi<<=1; xf*=2;
yi<<=1; yf*=2;
zi<<=1; zf*=2;
if (xf>=1.0f) { xi++; xf--; }
if (yf>=1.0f) { yi++; yf--; }
if (zf>=1.0f) { zi++; zf--; }
}
return r;
}
// [toxi 031112]
// now adjusts to the size of the cosLUT used via
// the new variables, defined above
private float noise_fsc(float i) {
// using bagel's cosine table instead
return 0.5f*(1.0f-perlin_cosTable[(int)(i*perlin_PI)%perlin_TWOPI]);
}
// [toxi 040903]
// make perlin noise quality user controlled to allow
// for different levels of detail. lower values will produce
// smoother results as higher octaves are surpressed
public void noiseDetail(int lod) {
if (lod>0) perlin_octaves=lod;
}
public void noiseDetail(int lod, float falloff) {
if (lod>0) perlin_octaves=lod;
if (falloff>0) perlin_amp_falloff=falloff;
}
public void noiseSeed(long what) {
if (perlinRandom == null) perlinRandom = new Random();
perlinRandom.setSeed(what);
// force table reset after changing the random number seed [0122]
perlin = null;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
protected String[] loadImageFormats;
/**
* Load an image from the data folder or a local directory.
* Supports .gif (including transparency), .tga, and .jpg images.
* In Java 1.3 or later, .png images are
* <A HREF="http://java.sun.com/j2se/1.3/docs/guide/2d/new_features.html">
* also supported</A>.
* <P>
* Generally, loadImage() should only be used during setup, because
* re-loading images inside draw() is likely to cause a significant
* delay while memory is allocated and the thread blocks while waiting
* for the image to load because loading is not asynchronous.
* <P>
* To load several images asynchronously, see more information in the
* FAQ about writing your own threaded image loading method.
* <P>
* As of 0096, returns null if no image of that name is found,
* rather than an error.
* <P>
* Release 0115 also provides support for reading TIFF and RLE-encoded
* Targa (.tga) files written by Processing via save() and saveFrame().
* Other TIFF and Targa files will probably not load, use a different
* format (gif, jpg and png are safest bets) when creating images with
* another application to use with Processing.
* <P>
* Also in release 0115, more image formats (BMP and others) can
* be read when using Java 1.4 and later. Because many people still
* use Java 1.1 and 1.3, these formats are not recommended for
* work that will be posted on the web. To get a list of possible
* image formats for use with Java 1.4 and later, use the following:
* <TT>println(javax.imageio.ImageIO.getReaderFormatNames())</TT>
* <P>
* Images are loaded via a byte array that is passed to
* Toolkit.createImage(). Unfortunately, we cannot use Applet.getImage()
* because it takes a URL argument, which would be a pain in the a--
* to make work consistently for online and local sketches.
* Sometimes this causes problems, resulting in issues like
* <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=279">Bug 279</A>
* and
* <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=305">Bug 305</A>.
* In release 0115, everything was instead run through javax.imageio,
* but that turned out to be very slow, see
* <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=392">Bug 392</A>.
* As a result, starting with 0116, the following happens:
* <UL>
* <LI>TGA and TIFF images are loaded using the internal load methods.
* <LI>JPG, GIF, and PNG images are loaded via loadBytes().
* <LI>If the image still isn't loaded, it's passed to javax.imageio.
* </UL>
* For releases 0116 and later, if you have problems such as those seen
* in Bugs 279 and 305, use Applet.getImage() instead. You'll be stuck
* with the limitations of getImage() (the headache of dealing with
* online/offline use). Set up your own MediaTracker, and pass the resulting
* java.awt.Image to the PImage constructor that takes an AWT image.
*/
public PImage loadImage(String filename) {
return loadImage(filename, null);
}
/**
* Identical to loadImage, but allows you to specify the type of
* image by its extension. Especially useful when downloading from
* CGI scripts.
* <br/> <br/>
* Use 'unknown' as the extension to pass off to the default
* image loader that handles gif, jpg, and png.
*/
public PImage loadImage(String filename, String extension) {
if (extension == null) {
String lower = filename.toLowerCase();
int dot = filename.lastIndexOf('.');
if (dot == -1) {
extension = "unknown"; // no extension found
}
extension = lower.substring(dot + 1);
// check for, and strip any parameters on the url, i.e.
// filename.jpg?blah=blah&something=that
int question = extension.indexOf('?');
if (question != -1) {
extension = extension.substring(0, question);
}
}
// just in case. them users will try anything!
extension = extension.toLowerCase();
if (extension.equals("tga")) {
try {
return loadImageTGA(filename);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
if (extension.equals("tif") || extension.equals("tiff")) {
byte bytes[] = loadBytes(filename);
return (bytes == null) ? null : PImage.loadTIFF(bytes);
}
// For jpeg, gif, and png, load them using createImage(),
// because the javax.imageio code was found to be much slower, see
// <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=392">Bug 392</A>.
try {
if (extension.equals("jpg") || extension.equals("jpeg") ||
extension.equals("gif") || extension.equals("png") ||
extension.equals("unknown")) {
byte bytes[] = loadBytes(filename);
if (bytes == null) {
return null;
} else {
Image awtImage = Toolkit.getDefaultToolkit().createImage(bytes);
PImage image = loadImageMT(awtImage);
if (image.width == -1) {
System.err.println("The file " + filename +
" contains bad image data, or may not be an image.");
}
// if it's a .gif image, test to see if it has transparency
if (extension.equals("gif") || extension.equals("png")) {
image.checkAlpha();
}
return image;
}
}
} catch (Exception e) {
// show error, but move on to the stuff below, see if it'll work
e.printStackTrace();
}
if (loadImageFormats == null) {
loadImageFormats = ImageIO.getReaderFormatNames();
}
if (loadImageFormats != null) {
for (int i = 0; i < loadImageFormats.length; i++) {
if (extension.equals(loadImageFormats[i])) {
return loadImageIO(filename);
}
}
}
// failed, could not load image after all those attempts
System.err.println("Could not find a method to load " + filename);
return null;
}
public PImage requestImage(String filename) {
return requestImage(filename, null);
}
public PImage requestImage(String filename, String extension) {
PImage vessel = createImage(0, 0, ARGB);
AsyncImageLoader ail =
new AsyncImageLoader(filename, extension, vessel);
ail.start();
return vessel;
}
/**
* By trial and error, four image loading threads seem to work best when
* loading images from online. This is consistent with the number of open
* connections that web browsers will maintain. The variable is made public
* (however no accessor has been added since it's esoteric) if you really
* want to have control over the value used. For instance, when loading local
* files, it might be better to only have a single thread (or two) loading
* images so that you're disk isn't simply jumping around.
*/
public int requestImageMax = 4;
volatile int requestImageCount;
class AsyncImageLoader extends Thread {
String filename;
String extension;
PImage vessel;
public AsyncImageLoader(String filename, String extension, PImage vessel) {
this.filename = filename;
this.extension = extension;
this.vessel = vessel;
}
public void run() {
while (requestImageCount == requestImageMax) {
try {
Thread.sleep(10);
} catch (InterruptedException e) { }
}
requestImageCount++;
PImage actual = loadImage(filename, extension);
// An error message should have already printed
if (actual == null) {
vessel.width = -1;
vessel.height = -1;
} else {
vessel.width = actual.width;
vessel.height = actual.height;
vessel.format = actual.format;
vessel.pixels = actual.pixels;
}
requestImageCount--;
}
}
/**
* Load an AWT image synchronously by setting up a MediaTracker for
* a single image, and blocking until it has loaded.
*/
protected PImage loadImageMT(Image awtImage) {
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(awtImage, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) {
//e.printStackTrace(); // non-fatal, right?
}
PImage image = new PImage(awtImage);
image.parent = this;
return image;
}
/**
* Use Java 1.4 ImageIO methods to load an image.
*/
protected PImage loadImageIO(String filename) {
InputStream stream = createInput(filename);
if (stream == null) {
System.err.println("The image " + filename + " could not be found.");
return null;
}
try {
BufferedImage bi = ImageIO.read(stream);
PImage outgoing = new PImage(bi.getWidth(), bi.getHeight());
outgoing.parent = this;
bi.getRGB(0, 0, outgoing.width, outgoing.height,
outgoing.pixels, 0, outgoing.width);
// check the alpha for this image
// was gonna call getType() on the image to see if RGB or ARGB,
// but it's not actually useful, since gif images will come through
// as TYPE_BYTE_INDEXED, which means it'll still have to check for
// the transparency. also, would have to iterate through all the other
// types and guess whether alpha was in there, so.. just gonna stick
// with the old method.
outgoing.checkAlpha();
// return the image
return outgoing;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Targa image loader for RLE-compressed TGA files.
* <P>
* Rewritten for 0115 to read/write RLE-encoded targa images.
* For 0125, non-RLE encoded images are now supported, along with
* images whose y-order is reversed (which is standard for TGA files).
*/
protected PImage loadImageTGA(String filename) throws IOException {
InputStream is = createInput(filename);
if (is == null) return null;
byte header[] = new byte[18];
int offset = 0;
do {
int count = is.read(header, offset, header.length - offset);
if (count == -1) return null;
offset += count;
} while (offset < 18);
/*
header[2] image type code
2 (0x02) - Uncompressed, RGB images.
3 (0x03) - Uncompressed, black and white images.
10 (0x0A) - Runlength encoded RGB images.
11 (0x0B) - Compressed, black and white images. (grayscale?)
header[16] is the bit depth (8, 24, 32)
header[17] image descriptor (packed bits)
0x20 is 32 = origin upper-left
0x28 is 32 + 8 = origin upper-left + 32 bits
7 6 5 4 3 2 1 0
128 64 32 16 8 4 2 1
*/
int format = 0;
if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not
(header[16] == 8) && // 8 bits
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit
format = ALPHA;
} else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not
(header[16] == 24) && // 24 bits
((header[17] == 0x20) || (header[17] == 0))) { // origin
format = RGB;
} else if (((header[2] == 2) || (header[2] == 10)) &&
(header[16] == 32) &&
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32
format = ARGB;
}
if (format == 0) {
System.err.println("Unknown .tga file format for " + filename);
//" (" + header[2] + " " +
//(header[16] & 0xff) + " " +
//hex(header[17], 2) + ")");
return null;
}
int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff);
int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff);
PImage outgoing = createImage(w, h, format);
// where "reversed" means upper-left corner (normal for most of
// the modernized world, but "reversed" for the tga spec)
boolean reversed = (header[17] & 0x20) != 0;
if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded
if (reversed) {
int index = (h-1) * w;
switch (format) {
case ALPHA:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] = is.read();
}
index -= w;
}
break;
case RGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
index -= w;
}
break;
case ARGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
index -= w;
}
}
} else { // not reversed
int count = w * h;
switch (format) {
case ALPHA:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] = is.read();
}
break;
case RGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
break;
case ARGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
break;
}
}
} else { // header[2] is 10 or 11
int index = 0;
int px[] = outgoing.pixels;
while (index < px.length) {
int num = is.read();
boolean isRLE = (num & 0x80) != 0;
if (isRLE) {
num -= 127; // (num & 0x7F) + 1
int pixel = 0;
switch (format) {
case ALPHA:
pixel = is.read();
break;
case RGB:
pixel = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
break;
case ARGB:
pixel = is.read() |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
break;
}
for (int i = 0; i < num; i++) {
px[index++] = pixel;
if (index == px.length) break;
}
} else { // write up to 127 bytes as uncompressed
num += 1;
switch (format) {
case ALPHA:
for (int i = 0; i < num; i++) {
px[index++] = is.read();
}
break;
case RGB:
for (int i = 0; i < num; i++) {
px[index++] = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
case ARGB:
for (int i = 0; i < num; i++) {
px[index++] = is.read() | //(is.read() << 24) |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
}
}
}
if (!reversed) {
int[] temp = new int[w];
for (int y = 0; y < h/2; y++) {
int z = (h-1) - y;
System.arraycopy(px, y*w, temp, 0, w);
System.arraycopy(px, z*w, px, y*w, w);
System.arraycopy(temp, 0, px, z*w, w);
}
}
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// SHAPE I/O
/**
* Load a geometry from a file as a PShape. Currently only supports SVG data.
*/
public PShape loadShape(String filename) {
if (filename.toLowerCase().endsWith(".svg")) {
return new PShapeSVG(this, filename);
}
return null;
}
//////////////////////////////////////////////////////////////
// FONT I/O
public PFont loadFont(String filename) {
try {
InputStream input = createInput(filename);
return new PFont(input);
} catch (Exception e) {
die("Could not load font " + filename + ". " +
"Make sure that the font has been copied " +
"to the data folder of your sketch.", e);
}
return null;
}
public PFont createFont(String name, float size) {
return createFont(name, size, true, PFont.DEFAULT_CHARSET);
}
public PFont createFont(String name, float size, boolean smooth) {
return createFont(name, size, smooth, PFont.DEFAULT_CHARSET);
}
/**
* Create a .vlw font on the fly from either a font name that's
* installed on the system, or from a .ttf or .otf that's inside
* the data folder of this sketch.
* <P/>
* Only works with Java 1.3 or later. Many .otf fonts don't seem
* to be supported by Java, perhaps because they're CFF based?
* <P/>
* Font names are inconsistent across platforms and Java versions.
* On Mac OS X, Java 1.3 uses the font menu name of the font,
* whereas Java 1.4 uses the PostScript name of the font. Java 1.4
* on OS X will also accept the font menu name as well. On Windows,
* it appears that only the menu names are used, no matter what
* Java version is in use. Naming system unknown/untested for 1.5.
* <P/>
* Use 'null' for the charset if you want to use any of the 65,536
* unicode characters that exist in the font. Note that this can
* produce an enormous file or may cause an OutOfMemoryError.
*/
public PFont createFont(String name, float size,
boolean smooth, char charset[]) {
String lowerName = name.toLowerCase();
Font baseFont = null;
try {
if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) {
InputStream stream = createInput(name);
if (stream == null) {
System.err.println("The font \"" + name + "\" " +
"is missing or inaccessible, make sure " +
"the URL is valid or that the file has been " +
"added to your sketch and is readable.");
return null;
}
baseFont = Font.createFont(Font.TRUETYPE_FONT, createInput(name));
} else {
//baseFont = new Font(name, Font.PLAIN, 1);
baseFont = PFont.findFont(name);
}
} catch (Exception e) {
System.err.println("Problem using createFont() with " + name);
e.printStackTrace();
}
return new PFont(baseFont.deriveFont(size), smooth, charset);
}
//////////////////////////////////////////////////////////////
// FILE/FOLDER SELECTION
public File selectedFile;
protected Frame parentFrame;
protected void checkParentFrame() {
if (parentFrame == null) {
Component comp = getParent();
while (comp != null) {
if (comp instanceof Frame) {
parentFrame = (Frame) comp;
break;
}
comp = comp.getParent();
}
// Who you callin' a hack?
if (parentFrame == null) {
parentFrame = new Frame();
}
}
}
/**
* Open a platform-specific file chooser dialog to select a file for input.
* @return full path to the selected file, or null if no selection.
*/
public String selectInput() {
return selectInput("Select a file...");
}
/**
* Open a platform-specific file chooser dialog to select a file for input.
* @param prompt Mesage to show the user when prompting for a file.
* @return full path to the selected file, or null if canceled.
*/
public String selectInput(String prompt) {
return selectFileImpl(prompt, FileDialog.LOAD);
}
/**
* Open a platform-specific file save dialog to select a file for output.
* @return full path to the file entered, or null if canceled.
*/
public String selectOutput() {
return selectOutput("Save as...");
}
/**
* Open a platform-specific file save dialog to select a file for output.
* @param prompt Mesage to show the user when prompting for a file.
* @return full path to the file entered, or null if canceled.
*/
public String selectOutput(String prompt) {
return selectFileImpl(prompt, FileDialog.SAVE);
}
protected String selectFileImpl(final String prompt, final int mode) {
checkParentFrame();
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
FileDialog fileDialog =
new FileDialog(parentFrame, prompt, mode);
fileDialog.setVisible(true);
String directory = fileDialog.getDirectory();
String filename = fileDialog.getFile();
selectedFile =
(filename == null) ? null : new File(directory, filename);
}
});
return (selectedFile == null) ? null : selectedFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Open a platform-specific folder chooser dialog.
* @return full path to the selected folder, or null if no selection.
*/
public String selectFolder() {
return selectFolder("Select a folder...");
}
/**
* Open a platform-specific folder chooser dialog.
* @param prompt Mesage to show the user when prompting for a file.
* @return full path to the selected folder, or null if no selection.
*/
public String selectFolder(final String prompt) {
checkParentFrame();
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
if (platform == MACOSX) {
FileDialog fileDialog =
new FileDialog(parentFrame, prompt, FileDialog.LOAD);
System.setProperty("apple.awt.fileDialogForDirectories", "true");
fileDialog.setVisible(true);
System.setProperty("apple.awt.fileDialogForDirectories", "false");
String filename = fileDialog.getFile();
selectedFile = (filename == null) ? null :
new File(fileDialog.getDirectory(), fileDialog.getFile());
} else {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle(prompt);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returned = fileChooser.showOpenDialog(parentFrame);
System.out.println(returned);
if (returned == JFileChooser.CANCEL_OPTION) {
selectedFile = null;
} else {
selectedFile = fileChooser.getSelectedFile();
}
}
}
});
return (selectedFile == null) ? null : selectedFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//////////////////////////////////////////////////////////////
// READERS AND WRITERS
/**
* I want to read lines from a file. I have RSI from typing these
* eight lines of code so many times.
*/
public BufferedReader createReader(String filename) {
try {
InputStream is = createInput(filename);
if (is == null) {
System.err.println(filename + " does not exist or could not be read");
return null;
}
return createReader(is);
} catch (Exception e) {
if (filename == null) {
System.err.println("Filename passed to reader() was null");
} else {
System.err.println("Couldn't create a reader for " + filename);
}
}
return null;
}
/**
* I want to read lines from a file. And I'm still annoyed.
*/
static public BufferedReader createReader(File file) {
try {
InputStream is = new FileInputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
is = new GZIPInputStream(is);
}
return createReader(is);
} catch (Exception e) {
if (file == null) {
throw new RuntimeException("File passed to createReader() was null");
} else {
e.printStackTrace();
throw new RuntimeException("Couldn't create a reader for " +
file.getAbsolutePath());
}
}
//return null;
}
/**
* I want to read lines from a stream. If I have to type the
* following lines any more I'm gonna send Sun my medical bills.
*/
static public BufferedReader createReader(InputStream input) {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(input, "UTF-8");
} catch (UnsupportedEncodingException e) { } // not gonna happen
return new BufferedReader(isr);
}
/**
* I want to print lines to a file. Why can't I?
*/
public PrintWriter createWriter(String filename) {
return createWriter(saveFile(filename));
}
/**
* I want to print lines to a file. I have RSI from typing these
* eight lines of code so many times.
*/
static public PrintWriter createWriter(File file) {
try {
OutputStream output = new FileOutputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
output = new GZIPOutputStream(output);
}
return createWriter(output);
} catch (Exception e) {
if (file == null) {
throw new RuntimeException("File passed to createWriter() was null");
} else {
e.printStackTrace();
throw new RuntimeException("Couldn't create a writer for " +
file.getAbsolutePath());
}
}
//return null;
}
/**
* I want to print lines to a file. Why am I always explaining myself?
* It's the JavaSoft API engineers who need to explain themselves.
*/
static public PrintWriter createWriter(OutputStream output) {
try {
OutputStreamWriter osw = new OutputStreamWriter(output, "UTF-8");
return new PrintWriter(osw);
} catch (UnsupportedEncodingException e) { } // not gonna happen
return null;
}
//////////////////////////////////////////////////////////////
// FILE INPUT
/**
* @deprecated As of release 0136, use createInput() instead.
*/
public InputStream openStream(String filename) {
return createInput(filename);
}
/**
* Simplified method to open a Java InputStream.
* <P>
* This method is useful if you want to use the facilities provided
* by PApplet to easily open things from the data folder or from a URL,
* but want an InputStream object so that you can use other Java
* methods to take more control of how the stream is read.
* <P>
* If the requested item doesn't exist, null is returned.
* (Prior to 0096, die() would be called, killing the applet)
* <P>
* For 0096+, the "data" folder is exported intact with subfolders,
* and openStream() properly handles subdirectories from the data folder
* <P>
* If not online, this will also check to see if the user is asking
* for a file whose name isn't properly capitalized. This helps prevent
* issues when a sketch is exported to the web, where case sensitivity
* matters, as opposed to Windows and the Mac OS default where
* case sensitivity is preserved but ignored.
* <P>
* It is strongly recommended that libraries use this method to open
* data files, so that the loading sequence is handled in the same way
* as functions like loadBytes(), loadImage(), etc.
* <P>
* The filename passed in can be:
* <UL>
* <LI>A URL, for instance openStream("http://processing.org/");
* <LI>A file in the sketch's data folder
* <LI>Another file to be opened locally (when running as an application)
* </UL>
*/
public InputStream createInput(String filename) {
InputStream input = createInputRaw(filename);
if ((input != null) && filename.toLowerCase().endsWith(".gz")) {
try {
return new GZIPInputStream(input);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return input;
}
/**
* Call openStream() without automatic gzip decompression.
*/
public InputStream createInputRaw(String filename) {
InputStream stream = null;
if (filename == null) return null;
if (filename.length() == 0) {
// an error will be called by the parent function
//System.err.println("The filename passed to openStream() was empty.");
return null;
}
// safe to check for this as a url first. this will prevent online
// access logs from being spammed with GET /sketchfolder/http://blahblah
try {
URL url = new URL(filename);
stream = url.openStream();
return stream;
} catch (MalformedURLException mfue) {
// not a url, that's fine
} catch (FileNotFoundException fnfe) {
// Java 1.5 likes to throw this when URL not available. (fix for 0119)
// http://dev.processing.org/bugs/show_bug.cgi?id=403
} catch (IOException e) {
// changed for 0117, shouldn't be throwing exception
e.printStackTrace();
//System.err.println("Error downloading from URL " + filename);
return null;
//throw new RuntimeException("Error downloading from URL " + filename);
}
// Moved this earlier than the getResourceAsStream() checks, because
// calling getResourceAsStream() on a directory lists its contents.
// http://dev.processing.org/bugs/show_bug.cgi?id=716
try {
// First see if it's in a data folder. This may fail by throwing
// a SecurityException. If so, this whole block will be skipped.
File file = new File(dataPath(filename));
if (!file.exists()) {
// next see if it's just in the sketch folder
file = new File(sketchPath, filename);
}
if (file.isDirectory()) {
return null;
}
if (file.exists()) {
try {
// handle case sensitivity check
String filePath = file.getCanonicalPath();
String filenameActual = new File(filePath).getName();
// make sure there isn't a subfolder prepended to the name
String filenameShort = new File(filename).getName();
// if the actual filename is the same, but capitalized
// differently, warn the user.
//if (filenameActual.equalsIgnoreCase(filenameShort) &&
//!filenameActual.equals(filenameShort)) {
if (!filenameActual.equals(filenameShort)) {
throw new RuntimeException("This file is named " +
filenameActual + " not " +
filename + ". Rename the file " +
"or change your code.");
}
} catch (IOException e) { }
}
// if this file is ok, may as well just load it
stream = new FileInputStream(file);
if (stream != null) return stream;
// have to break these out because a general Exception might
// catch the RuntimeException being thrown above
} catch (IOException ioe) {
} catch (SecurityException se) { }
// Using getClassLoader() prevents java from converting dots
// to slashes or requiring a slash at the beginning.
// (a slash as a prefix means that it'll load from the root of
// the jar, rather than trying to dig into the package location)
ClassLoader cl = getClass().getClassLoader();
// by default, data files are exported to the root path of the jar.
// (not the data folder) so check there first.
stream = cl.getResourceAsStream("data/" + filename);
if (stream != null) {
String cn = stream.getClass().getName();
// this is an irritation of sun's java plug-in, which will return
// a non-null stream for an object that doesn't exist. like all good
// things, this is probably introduced in java 1.5. awesome!
// http://dev.processing.org/bugs/show_bug.cgi?id=359
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
return stream;
}
}
// When used with an online script, also need to check without the
// data folder, in case it's not in a subfolder called 'data'.
// http://dev.processing.org/bugs/show_bug.cgi?id=389
stream = cl.getResourceAsStream(filename);
if (stream != null) {
String cn = stream.getClass().getName();
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
return stream;
}
}
try {
// attempt to load from a local file, used when running as
// an application, or as a signed applet
try { // first try to catch any security exceptions
try {
stream = new FileInputStream(dataPath(filename));
if (stream != null) return stream;
} catch (IOException e2) { }
try {
stream = new FileInputStream(sketchPath(filename));
if (stream != null) return stream;
} catch (Exception e) { } // ignored
try {
stream = new FileInputStream(filename);
if (stream != null) return stream;
} catch (IOException e1) { }
} catch (SecurityException se) { } // online, whups
} catch (Exception e) {
//die(e.getMessage(), e);
e.printStackTrace();
}
return null;
}
static public InputStream createInput(File file) {
try {
InputStream input = new FileInputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
return new GZIPInputStream(input);
}
return input;
} catch (IOException e) {
if (file == null) {
throw new RuntimeException("File passed to openStream() was null");
} else {
e.printStackTrace();
throw new RuntimeException("Couldn't openStream() for " +
file.getAbsolutePath());
}
}
}
public byte[] loadBytes(String filename) {
InputStream is = createInput(filename);
if (is != null) return loadBytes(is);
System.err.println("The file \"" + filename + "\" " +
"is missing or inaccessible, make sure " +
"the URL is valid or that the file has been " +
"added to your sketch and is readable.");
return null;
}
static public byte[] loadBytes(InputStream input) {
try {
BufferedInputStream bis = new BufferedInputStream(input);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int c = bis.read();
while (c != -1) {
out.write(c);
c = bis.read();
}
return out.toByteArray();
} catch (IOException e) {
e.printStackTrace();
//throw new RuntimeException("Couldn't load bytes from stream");
}
return null;
}
static public byte[] loadBytes(File file) {
InputStream is = createInput(file);
return loadBytes(is);
}
static public String[] loadStrings(File file) {
InputStream is = createInput(file);
if (is != null) return loadStrings(is);
return null;
}
/**
* Load data from a file and shove it into a String array.
* <P>
* Exceptions are handled internally, when an error, occurs, an
* exception is printed to the console and 'null' is returned,
* but the program continues running. This is a tradeoff between
* 1) showing the user that there was a problem but 2) not requiring
* that all i/o code is contained in try/catch blocks, for the sake
* of new users (or people who are just trying to get things done
* in a "scripting" fashion. If you want to handle exceptions,
* use Java methods for I/O.
*/
public String[] loadStrings(String filename) {
InputStream is = createInput(filename);
if (is != null) return loadStrings(is);
System.err.println("The file \"" + filename + "\" " +
"is missing or inaccessible, make sure " +
"the URL is valid or that the file has been " +
"added to your sketch and is readable.");
return null;
}
static public String[] loadStrings(InputStream input) {
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(input, "UTF-8"));
String lines[] = new String[100];
int lineCount = 0;
String line = null;
while ((line = reader.readLine()) != null) {
if (lineCount == lines.length) {
String temp[] = new String[lineCount << 1];
System.arraycopy(lines, 0, temp, 0, lineCount);
lines = temp;
}
lines[lineCount++] = line;
}
reader.close();
if (lineCount == lines.length) {
return lines;
}
// resize array to appropriate amount for these lines
String output[] = new String[lineCount];
System.arraycopy(lines, 0, output, 0, lineCount);
return output;
} catch (IOException e) {
e.printStackTrace();
//throw new RuntimeException("Error inside loadStrings()");
}
return null;
}
//////////////////////////////////////////////////////////////
// FILE OUTPUT
/**
* Similar to createInput() (formerly openStream), this creates a Java
* OutputStream for a given filename or path. The file will be created in
* the sketch folder, or in the same folder as an exported application.
* <p/>
* If the path does not exist, intermediate folders will be created. If an
* exception occurs, it will be printed to the console, and null will be
* returned.
* <p/>
* Future releases may also add support for handling HTTP POST via this
* method (for better symmetry with createInput), however that's maybe a
* little too clever (and then we'd have to add the same features to the
* other file functions like createWriter). Who you callin' bloated?
*/
public OutputStream createOutput(String filename) {
return createOutput(saveFile(filename));
}
static public OutputStream createOutput(File file) {
try {
FileOutputStream fos = new FileOutputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
return new GZIPOutputStream(fos);
}
return fos;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Save the contents of a stream to a file in the sketch folder.
* This is basically saveBytes(blah, loadBytes()), but done
* more efficiently (and with less confusing syntax).
*/
public void saveStream(String targetFilename, String sourceLocation) {
saveStream(saveFile(targetFilename), sourceLocation);
}
/**
* Identical to the other saveStream(), but writes to a File
* object, for greater control over the file location.
* Note that unlike other api methods, this will not automatically
* compress or uncompress gzip files.
*/
public void saveStream(File targetFile, String sourceLocation) {
saveStream(targetFile, createInputRaw(sourceLocation));
}
static public void saveStream(File targetFile, InputStream sourceStream) {
File tempFile = null;
try {
File parentDir = targetFile.getParentFile();
tempFile = File.createTempFile(targetFile.getName(), null, parentDir);
BufferedInputStream bis = new BufferedInputStream(sourceStream, 16384);
FileOutputStream fos = new FileOutputStream(tempFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
bos.close();
bos = null;
if (!tempFile.renameTo(targetFile)) {
System.err.println("Could not rename temporary file " +
tempFile.getAbsolutePath());
}
} catch (IOException e) {
if (tempFile != null) {
tempFile.delete();
}
e.printStackTrace();
}
}
/**
* Saves bytes to a file to inside the sketch folder.
* The filename can be a relative path, i.e. "poo/bytefun.txt"
* would save to a file named "bytefun.txt" to a subfolder
* called 'poo' inside the sketch folder. If the in-between
* subfolders don't exist, they'll be created.
*/
public void saveBytes(String filename, byte buffer[]) {
saveBytes(saveFile(filename), buffer);
}
/**
* Saves bytes to a specific File location specified by the user.
*/
static public void saveBytes(File file, byte buffer[]) {
try {
String filename = file.getAbsolutePath();
createPath(filename);
OutputStream output = new FileOutputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
output = new GZIPOutputStream(output);
}
saveBytes(output, buffer);
output.close();
} catch (IOException e) {
System.err.println("error saving bytes to " + file);
e.printStackTrace();
}
}
/**
* Spews a buffer of bytes to an OutputStream.
*/
static public void saveBytes(OutputStream output, byte buffer[]) {
try {
output.write(buffer);
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
//
public void saveStrings(String filename, String strings[]) {
saveStrings(saveFile(filename), strings);
}
static public void saveStrings(File file, String strings[]) {
try {
String location = file.getAbsolutePath();
createPath(location);
OutputStream output = new FileOutputStream(location);
if (file.getName().toLowerCase().endsWith(".gz")) {
output = new GZIPOutputStream(output);
}
saveStrings(output, strings);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static public void saveStrings(OutputStream output, String strings[]) {
try {
OutputStreamWriter osw = new OutputStreamWriter(output, "UTF-8");
PrintWriter writer = new PrintWriter(osw);
for (int i = 0; i < strings.length; i++) {
writer.println(strings[i]);
}
writer.flush();
} catch (UnsupportedEncodingException e) { } // will not happen
}
//////////////////////////////////////////////////////////////
/**
* Prepend the sketch folder path to the filename (or path) that is
* passed in. External libraries should use this function to save to
* the sketch folder.
* <p/>
* Note that when running as an applet inside a web browser,
* the sketchPath will be set to null, because security restrictions
* prevent applets from accessing that information.
* <p/>
* This will also cause an error if the sketch is not inited properly,
* meaning that init() was never called on the PApplet when hosted
* my some other main() or by other code. For proper use of init(),
* see the examples in the main description text for PApplet.
*/
public String sketchPath(String where) {
if (sketchPath == null) {
return where;
// throw new RuntimeException("The applet was not inited properly, " +
// "or security restrictions prevented " +
// "it from determining its path.");
}
// isAbsolute() could throw an access exception, but so will writing
// to the local disk using the sketch path, so this is safe here.
// for 0120, added a try/catch anyways.
try {
if (new File(where).isAbsolute()) return where;
} catch (Exception e) { }
return sketchPath + File.separator + where;
}
public File sketchFile(String where) {
return new File(sketchPath(where));
}
/**
* Returns a path inside the applet folder to save to. Like sketchPath(),
* but creates any in-between folders so that things save properly.
* <p/>
* All saveXxxx() functions use the path to the sketch folder, rather than
* its data folder. Once exported, the data folder will be found inside the
* jar file of the exported application or applet. In this case, it's not
* possible to save data into the jar file, because it will often be running
* from a server, or marked in-use if running from a local file system.
* With this in mind, saving to the data path doesn't make sense anyway.
* If you know you're running locally, and want to save to the data folder,
* use <TT>saveXxxx("data/blah.dat")</TT>.
*/
public String savePath(String where) {
if (where == null) return null;
String filename = sketchPath(where);
createPath(filename);
return filename;
}
/**
* Identical to savePath(), but returns a File object.
*/
public File saveFile(String where) {
return new File(savePath(where));
}
/**
* Return a full path to an item in the data folder.
* <p>
* In this method, the data path is defined not as the applet's actual
* data path, but a folder titled "data" in the sketch's working
* directory. When running inside the PDE, this will be the sketch's
* "data" folder. However, when exported (as application or applet),
* sketch's data folder is exported as part of the applications jar file,
* and it's not possible to read/write from the jar file in a generic way.
* If you need to read data from the jar file, you should use createInput().
*/
public String dataPath(String where) {
// isAbsolute() could throw an access exception, but so will writing
// to the local disk using the sketch path, so this is safe here.
if (new File(where).isAbsolute()) return where;
return sketchPath + File.separator + "data" + File.separator + where;
}
/**
* Return a full path to an item in the data folder as a File object.
* See the dataPath() method for more information.
*/
public File dataFile(String where) {
return new File(dataPath(where));
}
/**
* Takes a path and creates any in-between folders if they don't
* already exist. Useful when trying to save to a subfolder that
* may not actually exist.
*/
static public void createPath(String path) {
try {
File file = new File(path);
String parent = file.getParent();
if (parent != null) {
File unit = new File(parent);
if (!unit.exists()) unit.mkdirs();
}
} catch (SecurityException se) {
System.err.println("You don't have permissions to create " + path);
}
}
//////////////////////////////////////////////////////////////
// SORT
static public byte[] sort(byte what[]) {
return sort(what, what.length);
}
static public byte[] sort(byte[] what, int count) {
byte[] outgoing = new byte[what.length];
System.arraycopy(what, 0, outgoing, 0, what.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public char[] sort(char what[]) {
return sort(what, what.length);
}
static public char[] sort(char[] what, int count) {
char[] outgoing = new char[what.length];
System.arraycopy(what, 0, outgoing, 0, what.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public int[] sort(int what[]) {
return sort(what, what.length);
}
static public int[] sort(int[] what, int count) {
int[] outgoing = new int[what.length];
System.arraycopy(what, 0, outgoing, 0, what.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public float[] sort(float what[]) {
return sort(what, what.length);
}
static public float[] sort(float[] what, int count) {
float[] outgoing = new float[what.length];
System.arraycopy(what, 0, outgoing, 0, what.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public String[] sort(String what[]) {
return sort(what, what.length);
}
static public String[] sort(String[] what, int count) {
String[] outgoing = new String[what.length];
System.arraycopy(what, 0, outgoing, 0, what.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
//////////////////////////////////////////////////////////////
// ARRAY UTILITIES
/**
* Calls System.arraycopy(), included here so that we can
* avoid people needing to learn about the System object
* before they can just copy an array.
*/
static public void arrayCopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* Convenience method for arraycopy().
* Identical to <CODE>arraycopy(src, 0, dst, 0, length);</CODE>
*/
static public void arrayCopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* Shortcut to copy the entire contents of
* the source into the destination array.
* Identical to <CODE>arraycopy(src, 0, dst, 0, src.length);</CODE>
*/
static public void arrayCopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
//
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
//
static public boolean[] expand(boolean list[]) {
return expand(list, list.length << 1);
}
static public boolean[] expand(boolean list[], int newSize) {
boolean temp[] = new boolean[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public byte[] expand(byte list[]) {
return expand(list, list.length << 1);
}
static public byte[] expand(byte list[], int newSize) {
byte temp[] = new byte[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public char[] expand(char list[]) {
return expand(list, list.length << 1);
}
static public char[] expand(char list[], int newSize) {
char temp[] = new char[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public int[] expand(int list[]) {
return expand(list, list.length << 1);
}
static public int[] expand(int list[], int newSize) {
int temp[] = new int[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public float[] expand(float list[]) {
return expand(list, list.length << 1);
}
static public float[] expand(float list[], int newSize) {
float temp[] = new float[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public String[] expand(String list[]) {
return expand(list, list.length << 1);
}
static public String[] expand(String list[], int newSize) {
String temp[] = new String[newSize];
// in case the new size is smaller than list.length
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public Object expand(Object array) {
return expand(array, Array.getLength(array) << 1);
}
static public Object expand(Object list, int newSize) {
Class<?> type = list.getClass().getComponentType();
Object temp = Array.newInstance(type, newSize);
System.arraycopy(list, 0, temp, 0,
Math.min(Array.getLength(list), newSize));
return temp;
}
//
// contract() has been removed in revision 0124, use subset() instead.
// (expand() is also functionally equivalent)
//
static public byte[] append(byte b[], byte value) {
b = expand(b, b.length + 1);
b[b.length-1] = value;
return b;
}
static public char[] append(char b[], char value) {
b = expand(b, b.length + 1);
b[b.length-1] = value;
return b;
}
static public int[] append(int b[], int value) {
b = expand(b, b.length + 1);
b[b.length-1] = value;
return b;
}
static public float[] append(float b[], float value) {
b = expand(b, b.length + 1);
b[b.length-1] = value;
return b;
}
static public String[] append(String b[], String value) {
b = expand(b, b.length + 1);
b[b.length-1] = value;
return b;
}
static public Object append(Object b, Object value) {
int length = Array.getLength(b);
b = expand(b, length + 1);
Array.set(b, length, value);
return b;
}
//
static public boolean[] shorten(boolean list[]) {
return subset(list, 0, list.length-1);
}
static public byte[] shorten(byte list[]) {
return subset(list, 0, list.length-1);
}
static public char[] shorten(char list[]) {
return subset(list, 0, list.length-1);
}
static public int[] shorten(int list[]) {
return subset(list, 0, list.length-1);
}
static public float[] shorten(float list[]) {
return subset(list, 0, list.length-1);
}
static public String[] shorten(String list[]) {
return subset(list, 0, list.length-1);
}
static public Object shorten(Object list) {
int length = Array.getLength(list);
return subset(list, 0, length - 1);
}
//
static final public boolean[] splice(boolean list[],
boolean v, int index) {
boolean outgoing[] = new boolean[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = v;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public boolean[] splice(boolean list[],
boolean v[], int index) {
boolean outgoing[] = new boolean[list.length + v.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(v, 0, outgoing, index, v.length);
System.arraycopy(list, index, outgoing, index + v.length,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte v, int index) {
byte outgoing[] = new byte[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = v;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte v[], int index) {
byte outgoing[] = new byte[list.length + v.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(v, 0, outgoing, index, v.length);
System.arraycopy(list, index, outgoing, index + v.length,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char v, int index) {
char outgoing[] = new char[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = v;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char v[], int index) {
char outgoing[] = new char[list.length + v.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(v, 0, outgoing, index, v.length);
System.arraycopy(list, index, outgoing, index + v.length,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int v, int index) {
int outgoing[] = new int[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = v;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int v[], int index) {
int outgoing[] = new int[list.length + v.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(v, 0, outgoing, index, v.length);
System.arraycopy(list, index, outgoing, index + v.length,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float v, int index) {
float outgoing[] = new float[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = v;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float v[], int index) {
float outgoing[] = new float[list.length + v.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(v, 0, outgoing, index, v.length);
System.arraycopy(list, index, outgoing, index + v.length,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String v, int index) {
String outgoing[] = new String[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = v;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String v[], int index) {
String outgoing[] = new String[list.length + v.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(v, 0, outgoing, index, v.length);
System.arraycopy(list, index, outgoing, index + v.length,
list.length - index);
return outgoing;
}
static final public Object splice(Object list, Object v, int index) {
Object[] outgoing = null;
int length = Array.getLength(list);
// check whether item being spliced in is an array
if (v.getClass().getName().charAt(0) == '[') {
int vlength = Array.getLength(v);
outgoing = new Object[length + vlength];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(v, 0, outgoing, index, vlength);
System.arraycopy(list, index, outgoing, index + vlength, length - index);
} else {
outgoing = new Object[length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
Array.set(outgoing, index, v);
System.arraycopy(list, index, outgoing, index + 1, length - index);
}
return outgoing;
}
//
static public boolean[] subset(boolean list[], int start) {
return subset(list, start, list.length - start);
}
static public boolean[] subset(boolean list[], int start, int count) {
boolean output[] = new boolean[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public byte[] subset(byte list[], int start) {
return subset(list, start, list.length - start);
}
static public byte[] subset(byte list[], int start, int count) {
byte output[] = new byte[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public char[] subset(char list[], int start) {
return subset(list, start, list.length - start);
}
static public char[] subset(char list[], int start, int count) {
char output[] = new char[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public int[] subset(int list[], int start) {
return subset(list, start, list.length - start);
}
static public int[] subset(int list[], int start, int count) {
int output[] = new int[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public float[] subset(float list[], int start) {
return subset(list, start, list.length - start);
}
static public float[] subset(float list[], int start, int count) {
float output[] = new float[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public String[] subset(String list[], int start) {
return subset(list, start, list.length - start);
}
static public String[] subset(String list[], int start, int count) {
String output[] = new String[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public Object subset(Object list, int start) {
int length = Array.getLength(list);
return subset(list, start, length - start);
}
static public Object subset(Object list, int start, int count) {
Class<?> type = list.getClass().getComponentType();
Object outgoing = Array.newInstance(type, count);
System.arraycopy(list, start, outgoing, 0, count);
return outgoing;
}
//
static public boolean[] concat(boolean a[], boolean b[]) {
boolean c[] = new boolean[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public byte[] concat(byte a[], byte b[]) {
byte c[] = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public char[] concat(char a[], char b[]) {
char c[] = new char[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public int[] concat(int a[], int b[]) {
int c[] = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public float[] concat(float a[], float b[]) {
float c[] = new float[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public String[] concat(String a[], String b[]) {
String c[] = new String[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public Object concat(Object a, Object b) {
Class<?> type = a.getClass().getComponentType();
int alength = Array.getLength(a);
int blength = Array.getLength(b);
Object outgoing = Array.newInstance(type, alength + blength);
System.arraycopy(a, 0, outgoing, 0, alength);
System.arraycopy(b, 0, outgoing, alength, blength);
return outgoing;
}
//
static public boolean[] reverse(boolean list[]) {
boolean outgoing[] = new boolean[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public byte[] reverse(byte list[]) {
byte outgoing[] = new byte[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public char[] reverse(char list[]) {
char outgoing[] = new char[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public int[] reverse(int list[]) {
int outgoing[] = new int[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public float[] reverse(float list[]) {
float outgoing[] = new float[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public String[] reverse(String list[]) {
String outgoing[] = new String[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public Object reverse(Object list) {
Class<?> type = list.getClass().getComponentType();
int length = Array.getLength(list);
Object outgoing = Array.newInstance(type, length);
for (int i = 0; i < length; i++) {
Array.set(outgoing, i, Array.get(list, (length - 1) - i));
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// STRINGS
/**
* Remove whitespace characters from the beginning and ending
* of a String. Works like String.trim() but includes the
* unicode nbsp character as well.
*/
static public String trim(String str) {
return str.replace('\u00A0', ' ').trim();
}
/**
* Trim the whitespace from a String array. This returns a new
* array and does not affect the passed-in array.
*/
static public String[] trim(String[] array) {
String[] outgoing = new String[array.length];
for (int i = 0; i < array.length; i++) {
outgoing[i] = array[i].replace('\u00A0', ' ').trim();
}
return outgoing;
}
/**
* Join an array of Strings together as a single String,
* separated by the whatever's passed in for the separator.
*/
static public String join(String str[], char separator) {
return join(str, String.valueOf(separator));
}
/**
* Join an array of Strings together as a single String,
* separated by the whatever's passed in for the separator.
* <P>
* To use this on numbers, first pass the array to nf() or nfs()
* to get a list of String objects, then use join on that.
* <PRE>
* e.g. String stuff[] = { "apple", "bear", "cat" };
* String list = join(stuff, ", ");
* // list is now "apple, bear, cat"</PRE>
*/
static public String join(String str[], String separator) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < str.length; i++) {
if (i != 0) buffer.append(separator);
buffer.append(str[i]);
}
return buffer.toString();
}
/**
* Split the provided String at wherever whitespace occurs.
* Multiple whitespace (extra spaces or tabs or whatever)
* between items will count as a single break.
* <P>
* The whitespace characters are "\t\n\r\f", which are the defaults
* for java.util.StringTokenizer, plus the unicode non-breaking space
* character, which is found commonly on files created by or used
* in conjunction with Mac OS X (character 160, or 0x00A0 in hex).
* <PRE>
* i.e. splitTokens("a b") -> { "a", "b" }
* splitTokens("a b") -> { "a", "b" }
* splitTokens("a\tb") -> { "a", "b" }
* splitTokens("a \t b ") -> { "a", "b" }</PRE>
*/
static public String[] splitTokens(String what) {
return splitTokens(what, WHITESPACE);
}
/**
* Splits a string into pieces, using any of the chars in the
* String 'delim' as separator characters. For instance,
* in addition to white space, you might want to treat commas
* as a separator. The delimeter characters won't appear in
* the returned String array.
* <PRE>
* i.e. splitTokens("a, b", " ,") -> { "a", "b" }
* </PRE>
* To include all the whitespace possibilities, use the variable
* WHITESPACE, found in PConstants:
* <PRE>
* i.e. splitTokens("a | b", WHITESPACE + "|"); -> { "a", "b" }</PRE>
*/
static public String[] splitTokens(String what, String delim) {
StringTokenizer toker = new StringTokenizer(what, delim);
String pieces[] = new String[toker.countTokens()];
int index = 0;
while (toker.hasMoreTokens()) {
pieces[index++] = toker.nextToken();
}
return pieces;
}
/**
* Split a string into pieces along a specific character.
* Most commonly used to break up a String along a space or a tab
* character.
* <P>
* This operates differently than the others, where the
* single delimeter is the only breaking point, and consecutive
* delimeters will produce an empty string (""). This way,
* one can split on tab characters, but maintain the column
* alignments (of say an excel file) where there are empty columns.
*/
static public String[] split(String what, char delim) {
// do this so that the exception occurs inside the user's
// program, rather than appearing to be a bug inside split()
if (what == null) return null;
//return split(what, String.valueOf(delim)); // huh
char chars[] = what.toCharArray();
int splitCount = 0; //1;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) splitCount++;
}
// make sure that there is something in the input string
//if (chars.length > 0) {
// if the last char is a delimeter, get rid of it..
//if (chars[chars.length-1] == delim) splitCount--;
// on second thought, i don't agree with this, will disable
//}
if (splitCount == 0) {
String splits[] = new String[1];
splits[0] = new String(what);
return splits;
}
//int pieceCount = splitCount + 1;
String splits[] = new String[splitCount + 1];
int splitIndex = 0;
int startIndex = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) {
splits[splitIndex++] =
new String(chars, startIndex, i-startIndex);
startIndex = i + 1;
}
}
//if (startIndex != chars.length) {
splits[splitIndex] =
new String(chars, startIndex, chars.length-startIndex);
//}
return splits;
}
/**
* Split a String on a specific delimiter.
*/
static public String[] split(String what, String delim) {
return what.split(delim);
}
/**
* Match a string with a regular expression, and returns the match as an
* array. The first index is the matching expression, and array elements
* [1] and higher represent each of the groups (sequences found in parens).
*
* This uses multiline matching (Pattern.MULTILINE) and dotall mode
* (Pattern.DOTALL) by default, so that ^ and $ match the beginning and
* end of any lines found in the source, and the . operator will also
* pick up newline characters.
*/
static public String[] match(String what, String regexp) {
Pattern p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
Matcher m = p.matcher(what);
if (m.find()) {
int count = m.groupCount() + 1;
String[] groups = new String[count];
for (int i = 0; i < count; i++) {
groups[i] = m.group(i);
}
return groups;
}
return null;
}
/**
* Identical to match(), except that it returns an array of all matches in
* the specified String, rather than just the first.
*/
static public String[][] matchAll(String what, String regexp) {
Pattern p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
Matcher m = p.matcher(what);
ArrayList<String[]> results = new ArrayList<String[]>();
int count = m.groupCount() + 1;
while (m.find()) {
String[] groups = new String[count];
for (int i = 0; i < count; i++) {
groups[i] = m.group(i);
}
results.add(groups);
}
if (results.isEmpty()) {
return null;
}
String[][] matches = new String[results.size()][count];
for (int i = 0; i < matches.length; i++) {
matches[i] = (String[]) results.get(i);
}
return matches;
}
//////////////////////////////////////////////////////////////
// CASTING FUNCTIONS, INSERTED BY PREPROC
/**
* Convert a char to a boolean. 'T', 't', and '1' will become the
* boolean value true, while 'F', 'f', or '0' will become false.
*/
/*
static final public boolean parseBoolean(char what) {
return ((what == 't') || (what == 'T') || (what == '1'));
}
*/
/**
* <p>Convert an integer to a boolean. Because of how Java handles upgrading
* numbers, this will also cover byte and char (as they will upgrade to
* an int without any sort of explicit cast).</p>
* <p>The preprocessor will convert boolean(what) to parseBoolean(what).</p>
* @return false if 0, true if any other number
*/
static final public boolean parseBoolean(int what) {
return (what != 0);
}
/*
// removed because this makes no useful sense
static final public boolean parseBoolean(float what) {
return (what != 0);
}
*/
/**
* Convert the string "true" or "false" to a boolean.
* @return true if 'what' is "true" or "TRUE", false otherwise
*/
static final public boolean parseBoolean(String what) {
return new Boolean(what).booleanValue();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
// removed, no need to introduce strange syntax from other languages
static final public boolean[] parseBoolean(char what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] =
((what[i] == 't') || (what[i] == 'T') || (what[i] == '1'));
}
return outgoing;
}
*/
/**
* Convert a byte array to a boolean array. Each element will be
* evaluated identical to the integer case, where a byte equal
* to zero will return false, and any other value will return true.
* @return array of boolean elements
*/
static final public boolean[] parseBoolean(byte what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
/**
* Convert an int array to a boolean array. An int equal
* to zero will return false, and any other value will return true.
* @return array of boolean elements
*/
static final public boolean[] parseBoolean(int what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
/*
// removed, not necessary... if necessary, convert to int array first
static final public boolean[] parseBoolean(float what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
*/
static final public boolean[] parseBoolean(String what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = new Boolean(what[i]).booleanValue();
}
return outgoing;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public byte parseByte(boolean what) {
return what ? (byte)1 : 0;
}
static final public byte parseByte(char what) {
return (byte) what;
}
static final public byte parseByte(int what) {
return (byte) what;
}
static final public byte parseByte(float what) {
return (byte) what;
}
/*
// nixed, no precedent
static final public byte[] parseByte(String what) { // note: array[]
return what.getBytes();
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public byte[] parseByte(boolean what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i] ? (byte)1 : 0;
}
return outgoing;
}
static final public byte[] parseByte(char what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
static final public byte[] parseByte(int what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
static final public byte[] parseByte(float what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
/*
static final public byte[][] parseByte(String what[]) { // note: array[][]
byte outgoing[][] = new byte[what.length][];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i].getBytes();
}
return outgoing;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public char parseChar(boolean what) { // 0/1 or T/F ?
return what ? 't' : 'f';
}
*/
static final public char parseChar(byte what) {
return (char) (what & 0xff);
}
static final public char parseChar(int what) {
return (char) what;
}
/*
static final public char parseChar(float what) { // nonsensical
return (char) what;
}
static final public char[] parseChar(String what) { // note: array[]
return what.toCharArray();
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ?
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i] ? 't' : 'f';
}
return outgoing;
}
*/
static final public char[] parseChar(byte what[]) {
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) (what[i] & 0xff);
}
return outgoing;
}
static final public char[] parseChar(int what[]) {
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) what[i];
}
return outgoing;
}
/*
static final public char[] parseChar(float what[]) { // nonsensical
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) what[i];
}
return outgoing;
}
static final public char[][] parseChar(String what[]) { // note: array[][]
char outgoing[][] = new char[what.length][];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i].toCharArray();
}
return outgoing;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public int parseInt(boolean what) {
return what ? 1 : 0;
}
/**
* Note that parseInt() will un-sign a signed byte value.
*/
static final public int parseInt(byte what) {
return what & 0xff;
}
/**
* Note that parseInt('5') is unlike String in the sense that it
* won't return 5, but the ascii value. This is because ((int) someChar)
* returns the ascii value, and parseInt() is just longhand for the cast.
*/
static final public int parseInt(char what) {
return what;
}
/**
* Same as floor(), or an (int) cast.
*/
static final public int parseInt(float what) {
return (int) what;
}
/**
* Parse a String into an int value. Returns 0 if the value is bad.
*/
static final public int parseInt(String what) {
return parseInt(what, 0);
}
/**
* Parse a String to an int, and provide an alternate value that
* should be used when the number is invalid.
*/
static final public int parseInt(String what, int otherwise) {
try {
int offset = what.indexOf('.');
if (offset == -1) {
return Integer.parseInt(what);
} else {
return Integer.parseInt(what.substring(0, offset));
}
} catch (NumberFormatException e) { }
return otherwise;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public int[] parseInt(boolean what[]) {
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = what[i] ? 1 : 0;
}
return list;
}
static final public int[] parseInt(byte what[]) { // note this unsigns
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = (what[i] & 0xff);
}
return list;
}
static final public int[] parseInt(char what[]) {
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = what[i];
}
return list;
}
static public int[] parseInt(float what[]) {
int inties[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
inties[i] = (int)what[i];
}
return inties;
}
/**
* Make an array of int elements from an array of String objects.
* If the String can't be parsed as a number, it will be set to zero.
*
* String s[] = { "1", "300", "44" };
* int numbers[] = parseInt(s);
*
* numbers will contain { 1, 300, 44 }
*/
static public int[] parseInt(String what[]) {
return parseInt(what, 0);
}
/**
* Make an array of int elements from an array of String objects.
* If the String can't be parsed as a number, its entry in the
* array will be set to the value of the "missing" parameter.
*
* String s[] = { "1", "300", "apple", "44" };
* int numbers[] = parseInt(s, 9999);
*
* numbers will contain { 1, 300, 9999, 44 }
*/
static public int[] parseInt(String what[], int missing) {
int output[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
try {
output[i] = Integer.parseInt(what[i]);
} catch (NumberFormatException e) {
output[i] = missing;
}
}
return output;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public float parseFloat(boolean what) {
return what ? 1 : 0;
}
*/
/**
* Convert an int to a float value. Also handles bytes because of
* Java's rules for upgrading values.
*/
static final public float parseFloat(int what) { // also handles byte
return (float)what;
}
static final public float parseFloat(String what) {
return parseFloat(what, Float.NaN);
}
static final public float parseFloat(String what, float otherwise) {
try {
return new Float(what).floatValue();
} catch (NumberFormatException e) { }
return otherwise;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public float[] parseFloat(boolean what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i] ? 1 : 0;
}
return floaties;
}
static final public float[] parseFloat(char what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = (char) what[i];
}
return floaties;
}
*/
static final public float[] parseByte(byte what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i];
}
return floaties;
}
static final public float[] parseFloat(int what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i];
}
return floaties;
}
static final public float[] parseFloat(String what[]) {
return parseFloat(what, Float.NaN);
}
static final public float[] parseFloat(String what[], float missing) {
float output[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
try {
output[i] = new Float(what[i]).floatValue();
} catch (NumberFormatException e) {
output[i] = missing;
}
}
return output;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public String str(boolean x) {
return String.valueOf(x);
}
static final public String str(byte x) {
return String.valueOf(x);
}
static final public String str(char x) {
return String.valueOf(x);
}
static final public String str(int x) {
return String.valueOf(x);
}
static final public String str(float x) {
return String.valueOf(x);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public String[] str(boolean x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(byte x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(char x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(int x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(float x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
//////////////////////////////////////////////////////////////
// INT NUMBER FORMATTING
/**
* Integer number formatter.
*/
static private NumberFormat int_nf;
static private int int_nf_digits;
static private boolean int_nf_commas;
static public String[] nf(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nf(num[i], digits);
}
return formatted;
}
static public String nf(int num, int digits) {
if ((int_nf != null) &&
(int_nf_digits == digits) &&
!int_nf_commas) {
return int_nf.format(num);
}
int_nf = NumberFormat.getInstance();
int_nf.setGroupingUsed(false); // no commas
int_nf_commas = false;
int_nf.setMinimumIntegerDigits(digits);
int_nf_digits = digits;
return int_nf.format(num);
}
static public String[] nfc(int num[]) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfc(num[i]);
}
return formatted;
}
static public String nfc(int num) {
if ((int_nf != null) &&
(int_nf_digits == 0) &&
int_nf_commas) {
return int_nf.format(num);
}
int_nf = NumberFormat.getInstance();
int_nf.setGroupingUsed(true);
int_nf_commas = true;
int_nf.setMinimumIntegerDigits(0);
int_nf_digits = 0;
return int_nf.format(num);
}
/**
* number format signed (or space)
* Formats a number but leaves a blank space in the front
* when it's positive so that it can be properly aligned with
* numbers that have a negative sign in front of them.
*/
static public String nfs(int num, int digits) {
return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits));
}
static public String[] nfs(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfs(num[i], digits);
}
return formatted;
}
//
/**
* number format positive (or plus)
* Formats a number, always placing a - or + sign
* in the front when it's negative or positive.
*/
static public String nfp(int num, int digits) {
return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits));
}
static public String[] nfp(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfp(num[i], digits);
}
return formatted;
}
//////////////////////////////////////////////////////////////
// FLOAT NUMBER FORMATTING
static private NumberFormat float_nf;
static private int float_nf_left, float_nf_right;
static private boolean float_nf_commas;
static public String[] nf(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nf(num[i], left, right);
}
return formatted;
}
static public String nf(float num, int left, int right) {
if ((float_nf != null) &&
(float_nf_left == left) &&
(float_nf_right == right) &&
!float_nf_commas) {
return float_nf.format(num);
}
float_nf = NumberFormat.getInstance();
float_nf.setGroupingUsed(false);
float_nf_commas = false;
if (left != 0) float_nf.setMinimumIntegerDigits(left);
if (right != 0) {
float_nf.setMinimumFractionDigits(right);
float_nf.setMaximumFractionDigits(right);
}
float_nf_left = left;
float_nf_right = right;
return float_nf.format(num);
}
static public String[] nfc(float num[], int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfc(num[i], right);
}
return formatted;
}
static public String nfc(float num, int right) {
if ((float_nf != null) &&
(float_nf_left == 0) &&
(float_nf_right == right) &&
float_nf_commas) {
return float_nf.format(num);
}
float_nf = NumberFormat.getInstance();
float_nf.setGroupingUsed(true);
float_nf_commas = true;
if (right != 0) {
float_nf.setMinimumFractionDigits(right);
float_nf.setMaximumFractionDigits(right);
}
float_nf_left = 0;
float_nf_right = right;
return float_nf.format(num);
}
/**
* Number formatter that takes into account whether the number
* has a sign (positive, negative, etc) in front of it.
*/
static public String[] nfs(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfs(num[i], left, right);
}
return formatted;
}
static public String nfs(float num, int left, int right) {
return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right));
}
static public String[] nfp(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfp(num[i], left, right);
}
return formatted;
}
static public String nfp(float num, int left, int right) {
return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right));
}
//////////////////////////////////////////////////////////////
// HEX/BINARY CONVERSION
static final public String hex(byte what) {
return hex(what, 2);
}
static final public String hex(char what) {
return hex(what, 4);
}
static final public String hex(int what) {
return hex(what, 8);
}
static final public String hex(int what, int digits) {
String stuff = Integer.toHexString(what).toUpperCase();
int length = stuff.length();
if (length > digits) {
return stuff.substring(length - digits);
} else if (length < digits) {
return "00000000".substring(8 - (digits-length)) + stuff;
}
return stuff;
}
static final public int unhex(String what) {
// has to parse as a Long so that it'll work for numbers bigger than 2^31
return (int) (Long.parseLong(what, 16));
}
//
/**
* Returns a String that contains the binary value of a byte.
* The returned value will always have 8 digits.
*/
static final public String binary(byte what) {
return binary(what, 8);
}
/**
* Returns a String that contains the binary value of a char.
* The returned value will always have 16 digits because chars
* are two bytes long.
*/
static final public String binary(char what) {
return binary(what, 16);
}
/**
* Returns a String that contains the binary value of an int.
* The length depends on the size of the number itself.
* An int can be up to 32 binary digits, but that seems like
* overkill for almost any situation, so this function just
* auto-size. If you want a specific number of digits (like all 32)
* use binary(int what, int digits) to specify how many digits.
*/
static final public String binary(int what) {
return Integer.toBinaryString(what);
//return binary(what, 32);
}
/**
* Returns a String that contains the binary value of an int.
* The digits parameter determines how many digits will be used.
*/
static final public String binary(int what, int digits) {
String stuff = Integer.toBinaryString(what);
int length = stuff.length();
if (length > digits) {
return stuff.substring(length - digits);
} else if (length < digits) {
int offset = 32 - (digits-length);
return "00000000000000000000000000000000".substring(offset) + stuff;
}
return stuff;
}
/**
* Unpack a binary String into an int.
* i.e. unbinary("00001000") would return 8.
*/
static final public int unbinary(String what) {
return Integer.parseInt(what, 2);
}
//////////////////////////////////////////////////////////////
// COLOR FUNCTIONS
// moved here so that they can work without
// the graphics actually being instantiated (outside setup)
public final int color(int gray) {
if (g == null) {
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(gray);
}
public final int color(float fgray) {
if (g == null) {
int gray = (int) fgray;
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(fgray);
}
/**
* As of 0116 this also takes color(#FF8800, alpha)
*/
public final int color(int gray, int alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (gray > 255) {
// then assume this is actually a #FF8800
return (alpha << 24) | (gray & 0xFFFFFF);
} else {
//if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return (alpha << 24) | (gray << 16) | (gray << 8) | gray;
}
}
return g.color(gray, alpha);
}
public final int color(float fgray, float falpha) {
if (g == null) {
int gray = (int) fgray;
int alpha = (int) falpha;
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(fgray, falpha);
}
public final int color(int x, int y, int z) {
if (g == null) {
if (x > 255) x = 255; else if (x < 0) x = 0;
if (y > 255) y = 255; else if (y < 0) y = 0;
if (z > 255) z = 255; else if (z < 0) z = 0;
return 0xff000000 | (x << 16) | (y << 8) | z;
}
return g.color(x, y, z);
}
public final int color(float x, float y, float z) {
if (g == null) {
if (x > 255) x = 255; else if (x < 0) x = 0;
if (y > 255) y = 255; else if (y < 0) y = 0;
if (z > 255) z = 255; else if (z < 0) z = 0;
return 0xff000000 | ((int)x << 16) | ((int)y << 8) | (int)z;
}
return g.color(x, y, z);
}
public final int color(int x, int y, int z, int a) {
if (g == null) {
if (a > 255) a = 255; else if (a < 0) a = 0;
if (x > 255) x = 255; else if (x < 0) x = 0;
if (y > 255) y = 255; else if (y < 0) y = 0;
if (z > 255) z = 255; else if (z < 0) z = 0;
return (a << 24) | (x << 16) | (y << 8) | z;
}
return g.color(x, y, z, a);
}
public final int color(float x, float y, float z, float a) {
if (g == null) {
if (a > 255) a = 255; else if (a < 0) a = 0;
if (x > 255) x = 255; else if (x < 0) x = 0;
if (y > 255) y = 255; else if (y < 0) y = 0;
if (z > 255) z = 255; else if (z < 0) z = 0;
return ((int)a << 24) | ((int)x << 16) | ((int)y << 8) | (int)z;
}
return g.color(x, y, z, a);
}
//////////////////////////////////////////////////////////////
// MAIN
/**
* Set this sketch to communicate its state back to the PDE.
* <p/>
* This uses the stderr stream to write positions of the window
* (so that it will be saved by the PDE for the next run) and
* notify on quit. See more notes in the Worker class.
*/
public void setupExternalMessages() {
frame.addComponentListener(new ComponentAdapter() {
public void componentMoved(ComponentEvent e) {
Point where = ((Frame) e.getSource()).getLocation();
System.err.println(PApplet.EXTERNAL_MOVE + " " +
where.x + " " + where.y);
System.err.flush(); // doesn't seem to help or hurt
}
});
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
// System.err.println(PApplet.EXTERNAL_QUIT);
// System.err.flush(); // important
// System.exit(0);
exit(); // don't quit, need to just shut everything down (0133)
}
});
}
/**
* Set up a listener that will fire proper component resize events
* in cases where frame.setResizable(true) is called.
*/
public void setupFrameResizeListener() {
frame.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
// Ignore bad resize events fired during setup to fix
// http://dev.processing.org/bugs/show_bug.cgi?id=341
// This should also fix the blank screen on Linux bug
// http://dev.processing.org/bugs/show_bug.cgi?id=282
if (frame.isResizable()) {
// might be multiple resize calls before visible (i.e. first
// when pack() is called, then when it's resized for use).
// ignore them because it's not the user resizing things.
Frame farm = (Frame) e.getComponent();
if (farm.isVisible()) {
Insets insets = farm.getInsets();
Dimension windowSize = farm.getSize();
int usableW = windowSize.width - insets.left - insets.right;
int usableH = windowSize.height - insets.top - insets.bottom;
// the ComponentListener in PApplet will handle calling size()
setBounds(insets.left, insets.top, usableW, usableH);
}
}
}
});
}
/**
* GIF image of the Processing logo.
*/
static public final byte[] ICON_IMAGE = {
71, 73, 70, 56, 57, 97, 16, 0, 16, 0, -77, 0, 0, 0, 0, 0, -1, -1, -1, 12,
12, 13, -15, -15, -14, 45, 57, 74, 54, 80, 111, 47, 71, 97, 62, 88, 117,
1, 14, 27, 7, 41, 73, 15, 52, 85, 2, 31, 55, 4, 54, 94, 18, 69, 109, 37,
87, 126, -1, -1, -1, 33, -7, 4, 1, 0, 0, 15, 0, 44, 0, 0, 0, 0, 16, 0, 16,
0, 0, 4, 122, -16, -107, 114, -86, -67, 83, 30, -42, 26, -17, -100, -45,
56, -57, -108, 48, 40, 122, -90, 104, 67, -91, -51, 32, -53, 77, -78, -100,
47, -86, 12, 76, -110, -20, -74, -101, 97, -93, 27, 40, 20, -65, 65, 48,
-111, 99, -20, -112, -117, -123, -47, -105, 24, 114, -112, 74, 69, 84, 25,
93, 88, -75, 9, 46, 2, 49, 88, -116, -67, 7, -19, -83, 60, 38, 3, -34, 2,
66, -95, 27, -98, 13, 4, -17, 55, 33, 109, 11, 11, -2, -128, 121, 123, 62,
91, 120, -128, 127, 122, 115, 102, 2, 119, 0, -116, -113, -119, 6, 102,
121, -108, -126, 5, 18, 6, 4, -102, -101, -100, 114, 15, 17, 0, 59
};
/**
* main() method for running this class from the command line.
* <P>
* <B>The options shown here are not yet finalized and will be
* changing over the next several releases.</B>
* <P>
* The simplest way to turn and applet into an application is to
* add the following code to your program:
* <PRE>static public void main(String args[]) {
* PApplet.main(new String[] { "YourSketchName" });
* }</PRE>
* This will properly launch your applet from a double-clickable
* .jar or from the command line.
* <PRE>
* Parameters useful for launching or also used by the PDE:
*
* --location=x,y upper-lefthand corner of where the applet
* should appear on screen. if not used,
* the default is to center on the main screen.
*
* --present put the applet into full screen presentation
* mode. requires java 1.4 or later.
*
* --hide-stop use to hide the stop button in situations where
* you don't want to allow users to exit. also
* see the FAQ on information for capturing the ESC
* key when running in presentation mode.
*
* --stop-color color of the 'stop' text used to quit an
* sketch when it's in present mode.
*
* --bgcolor=#xxxxxx background color of the window.
*
* --sketch-path location of where to save files from functions
* like saveStrings() or saveFrame(). defaults to
* the folder that the java application was
* launched from, which means if this isn't set by
* the pde, everything goes into the same folder
* as processing.exe.
*
* --display=n set what display should be used by this applet.
* displays are numbered starting from 1.
*
* Parameters used by Processing when running via the PDE
*
* --external set when the applet is being used by the PDE
*
* --editor-location=x,y position of the upper-lefthand corner of the
* editor window, for placement of applet window
* </PRE>
*/
static public void main(String args[]) {
// Disable abyssmally slow Sun renderer on OS X 10.5.
if (platform == MACOSX) {
// Only run this on OS X otherwise it can cause a permissions error.
// http://dev.processing.org/bugs/show_bug.cgi?id=976
System.setProperty("apple.awt.graphics.UseQuartz", "true");
}
- if (platform == WINDOWS) {
- // For now, disable the D3D renderer on Java 6u10 because
- // it causes problems with Present mode.
- // http://dev.processing.org/bugs/show_bug.cgi?id=1009
- System.setProperty("sun.java2d.d3d", "false");
- }
+ // This doesn't do anything.
+// if (platform == WINDOWS) {
+// // For now, disable the D3D renderer on Java 6u10 because
+// // it causes problems with Present mode.
+// // http://dev.processing.org/bugs/show_bug.cgi?id=1009
+// System.setProperty("sun.java2d.d3d", "false");
+// }
if (args.length < 1) {
System.err.println("Usage: PApplet <appletname>");
System.err.println("For additional options, " +
"see the Javadoc for PApplet");
System.exit(1);
}
try {
boolean external = false;
int location[] = null;
int editorLocation[] = null;
String name = null;
boolean present = false;
- Color backgroundColor = Color.black; //BLACK;
- Color stopColor = Color.gray; //GRAY;
+ Color backgroundColor = Color.BLACK;
+ Color stopColor = Color.GRAY;
GraphicsDevice displayDevice = null;
boolean hideStop = false;
String param = null, value = null;
// try to get the user folder. if running under java web start,
// this may cause a security exception if the code is not signed.
// http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274
String folder = null;
try {
folder = System.getProperty("user.dir");
} catch (Exception e) { }
int argIndex = 0;
while (argIndex < args.length) {
int equals = args[argIndex].indexOf('=');
if (equals != -1) {
param = args[argIndex].substring(0, equals);
value = args[argIndex].substring(equals + 1);
if (param.equals(ARGS_EDITOR_LOCATION)) {
external = true;
editorLocation = parseInt(split(value, ','));
} else if (param.equals(ARGS_DISPLAY)) {
int deviceIndex = Integer.parseInt(value) - 1;
//DisplayMode dm = device.getDisplayMode();
//if ((dm.getWidth() == 1024) && (dm.getHeight() == 768)) {
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice devices[] = environment.getScreenDevices();
if ((deviceIndex >= 0) && (deviceIndex < devices.length)) {
displayDevice = devices[deviceIndex];
} else {
System.err.println("Display " + value + " does not exist, " +
"using the default display instead.");
}
} else if (param.equals(ARGS_BGCOLOR)) {
if (value.charAt(0) == '#') value = value.substring(1);
backgroundColor = new Color(Integer.parseInt(value, 16));
} else if (param.equals(ARGS_STOP_COLOR)) {
if (value.charAt(0) == '#') value = value.substring(1);
stopColor = new Color(Integer.parseInt(value, 16));
} else if (param.equals(ARGS_SKETCH_FOLDER)) {
folder = value;
} else if (param.equals(ARGS_LOCATION)) {
location = parseInt(split(value, ','));
}
} else {
if (args[argIndex].equals(ARGS_PRESENT)) {
present = true;
} else if (args[argIndex].equals(ARGS_HIDE_STOP)) {
hideStop = true;
} else if (args[argIndex].equals(ARGS_EXTERNAL)) {
external = true;
} else {
name = args[argIndex];
break;
}
}
argIndex++;
}
// Set this property before getting into any GUI init code
//System.setProperty("com.apple.mrj.application.apple.menu.about.name", name);
// This )*)(*@#$ Apple crap don't work no matter where you put it
// (static method of the class, at the top of main, wherever)
if (displayDevice == null) {
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
displayDevice = environment.getDefaultScreenDevice();
}
Frame frame = new Frame(displayDevice.getDefaultConfiguration());
/*
Frame frame = null;
if (displayDevice != null) {
frame = new Frame(displayDevice.getDefaultConfiguration());
} else {
frame = new Frame();
}
*/
//Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
// remove the grow box by default
// users who want it back can call frame.setResizable(true)
frame.setResizable(false);
// Set the trimmings around the image
Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE);
frame.setIconImage(image);
frame.setTitle(name);
// Class c = Class.forName(name);
Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(name);
PApplet applet = (PApplet) c.newInstance();
// these are needed before init/start
applet.frame = frame;
applet.sketchPath = folder;
applet.args = PApplet.subset(args, 1);
applet.external = external;
// Need to save the window bounds at full screen,
// because pack() will cause the bounds to go to zero.
// http://dev.processing.org/bugs/show_bug.cgi?id=923
Rectangle fullScreenRect = null;
// For 0149, moving this code (up to the pack() method) before init().
// For OpenGL (and perhaps other renderers in the future), a peer is
// needed before a GLDrawable can be created. So pack() needs to be
// called on the Frame before applet.init(), which itself calls size(),
// and launches the Thread that will kick off setup().
// http://dev.processing.org/bugs/show_bug.cgi?id=891
// http://dev.processing.org/bugs/show_bug.cgi?id=908
if (present) {
frame.setUndecorated(true);
frame.setBackground(backgroundColor);
- displayDevice.setFullScreenWindow(frame);
- fullScreenRect = frame.getBounds();
+ if (platform == MACOSX) {
+ displayDevice.setFullScreenWindow(frame);
+ fullScreenRect = frame.getBounds();
+ } else {
+ DisplayMode mode = displayDevice.getDisplayMode();
+ fullScreenRect = new Rectangle(0, 0, mode.getWidth(), mode.getHeight());
+ frame.setBounds(fullScreenRect);
+ frame.setVisible(true);
+ }
}
frame.setLayout(null);
frame.add(applet);
- frame.pack();
+ //frame.pack();
+ frame.validate();
applet.init();
// Wait until the applet has figured out its width.
// In a static mode app, this will be after setup() has completed,
// and the empty draw() has set "finished" to true.
// TODO make sure this won't hang if the applet has an exception.
while (applet.defaultSize && !applet.finished) {
//System.out.println("default size");
try {
Thread.sleep(5);
} catch (InterruptedException e) {
//System.out.println("interrupt");
}
}
//println("not default size " + applet.width + " " + applet.height);
//println(" (g width/height is " + applet.g.width + "x" + applet.g.height + ")");
if (present) {
// After the pack(), the screen bounds are gonna be 0s
frame.setBounds(fullScreenRect);
applet.setBounds((fullScreenRect.width - applet.width) / 2,
(fullScreenRect.height - applet.height) / 2,
applet.width, applet.height);
if (!hideStop) {
Label label = new Label("stop");
label.setForeground(stopColor);
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
System.exit(0);
}
});
frame.add(label);
Dimension labelSize = label.getPreferredSize();
// sometimes shows up truncated on mac
//System.out.println("label width is " + labelSize.width);
labelSize = new Dimension(100, labelSize.height);
label.setSize(labelSize);
label.setLocation(20, fullScreenRect.height - labelSize.height - 20);
}
// not always running externally when in present mode
if (external) {
applet.setupExternalMessages();
}
} else { // if not presenting
// can't do pack earlier cuz present mode don't like it
// (can't go full screen with a frame after calling pack)
// frame.pack(); // get insets. get more.
Insets insets = frame.getInsets();
int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) +
insets.left + insets.right;
int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) +
insets.top + insets.bottom;
frame.setSize(windowW, windowH);
if (location != null) {
// a specific location was received from PdeRuntime
// (applet has been run more than once, user placed window)
frame.setLocation(location[0], location[1]);
} else if (external) {
int locationX = editorLocation[0] - 20;
int locationY = editorLocation[1];
if (locationX - windowW > 10) {
// if it fits to the left of the window
frame.setLocation(locationX - windowW, locationY);
} else { // doesn't fit
// if it fits inside the editor window,
// offset slightly from upper lefthand corner
// so that it's plunked inside the text area
locationX = editorLocation[0] + 66;
locationY = editorLocation[1] + 66;
if ((locationX + windowW > applet.screen.width - 33) ||
(locationY + windowH > applet.screen.height - 33)) {
// otherwise center on screen
locationX = (applet.screen.width - windowW) / 2;
locationY = (applet.screen.height - windowH) / 2;
}
frame.setLocation(locationX, locationY);
}
} else { // just center on screen
frame.setLocation((applet.screen.width - applet.width) / 2,
(applet.screen.height - applet.height) / 2);
}
// frame.setLayout(null);
// frame.add(applet);
if (backgroundColor == Color.black) { //BLACK) {
// this means no bg color unless specified
backgroundColor = SystemColor.control;
}
frame.setBackground(backgroundColor);
int usableWindowH = windowH - insets.top - insets.bottom;
applet.setBounds((windowW - applet.width)/2,
insets.top + (usableWindowH - applet.height)/2,
applet.width, applet.height);
if (external) {
applet.setupExternalMessages();
} else { // !external
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
// handle frame resizing events
applet.setupFrameResizeListener();
// all set for rockin
if (applet.displayable()) {
frame.setVisible(true);
}
}
//System.out.println("showing frame");
//System.out.println("applet requesting focus");
applet.requestFocus(); // ask for keydowns
//System.out.println("exiting main()");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
//////////////////////////////////////////////////////////////
/**
* Begin recording to a new renderer of the specified type, using the width
* and height of the main drawing surface.
*/
public PGraphics beginRecord(String renderer, String filename) {
filename = insertFrame(filename);
PGraphics rec = createGraphics(width, height, renderer, filename);
beginRecord(rec);
return rec;
}
/**
* Begin recording (echoing) commands to the specified PGraphics object.
*/
public void beginRecord(PGraphics recorder) {
this.recorder = recorder;
recorder.beginDraw();
}
public void endRecord() {
if (recorder != null) {
recorder.endDraw();
recorder.dispose();
recorder = null;
}
}
/**
* Begin recording raw shape data to a renderer of the specified type,
* using the width and height of the main drawing surface.
*
* If hashmarks (###) are found in the filename, they'll be replaced
* by the current frame number (frameCount).
*/
public PGraphics beginRaw(String renderer, String filename) {
filename = insertFrame(filename);
PGraphics rec = createGraphics(width, height, renderer, filename);
g.beginRaw(rec);
return rec;
}
/**
* Begin recording raw shape data to the specified renderer.
*
* This simply echoes to g.beginRaw(), but since is placed here (rather than
* generated by preproc.pl) for clarity and so that it doesn't echo the
* command should beginRecord() be in use.
*/
public void beginRaw(PGraphics rawGraphics) {
g.beginRaw(rawGraphics);
}
/**
* Stop recording raw shape data to the specified renderer.
*
* This simply echoes to g.beginRaw(), but since is placed here (rather than
* generated by preproc.pl) for clarity and so that it doesn't echo the
* command should beginRecord() be in use.
*/
public void endRaw() {
g.endRaw();
}
//////////////////////////////////////////////////////////////
/**
* Override the g.pixels[] function to set the pixels[] array
* that's part of the PApplet object. Allows the use of
* pixels[] in the code, rather than g.pixels[].
*/
public void loadPixels() {
g.loadPixels();
pixels = g.pixels;
}
public void updatePixels() {
g.updatePixels();
}
public void updatePixels(int x1, int y1, int x2, int y2) {
g.updatePixels(x1, y1, x2, y2);
}
//////////////////////////////////////////////////////////////
// everything below this line is automatically generated. no touch.
// public functions for processing.core
public void flush() {
if (recorder != null) recorder.flush();
g.flush();
}
public void hint(int which) {
if (recorder != null) recorder.hint(which);
g.hint(which);
}
public void beginShape() {
if (recorder != null) recorder.beginShape();
g.beginShape();
}
public void beginShape(int kind) {
if (recorder != null) recorder.beginShape(kind);
g.beginShape(kind);
}
public void edge(boolean edge) {
if (recorder != null) recorder.edge(edge);
g.edge(edge);
}
public void normal(float nx, float ny, float nz) {
if (recorder != null) recorder.normal(nx, ny, nz);
g.normal(nx, ny, nz);
}
public void textureMode(int mode) {
if (recorder != null) recorder.textureMode(mode);
g.textureMode(mode);
}
public void texture(PImage image) {
if (recorder != null) recorder.texture(image);
g.texture(image);
}
public void vertex(float x, float y) {
if (recorder != null) recorder.vertex(x, y);
g.vertex(x, y);
}
public void vertex(float x, float y, float z) {
if (recorder != null) recorder.vertex(x, y, z);
g.vertex(x, y, z);
}
public void vertex(float[] v) {
if (recorder != null) recorder.vertex(v);
g.vertex(v);
}
public void vertex(float x, float y, float u, float v) {
if (recorder != null) recorder.vertex(x, y, u, v);
g.vertex(x, y, u, v);
}
public void vertex(float x, float y, float z, float u, float v) {
if (recorder != null) recorder.vertex(x, y, z, u, v);
g.vertex(x, y, z, u, v);
}
public void breakShape() {
if (recorder != null) recorder.breakShape();
g.breakShape();
}
public void endShape() {
if (recorder != null) recorder.endShape();
g.endShape();
}
public void endShape(int mode) {
if (recorder != null) recorder.endShape(mode);
g.endShape(mode);
}
public void bezierVertex(float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4);
g.bezierVertex(x2, y2, x3, y3, x4, y4);
}
public void bezierVertex(float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
public void curveVertex(float x, float y) {
if (recorder != null) recorder.curveVertex(x, y);
g.curveVertex(x, y);
}
public void curveVertex(float x, float y, float z) {
if (recorder != null) recorder.curveVertex(x, y, z);
g.curveVertex(x, y, z);
}
public void point(float x, float y) {
if (recorder != null) recorder.point(x, y);
g.point(x, y);
}
public void point(float x, float y, float z) {
if (recorder != null) recorder.point(x, y, z);
g.point(x, y, z);
}
public void line(float x1, float y1, float x2, float y2) {
if (recorder != null) recorder.line(x1, y1, x2, y2);
g.line(x1, y1, x2, y2);
}
public void line(float x1, float y1, float z1,
float x2, float y2, float z2) {
if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2);
g.line(x1, y1, z1, x2, y2, z2);
}
public void triangle(float x1, float y1, float x2, float y2,
float x3, float y3) {
if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3);
g.triangle(x1, y1, x2, y2, x3, y3);
}
public void quad(float x1, float y1, float x2, float y2,
float x3, float y3, float x4, float y4) {
if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4);
g.quad(x1, y1, x2, y2, x3, y3, x4, y4);
}
public void rectMode(int mode) {
if (recorder != null) recorder.rectMode(mode);
g.rectMode(mode);
}
public void rect(float a, float b, float c, float d) {
if (recorder != null) recorder.rect(a, b, c, d);
g.rect(a, b, c, d);
}
public void ellipseMode(int mode) {
if (recorder != null) recorder.ellipseMode(mode);
g.ellipseMode(mode);
}
public void ellipse(float a, float b, float c, float d) {
if (recorder != null) recorder.ellipse(a, b, c, d);
g.ellipse(a, b, c, d);
}
public void arc(float a, float b, float c, float d,
float start, float stop) {
if (recorder != null) recorder.arc(a, b, c, d, start, stop);
g.arc(a, b, c, d, start, stop);
}
public void box(float size) {
if (recorder != null) recorder.box(size);
g.box(size);
}
public void box(float w, float h, float d) {
if (recorder != null) recorder.box(w, h, d);
g.box(w, h, d);
}
public void sphereDetail(int res) {
if (recorder != null) recorder.sphereDetail(res);
g.sphereDetail(res);
}
public void sphereDetail(int ures, int vres) {
if (recorder != null) recorder.sphereDetail(ures, vres);
g.sphereDetail(ures, vres);
}
public void sphere(float r) {
if (recorder != null) recorder.sphere(r);
g.sphere(r);
}
public float bezierPoint(float a, float b, float c, float d, float t) {
return g.bezierPoint(a, b, c, d, t);
}
public float bezierTangent(float a, float b, float c, float d, float t) {
return g.bezierTangent(a, b, c, d, t);
}
public void bezierDetail(int detail) {
if (recorder != null) recorder.bezierDetail(detail);
g.bezierDetail(detail);
}
public void bezier(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
g.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
}
public void bezier(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
public float curvePoint(float a, float b, float c, float d, float t) {
return g.curvePoint(a, b, c, d, t);
}
public float curveTangent(float a, float b, float c, float d, float t) {
return g.curveTangent(a, b, c, d, t);
}
public void curveDetail(int detail) {
if (recorder != null) recorder.curveDetail(detail);
g.curveDetail(detail);
}
public void curveTightness(float tightness) {
if (recorder != null) recorder.curveTightness(tightness);
g.curveTightness(tightness);
}
public void curve(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4);
g.curve(x1, y1, x2, y2, x3, y3, x4, y4);
}
public void curve(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
public void smooth() {
if (recorder != null) recorder.smooth();
g.smooth();
}
public void noSmooth() {
if (recorder != null) recorder.noSmooth();
g.noSmooth();
}
public void imageMode(int mode) {
if (recorder != null) recorder.imageMode(mode);
g.imageMode(mode);
}
public void image(PImage image, float x, float y) {
if (recorder != null) recorder.image(image, x, y);
g.image(image, x, y);
}
public void image(PImage image, float x, float y, float c, float d) {
if (recorder != null) recorder.image(image, x, y, c, d);
g.image(image, x, y, c, d);
}
public void image(PImage image,
float a, float b, float c, float d,
int u1, int v1, int u2, int v2) {
if (recorder != null) recorder.image(image, a, b, c, d, u1, v1, u2, v2);
g.image(image, a, b, c, d, u1, v1, u2, v2);
}
public void shapeMode(int mode) {
if (recorder != null) recorder.shapeMode(mode);
g.shapeMode(mode);
}
public void shape(PShape shape) {
if (recorder != null) recorder.shape(shape);
g.shape(shape);
}
public void shape(PShape shape, float x, float y) {
if (recorder != null) recorder.shape(shape, x, y);
g.shape(shape, x, y);
}
public void shape(PShape shape, float x, float y, float c, float d) {
if (recorder != null) recorder.shape(shape, x, y, c, d);
g.shape(shape, x, y, c, d);
}
public void textAlign(int align) {
if (recorder != null) recorder.textAlign(align);
g.textAlign(align);
}
public void textAlign(int alignX, int alignY) {
if (recorder != null) recorder.textAlign(alignX, alignY);
g.textAlign(alignX, alignY);
}
public float textAscent() {
return g.textAscent();
}
public float textDescent() {
return g.textDescent();
}
public void textFont(PFont which) {
if (recorder != null) recorder.textFont(which);
g.textFont(which);
}
public void textFont(PFont which, float size) {
if (recorder != null) recorder.textFont(which, size);
g.textFont(which, size);
}
public void textLeading(float leading) {
if (recorder != null) recorder.textLeading(leading);
g.textLeading(leading);
}
public void textMode(int mode) {
if (recorder != null) recorder.textMode(mode);
g.textMode(mode);
}
public void textSize(float size) {
if (recorder != null) recorder.textSize(size);
g.textSize(size);
}
public float textWidth(char c) {
return g.textWidth(c);
}
public float textWidth(String str) {
return g.textWidth(str);
}
public void text(char c) {
if (recorder != null) recorder.text(c);
g.text(c);
}
public void text(char c, float x, float y) {
if (recorder != null) recorder.text(c, x, y);
g.text(c, x, y);
}
public void text(char c, float x, float y, float z) {
if (recorder != null) recorder.text(c, x, y, z);
g.text(c, x, y, z);
}
public void text(String str) {
if (recorder != null) recorder.text(str);
g.text(str);
}
public void text(String str, float x, float y) {
if (recorder != null) recorder.text(str, x, y);
g.text(str, x, y);
}
public void text(String str, float x, float y, float z) {
if (recorder != null) recorder.text(str, x, y, z);
g.text(str, x, y, z);
}
public void text(String str, float x1, float y1, float x2, float y2) {
if (recorder != null) recorder.text(str, x1, y1, x2, y2);
g.text(str, x1, y1, x2, y2);
}
public void text(String s, float x1, float y1, float x2, float y2, float z) {
if (recorder != null) recorder.text(s, x1, y1, x2, y2, z);
g.text(s, x1, y1, x2, y2, z);
}
public void text(int num, float x, float y) {
if (recorder != null) recorder.text(num, x, y);
g.text(num, x, y);
}
public void text(int num, float x, float y, float z) {
if (recorder != null) recorder.text(num, x, y, z);
g.text(num, x, y, z);
}
public void text(float num, float x, float y) {
if (recorder != null) recorder.text(num, x, y);
g.text(num, x, y);
}
public void text(float num, float x, float y, float z) {
if (recorder != null) recorder.text(num, x, y, z);
g.text(num, x, y, z);
}
public void pushMatrix() {
if (recorder != null) recorder.pushMatrix();
g.pushMatrix();
}
public void popMatrix() {
if (recorder != null) recorder.popMatrix();
g.popMatrix();
}
public void translate(float tx, float ty) {
if (recorder != null) recorder.translate(tx, ty);
g.translate(tx, ty);
}
public void translate(float tx, float ty, float tz) {
if (recorder != null) recorder.translate(tx, ty, tz);
g.translate(tx, ty, tz);
}
public void rotate(float angle) {
if (recorder != null) recorder.rotate(angle);
g.rotate(angle);
}
public void rotateX(float angle) {
if (recorder != null) recorder.rotateX(angle);
g.rotateX(angle);
}
public void rotateY(float angle) {
if (recorder != null) recorder.rotateY(angle);
g.rotateY(angle);
}
public void rotateZ(float angle) {
if (recorder != null) recorder.rotateZ(angle);
g.rotateZ(angle);
}
public void rotate(float angle, float vx, float vy, float vz) {
if (recorder != null) recorder.rotate(angle, vx, vy, vz);
g.rotate(angle, vx, vy, vz);
}
public void scale(float s) {
if (recorder != null) recorder.scale(s);
g.scale(s);
}
public void scale(float sx, float sy) {
if (recorder != null) recorder.scale(sx, sy);
g.scale(sx, sy);
}
public void scale(float x, float y, float z) {
if (recorder != null) recorder.scale(x, y, z);
g.scale(x, y, z);
}
public void resetMatrix() {
if (recorder != null) recorder.resetMatrix();
g.resetMatrix();
}
public void applyMatrix(PMatrix source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
public void applyMatrix(PMatrix2D source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
public void applyMatrix(float n00, float n01, float n02,
float n10, float n11, float n12) {
if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12);
g.applyMatrix(n00, n01, n02, n10, n11, n12);
}
public void applyMatrix(PMatrix3D source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
public void applyMatrix(float n00, float n01, float n02, float n03,
float n10, float n11, float n12, float n13,
float n20, float n21, float n22, float n23,
float n30, float n31, float n32, float n33) {
if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
}
public PMatrix getMatrix() {
return g.getMatrix();
}
public PMatrix2D getMatrix(PMatrix2D target) {
return g.getMatrix(target);
}
public PMatrix3D getMatrix(PMatrix3D target) {
return g.getMatrix(target);
}
public void setMatrix(PMatrix source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
public void setMatrix(PMatrix2D source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
public void setMatrix(PMatrix3D source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
public void printMatrix() {
if (recorder != null) recorder.printMatrix();
g.printMatrix();
}
public void beginCamera() {
if (recorder != null) recorder.beginCamera();
g.beginCamera();
}
public void endCamera() {
if (recorder != null) recorder.endCamera();
g.endCamera();
}
public void camera() {
if (recorder != null) recorder.camera();
g.camera();
}
public void camera(float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ,
float upX, float upY, float upZ) {
if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
}
public void printCamera() {
if (recorder != null) recorder.printCamera();
g.printCamera();
}
public void ortho() {
if (recorder != null) recorder.ortho();
g.ortho();
}
public void ortho(float left, float right,
float bottom, float top,
float near, float far) {
if (recorder != null) recorder.ortho(left, right, bottom, top, near, far);
g.ortho(left, right, bottom, top, near, far);
}
public void perspective() {
if (recorder != null) recorder.perspective();
g.perspective();
}
public void perspective(float fovy, float aspect, float zNear, float zFar) {
if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar);
g.perspective(fovy, aspect, zNear, zFar);
}
public void frustum(float left, float right,
float bottom, float top,
float near, float far) {
if (recorder != null) recorder.frustum(left, right, bottom, top, near, far);
g.frustum(left, right, bottom, top, near, far);
}
public void printProjection() {
if (recorder != null) recorder.printProjection();
g.printProjection();
}
public float screenX(float x, float y) {
return g.screenX(x, y);
}
public float screenY(float x, float y) {
return g.screenY(x, y);
}
public float screenX(float x, float y, float z) {
return g.screenX(x, y, z);
}
public float screenY(float x, float y, float z) {
return g.screenY(x, y, z);
}
public float screenZ(float x, float y, float z) {
return g.screenZ(x, y, z);
}
public float modelX(float x, float y, float z) {
return g.modelX(x, y, z);
}
public float modelY(float x, float y, float z) {
return g.modelY(x, y, z);
}
public float modelZ(float x, float y, float z) {
return g.modelZ(x, y, z);
}
public void pushStyle() {
if (recorder != null) recorder.pushStyle();
g.pushStyle();
}
public void popStyle() {
if (recorder != null) recorder.popStyle();
g.popStyle();
}
public void style(PStyle s) {
if (recorder != null) recorder.style(s);
g.style(s);
}
public void strokeWeight(float weight) {
if (recorder != null) recorder.strokeWeight(weight);
g.strokeWeight(weight);
}
public void strokeJoin(int join) {
if (recorder != null) recorder.strokeJoin(join);
g.strokeJoin(join);
}
public void strokeCap(int cap) {
if (recorder != null) recorder.strokeCap(cap);
g.strokeCap(cap);
}
public void noStroke() {
if (recorder != null) recorder.noStroke();
g.noStroke();
}
public void stroke(int rgb) {
if (recorder != null) recorder.stroke(rgb);
g.stroke(rgb);
}
public void stroke(int rgb, float alpha) {
if (recorder != null) recorder.stroke(rgb, alpha);
g.stroke(rgb, alpha);
}
public void stroke(float gray) {
if (recorder != null) recorder.stroke(gray);
g.stroke(gray);
}
public void stroke(float gray, float alpha) {
if (recorder != null) recorder.stroke(gray, alpha);
g.stroke(gray, alpha);
}
public void stroke(float x, float y, float z) {
if (recorder != null) recorder.stroke(x, y, z);
g.stroke(x, y, z);
}
public void stroke(float x, float y, float z, float a) {
if (recorder != null) recorder.stroke(x, y, z, a);
g.stroke(x, y, z, a);
}
public void noTint() {
if (recorder != null) recorder.noTint();
g.noTint();
}
public void tint(int rgb) {
if (recorder != null) recorder.tint(rgb);
g.tint(rgb);
}
public void tint(int rgb, float alpha) {
if (recorder != null) recorder.tint(rgb, alpha);
g.tint(rgb, alpha);
}
public void tint(float gray) {
if (recorder != null) recorder.tint(gray);
g.tint(gray);
}
public void tint(float gray, float alpha) {
if (recorder != null) recorder.tint(gray, alpha);
g.tint(gray, alpha);
}
public void tint(float x, float y, float z) {
if (recorder != null) recorder.tint(x, y, z);
g.tint(x, y, z);
}
public void tint(float x, float y, float z, float a) {
if (recorder != null) recorder.tint(x, y, z, a);
g.tint(x, y, z, a);
}
public void noFill() {
if (recorder != null) recorder.noFill();
g.noFill();
}
public void fill(int rgb) {
if (recorder != null) recorder.fill(rgb);
g.fill(rgb);
}
public void fill(int rgb, float alpha) {
if (recorder != null) recorder.fill(rgb, alpha);
g.fill(rgb, alpha);
}
public void fill(float gray) {
if (recorder != null) recorder.fill(gray);
g.fill(gray);
}
public void fill(float gray, float alpha) {
if (recorder != null) recorder.fill(gray, alpha);
g.fill(gray, alpha);
}
public void fill(float x, float y, float z) {
if (recorder != null) recorder.fill(x, y, z);
g.fill(x, y, z);
}
public void fill(float x, float y, float z, float a) {
if (recorder != null) recorder.fill(x, y, z, a);
g.fill(x, y, z, a);
}
public void ambient(int rgb) {
if (recorder != null) recorder.ambient(rgb);
g.ambient(rgb);
}
public void ambient(float gray) {
if (recorder != null) recorder.ambient(gray);
g.ambient(gray);
}
public void ambient(float x, float y, float z) {
if (recorder != null) recorder.ambient(x, y, z);
g.ambient(x, y, z);
}
public void specular(int rgb) {
if (recorder != null) recorder.specular(rgb);
g.specular(rgb);
}
public void specular(float gray) {
if (recorder != null) recorder.specular(gray);
g.specular(gray);
}
public void specular(float x, float y, float z) {
if (recorder != null) recorder.specular(x, y, z);
g.specular(x, y, z);
}
public void shininess(float shine) {
if (recorder != null) recorder.shininess(shine);
g.shininess(shine);
}
public void emissive(int rgb) {
if (recorder != null) recorder.emissive(rgb);
g.emissive(rgb);
}
public void emissive(float gray) {
if (recorder != null) recorder.emissive(gray);
g.emissive(gray);
}
public void emissive(float x, float y, float z) {
if (recorder != null) recorder.emissive(x, y, z);
g.emissive(x, y, z);
}
public void lights() {
if (recorder != null) recorder.lights();
g.lights();
}
public void noLights() {
if (recorder != null) recorder.noLights();
g.noLights();
}
public void ambientLight(float red, float green, float blue) {
if (recorder != null) recorder.ambientLight(red, green, blue);
g.ambientLight(red, green, blue);
}
public void ambientLight(float red, float green, float blue,
float x, float y, float z) {
if (recorder != null) recorder.ambientLight(red, green, blue, x, y, z);
g.ambientLight(red, green, blue, x, y, z);
}
public void directionalLight(float red, float green, float blue,
float nx, float ny, float nz) {
if (recorder != null) recorder.directionalLight(red, green, blue, nx, ny, nz);
g.directionalLight(red, green, blue, nx, ny, nz);
}
public void pointLight(float red, float green, float blue,
float x, float y, float z) {
if (recorder != null) recorder.pointLight(red, green, blue, x, y, z);
g.pointLight(red, green, blue, x, y, z);
}
public void spotLight(float red, float green, float blue,
float x, float y, float z,
float nx, float ny, float nz,
float angle, float concentration) {
if (recorder != null) recorder.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration);
g.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration);
}
public void lightFalloff(float constant, float linear, float quadratic) {
if (recorder != null) recorder.lightFalloff(constant, linear, quadratic);
g.lightFalloff(constant, linear, quadratic);
}
public void lightSpecular(float x, float y, float z) {
if (recorder != null) recorder.lightSpecular(x, y, z);
g.lightSpecular(x, y, z);
}
public void background(int rgb) {
if (recorder != null) recorder.background(rgb);
g.background(rgb);
}
public void background(int rgb, float alpha) {
if (recorder != null) recorder.background(rgb, alpha);
g.background(rgb, alpha);
}
public void background(float gray) {
if (recorder != null) recorder.background(gray);
g.background(gray);
}
public void background(float gray, float alpha) {
if (recorder != null) recorder.background(gray, alpha);
g.background(gray, alpha);
}
public void background(float x, float y, float z) {
if (recorder != null) recorder.background(x, y, z);
g.background(x, y, z);
}
public void background(float x, float y, float z, float a) {
if (recorder != null) recorder.background(x, y, z, a);
g.background(x, y, z, a);
}
public void background(PImage image) {
if (recorder != null) recorder.background(image);
g.background(image);
}
public void colorMode(int mode) {
if (recorder != null) recorder.colorMode(mode);
g.colorMode(mode);
}
public void colorMode(int mode, float max) {
if (recorder != null) recorder.colorMode(mode, max);
g.colorMode(mode, max);
}
public void colorMode(int mode, float maxX, float maxY, float maxZ) {
if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ);
g.colorMode(mode, maxX, maxY, maxZ);
}
public void colorMode(int mode,
float maxX, float maxY, float maxZ, float maxA) {
if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ, maxA);
g.colorMode(mode, maxX, maxY, maxZ, maxA);
}
public final float alpha(int what) {
return g.alpha(what);
}
public final float red(int what) {
return g.red(what);
}
public final float green(int what) {
return g.green(what);
}
public final float blue(int what) {
return g.blue(what);
}
public final float hue(int what) {
return g.hue(what);
}
public final float saturation(int what) {
return g.saturation(what);
}
public final float brightness(int what) {
return g.brightness(what);
}
public int lerpColor(int c1, int c2, float amt) {
return g.lerpColor(c1, c2, amt);
}
static public int lerpColor(int c1, int c2, float amt, int mode) {
return PGraphics.lerpColor(c1, c2, amt, mode);
}
public boolean displayable() {
return g.displayable();
}
public void setCache(Object parent, Object storage) {
if (recorder != null) recorder.setCache(parent, storage);
g.setCache(parent, storage);
}
public Object getCache(Object parent) {
return g.getCache(parent);
}
public void removeCache(Object parent) {
if (recorder != null) recorder.removeCache(parent);
g.removeCache(parent);
}
public int get(int x, int y) {
return g.get(x, y);
}
public PImage get(int x, int y, int w, int h) {
return g.get(x, y, w, h);
}
public PImage get() {
return g.get();
}
public void set(int x, int y, int c) {
if (recorder != null) recorder.set(x, y, c);
g.set(x, y, c);
}
public void set(int x, int y, PImage src) {
if (recorder != null) recorder.set(x, y, src);
g.set(x, y, src);
}
public void mask(int alpha[]) {
if (recorder != null) recorder.mask(alpha);
g.mask(alpha);
}
public void mask(PImage alpha) {
if (recorder != null) recorder.mask(alpha);
g.mask(alpha);
}
public void filter(int kind) {
if (recorder != null) recorder.filter(kind);
g.filter(kind);
}
public void filter(int kind, float param) {
if (recorder != null) recorder.filter(kind, param);
g.filter(kind, param);
}
public void copy(int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh);
g.copy(sx, sy, sw, sh, dx, dy, dw, dh);
}
public void copy(PImage src,
int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
}
static public int blendColor(int c1, int c2, int mode) {
return PGraphics.blendColor(c1, c2, mode);
}
public void blend(int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh, int mode) {
if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
}
public void blend(PImage src,
int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh, int mode) {
if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
}
}
| false | true |
static public void main(String args[]) {
// Disable abyssmally slow Sun renderer on OS X 10.5.
if (platform == MACOSX) {
// Only run this on OS X otherwise it can cause a permissions error.
// http://dev.processing.org/bugs/show_bug.cgi?id=976
System.setProperty("apple.awt.graphics.UseQuartz", "true");
}
if (platform == WINDOWS) {
// For now, disable the D3D renderer on Java 6u10 because
// it causes problems with Present mode.
// http://dev.processing.org/bugs/show_bug.cgi?id=1009
System.setProperty("sun.java2d.d3d", "false");
}
if (args.length < 1) {
System.err.println("Usage: PApplet <appletname>");
System.err.println("For additional options, " +
"see the Javadoc for PApplet");
System.exit(1);
}
try {
boolean external = false;
int location[] = null;
int editorLocation[] = null;
String name = null;
boolean present = false;
Color backgroundColor = Color.black; //BLACK;
Color stopColor = Color.gray; //GRAY;
GraphicsDevice displayDevice = null;
boolean hideStop = false;
String param = null, value = null;
// try to get the user folder. if running under java web start,
// this may cause a security exception if the code is not signed.
// http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274
String folder = null;
try {
folder = System.getProperty("user.dir");
} catch (Exception e) { }
int argIndex = 0;
while (argIndex < args.length) {
int equals = args[argIndex].indexOf('=');
if (equals != -1) {
param = args[argIndex].substring(0, equals);
value = args[argIndex].substring(equals + 1);
if (param.equals(ARGS_EDITOR_LOCATION)) {
external = true;
editorLocation = parseInt(split(value, ','));
} else if (param.equals(ARGS_DISPLAY)) {
int deviceIndex = Integer.parseInt(value) - 1;
//DisplayMode dm = device.getDisplayMode();
//if ((dm.getWidth() == 1024) && (dm.getHeight() == 768)) {
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice devices[] = environment.getScreenDevices();
if ((deviceIndex >= 0) && (deviceIndex < devices.length)) {
displayDevice = devices[deviceIndex];
} else {
System.err.println("Display " + value + " does not exist, " +
"using the default display instead.");
}
} else if (param.equals(ARGS_BGCOLOR)) {
if (value.charAt(0) == '#') value = value.substring(1);
backgroundColor = new Color(Integer.parseInt(value, 16));
} else if (param.equals(ARGS_STOP_COLOR)) {
if (value.charAt(0) == '#') value = value.substring(1);
stopColor = new Color(Integer.parseInt(value, 16));
} else if (param.equals(ARGS_SKETCH_FOLDER)) {
folder = value;
} else if (param.equals(ARGS_LOCATION)) {
location = parseInt(split(value, ','));
}
} else {
if (args[argIndex].equals(ARGS_PRESENT)) {
present = true;
} else if (args[argIndex].equals(ARGS_HIDE_STOP)) {
hideStop = true;
} else if (args[argIndex].equals(ARGS_EXTERNAL)) {
external = true;
} else {
name = args[argIndex];
break;
}
}
argIndex++;
}
// Set this property before getting into any GUI init code
//System.setProperty("com.apple.mrj.application.apple.menu.about.name", name);
// This )*)(*@#$ Apple crap don't work no matter where you put it
// (static method of the class, at the top of main, wherever)
if (displayDevice == null) {
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
displayDevice = environment.getDefaultScreenDevice();
}
Frame frame = new Frame(displayDevice.getDefaultConfiguration());
/*
Frame frame = null;
if (displayDevice != null) {
frame = new Frame(displayDevice.getDefaultConfiguration());
} else {
frame = new Frame();
}
*/
//Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
// remove the grow box by default
// users who want it back can call frame.setResizable(true)
frame.setResizable(false);
// Set the trimmings around the image
Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE);
frame.setIconImage(image);
frame.setTitle(name);
// Class c = Class.forName(name);
Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(name);
PApplet applet = (PApplet) c.newInstance();
// these are needed before init/start
applet.frame = frame;
applet.sketchPath = folder;
applet.args = PApplet.subset(args, 1);
applet.external = external;
// Need to save the window bounds at full screen,
// because pack() will cause the bounds to go to zero.
// http://dev.processing.org/bugs/show_bug.cgi?id=923
Rectangle fullScreenRect = null;
// For 0149, moving this code (up to the pack() method) before init().
// For OpenGL (and perhaps other renderers in the future), a peer is
// needed before a GLDrawable can be created. So pack() needs to be
// called on the Frame before applet.init(), which itself calls size(),
// and launches the Thread that will kick off setup().
// http://dev.processing.org/bugs/show_bug.cgi?id=891
// http://dev.processing.org/bugs/show_bug.cgi?id=908
if (present) {
frame.setUndecorated(true);
frame.setBackground(backgroundColor);
displayDevice.setFullScreenWindow(frame);
fullScreenRect = frame.getBounds();
}
frame.setLayout(null);
frame.add(applet);
frame.pack();
applet.init();
// Wait until the applet has figured out its width.
// In a static mode app, this will be after setup() has completed,
// and the empty draw() has set "finished" to true.
// TODO make sure this won't hang if the applet has an exception.
while (applet.defaultSize && !applet.finished) {
//System.out.println("default size");
try {
Thread.sleep(5);
} catch (InterruptedException e) {
//System.out.println("interrupt");
}
}
//println("not default size " + applet.width + " " + applet.height);
//println(" (g width/height is " + applet.g.width + "x" + applet.g.height + ")");
if (present) {
// After the pack(), the screen bounds are gonna be 0s
frame.setBounds(fullScreenRect);
applet.setBounds((fullScreenRect.width - applet.width) / 2,
(fullScreenRect.height - applet.height) / 2,
applet.width, applet.height);
if (!hideStop) {
Label label = new Label("stop");
label.setForeground(stopColor);
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
System.exit(0);
}
});
frame.add(label);
Dimension labelSize = label.getPreferredSize();
// sometimes shows up truncated on mac
//System.out.println("label width is " + labelSize.width);
labelSize = new Dimension(100, labelSize.height);
label.setSize(labelSize);
label.setLocation(20, fullScreenRect.height - labelSize.height - 20);
}
// not always running externally when in present mode
if (external) {
applet.setupExternalMessages();
}
} else { // if not presenting
// can't do pack earlier cuz present mode don't like it
// (can't go full screen with a frame after calling pack)
// frame.pack(); // get insets. get more.
Insets insets = frame.getInsets();
int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) +
insets.left + insets.right;
int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) +
insets.top + insets.bottom;
frame.setSize(windowW, windowH);
if (location != null) {
// a specific location was received from PdeRuntime
// (applet has been run more than once, user placed window)
frame.setLocation(location[0], location[1]);
} else if (external) {
int locationX = editorLocation[0] - 20;
int locationY = editorLocation[1];
if (locationX - windowW > 10) {
// if it fits to the left of the window
frame.setLocation(locationX - windowW, locationY);
} else { // doesn't fit
// if it fits inside the editor window,
// offset slightly from upper lefthand corner
// so that it's plunked inside the text area
locationX = editorLocation[0] + 66;
locationY = editorLocation[1] + 66;
if ((locationX + windowW > applet.screen.width - 33) ||
(locationY + windowH > applet.screen.height - 33)) {
// otherwise center on screen
locationX = (applet.screen.width - windowW) / 2;
locationY = (applet.screen.height - windowH) / 2;
}
frame.setLocation(locationX, locationY);
}
} else { // just center on screen
frame.setLocation((applet.screen.width - applet.width) / 2,
(applet.screen.height - applet.height) / 2);
}
// frame.setLayout(null);
// frame.add(applet);
if (backgroundColor == Color.black) { //BLACK) {
// this means no bg color unless specified
backgroundColor = SystemColor.control;
}
frame.setBackground(backgroundColor);
int usableWindowH = windowH - insets.top - insets.bottom;
applet.setBounds((windowW - applet.width)/2,
insets.top + (usableWindowH - applet.height)/2,
applet.width, applet.height);
if (external) {
applet.setupExternalMessages();
} else { // !external
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
// handle frame resizing events
applet.setupFrameResizeListener();
// all set for rockin
if (applet.displayable()) {
frame.setVisible(true);
}
}
//System.out.println("showing frame");
//System.out.println("applet requesting focus");
applet.requestFocus(); // ask for keydowns
//System.out.println("exiting main()");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
//////////////////////////////////////////////////////////////
/**
* Begin recording to a new renderer of the specified type, using the width
* and height of the main drawing surface.
*/
public PGraphics beginRecord(String renderer, String filename) {
filename = insertFrame(filename);
PGraphics rec = createGraphics(width, height, renderer, filename);
beginRecord(rec);
return rec;
}
/**
* Begin recording (echoing) commands to the specified PGraphics object.
*/
public void beginRecord(PGraphics recorder) {
this.recorder = recorder;
recorder.beginDraw();
}
public void endRecord() {
if (recorder != null) {
recorder.endDraw();
recorder.dispose();
recorder = null;
}
}
/**
* Begin recording raw shape data to a renderer of the specified type,
* using the width and height of the main drawing surface.
*
* If hashmarks (###) are found in the filename, they'll be replaced
* by the current frame number (frameCount).
*/
public PGraphics beginRaw(String renderer, String filename) {
filename = insertFrame(filename);
PGraphics rec = createGraphics(width, height, renderer, filename);
g.beginRaw(rec);
return rec;
}
/**
* Begin recording raw shape data to the specified renderer.
*
* This simply echoes to g.beginRaw(), but since is placed here (rather than
* generated by preproc.pl) for clarity and so that it doesn't echo the
* command should beginRecord() be in use.
*/
public void beginRaw(PGraphics rawGraphics) {
g.beginRaw(rawGraphics);
}
/**
* Stop recording raw shape data to the specified renderer.
*
* This simply echoes to g.beginRaw(), but since is placed here (rather than
* generated by preproc.pl) for clarity and so that it doesn't echo the
* command should beginRecord() be in use.
*/
public void endRaw() {
g.endRaw();
}
//////////////////////////////////////////////////////////////
/**
* Override the g.pixels[] function to set the pixels[] array
* that's part of the PApplet object. Allows the use of
* pixels[] in the code, rather than g.pixels[].
*/
public void loadPixels() {
g.loadPixels();
pixels = g.pixels;
}
public void updatePixels() {
g.updatePixels();
}
public void updatePixels(int x1, int y1, int x2, int y2) {
g.updatePixels(x1, y1, x2, y2);
}
//////////////////////////////////////////////////////////////
// everything below this line is automatically generated. no touch.
// public functions for processing.core
public void flush() {
if (recorder != null) recorder.flush();
g.flush();
}
public void hint(int which) {
if (recorder != null) recorder.hint(which);
g.hint(which);
}
public void beginShape() {
if (recorder != null) recorder.beginShape();
g.beginShape();
}
public void beginShape(int kind) {
if (recorder != null) recorder.beginShape(kind);
g.beginShape(kind);
}
public void edge(boolean edge) {
if (recorder != null) recorder.edge(edge);
g.edge(edge);
}
public void normal(float nx, float ny, float nz) {
if (recorder != null) recorder.normal(nx, ny, nz);
g.normal(nx, ny, nz);
}
public void textureMode(int mode) {
if (recorder != null) recorder.textureMode(mode);
g.textureMode(mode);
}
public void texture(PImage image) {
if (recorder != null) recorder.texture(image);
g.texture(image);
}
public void vertex(float x, float y) {
if (recorder != null) recorder.vertex(x, y);
g.vertex(x, y);
}
public void vertex(float x, float y, float z) {
if (recorder != null) recorder.vertex(x, y, z);
g.vertex(x, y, z);
}
public void vertex(float[] v) {
if (recorder != null) recorder.vertex(v);
g.vertex(v);
}
public void vertex(float x, float y, float u, float v) {
if (recorder != null) recorder.vertex(x, y, u, v);
g.vertex(x, y, u, v);
}
public void vertex(float x, float y, float z, float u, float v) {
if (recorder != null) recorder.vertex(x, y, z, u, v);
g.vertex(x, y, z, u, v);
}
public void breakShape() {
if (recorder != null) recorder.breakShape();
g.breakShape();
}
public void endShape() {
if (recorder != null) recorder.endShape();
g.endShape();
}
public void endShape(int mode) {
if (recorder != null) recorder.endShape(mode);
g.endShape(mode);
}
public void bezierVertex(float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4);
g.bezierVertex(x2, y2, x3, y3, x4, y4);
}
public void bezierVertex(float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
public void curveVertex(float x, float y) {
if (recorder != null) recorder.curveVertex(x, y);
g.curveVertex(x, y);
}
public void curveVertex(float x, float y, float z) {
if (recorder != null) recorder.curveVertex(x, y, z);
g.curveVertex(x, y, z);
}
public void point(float x, float y) {
if (recorder != null) recorder.point(x, y);
g.point(x, y);
}
public void point(float x, float y, float z) {
if (recorder != null) recorder.point(x, y, z);
g.point(x, y, z);
}
public void line(float x1, float y1, float x2, float y2) {
if (recorder != null) recorder.line(x1, y1, x2, y2);
g.line(x1, y1, x2, y2);
}
public void line(float x1, float y1, float z1,
float x2, float y2, float z2) {
if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2);
g.line(x1, y1, z1, x2, y2, z2);
}
public void triangle(float x1, float y1, float x2, float y2,
float x3, float y3) {
if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3);
g.triangle(x1, y1, x2, y2, x3, y3);
}
public void quad(float x1, float y1, float x2, float y2,
float x3, float y3, float x4, float y4) {
if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4);
g.quad(x1, y1, x2, y2, x3, y3, x4, y4);
}
public void rectMode(int mode) {
if (recorder != null) recorder.rectMode(mode);
g.rectMode(mode);
}
public void rect(float a, float b, float c, float d) {
if (recorder != null) recorder.rect(a, b, c, d);
g.rect(a, b, c, d);
}
public void ellipseMode(int mode) {
if (recorder != null) recorder.ellipseMode(mode);
g.ellipseMode(mode);
}
public void ellipse(float a, float b, float c, float d) {
if (recorder != null) recorder.ellipse(a, b, c, d);
g.ellipse(a, b, c, d);
}
public void arc(float a, float b, float c, float d,
float start, float stop) {
if (recorder != null) recorder.arc(a, b, c, d, start, stop);
g.arc(a, b, c, d, start, stop);
}
public void box(float size) {
if (recorder != null) recorder.box(size);
g.box(size);
}
public void box(float w, float h, float d) {
if (recorder != null) recorder.box(w, h, d);
g.box(w, h, d);
}
public void sphereDetail(int res) {
if (recorder != null) recorder.sphereDetail(res);
g.sphereDetail(res);
}
public void sphereDetail(int ures, int vres) {
if (recorder != null) recorder.sphereDetail(ures, vres);
g.sphereDetail(ures, vres);
}
public void sphere(float r) {
if (recorder != null) recorder.sphere(r);
g.sphere(r);
}
public float bezierPoint(float a, float b, float c, float d, float t) {
return g.bezierPoint(a, b, c, d, t);
}
public float bezierTangent(float a, float b, float c, float d, float t) {
return g.bezierTangent(a, b, c, d, t);
}
public void bezierDetail(int detail) {
if (recorder != null) recorder.bezierDetail(detail);
g.bezierDetail(detail);
}
public void bezier(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
g.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
}
public void bezier(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
public float curvePoint(float a, float b, float c, float d, float t) {
return g.curvePoint(a, b, c, d, t);
}
public float curveTangent(float a, float b, float c, float d, float t) {
return g.curveTangent(a, b, c, d, t);
}
public void curveDetail(int detail) {
if (recorder != null) recorder.curveDetail(detail);
g.curveDetail(detail);
}
public void curveTightness(float tightness) {
if (recorder != null) recorder.curveTightness(tightness);
g.curveTightness(tightness);
}
public void curve(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4);
g.curve(x1, y1, x2, y2, x3, y3, x4, y4);
}
public void curve(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
public void smooth() {
if (recorder != null) recorder.smooth();
g.smooth();
}
public void noSmooth() {
if (recorder != null) recorder.noSmooth();
g.noSmooth();
}
public void imageMode(int mode) {
if (recorder != null) recorder.imageMode(mode);
g.imageMode(mode);
}
public void image(PImage image, float x, float y) {
if (recorder != null) recorder.image(image, x, y);
g.image(image, x, y);
}
public void image(PImage image, float x, float y, float c, float d) {
if (recorder != null) recorder.image(image, x, y, c, d);
g.image(image, x, y, c, d);
}
public void image(PImage image,
float a, float b, float c, float d,
int u1, int v1, int u2, int v2) {
if (recorder != null) recorder.image(image, a, b, c, d, u1, v1, u2, v2);
g.image(image, a, b, c, d, u1, v1, u2, v2);
}
public void shapeMode(int mode) {
if (recorder != null) recorder.shapeMode(mode);
g.shapeMode(mode);
}
public void shape(PShape shape) {
if (recorder != null) recorder.shape(shape);
g.shape(shape);
}
public void shape(PShape shape, float x, float y) {
if (recorder != null) recorder.shape(shape, x, y);
g.shape(shape, x, y);
}
public void shape(PShape shape, float x, float y, float c, float d) {
if (recorder != null) recorder.shape(shape, x, y, c, d);
g.shape(shape, x, y, c, d);
}
public void textAlign(int align) {
if (recorder != null) recorder.textAlign(align);
g.textAlign(align);
}
public void textAlign(int alignX, int alignY) {
if (recorder != null) recorder.textAlign(alignX, alignY);
g.textAlign(alignX, alignY);
}
public float textAscent() {
return g.textAscent();
}
public float textDescent() {
return g.textDescent();
}
public void textFont(PFont which) {
if (recorder != null) recorder.textFont(which);
g.textFont(which);
}
public void textFont(PFont which, float size) {
if (recorder != null) recorder.textFont(which, size);
g.textFont(which, size);
}
public void textLeading(float leading) {
if (recorder != null) recorder.textLeading(leading);
g.textLeading(leading);
}
public void textMode(int mode) {
if (recorder != null) recorder.textMode(mode);
g.textMode(mode);
}
public void textSize(float size) {
if (recorder != null) recorder.textSize(size);
g.textSize(size);
}
public float textWidth(char c) {
return g.textWidth(c);
}
public float textWidth(String str) {
return g.textWidth(str);
}
public void text(char c) {
if (recorder != null) recorder.text(c);
g.text(c);
}
public void text(char c, float x, float y) {
if (recorder != null) recorder.text(c, x, y);
g.text(c, x, y);
}
public void text(char c, float x, float y, float z) {
if (recorder != null) recorder.text(c, x, y, z);
g.text(c, x, y, z);
}
public void text(String str) {
if (recorder != null) recorder.text(str);
g.text(str);
}
public void text(String str, float x, float y) {
if (recorder != null) recorder.text(str, x, y);
g.text(str, x, y);
}
public void text(String str, float x, float y, float z) {
if (recorder != null) recorder.text(str, x, y, z);
g.text(str, x, y, z);
}
public void text(String str, float x1, float y1, float x2, float y2) {
if (recorder != null) recorder.text(str, x1, y1, x2, y2);
g.text(str, x1, y1, x2, y2);
}
public void text(String s, float x1, float y1, float x2, float y2, float z) {
if (recorder != null) recorder.text(s, x1, y1, x2, y2, z);
g.text(s, x1, y1, x2, y2, z);
}
public void text(int num, float x, float y) {
if (recorder != null) recorder.text(num, x, y);
g.text(num, x, y);
}
public void text(int num, float x, float y, float z) {
if (recorder != null) recorder.text(num, x, y, z);
g.text(num, x, y, z);
}
public void text(float num, float x, float y) {
if (recorder != null) recorder.text(num, x, y);
g.text(num, x, y);
}
public void text(float num, float x, float y, float z) {
if (recorder != null) recorder.text(num, x, y, z);
g.text(num, x, y, z);
}
public void pushMatrix() {
if (recorder != null) recorder.pushMatrix();
g.pushMatrix();
}
public void popMatrix() {
if (recorder != null) recorder.popMatrix();
g.popMatrix();
}
public void translate(float tx, float ty) {
if (recorder != null) recorder.translate(tx, ty);
g.translate(tx, ty);
}
public void translate(float tx, float ty, float tz) {
if (recorder != null) recorder.translate(tx, ty, tz);
g.translate(tx, ty, tz);
}
public void rotate(float angle) {
if (recorder != null) recorder.rotate(angle);
g.rotate(angle);
}
public void rotateX(float angle) {
if (recorder != null) recorder.rotateX(angle);
g.rotateX(angle);
}
public void rotateY(float angle) {
if (recorder != null) recorder.rotateY(angle);
g.rotateY(angle);
}
public void rotateZ(float angle) {
if (recorder != null) recorder.rotateZ(angle);
g.rotateZ(angle);
}
public void rotate(float angle, float vx, float vy, float vz) {
if (recorder != null) recorder.rotate(angle, vx, vy, vz);
g.rotate(angle, vx, vy, vz);
}
public void scale(float s) {
if (recorder != null) recorder.scale(s);
g.scale(s);
}
public void scale(float sx, float sy) {
if (recorder != null) recorder.scale(sx, sy);
g.scale(sx, sy);
}
public void scale(float x, float y, float z) {
if (recorder != null) recorder.scale(x, y, z);
g.scale(x, y, z);
}
public void resetMatrix() {
if (recorder != null) recorder.resetMatrix();
g.resetMatrix();
}
public void applyMatrix(PMatrix source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
public void applyMatrix(PMatrix2D source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
public void applyMatrix(float n00, float n01, float n02,
float n10, float n11, float n12) {
if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12);
g.applyMatrix(n00, n01, n02, n10, n11, n12);
}
public void applyMatrix(PMatrix3D source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
public void applyMatrix(float n00, float n01, float n02, float n03,
float n10, float n11, float n12, float n13,
float n20, float n21, float n22, float n23,
float n30, float n31, float n32, float n33) {
if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
}
public PMatrix getMatrix() {
return g.getMatrix();
}
public PMatrix2D getMatrix(PMatrix2D target) {
return g.getMatrix(target);
}
public PMatrix3D getMatrix(PMatrix3D target) {
return g.getMatrix(target);
}
public void setMatrix(PMatrix source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
public void setMatrix(PMatrix2D source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
public void setMatrix(PMatrix3D source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
public void printMatrix() {
if (recorder != null) recorder.printMatrix();
g.printMatrix();
}
public void beginCamera() {
if (recorder != null) recorder.beginCamera();
g.beginCamera();
}
public void endCamera() {
if (recorder != null) recorder.endCamera();
g.endCamera();
}
public void camera() {
if (recorder != null) recorder.camera();
g.camera();
}
public void camera(float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ,
float upX, float upY, float upZ) {
if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
}
public void printCamera() {
if (recorder != null) recorder.printCamera();
g.printCamera();
}
public void ortho() {
if (recorder != null) recorder.ortho();
g.ortho();
}
public void ortho(float left, float right,
float bottom, float top,
float near, float far) {
if (recorder != null) recorder.ortho(left, right, bottom, top, near, far);
g.ortho(left, right, bottom, top, near, far);
}
public void perspective() {
if (recorder != null) recorder.perspective();
g.perspective();
}
public void perspective(float fovy, float aspect, float zNear, float zFar) {
if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar);
g.perspective(fovy, aspect, zNear, zFar);
}
public void frustum(float left, float right,
float bottom, float top,
float near, float far) {
if (recorder != null) recorder.frustum(left, right, bottom, top, near, far);
g.frustum(left, right, bottom, top, near, far);
}
public void printProjection() {
if (recorder != null) recorder.printProjection();
g.printProjection();
}
public float screenX(float x, float y) {
return g.screenX(x, y);
}
public float screenY(float x, float y) {
return g.screenY(x, y);
}
public float screenX(float x, float y, float z) {
return g.screenX(x, y, z);
}
public float screenY(float x, float y, float z) {
return g.screenY(x, y, z);
}
public float screenZ(float x, float y, float z) {
return g.screenZ(x, y, z);
}
public float modelX(float x, float y, float z) {
return g.modelX(x, y, z);
}
public float modelY(float x, float y, float z) {
return g.modelY(x, y, z);
}
public float modelZ(float x, float y, float z) {
return g.modelZ(x, y, z);
}
public void pushStyle() {
if (recorder != null) recorder.pushStyle();
g.pushStyle();
}
public void popStyle() {
if (recorder != null) recorder.popStyle();
g.popStyle();
}
public void style(PStyle s) {
if (recorder != null) recorder.style(s);
g.style(s);
}
public void strokeWeight(float weight) {
if (recorder != null) recorder.strokeWeight(weight);
g.strokeWeight(weight);
}
public void strokeJoin(int join) {
if (recorder != null) recorder.strokeJoin(join);
g.strokeJoin(join);
}
public void strokeCap(int cap) {
if (recorder != null) recorder.strokeCap(cap);
g.strokeCap(cap);
}
public void noStroke() {
if (recorder != null) recorder.noStroke();
g.noStroke();
}
public void stroke(int rgb) {
if (recorder != null) recorder.stroke(rgb);
g.stroke(rgb);
}
public void stroke(int rgb, float alpha) {
if (recorder != null) recorder.stroke(rgb, alpha);
g.stroke(rgb, alpha);
}
public void stroke(float gray) {
if (recorder != null) recorder.stroke(gray);
g.stroke(gray);
}
public void stroke(float gray, float alpha) {
if (recorder != null) recorder.stroke(gray, alpha);
g.stroke(gray, alpha);
}
public void stroke(float x, float y, float z) {
if (recorder != null) recorder.stroke(x, y, z);
g.stroke(x, y, z);
}
public void stroke(float x, float y, float z, float a) {
if (recorder != null) recorder.stroke(x, y, z, a);
g.stroke(x, y, z, a);
}
public void noTint() {
if (recorder != null) recorder.noTint();
g.noTint();
}
public void tint(int rgb) {
if (recorder != null) recorder.tint(rgb);
g.tint(rgb);
}
public void tint(int rgb, float alpha) {
if (recorder != null) recorder.tint(rgb, alpha);
g.tint(rgb, alpha);
}
public void tint(float gray) {
if (recorder != null) recorder.tint(gray);
g.tint(gray);
}
public void tint(float gray, float alpha) {
if (recorder != null) recorder.tint(gray, alpha);
g.tint(gray, alpha);
}
public void tint(float x, float y, float z) {
if (recorder != null) recorder.tint(x, y, z);
g.tint(x, y, z);
}
public void tint(float x, float y, float z, float a) {
if (recorder != null) recorder.tint(x, y, z, a);
g.tint(x, y, z, a);
}
public void noFill() {
if (recorder != null) recorder.noFill();
g.noFill();
}
public void fill(int rgb) {
if (recorder != null) recorder.fill(rgb);
g.fill(rgb);
}
public void fill(int rgb, float alpha) {
if (recorder != null) recorder.fill(rgb, alpha);
g.fill(rgb, alpha);
}
public void fill(float gray) {
if (recorder != null) recorder.fill(gray);
g.fill(gray);
}
public void fill(float gray, float alpha) {
if (recorder != null) recorder.fill(gray, alpha);
g.fill(gray, alpha);
}
public void fill(float x, float y, float z) {
if (recorder != null) recorder.fill(x, y, z);
g.fill(x, y, z);
}
public void fill(float x, float y, float z, float a) {
if (recorder != null) recorder.fill(x, y, z, a);
g.fill(x, y, z, a);
}
public void ambient(int rgb) {
if (recorder != null) recorder.ambient(rgb);
g.ambient(rgb);
}
public void ambient(float gray) {
if (recorder != null) recorder.ambient(gray);
g.ambient(gray);
}
public void ambient(float x, float y, float z) {
if (recorder != null) recorder.ambient(x, y, z);
g.ambient(x, y, z);
}
public void specular(int rgb) {
if (recorder != null) recorder.specular(rgb);
g.specular(rgb);
}
public void specular(float gray) {
if (recorder != null) recorder.specular(gray);
g.specular(gray);
}
public void specular(float x, float y, float z) {
if (recorder != null) recorder.specular(x, y, z);
g.specular(x, y, z);
}
public void shininess(float shine) {
if (recorder != null) recorder.shininess(shine);
g.shininess(shine);
}
public void emissive(int rgb) {
if (recorder != null) recorder.emissive(rgb);
g.emissive(rgb);
}
public void emissive(float gray) {
if (recorder != null) recorder.emissive(gray);
g.emissive(gray);
}
public void emissive(float x, float y, float z) {
if (recorder != null) recorder.emissive(x, y, z);
g.emissive(x, y, z);
}
public void lights() {
if (recorder != null) recorder.lights();
g.lights();
}
public void noLights() {
if (recorder != null) recorder.noLights();
g.noLights();
}
public void ambientLight(float red, float green, float blue) {
if (recorder != null) recorder.ambientLight(red, green, blue);
g.ambientLight(red, green, blue);
}
public void ambientLight(float red, float green, float blue,
float x, float y, float z) {
if (recorder != null) recorder.ambientLight(red, green, blue, x, y, z);
g.ambientLight(red, green, blue, x, y, z);
}
public void directionalLight(float red, float green, float blue,
float nx, float ny, float nz) {
if (recorder != null) recorder.directionalLight(red, green, blue, nx, ny, nz);
g.directionalLight(red, green, blue, nx, ny, nz);
}
public void pointLight(float red, float green, float blue,
float x, float y, float z) {
if (recorder != null) recorder.pointLight(red, green, blue, x, y, z);
g.pointLight(red, green, blue, x, y, z);
}
public void spotLight(float red, float green, float blue,
float x, float y, float z,
float nx, float ny, float nz,
float angle, float concentration) {
if (recorder != null) recorder.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration);
g.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration);
}
public void lightFalloff(float constant, float linear, float quadratic) {
if (recorder != null) recorder.lightFalloff(constant, linear, quadratic);
g.lightFalloff(constant, linear, quadratic);
}
public void lightSpecular(float x, float y, float z) {
if (recorder != null) recorder.lightSpecular(x, y, z);
g.lightSpecular(x, y, z);
}
public void background(int rgb) {
if (recorder != null) recorder.background(rgb);
g.background(rgb);
}
public void background(int rgb, float alpha) {
if (recorder != null) recorder.background(rgb, alpha);
g.background(rgb, alpha);
}
public void background(float gray) {
if (recorder != null) recorder.background(gray);
g.background(gray);
}
public void background(float gray, float alpha) {
if (recorder != null) recorder.background(gray, alpha);
g.background(gray, alpha);
}
public void background(float x, float y, float z) {
if (recorder != null) recorder.background(x, y, z);
g.background(x, y, z);
}
public void background(float x, float y, float z, float a) {
if (recorder != null) recorder.background(x, y, z, a);
g.background(x, y, z, a);
}
public void background(PImage image) {
if (recorder != null) recorder.background(image);
g.background(image);
}
public void colorMode(int mode) {
if (recorder != null) recorder.colorMode(mode);
g.colorMode(mode);
}
public void colorMode(int mode, float max) {
if (recorder != null) recorder.colorMode(mode, max);
g.colorMode(mode, max);
}
public void colorMode(int mode, float maxX, float maxY, float maxZ) {
if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ);
g.colorMode(mode, maxX, maxY, maxZ);
}
public void colorMode(int mode,
float maxX, float maxY, float maxZ, float maxA) {
if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ, maxA);
g.colorMode(mode, maxX, maxY, maxZ, maxA);
}
public final float alpha(int what) {
return g.alpha(what);
}
public final float red(int what) {
return g.red(what);
}
public final float green(int what) {
return g.green(what);
}
public final float blue(int what) {
return g.blue(what);
}
public final float hue(int what) {
return g.hue(what);
}
public final float saturation(int what) {
return g.saturation(what);
}
public final float brightness(int what) {
return g.brightness(what);
}
public int lerpColor(int c1, int c2, float amt) {
return g.lerpColor(c1, c2, amt);
}
static public int lerpColor(int c1, int c2, float amt, int mode) {
return PGraphics.lerpColor(c1, c2, amt, mode);
}
public boolean displayable() {
return g.displayable();
}
public void setCache(Object parent, Object storage) {
if (recorder != null) recorder.setCache(parent, storage);
g.setCache(parent, storage);
}
public Object getCache(Object parent) {
return g.getCache(parent);
}
public void removeCache(Object parent) {
if (recorder != null) recorder.removeCache(parent);
g.removeCache(parent);
}
public int get(int x, int y) {
return g.get(x, y);
}
public PImage get(int x, int y, int w, int h) {
return g.get(x, y, w, h);
}
public PImage get() {
return g.get();
}
public void set(int x, int y, int c) {
if (recorder != null) recorder.set(x, y, c);
g.set(x, y, c);
}
public void set(int x, int y, PImage src) {
if (recorder != null) recorder.set(x, y, src);
g.set(x, y, src);
}
public void mask(int alpha[]) {
if (recorder != null) recorder.mask(alpha);
g.mask(alpha);
}
public void mask(PImage alpha) {
if (recorder != null) recorder.mask(alpha);
g.mask(alpha);
}
public void filter(int kind) {
if (recorder != null) recorder.filter(kind);
g.filter(kind);
}
public void filter(int kind, float param) {
if (recorder != null) recorder.filter(kind, param);
g.filter(kind, param);
}
public void copy(int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh);
g.copy(sx, sy, sw, sh, dx, dy, dw, dh);
}
public void copy(PImage src,
int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
}
static public int blendColor(int c1, int c2, int mode) {
return PGraphics.blendColor(c1, c2, mode);
}
public void blend(int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh, int mode) {
if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
}
public void blend(PImage src,
int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh, int mode) {
if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
}
}
|
static public void main(String args[]) {
// Disable abyssmally slow Sun renderer on OS X 10.5.
if (platform == MACOSX) {
// Only run this on OS X otherwise it can cause a permissions error.
// http://dev.processing.org/bugs/show_bug.cgi?id=976
System.setProperty("apple.awt.graphics.UseQuartz", "true");
}
// This doesn't do anything.
// if (platform == WINDOWS) {
// // For now, disable the D3D renderer on Java 6u10 because
// // it causes problems with Present mode.
// // http://dev.processing.org/bugs/show_bug.cgi?id=1009
// System.setProperty("sun.java2d.d3d", "false");
// }
if (args.length < 1) {
System.err.println("Usage: PApplet <appletname>");
System.err.println("For additional options, " +
"see the Javadoc for PApplet");
System.exit(1);
}
try {
boolean external = false;
int location[] = null;
int editorLocation[] = null;
String name = null;
boolean present = false;
Color backgroundColor = Color.BLACK;
Color stopColor = Color.GRAY;
GraphicsDevice displayDevice = null;
boolean hideStop = false;
String param = null, value = null;
// try to get the user folder. if running under java web start,
// this may cause a security exception if the code is not signed.
// http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274
String folder = null;
try {
folder = System.getProperty("user.dir");
} catch (Exception e) { }
int argIndex = 0;
while (argIndex < args.length) {
int equals = args[argIndex].indexOf('=');
if (equals != -1) {
param = args[argIndex].substring(0, equals);
value = args[argIndex].substring(equals + 1);
if (param.equals(ARGS_EDITOR_LOCATION)) {
external = true;
editorLocation = parseInt(split(value, ','));
} else if (param.equals(ARGS_DISPLAY)) {
int deviceIndex = Integer.parseInt(value) - 1;
//DisplayMode dm = device.getDisplayMode();
//if ((dm.getWidth() == 1024) && (dm.getHeight() == 768)) {
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice devices[] = environment.getScreenDevices();
if ((deviceIndex >= 0) && (deviceIndex < devices.length)) {
displayDevice = devices[deviceIndex];
} else {
System.err.println("Display " + value + " does not exist, " +
"using the default display instead.");
}
} else if (param.equals(ARGS_BGCOLOR)) {
if (value.charAt(0) == '#') value = value.substring(1);
backgroundColor = new Color(Integer.parseInt(value, 16));
} else if (param.equals(ARGS_STOP_COLOR)) {
if (value.charAt(0) == '#') value = value.substring(1);
stopColor = new Color(Integer.parseInt(value, 16));
} else if (param.equals(ARGS_SKETCH_FOLDER)) {
folder = value;
} else if (param.equals(ARGS_LOCATION)) {
location = parseInt(split(value, ','));
}
} else {
if (args[argIndex].equals(ARGS_PRESENT)) {
present = true;
} else if (args[argIndex].equals(ARGS_HIDE_STOP)) {
hideStop = true;
} else if (args[argIndex].equals(ARGS_EXTERNAL)) {
external = true;
} else {
name = args[argIndex];
break;
}
}
argIndex++;
}
// Set this property before getting into any GUI init code
//System.setProperty("com.apple.mrj.application.apple.menu.about.name", name);
// This )*)(*@#$ Apple crap don't work no matter where you put it
// (static method of the class, at the top of main, wherever)
if (displayDevice == null) {
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
displayDevice = environment.getDefaultScreenDevice();
}
Frame frame = new Frame(displayDevice.getDefaultConfiguration());
/*
Frame frame = null;
if (displayDevice != null) {
frame = new Frame(displayDevice.getDefaultConfiguration());
} else {
frame = new Frame();
}
*/
//Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
// remove the grow box by default
// users who want it back can call frame.setResizable(true)
frame.setResizable(false);
// Set the trimmings around the image
Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE);
frame.setIconImage(image);
frame.setTitle(name);
// Class c = Class.forName(name);
Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(name);
PApplet applet = (PApplet) c.newInstance();
// these are needed before init/start
applet.frame = frame;
applet.sketchPath = folder;
applet.args = PApplet.subset(args, 1);
applet.external = external;
// Need to save the window bounds at full screen,
// because pack() will cause the bounds to go to zero.
// http://dev.processing.org/bugs/show_bug.cgi?id=923
Rectangle fullScreenRect = null;
// For 0149, moving this code (up to the pack() method) before init().
// For OpenGL (and perhaps other renderers in the future), a peer is
// needed before a GLDrawable can be created. So pack() needs to be
// called on the Frame before applet.init(), which itself calls size(),
// and launches the Thread that will kick off setup().
// http://dev.processing.org/bugs/show_bug.cgi?id=891
// http://dev.processing.org/bugs/show_bug.cgi?id=908
if (present) {
frame.setUndecorated(true);
frame.setBackground(backgroundColor);
if (platform == MACOSX) {
displayDevice.setFullScreenWindow(frame);
fullScreenRect = frame.getBounds();
} else {
DisplayMode mode = displayDevice.getDisplayMode();
fullScreenRect = new Rectangle(0, 0, mode.getWidth(), mode.getHeight());
frame.setBounds(fullScreenRect);
frame.setVisible(true);
}
}
frame.setLayout(null);
frame.add(applet);
//frame.pack();
frame.validate();
applet.init();
// Wait until the applet has figured out its width.
// In a static mode app, this will be after setup() has completed,
// and the empty draw() has set "finished" to true.
// TODO make sure this won't hang if the applet has an exception.
while (applet.defaultSize && !applet.finished) {
//System.out.println("default size");
try {
Thread.sleep(5);
} catch (InterruptedException e) {
//System.out.println("interrupt");
}
}
//println("not default size " + applet.width + " " + applet.height);
//println(" (g width/height is " + applet.g.width + "x" + applet.g.height + ")");
if (present) {
// After the pack(), the screen bounds are gonna be 0s
frame.setBounds(fullScreenRect);
applet.setBounds((fullScreenRect.width - applet.width) / 2,
(fullScreenRect.height - applet.height) / 2,
applet.width, applet.height);
if (!hideStop) {
Label label = new Label("stop");
label.setForeground(stopColor);
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
System.exit(0);
}
});
frame.add(label);
Dimension labelSize = label.getPreferredSize();
// sometimes shows up truncated on mac
//System.out.println("label width is " + labelSize.width);
labelSize = new Dimension(100, labelSize.height);
label.setSize(labelSize);
label.setLocation(20, fullScreenRect.height - labelSize.height - 20);
}
// not always running externally when in present mode
if (external) {
applet.setupExternalMessages();
}
} else { // if not presenting
// can't do pack earlier cuz present mode don't like it
// (can't go full screen with a frame after calling pack)
// frame.pack(); // get insets. get more.
Insets insets = frame.getInsets();
int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) +
insets.left + insets.right;
int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) +
insets.top + insets.bottom;
frame.setSize(windowW, windowH);
if (location != null) {
// a specific location was received from PdeRuntime
// (applet has been run more than once, user placed window)
frame.setLocation(location[0], location[1]);
} else if (external) {
int locationX = editorLocation[0] - 20;
int locationY = editorLocation[1];
if (locationX - windowW > 10) {
// if it fits to the left of the window
frame.setLocation(locationX - windowW, locationY);
} else { // doesn't fit
// if it fits inside the editor window,
// offset slightly from upper lefthand corner
// so that it's plunked inside the text area
locationX = editorLocation[0] + 66;
locationY = editorLocation[1] + 66;
if ((locationX + windowW > applet.screen.width - 33) ||
(locationY + windowH > applet.screen.height - 33)) {
// otherwise center on screen
locationX = (applet.screen.width - windowW) / 2;
locationY = (applet.screen.height - windowH) / 2;
}
frame.setLocation(locationX, locationY);
}
} else { // just center on screen
frame.setLocation((applet.screen.width - applet.width) / 2,
(applet.screen.height - applet.height) / 2);
}
// frame.setLayout(null);
// frame.add(applet);
if (backgroundColor == Color.black) { //BLACK) {
// this means no bg color unless specified
backgroundColor = SystemColor.control;
}
frame.setBackground(backgroundColor);
int usableWindowH = windowH - insets.top - insets.bottom;
applet.setBounds((windowW - applet.width)/2,
insets.top + (usableWindowH - applet.height)/2,
applet.width, applet.height);
if (external) {
applet.setupExternalMessages();
} else { // !external
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
// handle frame resizing events
applet.setupFrameResizeListener();
// all set for rockin
if (applet.displayable()) {
frame.setVisible(true);
}
}
//System.out.println("showing frame");
//System.out.println("applet requesting focus");
applet.requestFocus(); // ask for keydowns
//System.out.println("exiting main()");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
//////////////////////////////////////////////////////////////
/**
* Begin recording to a new renderer of the specified type, using the width
* and height of the main drawing surface.
*/
public PGraphics beginRecord(String renderer, String filename) {
filename = insertFrame(filename);
PGraphics rec = createGraphics(width, height, renderer, filename);
beginRecord(rec);
return rec;
}
/**
* Begin recording (echoing) commands to the specified PGraphics object.
*/
public void beginRecord(PGraphics recorder) {
this.recorder = recorder;
recorder.beginDraw();
}
public void endRecord() {
if (recorder != null) {
recorder.endDraw();
recorder.dispose();
recorder = null;
}
}
/**
* Begin recording raw shape data to a renderer of the specified type,
* using the width and height of the main drawing surface.
*
* If hashmarks (###) are found in the filename, they'll be replaced
* by the current frame number (frameCount).
*/
public PGraphics beginRaw(String renderer, String filename) {
filename = insertFrame(filename);
PGraphics rec = createGraphics(width, height, renderer, filename);
g.beginRaw(rec);
return rec;
}
/**
* Begin recording raw shape data to the specified renderer.
*
* This simply echoes to g.beginRaw(), but since is placed here (rather than
* generated by preproc.pl) for clarity and so that it doesn't echo the
* command should beginRecord() be in use.
*/
public void beginRaw(PGraphics rawGraphics) {
g.beginRaw(rawGraphics);
}
/**
* Stop recording raw shape data to the specified renderer.
*
* This simply echoes to g.beginRaw(), but since is placed here (rather than
* generated by preproc.pl) for clarity and so that it doesn't echo the
* command should beginRecord() be in use.
*/
public void endRaw() {
g.endRaw();
}
//////////////////////////////////////////////////////////////
/**
* Override the g.pixels[] function to set the pixels[] array
* that's part of the PApplet object. Allows the use of
* pixels[] in the code, rather than g.pixels[].
*/
public void loadPixels() {
g.loadPixels();
pixels = g.pixels;
}
public void updatePixels() {
g.updatePixels();
}
public void updatePixels(int x1, int y1, int x2, int y2) {
g.updatePixels(x1, y1, x2, y2);
}
//////////////////////////////////////////////////////////////
// everything below this line is automatically generated. no touch.
// public functions for processing.core
public void flush() {
if (recorder != null) recorder.flush();
g.flush();
}
public void hint(int which) {
if (recorder != null) recorder.hint(which);
g.hint(which);
}
public void beginShape() {
if (recorder != null) recorder.beginShape();
g.beginShape();
}
public void beginShape(int kind) {
if (recorder != null) recorder.beginShape(kind);
g.beginShape(kind);
}
public void edge(boolean edge) {
if (recorder != null) recorder.edge(edge);
g.edge(edge);
}
public void normal(float nx, float ny, float nz) {
if (recorder != null) recorder.normal(nx, ny, nz);
g.normal(nx, ny, nz);
}
public void textureMode(int mode) {
if (recorder != null) recorder.textureMode(mode);
g.textureMode(mode);
}
public void texture(PImage image) {
if (recorder != null) recorder.texture(image);
g.texture(image);
}
public void vertex(float x, float y) {
if (recorder != null) recorder.vertex(x, y);
g.vertex(x, y);
}
public void vertex(float x, float y, float z) {
if (recorder != null) recorder.vertex(x, y, z);
g.vertex(x, y, z);
}
public void vertex(float[] v) {
if (recorder != null) recorder.vertex(v);
g.vertex(v);
}
public void vertex(float x, float y, float u, float v) {
if (recorder != null) recorder.vertex(x, y, u, v);
g.vertex(x, y, u, v);
}
public void vertex(float x, float y, float z, float u, float v) {
if (recorder != null) recorder.vertex(x, y, z, u, v);
g.vertex(x, y, z, u, v);
}
public void breakShape() {
if (recorder != null) recorder.breakShape();
g.breakShape();
}
public void endShape() {
if (recorder != null) recorder.endShape();
g.endShape();
}
public void endShape(int mode) {
if (recorder != null) recorder.endShape(mode);
g.endShape(mode);
}
public void bezierVertex(float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4);
g.bezierVertex(x2, y2, x3, y3, x4, y4);
}
public void bezierVertex(float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
public void curveVertex(float x, float y) {
if (recorder != null) recorder.curveVertex(x, y);
g.curveVertex(x, y);
}
public void curveVertex(float x, float y, float z) {
if (recorder != null) recorder.curveVertex(x, y, z);
g.curveVertex(x, y, z);
}
public void point(float x, float y) {
if (recorder != null) recorder.point(x, y);
g.point(x, y);
}
public void point(float x, float y, float z) {
if (recorder != null) recorder.point(x, y, z);
g.point(x, y, z);
}
public void line(float x1, float y1, float x2, float y2) {
if (recorder != null) recorder.line(x1, y1, x2, y2);
g.line(x1, y1, x2, y2);
}
public void line(float x1, float y1, float z1,
float x2, float y2, float z2) {
if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2);
g.line(x1, y1, z1, x2, y2, z2);
}
public void triangle(float x1, float y1, float x2, float y2,
float x3, float y3) {
if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3);
g.triangle(x1, y1, x2, y2, x3, y3);
}
public void quad(float x1, float y1, float x2, float y2,
float x3, float y3, float x4, float y4) {
if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4);
g.quad(x1, y1, x2, y2, x3, y3, x4, y4);
}
public void rectMode(int mode) {
if (recorder != null) recorder.rectMode(mode);
g.rectMode(mode);
}
public void rect(float a, float b, float c, float d) {
if (recorder != null) recorder.rect(a, b, c, d);
g.rect(a, b, c, d);
}
public void ellipseMode(int mode) {
if (recorder != null) recorder.ellipseMode(mode);
g.ellipseMode(mode);
}
public void ellipse(float a, float b, float c, float d) {
if (recorder != null) recorder.ellipse(a, b, c, d);
g.ellipse(a, b, c, d);
}
public void arc(float a, float b, float c, float d,
float start, float stop) {
if (recorder != null) recorder.arc(a, b, c, d, start, stop);
g.arc(a, b, c, d, start, stop);
}
public void box(float size) {
if (recorder != null) recorder.box(size);
g.box(size);
}
public void box(float w, float h, float d) {
if (recorder != null) recorder.box(w, h, d);
g.box(w, h, d);
}
public void sphereDetail(int res) {
if (recorder != null) recorder.sphereDetail(res);
g.sphereDetail(res);
}
public void sphereDetail(int ures, int vres) {
if (recorder != null) recorder.sphereDetail(ures, vres);
g.sphereDetail(ures, vres);
}
public void sphere(float r) {
if (recorder != null) recorder.sphere(r);
g.sphere(r);
}
public float bezierPoint(float a, float b, float c, float d, float t) {
return g.bezierPoint(a, b, c, d, t);
}
public float bezierTangent(float a, float b, float c, float d, float t) {
return g.bezierTangent(a, b, c, d, t);
}
public void bezierDetail(int detail) {
if (recorder != null) recorder.bezierDetail(detail);
g.bezierDetail(detail);
}
public void bezier(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
g.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
}
public void bezier(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
public float curvePoint(float a, float b, float c, float d, float t) {
return g.curvePoint(a, b, c, d, t);
}
public float curveTangent(float a, float b, float c, float d, float t) {
return g.curveTangent(a, b, c, d, t);
}
public void curveDetail(int detail) {
if (recorder != null) recorder.curveDetail(detail);
g.curveDetail(detail);
}
public void curveTightness(float tightness) {
if (recorder != null) recorder.curveTightness(tightness);
g.curveTightness(tightness);
}
public void curve(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4);
g.curve(x1, y1, x2, y2, x3, y3, x4, y4);
}
public void curve(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
public void smooth() {
if (recorder != null) recorder.smooth();
g.smooth();
}
public void noSmooth() {
if (recorder != null) recorder.noSmooth();
g.noSmooth();
}
public void imageMode(int mode) {
if (recorder != null) recorder.imageMode(mode);
g.imageMode(mode);
}
public void image(PImage image, float x, float y) {
if (recorder != null) recorder.image(image, x, y);
g.image(image, x, y);
}
public void image(PImage image, float x, float y, float c, float d) {
if (recorder != null) recorder.image(image, x, y, c, d);
g.image(image, x, y, c, d);
}
public void image(PImage image,
float a, float b, float c, float d,
int u1, int v1, int u2, int v2) {
if (recorder != null) recorder.image(image, a, b, c, d, u1, v1, u2, v2);
g.image(image, a, b, c, d, u1, v1, u2, v2);
}
public void shapeMode(int mode) {
if (recorder != null) recorder.shapeMode(mode);
g.shapeMode(mode);
}
public void shape(PShape shape) {
if (recorder != null) recorder.shape(shape);
g.shape(shape);
}
public void shape(PShape shape, float x, float y) {
if (recorder != null) recorder.shape(shape, x, y);
g.shape(shape, x, y);
}
public void shape(PShape shape, float x, float y, float c, float d) {
if (recorder != null) recorder.shape(shape, x, y, c, d);
g.shape(shape, x, y, c, d);
}
public void textAlign(int align) {
if (recorder != null) recorder.textAlign(align);
g.textAlign(align);
}
public void textAlign(int alignX, int alignY) {
if (recorder != null) recorder.textAlign(alignX, alignY);
g.textAlign(alignX, alignY);
}
public float textAscent() {
return g.textAscent();
}
public float textDescent() {
return g.textDescent();
}
public void textFont(PFont which) {
if (recorder != null) recorder.textFont(which);
g.textFont(which);
}
public void textFont(PFont which, float size) {
if (recorder != null) recorder.textFont(which, size);
g.textFont(which, size);
}
public void textLeading(float leading) {
if (recorder != null) recorder.textLeading(leading);
g.textLeading(leading);
}
public void textMode(int mode) {
if (recorder != null) recorder.textMode(mode);
g.textMode(mode);
}
public void textSize(float size) {
if (recorder != null) recorder.textSize(size);
g.textSize(size);
}
public float textWidth(char c) {
return g.textWidth(c);
}
public float textWidth(String str) {
return g.textWidth(str);
}
public void text(char c) {
if (recorder != null) recorder.text(c);
g.text(c);
}
public void text(char c, float x, float y) {
if (recorder != null) recorder.text(c, x, y);
g.text(c, x, y);
}
public void text(char c, float x, float y, float z) {
if (recorder != null) recorder.text(c, x, y, z);
g.text(c, x, y, z);
}
public void text(String str) {
if (recorder != null) recorder.text(str);
g.text(str);
}
public void text(String str, float x, float y) {
if (recorder != null) recorder.text(str, x, y);
g.text(str, x, y);
}
public void text(String str, float x, float y, float z) {
if (recorder != null) recorder.text(str, x, y, z);
g.text(str, x, y, z);
}
public void text(String str, float x1, float y1, float x2, float y2) {
if (recorder != null) recorder.text(str, x1, y1, x2, y2);
g.text(str, x1, y1, x2, y2);
}
public void text(String s, float x1, float y1, float x2, float y2, float z) {
if (recorder != null) recorder.text(s, x1, y1, x2, y2, z);
g.text(s, x1, y1, x2, y2, z);
}
public void text(int num, float x, float y) {
if (recorder != null) recorder.text(num, x, y);
g.text(num, x, y);
}
public void text(int num, float x, float y, float z) {
if (recorder != null) recorder.text(num, x, y, z);
g.text(num, x, y, z);
}
public void text(float num, float x, float y) {
if (recorder != null) recorder.text(num, x, y);
g.text(num, x, y);
}
public void text(float num, float x, float y, float z) {
if (recorder != null) recorder.text(num, x, y, z);
g.text(num, x, y, z);
}
public void pushMatrix() {
if (recorder != null) recorder.pushMatrix();
g.pushMatrix();
}
public void popMatrix() {
if (recorder != null) recorder.popMatrix();
g.popMatrix();
}
public void translate(float tx, float ty) {
if (recorder != null) recorder.translate(tx, ty);
g.translate(tx, ty);
}
public void translate(float tx, float ty, float tz) {
if (recorder != null) recorder.translate(tx, ty, tz);
g.translate(tx, ty, tz);
}
public void rotate(float angle) {
if (recorder != null) recorder.rotate(angle);
g.rotate(angle);
}
public void rotateX(float angle) {
if (recorder != null) recorder.rotateX(angle);
g.rotateX(angle);
}
public void rotateY(float angle) {
if (recorder != null) recorder.rotateY(angle);
g.rotateY(angle);
}
public void rotateZ(float angle) {
if (recorder != null) recorder.rotateZ(angle);
g.rotateZ(angle);
}
public void rotate(float angle, float vx, float vy, float vz) {
if (recorder != null) recorder.rotate(angle, vx, vy, vz);
g.rotate(angle, vx, vy, vz);
}
public void scale(float s) {
if (recorder != null) recorder.scale(s);
g.scale(s);
}
public void scale(float sx, float sy) {
if (recorder != null) recorder.scale(sx, sy);
g.scale(sx, sy);
}
public void scale(float x, float y, float z) {
if (recorder != null) recorder.scale(x, y, z);
g.scale(x, y, z);
}
public void resetMatrix() {
if (recorder != null) recorder.resetMatrix();
g.resetMatrix();
}
public void applyMatrix(PMatrix source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
public void applyMatrix(PMatrix2D source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
public void applyMatrix(float n00, float n01, float n02,
float n10, float n11, float n12) {
if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12);
g.applyMatrix(n00, n01, n02, n10, n11, n12);
}
public void applyMatrix(PMatrix3D source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
public void applyMatrix(float n00, float n01, float n02, float n03,
float n10, float n11, float n12, float n13,
float n20, float n21, float n22, float n23,
float n30, float n31, float n32, float n33) {
if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
}
public PMatrix getMatrix() {
return g.getMatrix();
}
public PMatrix2D getMatrix(PMatrix2D target) {
return g.getMatrix(target);
}
public PMatrix3D getMatrix(PMatrix3D target) {
return g.getMatrix(target);
}
public void setMatrix(PMatrix source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
public void setMatrix(PMatrix2D source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
public void setMatrix(PMatrix3D source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
public void printMatrix() {
if (recorder != null) recorder.printMatrix();
g.printMatrix();
}
public void beginCamera() {
if (recorder != null) recorder.beginCamera();
g.beginCamera();
}
public void endCamera() {
if (recorder != null) recorder.endCamera();
g.endCamera();
}
public void camera() {
if (recorder != null) recorder.camera();
g.camera();
}
public void camera(float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ,
float upX, float upY, float upZ) {
if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
}
public void printCamera() {
if (recorder != null) recorder.printCamera();
g.printCamera();
}
public void ortho() {
if (recorder != null) recorder.ortho();
g.ortho();
}
public void ortho(float left, float right,
float bottom, float top,
float near, float far) {
if (recorder != null) recorder.ortho(left, right, bottom, top, near, far);
g.ortho(left, right, bottom, top, near, far);
}
public void perspective() {
if (recorder != null) recorder.perspective();
g.perspective();
}
public void perspective(float fovy, float aspect, float zNear, float zFar) {
if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar);
g.perspective(fovy, aspect, zNear, zFar);
}
public void frustum(float left, float right,
float bottom, float top,
float near, float far) {
if (recorder != null) recorder.frustum(left, right, bottom, top, near, far);
g.frustum(left, right, bottom, top, near, far);
}
public void printProjection() {
if (recorder != null) recorder.printProjection();
g.printProjection();
}
public float screenX(float x, float y) {
return g.screenX(x, y);
}
public float screenY(float x, float y) {
return g.screenY(x, y);
}
public float screenX(float x, float y, float z) {
return g.screenX(x, y, z);
}
public float screenY(float x, float y, float z) {
return g.screenY(x, y, z);
}
public float screenZ(float x, float y, float z) {
return g.screenZ(x, y, z);
}
public float modelX(float x, float y, float z) {
return g.modelX(x, y, z);
}
public float modelY(float x, float y, float z) {
return g.modelY(x, y, z);
}
public float modelZ(float x, float y, float z) {
return g.modelZ(x, y, z);
}
public void pushStyle() {
if (recorder != null) recorder.pushStyle();
g.pushStyle();
}
public void popStyle() {
if (recorder != null) recorder.popStyle();
g.popStyle();
}
public void style(PStyle s) {
if (recorder != null) recorder.style(s);
g.style(s);
}
public void strokeWeight(float weight) {
if (recorder != null) recorder.strokeWeight(weight);
g.strokeWeight(weight);
}
public void strokeJoin(int join) {
if (recorder != null) recorder.strokeJoin(join);
g.strokeJoin(join);
}
public void strokeCap(int cap) {
if (recorder != null) recorder.strokeCap(cap);
g.strokeCap(cap);
}
public void noStroke() {
if (recorder != null) recorder.noStroke();
g.noStroke();
}
public void stroke(int rgb) {
if (recorder != null) recorder.stroke(rgb);
g.stroke(rgb);
}
public void stroke(int rgb, float alpha) {
if (recorder != null) recorder.stroke(rgb, alpha);
g.stroke(rgb, alpha);
}
public void stroke(float gray) {
if (recorder != null) recorder.stroke(gray);
g.stroke(gray);
}
public void stroke(float gray, float alpha) {
if (recorder != null) recorder.stroke(gray, alpha);
g.stroke(gray, alpha);
}
public void stroke(float x, float y, float z) {
if (recorder != null) recorder.stroke(x, y, z);
g.stroke(x, y, z);
}
public void stroke(float x, float y, float z, float a) {
if (recorder != null) recorder.stroke(x, y, z, a);
g.stroke(x, y, z, a);
}
public void noTint() {
if (recorder != null) recorder.noTint();
g.noTint();
}
public void tint(int rgb) {
if (recorder != null) recorder.tint(rgb);
g.tint(rgb);
}
public void tint(int rgb, float alpha) {
if (recorder != null) recorder.tint(rgb, alpha);
g.tint(rgb, alpha);
}
public void tint(float gray) {
if (recorder != null) recorder.tint(gray);
g.tint(gray);
}
public void tint(float gray, float alpha) {
if (recorder != null) recorder.tint(gray, alpha);
g.tint(gray, alpha);
}
public void tint(float x, float y, float z) {
if (recorder != null) recorder.tint(x, y, z);
g.tint(x, y, z);
}
public void tint(float x, float y, float z, float a) {
if (recorder != null) recorder.tint(x, y, z, a);
g.tint(x, y, z, a);
}
public void noFill() {
if (recorder != null) recorder.noFill();
g.noFill();
}
public void fill(int rgb) {
if (recorder != null) recorder.fill(rgb);
g.fill(rgb);
}
public void fill(int rgb, float alpha) {
if (recorder != null) recorder.fill(rgb, alpha);
g.fill(rgb, alpha);
}
public void fill(float gray) {
if (recorder != null) recorder.fill(gray);
g.fill(gray);
}
public void fill(float gray, float alpha) {
if (recorder != null) recorder.fill(gray, alpha);
g.fill(gray, alpha);
}
public void fill(float x, float y, float z) {
if (recorder != null) recorder.fill(x, y, z);
g.fill(x, y, z);
}
public void fill(float x, float y, float z, float a) {
if (recorder != null) recorder.fill(x, y, z, a);
g.fill(x, y, z, a);
}
public void ambient(int rgb) {
if (recorder != null) recorder.ambient(rgb);
g.ambient(rgb);
}
public void ambient(float gray) {
if (recorder != null) recorder.ambient(gray);
g.ambient(gray);
}
public void ambient(float x, float y, float z) {
if (recorder != null) recorder.ambient(x, y, z);
g.ambient(x, y, z);
}
public void specular(int rgb) {
if (recorder != null) recorder.specular(rgb);
g.specular(rgb);
}
public void specular(float gray) {
if (recorder != null) recorder.specular(gray);
g.specular(gray);
}
public void specular(float x, float y, float z) {
if (recorder != null) recorder.specular(x, y, z);
g.specular(x, y, z);
}
public void shininess(float shine) {
if (recorder != null) recorder.shininess(shine);
g.shininess(shine);
}
public void emissive(int rgb) {
if (recorder != null) recorder.emissive(rgb);
g.emissive(rgb);
}
public void emissive(float gray) {
if (recorder != null) recorder.emissive(gray);
g.emissive(gray);
}
public void emissive(float x, float y, float z) {
if (recorder != null) recorder.emissive(x, y, z);
g.emissive(x, y, z);
}
public void lights() {
if (recorder != null) recorder.lights();
g.lights();
}
public void noLights() {
if (recorder != null) recorder.noLights();
g.noLights();
}
public void ambientLight(float red, float green, float blue) {
if (recorder != null) recorder.ambientLight(red, green, blue);
g.ambientLight(red, green, blue);
}
public void ambientLight(float red, float green, float blue,
float x, float y, float z) {
if (recorder != null) recorder.ambientLight(red, green, blue, x, y, z);
g.ambientLight(red, green, blue, x, y, z);
}
public void directionalLight(float red, float green, float blue,
float nx, float ny, float nz) {
if (recorder != null) recorder.directionalLight(red, green, blue, nx, ny, nz);
g.directionalLight(red, green, blue, nx, ny, nz);
}
public void pointLight(float red, float green, float blue,
float x, float y, float z) {
if (recorder != null) recorder.pointLight(red, green, blue, x, y, z);
g.pointLight(red, green, blue, x, y, z);
}
public void spotLight(float red, float green, float blue,
float x, float y, float z,
float nx, float ny, float nz,
float angle, float concentration) {
if (recorder != null) recorder.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration);
g.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration);
}
public void lightFalloff(float constant, float linear, float quadratic) {
if (recorder != null) recorder.lightFalloff(constant, linear, quadratic);
g.lightFalloff(constant, linear, quadratic);
}
public void lightSpecular(float x, float y, float z) {
if (recorder != null) recorder.lightSpecular(x, y, z);
g.lightSpecular(x, y, z);
}
public void background(int rgb) {
if (recorder != null) recorder.background(rgb);
g.background(rgb);
}
public void background(int rgb, float alpha) {
if (recorder != null) recorder.background(rgb, alpha);
g.background(rgb, alpha);
}
public void background(float gray) {
if (recorder != null) recorder.background(gray);
g.background(gray);
}
public void background(float gray, float alpha) {
if (recorder != null) recorder.background(gray, alpha);
g.background(gray, alpha);
}
public void background(float x, float y, float z) {
if (recorder != null) recorder.background(x, y, z);
g.background(x, y, z);
}
public void background(float x, float y, float z, float a) {
if (recorder != null) recorder.background(x, y, z, a);
g.background(x, y, z, a);
}
public void background(PImage image) {
if (recorder != null) recorder.background(image);
g.background(image);
}
public void colorMode(int mode) {
if (recorder != null) recorder.colorMode(mode);
g.colorMode(mode);
}
public void colorMode(int mode, float max) {
if (recorder != null) recorder.colorMode(mode, max);
g.colorMode(mode, max);
}
public void colorMode(int mode, float maxX, float maxY, float maxZ) {
if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ);
g.colorMode(mode, maxX, maxY, maxZ);
}
public void colorMode(int mode,
float maxX, float maxY, float maxZ, float maxA) {
if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ, maxA);
g.colorMode(mode, maxX, maxY, maxZ, maxA);
}
public final float alpha(int what) {
return g.alpha(what);
}
public final float red(int what) {
return g.red(what);
}
public final float green(int what) {
return g.green(what);
}
public final float blue(int what) {
return g.blue(what);
}
public final float hue(int what) {
return g.hue(what);
}
public final float saturation(int what) {
return g.saturation(what);
}
public final float brightness(int what) {
return g.brightness(what);
}
public int lerpColor(int c1, int c2, float amt) {
return g.lerpColor(c1, c2, amt);
}
static public int lerpColor(int c1, int c2, float amt, int mode) {
return PGraphics.lerpColor(c1, c2, amt, mode);
}
public boolean displayable() {
return g.displayable();
}
public void setCache(Object parent, Object storage) {
if (recorder != null) recorder.setCache(parent, storage);
g.setCache(parent, storage);
}
public Object getCache(Object parent) {
return g.getCache(parent);
}
public void removeCache(Object parent) {
if (recorder != null) recorder.removeCache(parent);
g.removeCache(parent);
}
public int get(int x, int y) {
return g.get(x, y);
}
public PImage get(int x, int y, int w, int h) {
return g.get(x, y, w, h);
}
public PImage get() {
return g.get();
}
public void set(int x, int y, int c) {
if (recorder != null) recorder.set(x, y, c);
g.set(x, y, c);
}
public void set(int x, int y, PImage src) {
if (recorder != null) recorder.set(x, y, src);
g.set(x, y, src);
}
public void mask(int alpha[]) {
if (recorder != null) recorder.mask(alpha);
g.mask(alpha);
}
public void mask(PImage alpha) {
if (recorder != null) recorder.mask(alpha);
g.mask(alpha);
}
public void filter(int kind) {
if (recorder != null) recorder.filter(kind);
g.filter(kind);
}
public void filter(int kind, float param) {
if (recorder != null) recorder.filter(kind, param);
g.filter(kind, param);
}
public void copy(int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh);
g.copy(sx, sy, sw, sh, dx, dy, dw, dh);
}
public void copy(PImage src,
int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
}
static public int blendColor(int c1, int c2, int mode) {
return PGraphics.blendColor(c1, c2, mode);
}
public void blend(int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh, int mode) {
if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
}
public void blend(PImage src,
int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh, int mode) {
if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
}
}
|
diff --git a/src/suncertify/ui/ConfigurationDialog.java b/src/suncertify/ui/ConfigurationDialog.java
index afc9b35..27ea535 100644
--- a/src/suncertify/ui/ConfigurationDialog.java
+++ b/src/suncertify/ui/ConfigurationDialog.java
@@ -1,481 +1,484 @@
package suncertify.ui;
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;
import suncertify.util.ApplicationMode;
import suncertify.util.PropertyManager;
/**
*
* @author William Brosnan
*/
public class ConfigurationDialog extends JDialog implements ActionListener {
/*
* Adding a logger instance for logging and debugging purposes.
*/
private Logger logger = Logger.getLogger("suncertify.ui");
/**
* Constant to represent property key in properties file
*/
public static final String DB_PATH = "dbPath";
/**
* Constant to represent property key in properties file
*/
public static final String RMI_HOST = "rmiHost";
/**
* Constant to represent property key in properties file
*/
public static final String RMI_PORT = "rmiPort";
/**
* Constant to represent confirmation in the dialog
*/
private static final String CONFIRM = "Confirm";
/**
* Constant to exit out of the entire application
*/
private static final String KILL = "Kill";
/**
* Constant to choose file with <code>JFileChooser</code>
*/
private static final String BROWSE = "Browse";
/**
* JPanel to hold the database selection components
*/
private JPanel dbPanel;
/**
* JPanel to hold the RMI configuration components
*/
private JPanel rmiPanel;
/**
* JPanel to hold confirmation buttons
*/
private JPanel confirmationPanel;
/**
* JLabel for database location
*/
private JLabel dbLabel;
/**
* JTextField for database location
*/
private JTextField dbField;
/**
* JButton for database location, action listener on button
* will call a JFileChooser making it easier for user to choose file
* can be used independently of dbField
*/
private JButton dbButton;
/**
* JLabel for port number for RMI server
*/
private JLabel portLabel;
/**
* JTextField to enter RMI port number
*/
private JTextField portField;
/**
* JLabel for host name for RMI
*/
private JLabel hostLabel;
/**
* JTextField for host name location
*/
private JTextField hostField;
/**
* The mode that the application is running in (standalone, server or
* network client)
*/
private ApplicationMode appMode;
/**
* JButton for confirmation
*/
private JButton okButton;
/**
* JButton to exit the dialog
*/
private JButton cancelButton;
/**
* flag to see if dbPath is valid
*/
private boolean dbFlag = false;
/**
* flag to see if rmiPort is valid
*/
private boolean portFlag = false;
/**
* flag to see if RMI host name is valid
*/
private boolean hostFlag = false;
/**
* Properties instance to get/set properties from properties file
*/
private PropertyManager properties = PropertyManager.getInstance();
/**
* String to hold database location
*/
private String dbPath = null;
/**
* String to hold port number
*/
private String rmiPort = null;
/**
* String to hold dbHost
*/
private String rmiHost = null;
/**
* Constructor for class, set parameters for the JFrame on startup
*/
public ConfigurationDialog(ApplicationMode applicationMode) {
appMode = applicationMode;
setTitle("Configure Options");
//Manually setting size
setSize(600,200);
setResizable(false);
//centers the GUI in the middle of the screen
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
add(loadDBPanel(), BorderLayout.NORTH);
add(loadRMIPanel(), BorderLayout.CENTER);
add(loadConfirmationPanel(), BorderLayout.SOUTH);
initComponents();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
getEvent(KILL);
}
});
}
/**
* Load a JPanel with the necessary swing components for the GUI
* @return JPanel which is added into main JFrame
*/
private JPanel loadDBPanel() {
dbPanel = new JPanel();
dbPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
dbLabel = new JLabel("Enter database location");
dbPanel.add(dbLabel);
//Manually set size of JTextField
dbField = new JTextField(30);
dbPanel.add(dbField);
dbButton = new JButton("Choose File");
dbButton.setActionCommand(BROWSE);
dbButton.addActionListener(this);
dbPanel.add(dbButton);
portLabel = new JLabel("Enter an RMI port");
dbPanel.add(portLabel);
//Manually set size of JTextField
portField = new JTextField(10);
dbPanel.add(portField);
hostLabel = new JLabel("Enter an RMI hostname");
dbPanel.add(hostLabel);
//Manually set size of JTextField
hostField = new JTextField(20);
dbPanel.add(hostField);
//returns the JPanel to the class constructor
return dbPanel;
}
/**
* Loads the components for the network/server application mode
* @return <code>JPanel</code> containing components
*/
private JPanel loadRMIPanel() {
rmiPanel = new JPanel();
portLabel = new JLabel("Enter an RMI port");
rmiPanel.add(portLabel);
//Manually set size of JTextField
portField = new JTextField("5005", 10);
rmiPanel.add(portField);
hostLabel = new JLabel("Enter an RMI hostname");
rmiPanel.add(hostLabel);
//Manually set size of JTextField
hostField = new JTextField(20);
rmiPanel.add(hostField);
//returns the JPanel to the class constructor
return rmiPanel;
}
/**
* Loads the components for confirmation/canceling
* @return <code>JPanel</code> containing components
*/
private JPanel loadConfirmationPanel() {
confirmationPanel = new JPanel();
okButton = new JButton("OK");
okButton.setActionCommand(CONFIRM);
okButton.addActionListener(this);
confirmationPanel.add(okButton);
cancelButton = new JButton("Cancel");
cancelButton.setActionCommand(KILL);
cancelButton.addActionListener(this);
confirmationPanel.add(cancelButton);
//returns the JPanel to the class constructor
return confirmationPanel;
}
/**
* Used to populate/disable fields based on application mode
*/
private void initComponents() {
dbFlag = false;
portFlag = false;
hostFlag = false;
System.out.println(properties.getProperty("dbPath"));
dbPath = properties.getProperty("dbPath");
rmiPort = properties.getProperty("rmiPort");
rmiHost = properties.getProperty("rmiHost");
switch (appMode) {
case ALONE :
dbField.setText(dbPath);
portField.setEnabled(false);
hostField.setEnabled(false);
break;
case SERVER :
dbField.setText(dbPath);
portField.setText(rmiPort);
hostField.setEnabled(false);
break;
case NETWORK :
dbField.setEnabled(false);
dbButton.setEnabled(false);
portField.setText(rmiPort);
hostField.setText(rmiHost);
break;
default :
throw new UnsupportedOperationException
("Invalid application startup mode");
}
}
/**
* Listener for ActionEvents on the GUI buttons
* @param ae
*/
public void actionPerformed(ActionEvent ae) {
getEvent(ae.getActionCommand());
}
/**
* Facilitator method to call the correct handler function to deal with
* the event being passed through.
*
* CONFIRM calls confirmation to verify parameters.
* BROWSE calls chooseFile to open the <code>JFileChooser</code>.
* KILL will exit the application.
* @param event
*/
private void getEvent(String event) {
if (CONFIRM.equals(event)) {
confirmation();
}
else if (BROWSE.equals(event)) {
chooseFile();
}
else {
properties = null;
logger.log(Level.INFO, "Closing down application");
System.exit(0);
}
}
/**
* Displays a <code>JFileChooser</code> when the Choose File button is fired
*/
private void chooseFile() {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Database file", "db");
fileChooser.setFileFilter(filter);
int returnVal = fileChooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
dbField.setText(fileChooser.getSelectedFile().toString());
}
}
/**
* Validates the configuration parameters entered and saves the new
* parameters to the properties file
*/
private void confirmation() {
switch (appMode) {
case ALONE:
portFlag = true;
hostFlag = true;
if (!dbField.getText().equals("")) {
File file = new File(dbPath);
if (file.exists() && file.isFile()) {
dbFlag = true;
dbPath = dbField.getText();
logger.log(Level.INFO, "Database location is: " + dbPath);
properties.setProperty("dbPath", dbPath);
this.setVisible(false);
} else {
JOptionPane.showMessageDialog(confirmationPanel,
"Path entered is invalid");
}
} else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a path to the local database");
}
break;
case SERVER:
hostFlag = true;
if (!dbField.getText().equals("")) {
File file = new File(dbPath);
if (file.exists() && file.isFile()) {
dbFlag = true;
dbPath = dbField.getText();
logger.log(Level.INFO, "Database location is: " + dbPath);
properties.setProperty("dbPath", dbPath);
} else {
JOptionPane.showMessageDialog(confirmationPanel,
"Path entered is invalid");
}
} else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a path to the local database");
}
if (!portField.getText().equals("")) {
if (isNumeric(portField.getText())) {
if (isInRange(portField.getText())) {
portFlag = true;
rmiPort = portField.getText();
logger.log(Level.INFO, "Port number is: " + rmiPort);
properties.setProperty("rmiPort", rmiPort);
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Port not in range, port must be between 0 and 65535");
}
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Port number supplied is not a recognised number");
}
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a port number");
}
if (dbFlag && portFlag && hostFlag) {
this.setVisible(false);
break;
}
case NETWORK:
dbFlag = true;
if (!portField.getText().equals("")) {
if (isNumeric(portField.getText())) {
if (isInRange(portField.getText())) {
portFlag = true;
rmiPort = portField.getText();
logger.log(Level.INFO, "Port number is: " + rmiPort);
properties.setProperty("rmiPort", rmiPort);
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Port not in range, port must be between 0 and 65535");
}
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Port number supplied is not a recognised number");
}
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a port number");
}
if (!hostField.getText().equals("")) {
hostFlag = true;
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a hostname");
}
- break;
+ if (dbFlag && portFlag && hostFlag) {
+ this.setVisible(false);
+ break;
+ }
default:
throw new UnsupportedOperationException
("Invalid application startup mode");
}
}
/**
* Helper method to verify if the port number entered is a recognized number
* @param possibleNumeric - The contents of the portField <code>JTextField</code>
* entered by the user.
* @return a boolean signifying if value is a valid number
*/
private boolean isNumeric(String possibleNumeric) {
try {
double dub = Double.parseDouble(possibleNumeric);
}
catch(NumberFormatException nfex) {
return false;
}
return true;
}
/**
* Helper method to verify if the port number supplied is in the range
* of valid ports
* @param possibleInRange - The contents of the portField <code>JTextField</code>
* entered by the user.
* @return a boolean signifying if value is in the accepted range
*/
private boolean isInRange(String possibleInRange) {
double dub = Double.parseDouble(possibleInRange);
if (dub > 0 && dub < 65535) {
return true;
}
logger.log(Level.INFO, "Port number out of bounds: " + dub);
return false;
}
/**
* Return the database location.
* @return String containing the database location.
*/
public String getDatabaseLocation() {
return dbPath;
}
/**
* Return the RMI port number.
* @return String containing the RMI port number.
*/
public String getRMIPort() {
return rmiPort;
}
/**
* Return the RMI host name.
* @return String containing the RMI host name.
*/
public String getRMIHost() {
return rmiHost;
}
}
| true | true |
private void confirmation() {
switch (appMode) {
case ALONE:
portFlag = true;
hostFlag = true;
if (!dbField.getText().equals("")) {
File file = new File(dbPath);
if (file.exists() && file.isFile()) {
dbFlag = true;
dbPath = dbField.getText();
logger.log(Level.INFO, "Database location is: " + dbPath);
properties.setProperty("dbPath", dbPath);
this.setVisible(false);
} else {
JOptionPane.showMessageDialog(confirmationPanel,
"Path entered is invalid");
}
} else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a path to the local database");
}
break;
case SERVER:
hostFlag = true;
if (!dbField.getText().equals("")) {
File file = new File(dbPath);
if (file.exists() && file.isFile()) {
dbFlag = true;
dbPath = dbField.getText();
logger.log(Level.INFO, "Database location is: " + dbPath);
properties.setProperty("dbPath", dbPath);
} else {
JOptionPane.showMessageDialog(confirmationPanel,
"Path entered is invalid");
}
} else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a path to the local database");
}
if (!portField.getText().equals("")) {
if (isNumeric(portField.getText())) {
if (isInRange(portField.getText())) {
portFlag = true;
rmiPort = portField.getText();
logger.log(Level.INFO, "Port number is: " + rmiPort);
properties.setProperty("rmiPort", rmiPort);
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Port not in range, port must be between 0 and 65535");
}
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Port number supplied is not a recognised number");
}
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a port number");
}
if (dbFlag && portFlag && hostFlag) {
this.setVisible(false);
break;
}
case NETWORK:
dbFlag = true;
if (!portField.getText().equals("")) {
if (isNumeric(portField.getText())) {
if (isInRange(portField.getText())) {
portFlag = true;
rmiPort = portField.getText();
logger.log(Level.INFO, "Port number is: " + rmiPort);
properties.setProperty("rmiPort", rmiPort);
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Port not in range, port must be between 0 and 65535");
}
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Port number supplied is not a recognised number");
}
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a port number");
}
if (!hostField.getText().equals("")) {
hostFlag = true;
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a hostname");
}
break;
default:
throw new UnsupportedOperationException
("Invalid application startup mode");
}
}
|
private void confirmation() {
switch (appMode) {
case ALONE:
portFlag = true;
hostFlag = true;
if (!dbField.getText().equals("")) {
File file = new File(dbPath);
if (file.exists() && file.isFile()) {
dbFlag = true;
dbPath = dbField.getText();
logger.log(Level.INFO, "Database location is: " + dbPath);
properties.setProperty("dbPath", dbPath);
this.setVisible(false);
} else {
JOptionPane.showMessageDialog(confirmationPanel,
"Path entered is invalid");
}
} else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a path to the local database");
}
break;
case SERVER:
hostFlag = true;
if (!dbField.getText().equals("")) {
File file = new File(dbPath);
if (file.exists() && file.isFile()) {
dbFlag = true;
dbPath = dbField.getText();
logger.log(Level.INFO, "Database location is: " + dbPath);
properties.setProperty("dbPath", dbPath);
} else {
JOptionPane.showMessageDialog(confirmationPanel,
"Path entered is invalid");
}
} else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a path to the local database");
}
if (!portField.getText().equals("")) {
if (isNumeric(portField.getText())) {
if (isInRange(portField.getText())) {
portFlag = true;
rmiPort = portField.getText();
logger.log(Level.INFO, "Port number is: " + rmiPort);
properties.setProperty("rmiPort", rmiPort);
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Port not in range, port must be between 0 and 65535");
}
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Port number supplied is not a recognised number");
}
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a port number");
}
if (dbFlag && portFlag && hostFlag) {
this.setVisible(false);
break;
}
case NETWORK:
dbFlag = true;
if (!portField.getText().equals("")) {
if (isNumeric(portField.getText())) {
if (isInRange(portField.getText())) {
portFlag = true;
rmiPort = portField.getText();
logger.log(Level.INFO, "Port number is: " + rmiPort);
properties.setProperty("rmiPort", rmiPort);
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Port not in range, port must be between 0 and 65535");
}
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Port number supplied is not a recognised number");
}
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a port number");
}
if (!hostField.getText().equals("")) {
hostFlag = true;
}
else {
JOptionPane.showMessageDialog(confirmationPanel,
"Please enter a hostname");
}
if (dbFlag && portFlag && hostFlag) {
this.setVisible(false);
break;
}
default:
throw new UnsupportedOperationException
("Invalid application startup mode");
}
}
|
diff --git a/Regex.java b/Regex.java
index b5c0b09..2e7a067 100644
--- a/Regex.java
+++ b/Regex.java
@@ -1,213 +1,219 @@
/**
* A regex object represents a regular expression. A regular expression can be
* recursively defined in the following way: r = <alphanumeric literal> Matches
* one copy of the literal given. r = . Matches precisely one character r = r1r2
* (concatenation of regexes) Matches the r1, then r2, starting from the end of
* the match of r1. r = r1* Matches zero or more copies of r1. r = r1+ Matches
* one or more copies of r1 r = [r1|r2] Matches r1 or r2, but not both.
*
* Notice that we are pretending that we are only interested in matching
* alphanumerics; this is to prevent us from having to deal with escape
* sequences and other ugliness.
*
* Here are some example regexes and strings:
*
* Regex String Matches?
* a a yes
* a b no
* . a yes
* . b yes
* a* yes
* a* a yes
* a* aaaa yes
* a* aab no
* a+ no
* a+ a yes
* a+b aaab yes
* a+b b no
* .*b aaab yes
* [a|b] a yes
* [a|b] b yes
* [a|b] no
*
* @author Nathan
*/
import java.text.ParseException;
public class Regex {
private String regex;
private boolean initialized;
public Regex() {
regex = null;
}
public Regex(String regex) throws ParseException {
initialize(regex);
}
/**
* Instantiates a Regex that matches against the regex given in the parameter.
* Checks to ensure that the syntax is valid, and throws an IllegalArgumentException if not.
*/
public void initialize(String regex) throws ParseException {
int offset = isValidSyntax(regex, 0);
if (offset == -1) {
this.regex = regex;
initialized = true;
} else {
throw new ParseException("Syntax Error in regex: "
+ regex + ".", offset);
}
}
/**
* checkSyntax verifies that the first token of the regular expression, then
* recursively calls checkSyntax on any unverified part of the expression.
* This method should return true if and only if the regex it receives as a parameter
* is a valid representation of a regular expression.
*/
private int isValidSyntax(String regex, int startPos) {
if (regex.length() == 0) {
return -1;
} else if (Character.isLetterOrDigit(regex.charAt(0))
|| regex.charAt(0) == '.') {
if (regex.length() > 1
&& (regex.charAt(1) == '+' || regex.charAt(1) == '*')) {
return isValidSyntax(regex.substring(2), startPos + 2);
} else {
return isValidSyntax(regex.substring(1), startPos + 1);
}
} else if (regex.charAt(0) == '[') {
int off = 0;
if ( (off = isValidSyntax(regex.substring(1, regex.indexOf('|')), startPos + 1)) >= 0 )
return off;
if ( (off = isValidSyntax(regex.substring(regex.indexOf('|') + 1, regex.lastIndexOf(']')), startPos + regex.indexOf('|') + 1)) >= 0 )
return off;
if ( (off = isValidSyntax("l" + regex.substring(regex.lastIndexOf(']') + 1), startPos + regex.lastIndexOf(']') + 1)) >= 0)
return off;
return -1;
} else {
return startPos;
}
}
/**
* Returns true if and only if this Regex matches the string given. See the class description
* for examples of matching.
* @param toMatch the string to match against
*/
public boolean matches(String toMatch) {
if (!initialized) return false;
return matches(this.regex, toMatch);
}
/**
* Returns true if the given string matches the given regex. Works recursively; matching
* the first token of the regex against the first token of the string to match, then stripping
* off the first token of the regex and the matched portion of the string and proceeding.
* @return true iff the regex matches the string toMatch.
*/
private static boolean matches(String regex, String toMatch) {
if (regex.length() == 0 && toMatch.length() == 0) {
// base case; both strings are empty, it's a match.
return true;
} else if (regex.length() == 0 && toMatch.length() > 0) {
// if we have portions of the string left over,
// and the regex is empty, we failed to match.
return false;
} else if (Character.isLetterOrDigit(regex.charAt(0))) {
// if we have a literal, we first check to see if it's modified by a * or +
if (regex.length() > 1 && regex.charAt(1) == '*') {
if (toMatch.length() > 0 && toMatch.charAt(0) == regex.charAt(0)) {
// if there's a star, we check to see if the character matches
// if it does, strip it off and leave the star on.
return matches(regex, toMatch.substring(1));
} else {
// if not, strip off the star.
return matches(regex.substring(2), toMatch);
}
} else if (regex.length() > 1 && regex.charAt(1) == '+') {
// plusses work much like stars, except that we can't have no match
if (toMatch.length() == 0) {
return false;
}
if (toMatch.charAt(0) == regex.charAt(0)) {
// they're so much like stars that after one match, we replace it with a star.
return matches(regex.charAt(0) + "*" + regex.substring(2),
toMatch.substring(1));
}
} else {
// if we don't have a star or a plus, we just make sure that we match the
// current character, then move on.
return (toMatch.length() != 0 && regex.charAt(0) == toMatch.charAt(0))
&& matches(regex.substring(1), toMatch.substring(1));
}
} else if (regex.charAt(0) == '.') {
if (regex.length() > 1) {
if (regex.charAt(1) == '*') {
// .* matches everything
return true;
} else if (regex.charAt(1) == '+') {
// .+ matches everything, if there's anything left to match
return toMatch.length() > 1;
}
} else {
// we'll match just a single character this way.
return matches(regex.substring(1), toMatch.substring(1));
}
} else if (regex.charAt(0) == '[') {
// split this into two regexes; if it matches the left part OR the right part, match.
String leftRegex = regex.substring(1, regex.lastIndexOf('|'));
String rightRegex = regex.substring(regex.lastIndexOf('|') + 1,
regex.lastIndexOf(']'));
String remainderRegex = regex.substring(regex.lastIndexOf(']') + 1);
+ if (leftRegex.length() == 0 || rightRegex.length() == 0 && remainderRegex.length() > 0) {
+ if (remainderRegex.charAt(0) == '+') {
+ // if we have E+ as one option, convert the plus to star
+ remainderRegex = '*' + remainderRegex.substring(1);
+ }
+ }
return matches(leftRegex + remainderRegex, toMatch)
|| matches(rightRegex + remainderRegex, toMatch);
}
// if we got a character we didn't expect in the regex, no match.
return false;
}
/**
* Returns the largest portion of the string, if any, which matches this Regex.
* @return the substring that matches this regex, or null if no substring matches.
*/
public String partialMatch(String toMatch) {
if (!initialized) return null;
// start from the beginning, and test every substring from beginning to end
String largestMatch = "";
boolean match = false;
for (int i = 0; i < toMatch.length(); i++) {
for (int j = i; j <= toMatch.length(); j++) {
if (matches(toMatch.substring(i, j))) {
match = true;
if (j - i > largestMatch.length()) {
largestMatch = toMatch.substring(i, j);
}
}
}
}
return (match) ? largestMatch : null;
}
/**
* Replaces every instance of a match with this regex.
* Overlapping match areas should be dealt with from left to right; for instance:
* new Regex("aaa").replaceMatching("aaaaaaa", "b") should return "bba", not "bab" or "abb".
* @param toMatch the string to find the regex in
* @param toReplace the text to replace the regex with
* @return the new string, with the text in toMatch that matches this regex replaced by toReplace.
*/
public String replaceMatching(String toMatch, String toReplace) {
if (!initialized) return toReplace;
while (partialMatch(toMatch) != null) {
String partialMatch = partialMatch(toMatch);
toMatch = toMatch.replace(partialMatch, toReplace);
}
return toMatch;
}
}
| true | true |
private static boolean matches(String regex, String toMatch) {
if (regex.length() == 0 && toMatch.length() == 0) {
// base case; both strings are empty, it's a match.
return true;
} else if (regex.length() == 0 && toMatch.length() > 0) {
// if we have portions of the string left over,
// and the regex is empty, we failed to match.
return false;
} else if (Character.isLetterOrDigit(regex.charAt(0))) {
// if we have a literal, we first check to see if it's modified by a * or +
if (regex.length() > 1 && regex.charAt(1) == '*') {
if (toMatch.length() > 0 && toMatch.charAt(0) == regex.charAt(0)) {
// if there's a star, we check to see if the character matches
// if it does, strip it off and leave the star on.
return matches(regex, toMatch.substring(1));
} else {
// if not, strip off the star.
return matches(regex.substring(2), toMatch);
}
} else if (regex.length() > 1 && regex.charAt(1) == '+') {
// plusses work much like stars, except that we can't have no match
if (toMatch.length() == 0) {
return false;
}
if (toMatch.charAt(0) == regex.charAt(0)) {
// they're so much like stars that after one match, we replace it with a star.
return matches(regex.charAt(0) + "*" + regex.substring(2),
toMatch.substring(1));
}
} else {
// if we don't have a star or a plus, we just make sure that we match the
// current character, then move on.
return (toMatch.length() != 0 && regex.charAt(0) == toMatch.charAt(0))
&& matches(regex.substring(1), toMatch.substring(1));
}
} else if (regex.charAt(0) == '.') {
if (regex.length() > 1) {
if (regex.charAt(1) == '*') {
// .* matches everything
return true;
} else if (regex.charAt(1) == '+') {
// .+ matches everything, if there's anything left to match
return toMatch.length() > 1;
}
} else {
// we'll match just a single character this way.
return matches(regex.substring(1), toMatch.substring(1));
}
} else if (regex.charAt(0) == '[') {
// split this into two regexes; if it matches the left part OR the right part, match.
String leftRegex = regex.substring(1, regex.lastIndexOf('|'));
String rightRegex = regex.substring(regex.lastIndexOf('|') + 1,
regex.lastIndexOf(']'));
String remainderRegex = regex.substring(regex.lastIndexOf(']') + 1);
return matches(leftRegex + remainderRegex, toMatch)
|| matches(rightRegex + remainderRegex, toMatch);
}
// if we got a character we didn't expect in the regex, no match.
return false;
}
|
private static boolean matches(String regex, String toMatch) {
if (regex.length() == 0 && toMatch.length() == 0) {
// base case; both strings are empty, it's a match.
return true;
} else if (regex.length() == 0 && toMatch.length() > 0) {
// if we have portions of the string left over,
// and the regex is empty, we failed to match.
return false;
} else if (Character.isLetterOrDigit(regex.charAt(0))) {
// if we have a literal, we first check to see if it's modified by a * or +
if (regex.length() > 1 && regex.charAt(1) == '*') {
if (toMatch.length() > 0 && toMatch.charAt(0) == regex.charAt(0)) {
// if there's a star, we check to see if the character matches
// if it does, strip it off and leave the star on.
return matches(regex, toMatch.substring(1));
} else {
// if not, strip off the star.
return matches(regex.substring(2), toMatch);
}
} else if (regex.length() > 1 && regex.charAt(1) == '+') {
// plusses work much like stars, except that we can't have no match
if (toMatch.length() == 0) {
return false;
}
if (toMatch.charAt(0) == regex.charAt(0)) {
// they're so much like stars that after one match, we replace it with a star.
return matches(regex.charAt(0) + "*" + regex.substring(2),
toMatch.substring(1));
}
} else {
// if we don't have a star or a plus, we just make sure that we match the
// current character, then move on.
return (toMatch.length() != 0 && regex.charAt(0) == toMatch.charAt(0))
&& matches(regex.substring(1), toMatch.substring(1));
}
} else if (regex.charAt(0) == '.') {
if (regex.length() > 1) {
if (regex.charAt(1) == '*') {
// .* matches everything
return true;
} else if (regex.charAt(1) == '+') {
// .+ matches everything, if there's anything left to match
return toMatch.length() > 1;
}
} else {
// we'll match just a single character this way.
return matches(regex.substring(1), toMatch.substring(1));
}
} else if (regex.charAt(0) == '[') {
// split this into two regexes; if it matches the left part OR the right part, match.
String leftRegex = regex.substring(1, regex.lastIndexOf('|'));
String rightRegex = regex.substring(regex.lastIndexOf('|') + 1,
regex.lastIndexOf(']'));
String remainderRegex = regex.substring(regex.lastIndexOf(']') + 1);
if (leftRegex.length() == 0 || rightRegex.length() == 0 && remainderRegex.length() > 0) {
if (remainderRegex.charAt(0) == '+') {
// if we have E+ as one option, convert the plus to star
remainderRegex = '*' + remainderRegex.substring(1);
}
}
return matches(leftRegex + remainderRegex, toMatch)
|| matches(rightRegex + remainderRegex, toMatch);
}
// if we got a character we didn't expect in the regex, no match.
return false;
}
|
diff --git a/src/com/dmdirc/ui/swing/dialogs/prefs/SwingPreferencesDialog.java b/src/com/dmdirc/ui/swing/dialogs/prefs/SwingPreferencesDialog.java
index 7cc9b61c8..997ea37fd 100644
--- a/src/com/dmdirc/ui/swing/dialogs/prefs/SwingPreferencesDialog.java
+++ b/src/com/dmdirc/ui/swing/dialogs/prefs/SwingPreferencesDialog.java
@@ -1,629 +1,629 @@
/*
* Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.ui.swing.dialogs.prefs;
import com.dmdirc.ui.swing.components.TextLabel;
import com.dmdirc.Main;
import com.dmdirc.config.IdentityManager;
import com.dmdirc.config.prefs.PreferencesCategory;
import com.dmdirc.config.prefs.PreferencesManager;
import com.dmdirc.config.prefs.PreferencesSetting;
import com.dmdirc.config.prefs.validator.NumericalValidator;
import com.dmdirc.ui.swing.MainFrame;
import com.dmdirc.ui.swing.components.ColourChooser;
import com.dmdirc.ui.swing.components.OptionalColourChooser;
import com.dmdirc.ui.swing.components.StandardDialog;
import com.dmdirc.ui.swing.components.TreeScroller;
import com.dmdirc.ui.swing.components.renderers.MapEntryRenderer;
import com.dmdirc.ui.swing.components.validating.ValidatingJTextField;
import static com.dmdirc.ui.swing.UIUtilities.LARGE_BORDER;
import static com.dmdirc.ui.swing.UIUtilities.SMALL_BORDER;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SpinnerNumberModel;
import javax.swing.SpringLayout;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.text.Position;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import net.miginfocom.swing.MigLayout;
/**
* Allows the user to modify global client preferences.
*/
public final class SwingPreferencesDialog extends StandardDialog implements
ActionListener, TreeSelectionListener {
/**
* A version number for this class. It should be changed whenever the
* class structure is changed (or anything else that would prevent
* serialized objects being unserialized with the new class).
*/
private static final long serialVersionUID = 8;
/** A map of settings to the components used to represent them. */
private final Map<PreferencesSetting, JComponent> components;
/** Categories in the dialog. */
private final Map<PreferencesCategory, JPanel> categories;
/** Nodes in the treeview. */
private final Map<TreeNode, String> nodes;
/** Paths to categories. */
private final Map<String, PreferencesCategory> paths;
/** Custom panels, not to be laid out automatically. */
private final List<JPanel> panels;
/** Preferences tab list, used to switch option types. */
private JTree tabList;
/** Main card layout. */
private CardLayout cardLayout;
/** Main panel. */
private JPanel mainPanel;
/** root node. */
private DefaultMutableTreeNode rootNode;
/** Previously selected category. */
private PreferencesCategory selected = null;
/** Preferences Manager. */
private final PreferencesManager manager;
/**
* Creates a new instance of SwingPreferencesDialog.
*/
public SwingPreferencesDialog() {
super((MainFrame) Main.getUI().getMainWindow(), false);
manager = new PreferencesManager();
categories = new HashMap<PreferencesCategory, JPanel>();
components = new HashMap<PreferencesSetting, JComponent>();
nodes = new HashMap<TreeNode, String>();
paths = new HashMap<String, PreferencesCategory>();
panels = new ArrayList<JPanel>();
initComponents();
new TreeScroller(tabList);
addCategories(manager.getCategories());
}
/**
* Initialises GUI components.
*/
private void initComponents() {
final SpringLayout layout = new SpringLayout();
final JButton button1 = new JButton();
final JButton button2 = new JButton();
cardLayout = new CardLayout();
mainPanel = new JPanel(cardLayout);
rootNode = new DefaultMutableTreeNode("root");
tabList = new JTree(new DefaultTreeModel(rootNode));
tabList.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
tabList.putClientProperty("JTree.lineStyle", "Angled");
tabList.setUI(new javax.swing.plaf.metal.MetalTreeUI());
tabList.setRootVisible(false);
tabList.setShowsRootHandles(false);
tabList.setCellRenderer(new PreferencesTreeCellRenderer());
tabList.addTreeSelectionListener(this);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(new GridBagLayout());
setTitle("Preferences");
setResizable(false);
mainPanel.setBorder(BorderFactory.createEmptyBorder(LARGE_BORDER,
LARGE_BORDER, SMALL_BORDER, LARGE_BORDER));
tabList.setBorder(BorderFactory.createCompoundBorder(BorderFactory
.createEtchedBorder(), BorderFactory.createEmptyBorder(
SMALL_BORDER, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER)));
getContentPane().setLayout(layout);
tabList.setPreferredSize(new Dimension(150, 550));
tabList.setMinimumSize(new Dimension(150, 550));
setMinimumSize(new Dimension(650, 600));
setPreferredSize(new Dimension(650, 600));
setMaximumSize(new Dimension(650, 600));
orderButtons(button1, button2);
getContentPane().add(tabList);
getContentPane().add(mainPanel);
getContentPane().add(Box.createHorizontalGlue());
getContentPane().add(button1);
getContentPane().add(button2);
getOkButton().addActionListener(this);
getCancelButton().addActionListener(this);
// tab list
layout.putConstraint(SpringLayout.WEST, tabList, LARGE_BORDER,
SpringLayout.WEST, getContentPane());
layout.putConstraint(SpringLayout.NORTH, tabList, LARGE_BORDER,
SpringLayout.NORTH, getContentPane());
// main panel
layout.putConstraint(SpringLayout.WEST, mainPanel, SMALL_BORDER,
SpringLayout.EAST, tabList);
layout.putConstraint(SpringLayout.NORTH, mainPanel, SMALL_BORDER,
SpringLayout.NORTH, getContentPane());
// ok button
layout.putConstraint(SpringLayout.EAST, getRightButton(), -LARGE_BORDER,
SpringLayout.EAST, getContentPane());
layout.putConstraint(SpringLayout.NORTH, getRightButton(), SMALL_BORDER,
SpringLayout.SOUTH, mainPanel);
// cancel button
layout.putConstraint(SpringLayout.EAST, getLeftButton(), -LARGE_BORDER,
SpringLayout.WEST, getRightButton());
layout.putConstraint(SpringLayout.NORTH, getLeftButton(), SMALL_BORDER,
SpringLayout.SOUTH, mainPanel);
// panel size
layout.putConstraint(SpringLayout.EAST, getContentPane(), LARGE_BORDER,
SpringLayout.EAST, mainPanel);
layout.putConstraint(SpringLayout.SOUTH, getContentPane(), LARGE_BORDER,
SpringLayout.SOUTH, getRightButton());
}
/**
* Initialises and adds a component to a panel.
*
* @param category The category the setting is being added to
* @param setting The setting to be used
*/
private void addComponent(final PreferencesCategory category,
final PreferencesSetting setting) {
final JLabel label = getLabel(setting);
final JComponent option = getComponent(setting);
categories.get(category).add(label);
label.setLabelFor(option);
categories.get(category).add(option, "wrap");
}
/**
* Retrieves the title label for the specified setting.
*
* @param setting The setting whose label is being requested
* @return A JLabel with the appropriate text and tooltip
*/
private JLabel getLabel(final PreferencesSetting setting) {
final JLabel label = new JLabel(setting.getTitle() + ": ", JLabel.TRAILING);
if (setting.getHelptext().isEmpty()) {
label.setToolTipText("No help available.");
} else {
label.setToolTipText(setting.getHelptext());
}
return label;
}
/**
* Retrieves the component for the specified setting.
*
* @param setting The setting whose component is being requested
* @return An appropriate JComponent descendant
*/
private final JComponent getComponent(final PreferencesSetting setting) {
JComponent option;
switch (setting.getType()) {
case TEXT:
option = new ValidatingJTextField(setting.getValidator());
((ValidatingJTextField) option).setText(setting.getValue());
((ValidatingJTextField) option).addKeyListener(new KeyAdapter() {
@Override
- public void keyTyped(final KeyEvent e) {
+ public void keyReleased(final KeyEvent e) {
setting.setValue(((JTextField) e.getSource()).getText());
}
});
break;
case BOOLEAN:
option = new JCheckBox();
((JCheckBox) option).setSelected(Boolean.parseBoolean(setting.getValue()));
((JCheckBox) option).addChangeListener(new ChangeListener(){
public void stateChanged(final ChangeEvent e) {
setting.setValue(String.valueOf(((JCheckBox) e.getSource()).isSelected()));
}
});
break;
case MULTICHOICE:
option = new JComboBox(setting.getComboOptions().entrySet().toArray());
((JComboBox) option).setRenderer(new MapEntryRenderer());
((JComboBox) option).setEditable(false);
for (Map.Entry<String, String> entry : setting.getComboOptions().entrySet()) {
if (entry.getKey().equals(setting.getValue())) {
((JComboBox) option).setSelectedItem(entry);
break;
}
}
((JComboBox) option).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setting.setValue((String) ((Map.Entry)
((JComboBox) e.getSource()).getSelectedItem()).getKey());
}
});
break;
case INTEGER:
case DURATION:
try {
if (setting.getValidator() instanceof NumericalValidator) {
option = new JSpinner(
new SpinnerNumberModel(Integer.parseInt(setting.getValue()),
((NumericalValidator) setting.getValidator()).getMin(),
((NumericalValidator) setting.getValidator()).getMax(),
1));
} else {
option = new JSpinner(new SpinnerNumberModel());
((JSpinner) option).setValue(Integer.parseInt(setting.getValue()));
}
} catch (NumberFormatException ex) {
option = new JSpinner(new SpinnerNumberModel());
}
((JSpinner) option).addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
setting.setValue(((JSpinner) e.getSource()).getValue().toString());
}
});
break;
case COLOUR:
option = new ColourChooser(setting.getValue(), true, true);
((ColourChooser) option).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setting.setValue(((ColourChooser) e.getSource()).getColour());
}
});
break;
case OPTIONALCOLOUR:
final boolean state = setting.getValue() != null &&
!setting.getValue().startsWith("false:");
final String colour = setting.getValue() == null ? "0" :
setting.getValue().substring(1 + setting.getValue().indexOf(':'));
option = new OptionalColourChooser(colour, state, true, true);
((OptionalColourChooser) option).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setting.setValue(
String.valueOf(((OptionalColourChooser) e.getSource()).isEnabled())
+ ":" + ((OptionalColourChooser) e.getSource()).getColour());
}
});
break;
default:
throw new IllegalArgumentException(setting.getType() + " is not a valid option");
}
components.put(setting, option);
option.setPreferredSize(new Dimension(Short.MAX_VALUE, option.getFont()
.getSize()));
return option;
}
/**
* Adds a new inline category.
*
* @param category The category to be added
* @param parent The panel to add the category to
*/
private void addInlineCategory(final PreferencesCategory category,
final JPanel parent) {
final JPanel panel = new JPanel(new MigLayout("fillx, gap " + LARGE_BORDER));
panel.setBorder(BorderFactory.createTitledBorder(category.getTitle()));
categories.put(category, panel);
parent.add(panel, "span, growx, wrap");
initCategory(category, panel, null, "");
}
/**
* Adds the specified category to the preferences dialog.
*
* @param category The category to be added
* @param parentNode the parent node of the category
* @param namePrefix Category name prefix
*/
private void addCategory(final PreferencesCategory category,
final DefaultMutableTreeNode parentNode, final String namePrefix) {
final JPanel panel = new JPanel(new MigLayout("fillx, gap " + LARGE_BORDER));
final String path = namePrefix + "/" + category.getTitle();
DefaultMutableTreeNode newNode;
newNode = new DefaultMutableTreeNode(category.getTitle());
categories.put(category, panel);
nodes.put(newNode, path);
paths.put(path, category);
mainPanel.add(panel, path);
((DefaultTreeModel) tabList.getModel()).insertNodeInto(newNode,
parentNode, parentNode.getChildCount());
tabList.scrollPathToVisible(new TreePath(newNode.getPath()));
initCategory(category, panel, newNode, path);
}
private void initCategory(final PreferencesCategory category, final JPanel panel,
final DefaultMutableTreeNode newNode, final String path) {
if (!category.getDescription().isEmpty()) {
final TextLabel infoLabel = new TextLabel(category.getDescription());
panel.add(infoLabel, "span, growx, wrap");
}
for (PreferencesCategory child : category.getSubcats()) {
if (child.isInline() && category.getInlineBefore()) {
addInlineCategory(child, panel);
} else if (!child.isInline()) {
addCategory(child, newNode, path);
}
}
if (category.hasObject()) {
if (!(category.getObject() instanceof JPanel)) {
throw new IllegalArgumentException("Custom preferences objects" +
" for this UI must extend JPanel.");
}
panels.add((JPanel) category.getObject());
categories.get(category).add((JPanel) category.getObject(), "growx");
return;
}
for (PreferencesSetting setting : category.getSettings()) {
addComponent(category, setting);
}
if (!category.getInlineBefore()) {
for (PreferencesCategory child : category.getSubcats()) {
if (child.isInline()) {
addInlineCategory(child, panel);
}
}
}
}
/**
* Adds the specified categories to the preferences dialog.
*
* @param categories The categories to be added
*/
public void addCategories(final Collection<? extends PreferencesCategory> categories) {
for (PreferencesCategory category : categories) {
addCategory(category, rootNode, "");
}
}
/**
* Handles the actions for the dialog.
*
* @param actionEvent Action event
*/
public void actionPerformed(final ActionEvent actionEvent) {
if (selected != null) {
selected.fireCategoryDeselected();
}
if (getOkButton().equals(actionEvent.getSource())) {
if (tabList.getSelectionPath() != null) {
final String node = tabList.getSelectionPath().toString();
IdentityManager.getConfigIdentity().setOption("dialogstate",
"preferences", node.substring(7, node.length() - 1).
replaceAll(", ", "->"));
}
saveOptions();
dispose();
} else if (getCancelButton().equals(actionEvent.getSource())) {
dispose();
}
}
/**
* Called when the selection in the tree changes.
*
* @param selectionEvent list selection event
*/
public void valueChanged(final TreeSelectionEvent selectionEvent) {
final String path = nodes.get(((JTree) selectionEvent.getSource())
.getSelectionPath().getLastPathComponent());
cardLayout.show(mainPanel, path);
if (selected != null) {
selected.fireCategoryDeselected();
}
selected = paths.get(path);
selected.fireCategorySelected();
}
/** {@inheritDoc} */
public void saveOptions() {
manager.fireSaveListeners();
boolean restart = false;
for (PreferencesSetting setting : components.keySet()) {
if (setting.save() && setting.isRestartNeeded()) {
restart = true;
}
}
if (restart) {
JOptionPane.showMessageDialog((MainFrame) Main.getUI().
getMainWindow(), "One or more of the changes you made "
+ "won't take effect until you restart the client.",
"Restart needed", JOptionPane.INFORMATION_MESSAGE);
}
}
/** {@inheritDoc} */
public void display() {
final String[] tabName = IdentityManager.getGlobalConfig().
getOption("dialogstate", "preferences", "").split("->");
TreePath path = new TreePath(tabList.getModel().getRoot());
for (String string : tabName) {
final TreePath treePath = tabList.getNextMatch(string, 0,
Position.Bias.Forward);
if (treePath != null) {
final TreeNode node = (TreeNode) treePath.getLastPathComponent();
if (node != null) {
path = path.pathByAddingChild(node);
}
}
}
if (path == null || path.getPathCount() <= 1) {
tabList.setSelectionPath(tabList.getPathForRow(0));
} else {
tabList.setSelectionPath(path);
}
pack();
setLocationRelativeTo((MainFrame) Main.getUI().getMainWindow());
setVisible(true);
}
/**
* Preferences tree cell renderer.
*/
private class PreferencesTreeCellRenderer extends JLabel implements TreeCellRenderer {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/**
* Creates a new instance of PreferencesTreeCellRenderer.
*/
public PreferencesTreeCellRenderer() {
super();
}
/**
* Configures the renderer based on the passed parameters.
* @param tree JTree for this renderer.
* @param value node to be renderered.
* @param sel whether the node is selected.
* @param expanded whether the node is expanded.
* @param leaf whether the node is a leaf.
* @param row the node's row.
* @param focused whether the node has focus.
* @return RendererComponent for this node.
*/
public final Component getTreeCellRendererComponent(final JTree tree,
final Object value, final boolean sel, final boolean expanded,
final boolean leaf, final int row, final boolean focused) {
setText(value.toString());
setBackground(tree.getBackground());
setForeground(tree.getForeground());
setOpaque(true);
setToolTipText(null);
setBorder(BorderFactory.createEmptyBorder(SMALL_BORDER,
SMALL_BORDER, SMALL_BORDER, SMALL_BORDER));
setPreferredSize(new Dimension((int) tabList.getPreferredSize().getWidth() - 20,
getFont().getSize() + SMALL_BORDER));
if (sel) {
setFont(getFont().deriveFont(Font.BOLD));
} else {
setFont(getFont().deriveFont(Font.PLAIN));
}
return this;
}
}
}
| true | true |
private final JComponent getComponent(final PreferencesSetting setting) {
JComponent option;
switch (setting.getType()) {
case TEXT:
option = new ValidatingJTextField(setting.getValidator());
((ValidatingJTextField) option).setText(setting.getValue());
((ValidatingJTextField) option).addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(final KeyEvent e) {
setting.setValue(((JTextField) e.getSource()).getText());
}
});
break;
case BOOLEAN:
option = new JCheckBox();
((JCheckBox) option).setSelected(Boolean.parseBoolean(setting.getValue()));
((JCheckBox) option).addChangeListener(new ChangeListener(){
public void stateChanged(final ChangeEvent e) {
setting.setValue(String.valueOf(((JCheckBox) e.getSource()).isSelected()));
}
});
break;
case MULTICHOICE:
option = new JComboBox(setting.getComboOptions().entrySet().toArray());
((JComboBox) option).setRenderer(new MapEntryRenderer());
((JComboBox) option).setEditable(false);
for (Map.Entry<String, String> entry : setting.getComboOptions().entrySet()) {
if (entry.getKey().equals(setting.getValue())) {
((JComboBox) option).setSelectedItem(entry);
break;
}
}
((JComboBox) option).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setting.setValue((String) ((Map.Entry)
((JComboBox) e.getSource()).getSelectedItem()).getKey());
}
});
break;
case INTEGER:
case DURATION:
try {
if (setting.getValidator() instanceof NumericalValidator) {
option = new JSpinner(
new SpinnerNumberModel(Integer.parseInt(setting.getValue()),
((NumericalValidator) setting.getValidator()).getMin(),
((NumericalValidator) setting.getValidator()).getMax(),
1));
} else {
option = new JSpinner(new SpinnerNumberModel());
((JSpinner) option).setValue(Integer.parseInt(setting.getValue()));
}
} catch (NumberFormatException ex) {
option = new JSpinner(new SpinnerNumberModel());
}
((JSpinner) option).addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
setting.setValue(((JSpinner) e.getSource()).getValue().toString());
}
});
break;
case COLOUR:
option = new ColourChooser(setting.getValue(), true, true);
((ColourChooser) option).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setting.setValue(((ColourChooser) e.getSource()).getColour());
}
});
break;
case OPTIONALCOLOUR:
final boolean state = setting.getValue() != null &&
!setting.getValue().startsWith("false:");
final String colour = setting.getValue() == null ? "0" :
setting.getValue().substring(1 + setting.getValue().indexOf(':'));
option = new OptionalColourChooser(colour, state, true, true);
((OptionalColourChooser) option).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setting.setValue(
String.valueOf(((OptionalColourChooser) e.getSource()).isEnabled())
+ ":" + ((OptionalColourChooser) e.getSource()).getColour());
}
});
break;
default:
throw new IllegalArgumentException(setting.getType() + " is not a valid option");
}
components.put(setting, option);
option.setPreferredSize(new Dimension(Short.MAX_VALUE, option.getFont()
.getSize()));
return option;
}
|
private final JComponent getComponent(final PreferencesSetting setting) {
JComponent option;
switch (setting.getType()) {
case TEXT:
option = new ValidatingJTextField(setting.getValidator());
((ValidatingJTextField) option).setText(setting.getValue());
((ValidatingJTextField) option).addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(final KeyEvent e) {
setting.setValue(((JTextField) e.getSource()).getText());
}
});
break;
case BOOLEAN:
option = new JCheckBox();
((JCheckBox) option).setSelected(Boolean.parseBoolean(setting.getValue()));
((JCheckBox) option).addChangeListener(new ChangeListener(){
public void stateChanged(final ChangeEvent e) {
setting.setValue(String.valueOf(((JCheckBox) e.getSource()).isSelected()));
}
});
break;
case MULTICHOICE:
option = new JComboBox(setting.getComboOptions().entrySet().toArray());
((JComboBox) option).setRenderer(new MapEntryRenderer());
((JComboBox) option).setEditable(false);
for (Map.Entry<String, String> entry : setting.getComboOptions().entrySet()) {
if (entry.getKey().equals(setting.getValue())) {
((JComboBox) option).setSelectedItem(entry);
break;
}
}
((JComboBox) option).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setting.setValue((String) ((Map.Entry)
((JComboBox) e.getSource()).getSelectedItem()).getKey());
}
});
break;
case INTEGER:
case DURATION:
try {
if (setting.getValidator() instanceof NumericalValidator) {
option = new JSpinner(
new SpinnerNumberModel(Integer.parseInt(setting.getValue()),
((NumericalValidator) setting.getValidator()).getMin(),
((NumericalValidator) setting.getValidator()).getMax(),
1));
} else {
option = new JSpinner(new SpinnerNumberModel());
((JSpinner) option).setValue(Integer.parseInt(setting.getValue()));
}
} catch (NumberFormatException ex) {
option = new JSpinner(new SpinnerNumberModel());
}
((JSpinner) option).addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
setting.setValue(((JSpinner) e.getSource()).getValue().toString());
}
});
break;
case COLOUR:
option = new ColourChooser(setting.getValue(), true, true);
((ColourChooser) option).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setting.setValue(((ColourChooser) e.getSource()).getColour());
}
});
break;
case OPTIONALCOLOUR:
final boolean state = setting.getValue() != null &&
!setting.getValue().startsWith("false:");
final String colour = setting.getValue() == null ? "0" :
setting.getValue().substring(1 + setting.getValue().indexOf(':'));
option = new OptionalColourChooser(colour, state, true, true);
((OptionalColourChooser) option).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setting.setValue(
String.valueOf(((OptionalColourChooser) e.getSource()).isEnabled())
+ ":" + ((OptionalColourChooser) e.getSource()).getColour());
}
});
break;
default:
throw new IllegalArgumentException(setting.getType() + " is not a valid option");
}
components.put(setting, option);
option.setPreferredSize(new Dimension(Short.MAX_VALUE, option.getFont()
.getSize()));
return option;
}
|
diff --git a/src/main/java/com/theminequest/MQCoreEvents/EntityEvent/HealthEntitySpawn.java b/src/main/java/com/theminequest/MQCoreEvents/EntityEvent/HealthEntitySpawn.java
index b1c1bad..10e3401 100644
--- a/src/main/java/com/theminequest/MQCoreEvents/EntityEvent/HealthEntitySpawn.java
+++ b/src/main/java/com/theminequest/MQCoreEvents/EntityEvent/HealthEntitySpawn.java
@@ -1,148 +1,153 @@
/*
* This file is part of MineQuest-NPC, Additional Events for MineQuest.
* MineQuest-NPC is licensed under GNU General Public License v3.
* Copyright (C) 2012 The MineQuest Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.theminequest.MQCoreEvents.EntityEvent;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.entity.EntityDamageEvent;
import com.theminequest.MineQuest.API.CompleteStatus;
import com.theminequest.MineQuest.API.Managers;
import com.theminequest.MineQuest.API.Events.DelayedQuestEvent;
import com.theminequest.MineQuest.API.Quest.QuestDetails;
import com.theminequest.MineQuest.API.Utils.MobUtils;
public class HealthEntitySpawn extends DelayedQuestEvent {
private long delay;
private int taskid;
private World w;
private Location loc;
private EntityType t;
private LivingEntity entity;
private int health;
private boolean stay;
private volatile boolean scheduled;
private final Object scheduledLock = new Object();
private int currentHealth;
/*
* (non-Javadoc)
* @see com.theminequest.MineQuest.Events.QEvent#parseDetails(java.lang.String[])
* [0] Delay in MS
* [1] Task
* [2] X
* [3] Y
* [4] Z
* [5] Mob Type
* [6] Health
* [7] Stay Put?
*/
@Override
public void parseDetails(String[] details) {
delay = Long.parseLong(details[0]);
taskid = Integer.parseInt(details[1]);
String worldname = getQuest().getDetails().getProperty(QuestDetails.QUEST_WORLD);
w = Bukkit.getWorld(worldname);
double x = Double.parseDouble(details[2]);
double y = Double.parseDouble(details[3]);
double z = Double.parseDouble(details[4]);
loc = new Location(w,x,y,z);
t = MobUtils.getEntityType(details[5]);
health = Integer.parseInt(details[6]);
stay = ("t".equalsIgnoreCase(details[7]));
entity = null;
scheduled = false;
currentHealth = health;
}
@Override
public boolean delayedConditions() {
if (!scheduled && (entity == null || stay)) {
synchronized (scheduledLock) {
if (!scheduled) {
scheduled = true;
Bukkit.getScheduler().scheduleSyncDelayedTask(Managers.getActivePlugin(), new Runnable() {
public void run() {
if (isComplete() == null) {
if (entity == null) {
entity = (LivingEntity) w.spawnEntity(loc, t);
if (health < entity.getMaxHealth())
entity.setHealth(health);
} else if (stay && !entity.isDead() && entity.isValid()) {
entity.teleport(loc);
}
}
scheduled = false;
}
});
}
}
}
+ if (entity != null) {
+ if (entity.isDead()) {
+ return true;
+ }
+ }
return false;
}
@Override
public boolean entityDamageCondition(EntityDamageEvent e){
if (entity == null)
return false;
if (!e.getEntity().equals(entity))
return false;
int eventDamage = e.getDamage();
// check no damage ticks first
if (eventDamage <= entity.getLastDamage() && entity.getNoDamageTicks() > entity.getMaximumNoDamageTicks() / 2)
return false;
if (currentHealth > entity.getMaxHealth()) {
entity.setHealth(entity.getMaxHealth());
} else if (entity.getHealth() < currentHealth)
entity.setHealth(currentHealth);
currentHealth -= eventDamage;
return false;
}
@Override
public CompleteStatus action() {
return CompleteStatus.SUCCESS;
}
@Override
public Integer switchTask() {
return taskid;
}
@Override
public long getDelay() {
return delay;
}
}
| true | true |
public boolean delayedConditions() {
if (!scheduled && (entity == null || stay)) {
synchronized (scheduledLock) {
if (!scheduled) {
scheduled = true;
Bukkit.getScheduler().scheduleSyncDelayedTask(Managers.getActivePlugin(), new Runnable() {
public void run() {
if (isComplete() == null) {
if (entity == null) {
entity = (LivingEntity) w.spawnEntity(loc, t);
if (health < entity.getMaxHealth())
entity.setHealth(health);
} else if (stay && !entity.isDead() && entity.isValid()) {
entity.teleport(loc);
}
}
scheduled = false;
}
});
}
}
}
return false;
}
|
public boolean delayedConditions() {
if (!scheduled && (entity == null || stay)) {
synchronized (scheduledLock) {
if (!scheduled) {
scheduled = true;
Bukkit.getScheduler().scheduleSyncDelayedTask(Managers.getActivePlugin(), new Runnable() {
public void run() {
if (isComplete() == null) {
if (entity == null) {
entity = (LivingEntity) w.spawnEntity(loc, t);
if (health < entity.getMaxHealth())
entity.setHealth(health);
} else if (stay && !entity.isDead() && entity.isValid()) {
entity.teleport(loc);
}
}
scheduled = false;
}
});
}
}
}
if (entity != null) {
if (entity.isDead()) {
return true;
}
}
return false;
}
|
diff --git a/src/org/ab/uae/Settings.java b/src/org/ab/uae/Settings.java
index 1730895..8573167 100755
--- a/src/org/ab/uae/Settings.java
+++ b/src/org/ab/uae/Settings.java
@@ -1,526 +1,531 @@
package org.ab.uae;
import org.ab.nativelayer.ImportView;
import org.ab.nativelayer.KeyPreference;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.preference.Preference.OnPreferenceChangeListener;
import android.view.KeyEvent;
public class Settings extends PreferenceActivity implements OnPreferenceChangeListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setPreferenceScreen(createPreferenceHierarchy());
}
Preference romPref ;
Preference romKeyPref ;
Preference hddFile ;
Preference hdfFile ;
Preference floppy1 ;
Preference floppy2 ;
Preference floppy3 ;
Preference floppy4 ;
ListPreference fsCpuModelPref;
ListPreference fsChipMemPref;
ListPreference fsFastMemPref;
ListPreference fsSlowMemPref;
ListPreference fsChipSetPref;
ListPreference fsCpuSpeedPref;
private PreferenceScreen createPreferenceHierarchy() {
// Root
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
root.setTitle(R.string.configure);
PreferenceCategory inlinePrefCat = new PreferenceCategory(this);
inlinePrefCat.setTitle(R.string.paths_section);
root.addPreference(inlinePrefCat);
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
romPref = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new RomImportView("rom"));
startActivityForResult(settingsIntent, Globals.PREFKEY_ROM_INT);
}
};
romPref.setTitle(R.string.rom_location);
String rompath = sp.getString(Globals.PREFKEY_ROM, null);
if (rompath != null)
romPref.setSummary(rompath);
inlinePrefCat.addPreference(romPref);
romKeyPref = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new RomImportView("key"));
startActivityForResult(settingsIntent, Globals.PREFKEY_ROMKEY_INT);
}
};
romKeyPref.setTitle(R.string.romkey_location);
String romkeypath = sp.getString(Globals.PREFKEY_ROMKEY, null);
if (romkeypath != null)
romKeyPref.setSummary(romkeypath);
inlinePrefCat.addPreference(romKeyPref);
hdfFile = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new RomImportView("hdf"));
startActivityForResult(settingsIntent, Globals.PREFKEY_HDF_INT);
}
};
rompath = sp.getString(Globals.PREFKEY_HDF, null);
if (rompath != null)
hdfFile.setSummary(rompath);
hdfFile.setTitle(R.string.hdf_location);
inlinePrefCat.addPreference(hdfFile);
if (rompath != null) {
Preference rFloppyHDF = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_HDF);
e.commit();
hdfFile.setSummary("");
}
};
rFloppyHDF.setTitle(R.string.remove_hdf);
inlinePrefCat.addPreference(rFloppyHDF);
}
hddFile = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new RomImportView("dir"));
startActivityForResult(settingsIntent, Globals.PREFKEY_HDD_INT);
}
};
rompath = sp.getString(Globals.PREFKEY_HDD, null);
if (rompath != null)
hddFile.setSummary(rompath);
hddFile.setTitle(R.string.hdd_location);
inlinePrefCat.addPreference(hddFile);
if (rompath != null) {
Preference rFloppyHDD = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_HDD);
e.commit();
hddFile.setSummary("");
}
};
rFloppyHDD.setTitle(R.string.remove_hdd);
inlinePrefCat.addPreference(rFloppyHDD);
}
floppy1 = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new FloppyImportView());
startActivityForResult(settingsIntent, Globals.PREFKEY_F1_INT);
}
};
rompath = sp.getString(Globals.PREFKEY_F1, null);
if (rompath != null)
floppy1.setSummary(rompath);
floppy1.setTitle(R.string.floppy1_location);
inlinePrefCat.addPreference(floppy1);
if (rompath != null) {
Preference rFloppy1 = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_F1);
e.commit();
floppy1.setSummary("");
}
};
rFloppy1.setTitle(R.string.remove_floppy1);
inlinePrefCat.addPreference(rFloppy1);
}
floppy2 = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new FloppyImportView());
startActivityForResult(settingsIntent, Globals.PREFKEY_F2_INT);
}
};
floppy2.setTitle(R.string.floppy2_location);
rompath = sp.getString(Globals.PREFKEY_F2, null);
if (rompath != null)
floppy2.setSummary(rompath);
inlinePrefCat.addPreference(floppy2);
if (rompath != null) {
Preference rFloppy2 = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_F2);
e.commit();
floppy2.setSummary("");
}
};
rFloppy2.setTitle(R.string.remove_floppy2);
inlinePrefCat.addPreference(rFloppy2);
}
floppy3 = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new FloppyImportView());
startActivityForResult(settingsIntent, Globals.PREFKEY_F3_INT);
}
};
floppy3.setTitle(R.string.floppy3_location);
rompath = sp.getString(Globals.PREFKEY_F3, null);
if (rompath != null)
floppy3.setSummary(rompath);
inlinePrefCat.addPreference(floppy3);
if (rompath != null) {
Preference rFloppy3 = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_F3);
e.commit();
floppy3.setSummary("");
}
};
rFloppy3.setTitle(R.string.remove_floppy3);
inlinePrefCat.addPreference(rFloppy3);
}
floppy4 = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new FloppyImportView());
startActivityForResult(settingsIntent, Globals.PREFKEY_F4_INT);
}
};
floppy4.setTitle(R.string.floppy4_location);
rompath = sp.getString(Globals.PREFKEY_F4, null);
if (rompath != null)
floppy4.setSummary(rompath);
inlinePrefCat.addPreference(floppy4);
if (rompath != null) {
Preference rFloppy4 = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_F4);
e.commit();
floppy4.setSummary("");
}
};
rFloppy4.setTitle(R.string.remove_floppy4);
inlinePrefCat.addPreference(rFloppy4);
}
PreferenceCategory perfPrefCat = new PreferenceCategory(this);
perfPrefCat.setTitle(R.string.perf_section);
root.addPreference(perfPrefCat);
CheckBoxPreference toggleSoundPref = new CheckBoxPreference(this);
toggleSoundPref.setKey(Globals.PREFKEY_SOUND);
toggleSoundPref.setTitle(R.string.sound);
toggleSoundPref.setDefaultValue(false);
perfPrefCat.addPreference(toggleSoundPref);
CheckBoxPreference toggleAFSPref = new CheckBoxPreference(this);
toggleAFSPref.setKey(Globals.PREFKEY_AFS);
toggleAFSPref.setTitle(R.string.auto_frameskip);
toggleAFSPref.setDefaultValue(true);
perfPrefCat.addPreference(toggleAFSPref);
ListPreference fs1Pref = new ListPreference(this);
fs1Pref.setEntries(R.array.fs_entries);
fs1Pref.setEntryValues(R.array.fs_entries);
fs1Pref.setDefaultValue("2");
fs1Pref.setDialogTitle(R.string.frameskip_value);
fs1Pref.setKey(Globals.PREFKEY_FS);
fs1Pref.setTitle(R.string.frameskip_value);
perfPrefCat.addPreference(fs1Pref);
CheckBoxPreference toggleDSPref = new CheckBoxPreference(this);
toggleDSPref.setKey(Globals.PREFKEY_DRIVESTATUS);
toggleDSPref.setTitle(R.string.drivestatus);
toggleDSPref.setDefaultValue(false);
perfPrefCat.addPreference(toggleDSPref);
CheckBoxPreference toggleNTSCPref = new CheckBoxPreference(this);
toggleNTSCPref.setKey(Globals.PREFKEY_NTSC);
toggleNTSCPref.setTitle(R.string.ntsc);
toggleNTSCPref.setDefaultValue(false);
perfPrefCat.addPreference(toggleNTSCPref);
fsCpuModelPref = new ListPreference(this);
fsCpuModelPref.setEntries(R.array.cpu_model_summary);
fsCpuModelPref.setEntryValues(R.array.cpu_model_entries);
fsCpuModelPref.setDefaultValue("0");
fsCpuModelPref.setDialogTitle(R.string.cpu_model);
fsCpuModelPref.setKey(Globals.PREF_CPU_MODEL);
fsCpuModelPref.setTitle(R.string.cpu_model);
fsCpuModelPref.setOnPreferenceChangeListener(this);
perfPrefCat.addPreference(fsCpuModelPref);
fsChipMemPref = new ListPreference(this);
fsChipMemPref.setEntries(R.array.mem_summary);
fsChipMemPref.setEntryValues(R.array.mem_entries);
fsChipMemPref.setDefaultValue("1");
fsChipMemPref.setDialogTitle(R.string.chipmem);
fsChipMemPref.setKey(Globals.PREF_CHIP_MEM);
fsChipMemPref.setTitle(R.string.chipmem);
+ fsChipMemPref.setOnPreferenceChangeListener(this);
perfPrefCat.addPreference(fsChipMemPref);
fsFastMemPref = new ListPreference(this);
fsFastMemPref.setEntries(R.array.mem2_summary);
fsFastMemPref.setEntryValues(R.array.mem2_entries);
fsFastMemPref.setDefaultValue("0");
fsFastMemPref.setDialogTitle(R.string.fastmem);
fsFastMemPref.setKey(Globals.PREF_FAST_MEM);
fsFastMemPref.setTitle(R.string.fastmem);
+ fsFastMemPref.setOnPreferenceChangeListener(this);
perfPrefCat.addPreference(fsFastMemPref);
fsSlowMemPref = new ListPreference(this);
fsSlowMemPref.setEntries(R.array.mem2_summary);
fsSlowMemPref.setEntryValues(R.array.mem2_entries);
fsSlowMemPref.setDefaultValue("0");
fsSlowMemPref.setDialogTitle(R.string.slowmem);
fsSlowMemPref.setKey(Globals.PREF_SLOW_MEM);
fsSlowMemPref.setTitle(R.string.slowmem);
+ fsSlowMemPref.setOnPreferenceChangeListener(this);
perfPrefCat.addPreference(fsSlowMemPref);
fsChipSetPref = new ListPreference(this);
fsChipSetPref.setEntries(R.array.chipset_summary);
fsChipSetPref.setEntryValues(R.array.chipset_entries);
fsChipSetPref.setDefaultValue("0");
fsChipSetPref.setDialogTitle(R.string.chipset);
fsChipSetPref.setKey(Globals.PREF_CHIPSET);
fsChipSetPref.setTitle(R.string.chipset);
+ fsChipSetPref.setOnPreferenceChangeListener(this);
perfPrefCat.addPreference(fsChipSetPref);
fsCpuSpeedPref = new ListPreference(this);
fsCpuSpeedPref.setEntries(R.array.cpu_speed_summary);
fsCpuSpeedPref.setEntryValues(R.array.cpu_speed_entries);
fsCpuSpeedPref.setDefaultValue("0");
fsCpuSpeedPref.setDialogTitle(R.string.cpu_speed);
fsCpuSpeedPref.setKey(Globals.PREF_CPU_SPEED);
fsCpuSpeedPref.setTitle(R.string.cpu_speed);
+ fsCpuSpeedPref.setOnPreferenceChangeListener(this);
perfPrefCat.addPreference(fsCpuSpeedPref);
/*ListPreference sc1Pref = new ListPreference(this);
sc1Pref.setEntries(R.array.sc_entries_summary);
sc1Pref.setEntryValues(R.array.sc_entries);
sc1Pref.setDefaultValue("0");
sc1Pref.setDialogTitle(R.string.system_clock);
sc1Pref.setKey(Globals.PREFKEY_SC);
sc1Pref.setTitle(R.string.system_clock);
sc1Pref.setSummary(R.string.system_clock_summary);
perfPrefCat.addPreference(sc1Pref);*/
PreferenceCategory portPrefCat = new PreferenceCategory(this);
portPrefCat.setTitle(R.string.mapping_settings);
root.addPreference(portPrefCat);
ListPreference joyLayoutPref = new ListPreference(this);
joyLayoutPref.setEntries(R.array.joystick_layout_test);
joyLayoutPref.setEntryValues(R.array.joystick_layout);
joyLayoutPref.setDefaultValue("bottom_bottom");
joyLayoutPref.setDialogTitle(R.string.joystick_layout_test);
joyLayoutPref.setKey("vkeypadLayout");
joyLayoutPref.setTitle(R.string.joystick_layout_test);
portPrefCat.addPreference(joyLayoutPref);
ListPreference joySizePref = new ListPreference(this);
joySizePref.setEntries(R.array.joystick_size);
joySizePref.setEntryValues(R.array.joystick_size);
joySizePref.setDefaultValue("medium");
joySizePref.setDialogTitle(R.string.joystick_layout_size);
joySizePref.setKey("vkeypadSize");
joySizePref.setTitle(R.string.joystick_layout_size);
portPrefCat.addPreference(joySizePref);
ListPreference screenSizePref = new ListPreference(this);
screenSizePref.setEntries(R.array.screen_size);
screenSizePref.setEntryValues(R.array.screen_size);
screenSizePref.setDefaultValue("stretched");
screenSizePref.setDialogTitle(R.string.screen_size_text);
screenSizePref.setKey("scale");
screenSizePref.setTitle(R.string.screen_size_text);
portPrefCat.addPreference(screenSizePref);
CheckBoxPreference toggleInputMethodPref = new CheckBoxPreference(this);
toggleInputMethodPref.setKey("useInputMethod");
toggleInputMethodPref.setTitle(R.string.useInputMethodTitle);
toggleInputMethodPref.setDefaultValue(false);
toggleInputMethodPref.setSummary(R.string.useInputMethod);
portPrefCat.addPreference(toggleInputMethodPref);
CheckBoxPreference twoPlayers = new CheckBoxPreference(this);
twoPlayers.setKey("twoPlayers");
twoPlayers.setTitle(R.string.twoPlayersTitle);
twoPlayers.setDefaultValue(false);
twoPlayers.setSummary(R.string.twoPlayers);
portPrefCat.addPreference(twoPlayers);
PreferenceScreen screenPref = getPreferenceManager().createPreferenceScreen(this);
screenPref.setKey("screen_preference");
screenPref.setTitle(R.string.custom_mappings);
portPrefCat.addPreference(screenPref);
for(int i=0;i<DemoActivity.default_keycodes.length;i++) {
screenPref.addPreference(new KeyPreference(this, null, DemoActivity.default_keycodes_string[i], DemoActivity.default_keycodes[i], new int [] { KeyEvent.KEYCODE_MENU }));
}
onPreferenceChange(fsCpuModelPref, sp.getString(Globals.PREF_CPU_MODEL, "0"));
onPreferenceChange(fsCpuSpeedPref, sp.getString(Globals.PREF_CPU_SPEED, "0"));
onPreferenceChange(fsChipMemPref, sp.getString(Globals.PREF_CHIP_MEM, "1"));
onPreferenceChange(fsFastMemPref, sp.getString(Globals.PREF_FAST_MEM, "0"));
onPreferenceChange(fsSlowMemPref, sp.getString(Globals.PREF_SLOW_MEM, "0"));
onPreferenceChange(fsChipSetPref, sp.getString(Globals.PREF_CHIPSET, "0"));
setResult(RESULT_OK);
return root;
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent extras) {
if (resultCode == RESULT_OK) {
String prefKey = null;
String path = null;
if (requestCode == Globals.PREFKEY_ROM_INT) {
prefKey = Globals.PREFKEY_ROM;
path = extras.getStringExtra("currentFile");
romPref.setSummary(path);
} else if (requestCode == Globals.PREFKEY_ROMKEY_INT) {
prefKey = Globals.PREFKEY_ROMKEY;
path = extras.getStringExtra("currentFile");
romKeyPref.setSummary(path);
} else if (requestCode == Globals.PREFKEY_HDD_INT) {
prefKey = Globals.PREFKEY_HDD;
path = extras.getStringExtra("currentFile");
hddFile.setSummary(path);
} else if (requestCode == Globals.PREFKEY_HDF_INT) {
prefKey = Globals.PREFKEY_HDF;
path = extras.getStringExtra("currentFile");
hdfFile.setSummary(path);
} else if (requestCode == Globals.PREFKEY_F1_INT) {
prefKey = Globals.PREFKEY_F1;
path = extras.getStringExtra("currentFile");
floppy1.setSummary(path);
} else if (requestCode == Globals.PREFKEY_F2_INT) {
prefKey = Globals.PREFKEY_F2;
path = extras.getStringExtra("currentFile");
floppy2.setSummary(path);
} else if (requestCode == Globals.PREFKEY_F3_INT) {
prefKey = Globals.PREFKEY_F3;
path = extras.getStringExtra("currentFile");
floppy3.setSummary(path);
} else if (requestCode == Globals.PREFKEY_F4_INT) {
prefKey = Globals.PREFKEY_F4;
path = extras.getStringExtra("currentFile");
floppy4.setSummary(path);
}
if (prefKey != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor e = sp.edit();
e.putString(prefKey, path);
e.commit();
}
}
}
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (Globals.PREF_CPU_MODEL.equals(preference.getKey())) {
int nV = Integer.parseInt(newValue.toString());
fsCpuModelPref.setSummary(getResources().getStringArray(R.array.cpu_model_summary)[nV]);
} else if (Globals.PREF_CPU_SPEED.equals(preference.getKey())) {
int nV = Integer.parseInt(newValue.toString());
fsCpuSpeedPref.setSummary(getResources().getStringArray(R.array.cpu_speed_summary)[nV]);
} else if (Globals.PREF_CHIP_MEM.equals(preference.getKey())) {
int nV = Integer.parseInt(newValue.toString());
fsChipMemPref.setSummary(getResources().getStringArray(R.array.mem_summary)[nV]);
} else if (Globals.PREF_FAST_MEM.equals(preference.getKey())) {
int nV = Integer.parseInt(newValue.toString());
fsFastMemPref.setSummary(getResources().getStringArray(R.array.mem2_summary)[nV]);
} else if (Globals.PREF_SLOW_MEM.equals(preference.getKey())) {
int nV = Integer.parseInt(newValue.toString());
fsSlowMemPref.setSummary(getResources().getStringArray(R.array.mem2_summary)[nV]);
} else if (Globals.PREF_CHIPSET.equals(preference.getKey())) {
int nV = Integer.parseInt(newValue.toString());
fsChipSetPref.setSummary(getResources().getStringArray(R.array.chipset_summary)[nV]);
}
return true;
}
}
| false | true |
private PreferenceScreen createPreferenceHierarchy() {
// Root
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
root.setTitle(R.string.configure);
PreferenceCategory inlinePrefCat = new PreferenceCategory(this);
inlinePrefCat.setTitle(R.string.paths_section);
root.addPreference(inlinePrefCat);
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
romPref = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new RomImportView("rom"));
startActivityForResult(settingsIntent, Globals.PREFKEY_ROM_INT);
}
};
romPref.setTitle(R.string.rom_location);
String rompath = sp.getString(Globals.PREFKEY_ROM, null);
if (rompath != null)
romPref.setSummary(rompath);
inlinePrefCat.addPreference(romPref);
romKeyPref = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new RomImportView("key"));
startActivityForResult(settingsIntent, Globals.PREFKEY_ROMKEY_INT);
}
};
romKeyPref.setTitle(R.string.romkey_location);
String romkeypath = sp.getString(Globals.PREFKEY_ROMKEY, null);
if (romkeypath != null)
romKeyPref.setSummary(romkeypath);
inlinePrefCat.addPreference(romKeyPref);
hdfFile = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new RomImportView("hdf"));
startActivityForResult(settingsIntent, Globals.PREFKEY_HDF_INT);
}
};
rompath = sp.getString(Globals.PREFKEY_HDF, null);
if (rompath != null)
hdfFile.setSummary(rompath);
hdfFile.setTitle(R.string.hdf_location);
inlinePrefCat.addPreference(hdfFile);
if (rompath != null) {
Preference rFloppyHDF = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_HDF);
e.commit();
hdfFile.setSummary("");
}
};
rFloppyHDF.setTitle(R.string.remove_hdf);
inlinePrefCat.addPreference(rFloppyHDF);
}
hddFile = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new RomImportView("dir"));
startActivityForResult(settingsIntent, Globals.PREFKEY_HDD_INT);
}
};
rompath = sp.getString(Globals.PREFKEY_HDD, null);
if (rompath != null)
hddFile.setSummary(rompath);
hddFile.setTitle(R.string.hdd_location);
inlinePrefCat.addPreference(hddFile);
if (rompath != null) {
Preference rFloppyHDD = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_HDD);
e.commit();
hddFile.setSummary("");
}
};
rFloppyHDD.setTitle(R.string.remove_hdd);
inlinePrefCat.addPreference(rFloppyHDD);
}
floppy1 = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new FloppyImportView());
startActivityForResult(settingsIntent, Globals.PREFKEY_F1_INT);
}
};
rompath = sp.getString(Globals.PREFKEY_F1, null);
if (rompath != null)
floppy1.setSummary(rompath);
floppy1.setTitle(R.string.floppy1_location);
inlinePrefCat.addPreference(floppy1);
if (rompath != null) {
Preference rFloppy1 = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_F1);
e.commit();
floppy1.setSummary("");
}
};
rFloppy1.setTitle(R.string.remove_floppy1);
inlinePrefCat.addPreference(rFloppy1);
}
floppy2 = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new FloppyImportView());
startActivityForResult(settingsIntent, Globals.PREFKEY_F2_INT);
}
};
floppy2.setTitle(R.string.floppy2_location);
rompath = sp.getString(Globals.PREFKEY_F2, null);
if (rompath != null)
floppy2.setSummary(rompath);
inlinePrefCat.addPreference(floppy2);
if (rompath != null) {
Preference rFloppy2 = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_F2);
e.commit();
floppy2.setSummary("");
}
};
rFloppy2.setTitle(R.string.remove_floppy2);
inlinePrefCat.addPreference(rFloppy2);
}
floppy3 = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new FloppyImportView());
startActivityForResult(settingsIntent, Globals.PREFKEY_F3_INT);
}
};
floppy3.setTitle(R.string.floppy3_location);
rompath = sp.getString(Globals.PREFKEY_F3, null);
if (rompath != null)
floppy3.setSummary(rompath);
inlinePrefCat.addPreference(floppy3);
if (rompath != null) {
Preference rFloppy3 = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_F3);
e.commit();
floppy3.setSummary("");
}
};
rFloppy3.setTitle(R.string.remove_floppy3);
inlinePrefCat.addPreference(rFloppy3);
}
floppy4 = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new FloppyImportView());
startActivityForResult(settingsIntent, Globals.PREFKEY_F4_INT);
}
};
floppy4.setTitle(R.string.floppy4_location);
rompath = sp.getString(Globals.PREFKEY_F4, null);
if (rompath != null)
floppy4.setSummary(rompath);
inlinePrefCat.addPreference(floppy4);
if (rompath != null) {
Preference rFloppy4 = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_F4);
e.commit();
floppy4.setSummary("");
}
};
rFloppy4.setTitle(R.string.remove_floppy4);
inlinePrefCat.addPreference(rFloppy4);
}
PreferenceCategory perfPrefCat = new PreferenceCategory(this);
perfPrefCat.setTitle(R.string.perf_section);
root.addPreference(perfPrefCat);
CheckBoxPreference toggleSoundPref = new CheckBoxPreference(this);
toggleSoundPref.setKey(Globals.PREFKEY_SOUND);
toggleSoundPref.setTitle(R.string.sound);
toggleSoundPref.setDefaultValue(false);
perfPrefCat.addPreference(toggleSoundPref);
CheckBoxPreference toggleAFSPref = new CheckBoxPreference(this);
toggleAFSPref.setKey(Globals.PREFKEY_AFS);
toggleAFSPref.setTitle(R.string.auto_frameskip);
toggleAFSPref.setDefaultValue(true);
perfPrefCat.addPreference(toggleAFSPref);
ListPreference fs1Pref = new ListPreference(this);
fs1Pref.setEntries(R.array.fs_entries);
fs1Pref.setEntryValues(R.array.fs_entries);
fs1Pref.setDefaultValue("2");
fs1Pref.setDialogTitle(R.string.frameskip_value);
fs1Pref.setKey(Globals.PREFKEY_FS);
fs1Pref.setTitle(R.string.frameskip_value);
perfPrefCat.addPreference(fs1Pref);
CheckBoxPreference toggleDSPref = new CheckBoxPreference(this);
toggleDSPref.setKey(Globals.PREFKEY_DRIVESTATUS);
toggleDSPref.setTitle(R.string.drivestatus);
toggleDSPref.setDefaultValue(false);
perfPrefCat.addPreference(toggleDSPref);
CheckBoxPreference toggleNTSCPref = new CheckBoxPreference(this);
toggleNTSCPref.setKey(Globals.PREFKEY_NTSC);
toggleNTSCPref.setTitle(R.string.ntsc);
toggleNTSCPref.setDefaultValue(false);
perfPrefCat.addPreference(toggleNTSCPref);
fsCpuModelPref = new ListPreference(this);
fsCpuModelPref.setEntries(R.array.cpu_model_summary);
fsCpuModelPref.setEntryValues(R.array.cpu_model_entries);
fsCpuModelPref.setDefaultValue("0");
fsCpuModelPref.setDialogTitle(R.string.cpu_model);
fsCpuModelPref.setKey(Globals.PREF_CPU_MODEL);
fsCpuModelPref.setTitle(R.string.cpu_model);
fsCpuModelPref.setOnPreferenceChangeListener(this);
perfPrefCat.addPreference(fsCpuModelPref);
fsChipMemPref = new ListPreference(this);
fsChipMemPref.setEntries(R.array.mem_summary);
fsChipMemPref.setEntryValues(R.array.mem_entries);
fsChipMemPref.setDefaultValue("1");
fsChipMemPref.setDialogTitle(R.string.chipmem);
fsChipMemPref.setKey(Globals.PREF_CHIP_MEM);
fsChipMemPref.setTitle(R.string.chipmem);
perfPrefCat.addPreference(fsChipMemPref);
fsFastMemPref = new ListPreference(this);
fsFastMemPref.setEntries(R.array.mem2_summary);
fsFastMemPref.setEntryValues(R.array.mem2_entries);
fsFastMemPref.setDefaultValue("0");
fsFastMemPref.setDialogTitle(R.string.fastmem);
fsFastMemPref.setKey(Globals.PREF_FAST_MEM);
fsFastMemPref.setTitle(R.string.fastmem);
perfPrefCat.addPreference(fsFastMemPref);
fsSlowMemPref = new ListPreference(this);
fsSlowMemPref.setEntries(R.array.mem2_summary);
fsSlowMemPref.setEntryValues(R.array.mem2_entries);
fsSlowMemPref.setDefaultValue("0");
fsSlowMemPref.setDialogTitle(R.string.slowmem);
fsSlowMemPref.setKey(Globals.PREF_SLOW_MEM);
fsSlowMemPref.setTitle(R.string.slowmem);
perfPrefCat.addPreference(fsSlowMemPref);
fsChipSetPref = new ListPreference(this);
fsChipSetPref.setEntries(R.array.chipset_summary);
fsChipSetPref.setEntryValues(R.array.chipset_entries);
fsChipSetPref.setDefaultValue("0");
fsChipSetPref.setDialogTitle(R.string.chipset);
fsChipSetPref.setKey(Globals.PREF_CHIPSET);
fsChipSetPref.setTitle(R.string.chipset);
perfPrefCat.addPreference(fsChipSetPref);
fsCpuSpeedPref = new ListPreference(this);
fsCpuSpeedPref.setEntries(R.array.cpu_speed_summary);
fsCpuSpeedPref.setEntryValues(R.array.cpu_speed_entries);
fsCpuSpeedPref.setDefaultValue("0");
fsCpuSpeedPref.setDialogTitle(R.string.cpu_speed);
fsCpuSpeedPref.setKey(Globals.PREF_CPU_SPEED);
fsCpuSpeedPref.setTitle(R.string.cpu_speed);
perfPrefCat.addPreference(fsCpuSpeedPref);
/*ListPreference sc1Pref = new ListPreference(this);
sc1Pref.setEntries(R.array.sc_entries_summary);
sc1Pref.setEntryValues(R.array.sc_entries);
sc1Pref.setDefaultValue("0");
sc1Pref.setDialogTitle(R.string.system_clock);
sc1Pref.setKey(Globals.PREFKEY_SC);
sc1Pref.setTitle(R.string.system_clock);
sc1Pref.setSummary(R.string.system_clock_summary);
perfPrefCat.addPreference(sc1Pref);*/
PreferenceCategory portPrefCat = new PreferenceCategory(this);
portPrefCat.setTitle(R.string.mapping_settings);
root.addPreference(portPrefCat);
ListPreference joyLayoutPref = new ListPreference(this);
joyLayoutPref.setEntries(R.array.joystick_layout_test);
joyLayoutPref.setEntryValues(R.array.joystick_layout);
joyLayoutPref.setDefaultValue("bottom_bottom");
joyLayoutPref.setDialogTitle(R.string.joystick_layout_test);
joyLayoutPref.setKey("vkeypadLayout");
joyLayoutPref.setTitle(R.string.joystick_layout_test);
portPrefCat.addPreference(joyLayoutPref);
ListPreference joySizePref = new ListPreference(this);
joySizePref.setEntries(R.array.joystick_size);
joySizePref.setEntryValues(R.array.joystick_size);
joySizePref.setDefaultValue("medium");
joySizePref.setDialogTitle(R.string.joystick_layout_size);
joySizePref.setKey("vkeypadSize");
joySizePref.setTitle(R.string.joystick_layout_size);
portPrefCat.addPreference(joySizePref);
ListPreference screenSizePref = new ListPreference(this);
screenSizePref.setEntries(R.array.screen_size);
screenSizePref.setEntryValues(R.array.screen_size);
screenSizePref.setDefaultValue("stretched");
screenSizePref.setDialogTitle(R.string.screen_size_text);
screenSizePref.setKey("scale");
screenSizePref.setTitle(R.string.screen_size_text);
portPrefCat.addPreference(screenSizePref);
CheckBoxPreference toggleInputMethodPref = new CheckBoxPreference(this);
toggleInputMethodPref.setKey("useInputMethod");
toggleInputMethodPref.setTitle(R.string.useInputMethodTitle);
toggleInputMethodPref.setDefaultValue(false);
toggleInputMethodPref.setSummary(R.string.useInputMethod);
portPrefCat.addPreference(toggleInputMethodPref);
CheckBoxPreference twoPlayers = new CheckBoxPreference(this);
twoPlayers.setKey("twoPlayers");
twoPlayers.setTitle(R.string.twoPlayersTitle);
twoPlayers.setDefaultValue(false);
twoPlayers.setSummary(R.string.twoPlayers);
portPrefCat.addPreference(twoPlayers);
PreferenceScreen screenPref = getPreferenceManager().createPreferenceScreen(this);
screenPref.setKey("screen_preference");
screenPref.setTitle(R.string.custom_mappings);
portPrefCat.addPreference(screenPref);
for(int i=0;i<DemoActivity.default_keycodes.length;i++) {
screenPref.addPreference(new KeyPreference(this, null, DemoActivity.default_keycodes_string[i], DemoActivity.default_keycodes[i], new int [] { KeyEvent.KEYCODE_MENU }));
}
onPreferenceChange(fsCpuModelPref, sp.getString(Globals.PREF_CPU_MODEL, "0"));
onPreferenceChange(fsCpuSpeedPref, sp.getString(Globals.PREF_CPU_SPEED, "0"));
onPreferenceChange(fsChipMemPref, sp.getString(Globals.PREF_CHIP_MEM, "1"));
onPreferenceChange(fsFastMemPref, sp.getString(Globals.PREF_FAST_MEM, "0"));
onPreferenceChange(fsSlowMemPref, sp.getString(Globals.PREF_SLOW_MEM, "0"));
onPreferenceChange(fsChipSetPref, sp.getString(Globals.PREF_CHIPSET, "0"));
setResult(RESULT_OK);
return root;
}
|
private PreferenceScreen createPreferenceHierarchy() {
// Root
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
root.setTitle(R.string.configure);
PreferenceCategory inlinePrefCat = new PreferenceCategory(this);
inlinePrefCat.setTitle(R.string.paths_section);
root.addPreference(inlinePrefCat);
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
romPref = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new RomImportView("rom"));
startActivityForResult(settingsIntent, Globals.PREFKEY_ROM_INT);
}
};
romPref.setTitle(R.string.rom_location);
String rompath = sp.getString(Globals.PREFKEY_ROM, null);
if (rompath != null)
romPref.setSummary(rompath);
inlinePrefCat.addPreference(romPref);
romKeyPref = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new RomImportView("key"));
startActivityForResult(settingsIntent, Globals.PREFKEY_ROMKEY_INT);
}
};
romKeyPref.setTitle(R.string.romkey_location);
String romkeypath = sp.getString(Globals.PREFKEY_ROMKEY, null);
if (romkeypath != null)
romKeyPref.setSummary(romkeypath);
inlinePrefCat.addPreference(romKeyPref);
hdfFile = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new RomImportView("hdf"));
startActivityForResult(settingsIntent, Globals.PREFKEY_HDF_INT);
}
};
rompath = sp.getString(Globals.PREFKEY_HDF, null);
if (rompath != null)
hdfFile.setSummary(rompath);
hdfFile.setTitle(R.string.hdf_location);
inlinePrefCat.addPreference(hdfFile);
if (rompath != null) {
Preference rFloppyHDF = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_HDF);
e.commit();
hdfFile.setSummary("");
}
};
rFloppyHDF.setTitle(R.string.remove_hdf);
inlinePrefCat.addPreference(rFloppyHDF);
}
hddFile = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new RomImportView("dir"));
startActivityForResult(settingsIntent, Globals.PREFKEY_HDD_INT);
}
};
rompath = sp.getString(Globals.PREFKEY_HDD, null);
if (rompath != null)
hddFile.setSummary(rompath);
hddFile.setTitle(R.string.hdd_location);
inlinePrefCat.addPreference(hddFile);
if (rompath != null) {
Preference rFloppyHDD = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_HDD);
e.commit();
hddFile.setSummary("");
}
};
rFloppyHDD.setTitle(R.string.remove_hdd);
inlinePrefCat.addPreference(rFloppyHDD);
}
floppy1 = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new FloppyImportView());
startActivityForResult(settingsIntent, Globals.PREFKEY_F1_INT);
}
};
rompath = sp.getString(Globals.PREFKEY_F1, null);
if (rompath != null)
floppy1.setSummary(rompath);
floppy1.setTitle(R.string.floppy1_location);
inlinePrefCat.addPreference(floppy1);
if (rompath != null) {
Preference rFloppy1 = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_F1);
e.commit();
floppy1.setSummary("");
}
};
rFloppy1.setTitle(R.string.remove_floppy1);
inlinePrefCat.addPreference(rFloppy1);
}
floppy2 = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new FloppyImportView());
startActivityForResult(settingsIntent, Globals.PREFKEY_F2_INT);
}
};
floppy2.setTitle(R.string.floppy2_location);
rompath = sp.getString(Globals.PREFKEY_F2, null);
if (rompath != null)
floppy2.setSummary(rompath);
inlinePrefCat.addPreference(floppy2);
if (rompath != null) {
Preference rFloppy2 = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_F2);
e.commit();
floppy2.setSummary("");
}
};
rFloppy2.setTitle(R.string.remove_floppy2);
inlinePrefCat.addPreference(rFloppy2);
}
floppy3 = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new FloppyImportView());
startActivityForResult(settingsIntent, Globals.PREFKEY_F3_INT);
}
};
floppy3.setTitle(R.string.floppy3_location);
rompath = sp.getString(Globals.PREFKEY_F3, null);
if (rompath != null)
floppy3.setSummary(rompath);
inlinePrefCat.addPreference(floppy3);
if (rompath != null) {
Preference rFloppy3 = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_F3);
e.commit();
floppy3.setSummary("");
}
};
rFloppy3.setTitle(R.string.remove_floppy3);
inlinePrefCat.addPreference(rFloppy3);
}
floppy4 = new Preference(this) {
@Override
protected void onClick() {
Intent settingsIntent = new Intent();
settingsIntent.setClass(getContext(), ImportView.class);
settingsIntent.putExtra("import", new FloppyImportView());
startActivityForResult(settingsIntent, Globals.PREFKEY_F4_INT);
}
};
floppy4.setTitle(R.string.floppy4_location);
rompath = sp.getString(Globals.PREFKEY_F4, null);
if (rompath != null)
floppy4.setSummary(rompath);
inlinePrefCat.addPreference(floppy4);
if (rompath != null) {
Preference rFloppy4 = new Preference(this) {
@Override
protected void onClick() {
Editor e = sp.edit();
e.remove(Globals.PREFKEY_F4);
e.commit();
floppy4.setSummary("");
}
};
rFloppy4.setTitle(R.string.remove_floppy4);
inlinePrefCat.addPreference(rFloppy4);
}
PreferenceCategory perfPrefCat = new PreferenceCategory(this);
perfPrefCat.setTitle(R.string.perf_section);
root.addPreference(perfPrefCat);
CheckBoxPreference toggleSoundPref = new CheckBoxPreference(this);
toggleSoundPref.setKey(Globals.PREFKEY_SOUND);
toggleSoundPref.setTitle(R.string.sound);
toggleSoundPref.setDefaultValue(false);
perfPrefCat.addPreference(toggleSoundPref);
CheckBoxPreference toggleAFSPref = new CheckBoxPreference(this);
toggleAFSPref.setKey(Globals.PREFKEY_AFS);
toggleAFSPref.setTitle(R.string.auto_frameskip);
toggleAFSPref.setDefaultValue(true);
perfPrefCat.addPreference(toggleAFSPref);
ListPreference fs1Pref = new ListPreference(this);
fs1Pref.setEntries(R.array.fs_entries);
fs1Pref.setEntryValues(R.array.fs_entries);
fs1Pref.setDefaultValue("2");
fs1Pref.setDialogTitle(R.string.frameskip_value);
fs1Pref.setKey(Globals.PREFKEY_FS);
fs1Pref.setTitle(R.string.frameskip_value);
perfPrefCat.addPreference(fs1Pref);
CheckBoxPreference toggleDSPref = new CheckBoxPreference(this);
toggleDSPref.setKey(Globals.PREFKEY_DRIVESTATUS);
toggleDSPref.setTitle(R.string.drivestatus);
toggleDSPref.setDefaultValue(false);
perfPrefCat.addPreference(toggleDSPref);
CheckBoxPreference toggleNTSCPref = new CheckBoxPreference(this);
toggleNTSCPref.setKey(Globals.PREFKEY_NTSC);
toggleNTSCPref.setTitle(R.string.ntsc);
toggleNTSCPref.setDefaultValue(false);
perfPrefCat.addPreference(toggleNTSCPref);
fsCpuModelPref = new ListPreference(this);
fsCpuModelPref.setEntries(R.array.cpu_model_summary);
fsCpuModelPref.setEntryValues(R.array.cpu_model_entries);
fsCpuModelPref.setDefaultValue("0");
fsCpuModelPref.setDialogTitle(R.string.cpu_model);
fsCpuModelPref.setKey(Globals.PREF_CPU_MODEL);
fsCpuModelPref.setTitle(R.string.cpu_model);
fsCpuModelPref.setOnPreferenceChangeListener(this);
perfPrefCat.addPreference(fsCpuModelPref);
fsChipMemPref = new ListPreference(this);
fsChipMemPref.setEntries(R.array.mem_summary);
fsChipMemPref.setEntryValues(R.array.mem_entries);
fsChipMemPref.setDefaultValue("1");
fsChipMemPref.setDialogTitle(R.string.chipmem);
fsChipMemPref.setKey(Globals.PREF_CHIP_MEM);
fsChipMemPref.setTitle(R.string.chipmem);
fsChipMemPref.setOnPreferenceChangeListener(this);
perfPrefCat.addPreference(fsChipMemPref);
fsFastMemPref = new ListPreference(this);
fsFastMemPref.setEntries(R.array.mem2_summary);
fsFastMemPref.setEntryValues(R.array.mem2_entries);
fsFastMemPref.setDefaultValue("0");
fsFastMemPref.setDialogTitle(R.string.fastmem);
fsFastMemPref.setKey(Globals.PREF_FAST_MEM);
fsFastMemPref.setTitle(R.string.fastmem);
fsFastMemPref.setOnPreferenceChangeListener(this);
perfPrefCat.addPreference(fsFastMemPref);
fsSlowMemPref = new ListPreference(this);
fsSlowMemPref.setEntries(R.array.mem2_summary);
fsSlowMemPref.setEntryValues(R.array.mem2_entries);
fsSlowMemPref.setDefaultValue("0");
fsSlowMemPref.setDialogTitle(R.string.slowmem);
fsSlowMemPref.setKey(Globals.PREF_SLOW_MEM);
fsSlowMemPref.setTitle(R.string.slowmem);
fsSlowMemPref.setOnPreferenceChangeListener(this);
perfPrefCat.addPreference(fsSlowMemPref);
fsChipSetPref = new ListPreference(this);
fsChipSetPref.setEntries(R.array.chipset_summary);
fsChipSetPref.setEntryValues(R.array.chipset_entries);
fsChipSetPref.setDefaultValue("0");
fsChipSetPref.setDialogTitle(R.string.chipset);
fsChipSetPref.setKey(Globals.PREF_CHIPSET);
fsChipSetPref.setTitle(R.string.chipset);
fsChipSetPref.setOnPreferenceChangeListener(this);
perfPrefCat.addPreference(fsChipSetPref);
fsCpuSpeedPref = new ListPreference(this);
fsCpuSpeedPref.setEntries(R.array.cpu_speed_summary);
fsCpuSpeedPref.setEntryValues(R.array.cpu_speed_entries);
fsCpuSpeedPref.setDefaultValue("0");
fsCpuSpeedPref.setDialogTitle(R.string.cpu_speed);
fsCpuSpeedPref.setKey(Globals.PREF_CPU_SPEED);
fsCpuSpeedPref.setTitle(R.string.cpu_speed);
fsCpuSpeedPref.setOnPreferenceChangeListener(this);
perfPrefCat.addPreference(fsCpuSpeedPref);
/*ListPreference sc1Pref = new ListPreference(this);
sc1Pref.setEntries(R.array.sc_entries_summary);
sc1Pref.setEntryValues(R.array.sc_entries);
sc1Pref.setDefaultValue("0");
sc1Pref.setDialogTitle(R.string.system_clock);
sc1Pref.setKey(Globals.PREFKEY_SC);
sc1Pref.setTitle(R.string.system_clock);
sc1Pref.setSummary(R.string.system_clock_summary);
perfPrefCat.addPreference(sc1Pref);*/
PreferenceCategory portPrefCat = new PreferenceCategory(this);
portPrefCat.setTitle(R.string.mapping_settings);
root.addPreference(portPrefCat);
ListPreference joyLayoutPref = new ListPreference(this);
joyLayoutPref.setEntries(R.array.joystick_layout_test);
joyLayoutPref.setEntryValues(R.array.joystick_layout);
joyLayoutPref.setDefaultValue("bottom_bottom");
joyLayoutPref.setDialogTitle(R.string.joystick_layout_test);
joyLayoutPref.setKey("vkeypadLayout");
joyLayoutPref.setTitle(R.string.joystick_layout_test);
portPrefCat.addPreference(joyLayoutPref);
ListPreference joySizePref = new ListPreference(this);
joySizePref.setEntries(R.array.joystick_size);
joySizePref.setEntryValues(R.array.joystick_size);
joySizePref.setDefaultValue("medium");
joySizePref.setDialogTitle(R.string.joystick_layout_size);
joySizePref.setKey("vkeypadSize");
joySizePref.setTitle(R.string.joystick_layout_size);
portPrefCat.addPreference(joySizePref);
ListPreference screenSizePref = new ListPreference(this);
screenSizePref.setEntries(R.array.screen_size);
screenSizePref.setEntryValues(R.array.screen_size);
screenSizePref.setDefaultValue("stretched");
screenSizePref.setDialogTitle(R.string.screen_size_text);
screenSizePref.setKey("scale");
screenSizePref.setTitle(R.string.screen_size_text);
portPrefCat.addPreference(screenSizePref);
CheckBoxPreference toggleInputMethodPref = new CheckBoxPreference(this);
toggleInputMethodPref.setKey("useInputMethod");
toggleInputMethodPref.setTitle(R.string.useInputMethodTitle);
toggleInputMethodPref.setDefaultValue(false);
toggleInputMethodPref.setSummary(R.string.useInputMethod);
portPrefCat.addPreference(toggleInputMethodPref);
CheckBoxPreference twoPlayers = new CheckBoxPreference(this);
twoPlayers.setKey("twoPlayers");
twoPlayers.setTitle(R.string.twoPlayersTitle);
twoPlayers.setDefaultValue(false);
twoPlayers.setSummary(R.string.twoPlayers);
portPrefCat.addPreference(twoPlayers);
PreferenceScreen screenPref = getPreferenceManager().createPreferenceScreen(this);
screenPref.setKey("screen_preference");
screenPref.setTitle(R.string.custom_mappings);
portPrefCat.addPreference(screenPref);
for(int i=0;i<DemoActivity.default_keycodes.length;i++) {
screenPref.addPreference(new KeyPreference(this, null, DemoActivity.default_keycodes_string[i], DemoActivity.default_keycodes[i], new int [] { KeyEvent.KEYCODE_MENU }));
}
onPreferenceChange(fsCpuModelPref, sp.getString(Globals.PREF_CPU_MODEL, "0"));
onPreferenceChange(fsCpuSpeedPref, sp.getString(Globals.PREF_CPU_SPEED, "0"));
onPreferenceChange(fsChipMemPref, sp.getString(Globals.PREF_CHIP_MEM, "1"));
onPreferenceChange(fsFastMemPref, sp.getString(Globals.PREF_FAST_MEM, "0"));
onPreferenceChange(fsSlowMemPref, sp.getString(Globals.PREF_SLOW_MEM, "0"));
onPreferenceChange(fsChipSetPref, sp.getString(Globals.PREF_CHIPSET, "0"));
setResult(RESULT_OK);
return root;
}
|
diff --git a/src/main/java/org/mozilla/gecko/background/healthreport/HealthReportGenerator.java b/src/main/java/org/mozilla/gecko/background/healthreport/HealthReportGenerator.java
index 990250b7a..d5e59b9d1 100644
--- a/src/main/java/org/mozilla/gecko/background/healthreport/HealthReportGenerator.java
+++ b/src/main/java/org/mozilla/gecko/background/healthreport/HealthReportGenerator.java
@@ -1,553 +1,554 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko.background.healthreport;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;
import org.mozilla.gecko.background.common.DateUtils;
import org.mozilla.gecko.background.common.log.Logger;
import org.mozilla.gecko.background.healthreport.HealthReportStorage.Field;
import android.database.Cursor;
import android.util.SparseArray;
public class HealthReportGenerator {
private static final int PAYLOAD_VERSION = 3;
private static final String LOG_TAG = "GeckoHealthGen";
private final HealthReportStorage storage;
public HealthReportGenerator(HealthReportStorage storage) {
this.storage = storage;
}
@SuppressWarnings("static-method")
protected long now() {
return System.currentTimeMillis();
}
/**
* @return null if no environment could be computed, or else the resulting document.
* @throws JSONException if there was an error adding environment data to the resulting document.
*/
public JSONObject generateDocument(long since, long lastPingTime, String profilePath) throws JSONException {
Logger.info(LOG_TAG, "Generating FHR document from " + since + "; last ping " + lastPingTime);
Logger.pii(LOG_TAG, "Generating for profile " + profilePath);
ProfileInformationCache cache = new ProfileInformationCache(profilePath);
if (!cache.restoreUnlessInitialized()) {
Logger.warn(LOG_TAG, "Not enough profile information to compute current environment.");
return null;
}
Environment current = EnvironmentBuilder.getCurrentEnvironment(cache);
return generateDocument(since, lastPingTime, current);
}
/**
* The document consists of:
*
*<ul>
*<li>Basic metadata: last ping time, current ping time, version.</li>
*<li>A map of environments: <code>current</code> and others named by hash. <code>current</code> is fully specified,
* and others are deltas from current.</li>
*<li>A <code>data</code> object. This includes <code>last</code> and <code>days</code>.</li>
*</ul>
*
* <code>days</code> is a map from date strings to <tt>{hash: {measurement: {_v: version, fields...}}}</tt>.
* @throws JSONException if there was an error adding environment data to the resulting document.
*/
public JSONObject generateDocument(long since, long lastPingTime, Environment currentEnvironment) throws JSONException {
final String currentHash = currentEnvironment.getHash();
Logger.debug(LOG_TAG, "Current environment hash: " + currentHash);
if (currentHash == null) {
Logger.warn(LOG_TAG, "Current hash is null; aborting.");
return null;
}
// We want to map field IDs to some strings as we go.
SparseArray<Environment> envs = storage.getEnvironmentRecordsByID();
JSONObject document = new JSONObject();
if (lastPingTime >= HealthReportConstants.EARLIEST_LAST_PING) {
document.put("lastPingDate", DateUtils.getDateString(lastPingTime));
}
document.put("thisPingDate", DateUtils.getDateString(now()));
document.put("version", PAYLOAD_VERSION);
document.put("environments", getEnvironmentsJSON(currentEnvironment, envs));
document.put("data", getDataJSON(currentEnvironment, envs, since));
return document;
}
protected JSONObject getDataJSON(Environment currentEnvironment,
SparseArray<Environment> envs, long since) throws JSONException {
SparseArray<Field> fields = storage.getFieldsByID();
JSONObject days = getDaysJSON(currentEnvironment, envs, fields, since);
JSONObject last = new JSONObject();
JSONObject data = new JSONObject();
data.put("days", days);
data.put("last", last);
return data;
}
protected JSONObject getDaysJSON(Environment currentEnvironment, SparseArray<Environment> envs, SparseArray<Field> fields, long since) throws JSONException {
if (Logger.shouldLogVerbose(LOG_TAG)) {
for (int i = 0; i < envs.size(); ++i) {
Logger.trace(LOG_TAG, "Days environment " + envs.keyAt(i) + ": " + envs.get(envs.keyAt(i)).getHash());
}
}
JSONObject days = new JSONObject();
Cursor cursor = storage.getRawEventsSince(since);
try {
if (!cursor.moveToFirst()) {
return days;
}
// A classic walking partition.
// Columns are "date", "env", "field", "value".
// Note that we care about the type (integer, string) and kind
// (last/counter, discrete) of each field.
// Each field will be accessed once for each date/env pair, so
// Field memoizes these facts.
// We also care about which measurement contains each field.
int lastDate = -1;
int lastEnv = -1;
JSONObject dateObject = null;
JSONObject envObject = null;
+ SparseArray<String> dayMemo = new SparseArray<String>(90); // A decent default size.
while (!cursor.isAfterLast()) {
int cEnv = cursor.getInt(1);
if (cEnv == -1 ||
(cEnv != lastEnv &&
envs.indexOfKey(cEnv) < 0)) {
Logger.warn(LOG_TAG, "Invalid environment " + cEnv + " in cursor. Skipping.");
cursor.moveToNext();
continue;
}
int cDate = cursor.getInt(0);
int cField = cursor.getInt(2);
Logger.trace(LOG_TAG, "Event row: " + cDate + ", " + cEnv + ", " + cField);
boolean dateChanged = cDate != lastDate;
boolean envChanged = cEnv != lastEnv;
if (dateChanged) {
if (dateObject != null) {
- days.put(DateUtils.getDateStringForDay(lastDate), dateObject);
+ days.put(DateUtils.getDateStringForDay(lastDate, dayMemo), dateObject);
}
dateObject = new JSONObject();
lastDate = cDate;
}
if (dateChanged || envChanged) {
envObject = new JSONObject();
// This is safe because we checked above that cEnv is valid.
dateObject.put(envs.get(cEnv).getHash(), envObject);
lastEnv = cEnv;
}
final Field field = fields.get(cField);
JSONObject measurement = envObject.optJSONObject(field.measurementName);
if (measurement == null) {
// We will never have more than one measurement version within a
// single environment -- to do so involves changing the build ID. And
// even if we did, we have no way to represent it. So just build the
// output object once.
measurement = new JSONObject();
measurement.put("_v", field.measurementVersion);
envObject.put(field.measurementName, measurement);
}
// How we record depends on the type of the field, so we
// break this out into a separate method for clarity.
recordMeasurementFromCursor(field, measurement, cursor);
cursor.moveToNext();
continue;
}
- days.put(DateUtils.getDateStringForDay(lastDate), dateObject);
+ days.put(DateUtils.getDateStringForDay(lastDate, dayMemo), dateObject);
} finally {
cursor.close();
}
return days;
}
/**
* Return the {@link JSONObject} parsed from the provided index of the given
* cursor, or {@link JSONObject#NULL} if either SQL <code>NULL</code> or
* string <code>"null"</code> is present at that index.
*/
private static Object getJSONAtIndex(Cursor cursor, int index) throws JSONException {
if (cursor.isNull(index)) {
return JSONObject.NULL;
}
final String value = cursor.getString(index);
if ("null".equals(value)) {
return JSONObject.NULL;
}
return new JSONObject(value);
}
protected static void recordMeasurementFromCursor(final Field field,
JSONObject measurement,
Cursor cursor)
throws JSONException {
if (field.isDiscreteField()) {
// Discrete counted. Increment the named counter.
if (field.isCountedField()) {
if (!field.isStringField()) {
throw new IllegalStateException("Unable to handle non-string counted types.");
}
HealthReportUtils.count(measurement, field.fieldName, cursor.getString(3));
return;
}
// Discrete string or integer. Append it.
if (field.isStringField()) {
HealthReportUtils.append(measurement, field.fieldName, cursor.getString(3));
return;
}
if (field.isJSONField()) {
HealthReportUtils.append(measurement, field.fieldName, getJSONAtIndex(cursor, 3));
return;
}
if (field.isIntegerField()) {
HealthReportUtils.append(measurement, field.fieldName, cursor.getLong(3));
return;
}
throw new IllegalStateException("Unknown field type: " + field.flags);
}
// Non-discrete -- must be LAST or COUNTER, so just accumulate the value.
if (field.isStringField()) {
measurement.put(field.fieldName, cursor.getString(3));
return;
}
if (field.isJSONField()) {
measurement.put(field.fieldName, getJSONAtIndex(cursor, 3));
return;
}
measurement.put(field.fieldName, cursor.getLong(3));
}
public static JSONObject getEnvironmentsJSON(Environment currentEnvironment,
SparseArray<Environment> envs) throws JSONException {
JSONObject environments = new JSONObject();
// Always do this, even if it hasn't recorded anything in the DB.
environments.put("current", jsonify(currentEnvironment, null));
String currentHash = currentEnvironment.getHash();
for (int i = 0; i < envs.size(); i++) {
Environment e = envs.valueAt(i);
if (currentHash.equals(e.getHash())) {
continue;
}
environments.put(e.getHash(), jsonify(e, currentEnvironment));
}
return environments;
}
public static JSONObject jsonify(Environment e, Environment current) throws JSONException {
JSONObject age = getProfileAge(e, current);
JSONObject sysinfo = getSysInfo(e, current);
JSONObject gecko = getGeckoInfo(e, current);
JSONObject appinfo = getAppInfo(e, current);
JSONObject counts = getAddonCounts(e, current);
JSONObject out = new JSONObject();
if (age != null)
out.put("org.mozilla.profile.age", age);
if (sysinfo != null)
out.put("org.mozilla.sysinfo.sysinfo", sysinfo);
if (gecko != null)
out.put("geckoAppInfo", gecko);
if (appinfo != null)
out.put("org.mozilla.appInfo.appinfo", appinfo);
if (counts != null)
out.put("org.mozilla.addons.counts", counts);
JSONObject active = getActiveAddons(e, current);
if (active != null)
out.put("org.mozilla.addons.active", active);
if (current == null) {
out.put("hash", e.getHash());
}
return out;
}
private static JSONObject getProfileAge(Environment e, Environment current) throws JSONException {
JSONObject age = new JSONObject();
int changes = 0;
if (current == null || current.profileCreation != e.profileCreation) {
age.put("profileCreation", e.profileCreation);
changes++;
}
if (current != null && changes == 0) {
return null;
}
age.put("_v", 1);
return age;
}
private static JSONObject getSysInfo(Environment e, Environment current) throws JSONException {
JSONObject sysinfo = new JSONObject();
int changes = 0;
if (current == null || current.cpuCount != e.cpuCount) {
sysinfo.put("cpuCount", e.cpuCount);
changes++;
}
if (current == null || current.memoryMB != e.memoryMB) {
sysinfo.put("memoryMB", e.memoryMB);
changes++;
}
if (current == null || !current.architecture.equals(e.architecture)) {
sysinfo.put("architecture", e.architecture);
changes++;
}
if (current == null || !current.sysName.equals(e.sysName)) {
sysinfo.put("name", e.sysName);
changes++;
}
if (current == null || !current.sysVersion.equals(e.sysVersion)) {
sysinfo.put("version", e.sysVersion);
changes++;
}
if (current != null && changes == 0) {
return null;
}
sysinfo.put("_v", 1);
return sysinfo;
}
private static JSONObject getGeckoInfo(Environment e, Environment current) throws JSONException {
JSONObject gecko = new JSONObject();
int changes = 0;
if (current == null || !current.vendor.equals(e.vendor)) {
gecko.put("vendor", e.vendor);
changes++;
}
if (current == null || !current.appName.equals(e.appName)) {
gecko.put("name", e.appName);
changes++;
}
if (current == null || !current.appID.equals(e.appID)) {
gecko.put("id", e.appID);
changes++;
}
if (current == null || !current.appVersion.equals(e.appVersion)) {
gecko.put("version", e.appVersion);
changes++;
}
if (current == null || !current.appBuildID.equals(e.appBuildID)) {
gecko.put("appBuildID", e.appBuildID);
changes++;
}
if (current == null || !current.platformVersion.equals(e.platformVersion)) {
gecko.put("platformVersion", e.platformVersion);
changes++;
}
if (current == null || !current.platformBuildID.equals(e.platformBuildID)) {
gecko.put("platformBuildID", e.platformBuildID);
changes++;
}
if (current == null || !current.os.equals(e.os)) {
gecko.put("os", e.os);
changes++;
}
if (current == null || !current.xpcomabi.equals(e.xpcomabi)) {
gecko.put("xpcomabi", e.xpcomabi);
changes++;
}
if (current == null || !current.updateChannel.equals(e.updateChannel)) {
gecko.put("updateChannel", e.updateChannel);
changes++;
}
if (current != null && changes == 0) {
return null;
}
gecko.put("_v", 1);
return gecko;
}
private static JSONObject getAppInfo(Environment e, Environment current) throws JSONException {
JSONObject appinfo = new JSONObject();
int changes = 0;
if (current == null || current.isBlocklistEnabled != e.isBlocklistEnabled) {
appinfo.put("isBlocklistEnabled", e.isBlocklistEnabled);
changes++;
}
if (current == null || current.isTelemetryEnabled != e.isTelemetryEnabled) {
appinfo.put("isTelemetryEnabled", e.isTelemetryEnabled);
changes++;
}
if (current != null && changes == 0) {
return null;
}
appinfo.put("_v", 2);
return appinfo;
}
private static JSONObject getAddonCounts(Environment e, Environment current) throws JSONException {
JSONObject counts = new JSONObject();
int changes = 0;
if (current == null || current.extensionCount != e.extensionCount) {
counts.put("extension", e.extensionCount);
changes++;
}
if (current == null || current.pluginCount != e.pluginCount) {
counts.put("plugin", e.pluginCount);
changes++;
}
if (current == null || current.themeCount != e.themeCount) {
counts.put("theme", e.themeCount);
changes++;
}
if (current != null && changes == 0) {
return null;
}
counts.put("_v", 1);
return counts;
}
/**
* Compute the *tree* difference set between the two objects. If the two
* objects are identical, returns <code>null</code>. If <code>from</code> is
* <code>null</code>, returns <code>to</code>. If <code>to</code> is
* <code>null</code>, behaves as if <code>to</code> were an empty object.
*
* (Note that this method does not check for {@link JSONObject#NULL}, because
* by definition it can't be provided as input to this method.)
*
* This behavior is intended to simplify life for callers: a missing object
* can be viewed as (and behaves as) an empty map, to a useful extent, rather
* than throwing an exception.
*
* @param from
* a JSONObject.
* @param to
* a JSONObject.
* @param includeNull
* if true, keys present in <code>from</code> but not in
* <code>to</code> are included as {@link JSONObject#NULL} in the
* output.
*
* @return a JSONObject, or null if the two objects are identical.
* @throws JSONException
* should not occur, but...
*/
public static JSONObject diff(JSONObject from,
JSONObject to,
boolean includeNull) throws JSONException {
if (from == null) {
return to;
}
if (to == null) {
return diff(from, new JSONObject(), includeNull);
}
JSONObject out = new JSONObject();
HashSet<String> toKeys = includeNull ? new HashSet<String>(to.length())
: null;
@SuppressWarnings("unchecked")
Iterator<String> it = to.keys();
while (it.hasNext()) {
String key = it.next();
// Track these as we go if we'll need them later.
if (includeNull) {
toKeys.add(key);
}
Object value = to.get(key);
if (!from.has(key)) {
// It must be new.
out.put(key, value);
continue;
}
// Not new? Then see if it changed.
Object old = from.get(key);
// Two JSONObjects should be diffed.
if (old instanceof JSONObject && value instanceof JSONObject) {
JSONObject innerDiff = diff(((JSONObject) old), ((JSONObject) value),
includeNull);
// No change? No output.
if (innerDiff == null) {
continue;
}
// Otherwise include the diff.
out.put(key, innerDiff);
continue;
}
// A regular value, or a type change. Only skip if they're the same.
if (value.equals(old)) {
continue;
}
out.put(key, value);
}
// Now -- if requested -- include any removed keys.
if (includeNull) {
Set<String> fromKeys = HealthReportUtils.keySet(from);
fromKeys.removeAll(toKeys);
for (String notPresent : fromKeys) {
out.put(notPresent, JSONObject.NULL);
}
}
if (out.length() == 0) {
return null;
}
return out;
}
private static JSONObject getActiveAddons(Environment e, Environment current) throws JSONException {
// Just return the current add-on set, with a version annotation.
// To do so requires copying.
if (current == null) {
JSONObject out = e.getNonIgnoredAddons();
if (out == null) {
Logger.warn(LOG_TAG, "Null add-ons to return in FHR document. Returning {}.");
out = new JSONObject(); // So that we always return something.
}
out.put("_v", 1);
return out;
}
// Otherwise, return the diff.
JSONObject diff = diff(current.getNonIgnoredAddons(), e.getNonIgnoredAddons(), true);
if (diff == null) {
return null;
}
if (diff == e.addons) {
// Again, needs to copy.
return getActiveAddons(e, null);
}
diff.put("_v", 1);
return diff;
}
}
| false | true |
protected JSONObject getDaysJSON(Environment currentEnvironment, SparseArray<Environment> envs, SparseArray<Field> fields, long since) throws JSONException {
if (Logger.shouldLogVerbose(LOG_TAG)) {
for (int i = 0; i < envs.size(); ++i) {
Logger.trace(LOG_TAG, "Days environment " + envs.keyAt(i) + ": " + envs.get(envs.keyAt(i)).getHash());
}
}
JSONObject days = new JSONObject();
Cursor cursor = storage.getRawEventsSince(since);
try {
if (!cursor.moveToFirst()) {
return days;
}
// A classic walking partition.
// Columns are "date", "env", "field", "value".
// Note that we care about the type (integer, string) and kind
// (last/counter, discrete) of each field.
// Each field will be accessed once for each date/env pair, so
// Field memoizes these facts.
// We also care about which measurement contains each field.
int lastDate = -1;
int lastEnv = -1;
JSONObject dateObject = null;
JSONObject envObject = null;
while (!cursor.isAfterLast()) {
int cEnv = cursor.getInt(1);
if (cEnv == -1 ||
(cEnv != lastEnv &&
envs.indexOfKey(cEnv) < 0)) {
Logger.warn(LOG_TAG, "Invalid environment " + cEnv + " in cursor. Skipping.");
cursor.moveToNext();
continue;
}
int cDate = cursor.getInt(0);
int cField = cursor.getInt(2);
Logger.trace(LOG_TAG, "Event row: " + cDate + ", " + cEnv + ", " + cField);
boolean dateChanged = cDate != lastDate;
boolean envChanged = cEnv != lastEnv;
if (dateChanged) {
if (dateObject != null) {
days.put(DateUtils.getDateStringForDay(lastDate), dateObject);
}
dateObject = new JSONObject();
lastDate = cDate;
}
if (dateChanged || envChanged) {
envObject = new JSONObject();
// This is safe because we checked above that cEnv is valid.
dateObject.put(envs.get(cEnv).getHash(), envObject);
lastEnv = cEnv;
}
final Field field = fields.get(cField);
JSONObject measurement = envObject.optJSONObject(field.measurementName);
if (measurement == null) {
// We will never have more than one measurement version within a
// single environment -- to do so involves changing the build ID. And
// even if we did, we have no way to represent it. So just build the
// output object once.
measurement = new JSONObject();
measurement.put("_v", field.measurementVersion);
envObject.put(field.measurementName, measurement);
}
// How we record depends on the type of the field, so we
// break this out into a separate method for clarity.
recordMeasurementFromCursor(field, measurement, cursor);
cursor.moveToNext();
continue;
}
days.put(DateUtils.getDateStringForDay(lastDate), dateObject);
} finally {
cursor.close();
}
return days;
}
|
protected JSONObject getDaysJSON(Environment currentEnvironment, SparseArray<Environment> envs, SparseArray<Field> fields, long since) throws JSONException {
if (Logger.shouldLogVerbose(LOG_TAG)) {
for (int i = 0; i < envs.size(); ++i) {
Logger.trace(LOG_TAG, "Days environment " + envs.keyAt(i) + ": " + envs.get(envs.keyAt(i)).getHash());
}
}
JSONObject days = new JSONObject();
Cursor cursor = storage.getRawEventsSince(since);
try {
if (!cursor.moveToFirst()) {
return days;
}
// A classic walking partition.
// Columns are "date", "env", "field", "value".
// Note that we care about the type (integer, string) and kind
// (last/counter, discrete) of each field.
// Each field will be accessed once for each date/env pair, so
// Field memoizes these facts.
// We also care about which measurement contains each field.
int lastDate = -1;
int lastEnv = -1;
JSONObject dateObject = null;
JSONObject envObject = null;
SparseArray<String> dayMemo = new SparseArray<String>(90); // A decent default size.
while (!cursor.isAfterLast()) {
int cEnv = cursor.getInt(1);
if (cEnv == -1 ||
(cEnv != lastEnv &&
envs.indexOfKey(cEnv) < 0)) {
Logger.warn(LOG_TAG, "Invalid environment " + cEnv + " in cursor. Skipping.");
cursor.moveToNext();
continue;
}
int cDate = cursor.getInt(0);
int cField = cursor.getInt(2);
Logger.trace(LOG_TAG, "Event row: " + cDate + ", " + cEnv + ", " + cField);
boolean dateChanged = cDate != lastDate;
boolean envChanged = cEnv != lastEnv;
if (dateChanged) {
if (dateObject != null) {
days.put(DateUtils.getDateStringForDay(lastDate, dayMemo), dateObject);
}
dateObject = new JSONObject();
lastDate = cDate;
}
if (dateChanged || envChanged) {
envObject = new JSONObject();
// This is safe because we checked above that cEnv is valid.
dateObject.put(envs.get(cEnv).getHash(), envObject);
lastEnv = cEnv;
}
final Field field = fields.get(cField);
JSONObject measurement = envObject.optJSONObject(field.measurementName);
if (measurement == null) {
// We will never have more than one measurement version within a
// single environment -- to do so involves changing the build ID. And
// even if we did, we have no way to represent it. So just build the
// output object once.
measurement = new JSONObject();
measurement.put("_v", field.measurementVersion);
envObject.put(field.measurementName, measurement);
}
// How we record depends on the type of the field, so we
// break this out into a separate method for clarity.
recordMeasurementFromCursor(field, measurement, cursor);
cursor.moveToNext();
continue;
}
days.put(DateUtils.getDateStringForDay(lastDate, dayMemo), dateObject);
} finally {
cursor.close();
}
return days;
}
|
diff --git a/plugins-dev/echosounder/pt/up/fe/dceg/neptus/plugins/sidescan/ImcSidescanParser.java b/plugins-dev/echosounder/pt/up/fe/dceg/neptus/plugins/sidescan/ImcSidescanParser.java
index 421fa54c6..de37723ea 100644
--- a/plugins-dev/echosounder/pt/up/fe/dceg/neptus/plugins/sidescan/ImcSidescanParser.java
+++ b/plugins-dev/echosounder/pt/up/fe/dceg/neptus/plugins/sidescan/ImcSidescanParser.java
@@ -1,339 +1,339 @@
/*
* Copyright (c) 2004-2013 Universidade do Porto - Faculdade de Engenharia
* Laboratório de Sistemas e Tecnologia Subaquática (LSTS)
* All rights reserved.
* Rua Dr. Roberto Frias s/n, sala I203, 4200-465 Porto, Portugal
*
* This file is part of Neptus, Command and Control Framework.
*
* Commercial Licence Usage
* Licencees holding valid commercial Neptus licences may use this file
* in accordance with the commercial licence agreement provided with the
* Software or, alternatively, in accordance with the terms contained in a
* written agreement between you and Universidade do Porto. For licensing
* terms, conditions, and further information contact [email protected].
*
* European Union Public Licence - EUPL v.1.1 Usage
* Alternatively, this file may be used under the terms of the EUPL,
* Version 1.1 only (the "Licence"), appearing in the file LICENCE.md
* included in the packaging of this file. You may not use this work
* except in compliance with the Licence. Unless required by applicable
* law or agreed to in writing, software distributed under the Licence is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the Licence for the specific
* language governing permissions and limitations at
* https://www.lsts.pt/neptus/licence.
*
* For more information please see <http://lsts.fe.up.pt/neptus>.
*
* Author: José Correia
* Feb 5, 2013
*/
package pt.up.fe.dceg.neptus.plugins.sidescan;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import pt.up.fe.dceg.neptus.colormap.ColorMap;
import pt.up.fe.dceg.neptus.colormap.ColorMapFactory;
import pt.up.fe.dceg.neptus.imc.EstimatedState;
import pt.up.fe.dceg.neptus.imc.IMCMessage;
import pt.up.fe.dceg.neptus.imc.SonarData;
import pt.up.fe.dceg.neptus.mp.SystemPositionAndAttitude;
import pt.up.fe.dceg.neptus.mra.importers.IMraLog;
import pt.up.fe.dceg.neptus.mra.importers.IMraLogGroup;
import pt.up.fe.dceg.neptus.util.ImageUtils;
/**
* @author jqcorreia
*
*/
public class ImcSidescanParser implements SidescanParser {
IMraLog pingParser;
IMraLog stateParser;
ColorMap colormap = ColorMapFactory.createBronzeColormap();
long firstTimestamp = -1;
long lastTimestamp = -1;
public ImcSidescanParser(IMraLogGroup source) {
pingParser = source.getLog("SonarData");
stateParser = source.getLog("EstimatedState");
}
@Override
public long firstPingTimestamp() {
if(firstTimestamp != -1 ) return firstTimestamp;
firstTimestamp = pingParser.firstLogEntry().getTimestampMillis();
return firstTimestamp;
};
@Override
public long lastPingTimestamp() {
if(lastTimestamp != -1 ) return lastTimestamp;
lastTimestamp = pingParser.getLastEntry().getTimestampMillis();
return lastTimestamp;
}
public ArrayList<Integer> getSubsystemList() {
// For now just return a list with 1 item. In the future IMC will accomodate various SonarData subsystems
ArrayList<Integer> l = new ArrayList<Integer>();
l.add(1);
return l;
};
@Override
public SidescanLine nextSidescanLine(double freq, int lineWidth) {
IMCMessage currentPing = pingParser.getCurrentEntry();
IMCMessage nextPing = getNextMessageWithFrequency(pingParser, freq);
if (nextPing == null)
return null;
SidescanLine line = generateLine(currentPing, nextPing, freq, lineWidth, ColorMapFactory.createCopperColorMap());
return line;
}
@Override
public SidescanLine getSidescanLineAt(long timestamp, double freq, int lineWidth) {
IMCMessage ping = pingParser.getEntryAtOrAfter(timestamp);
if (ping == null)
return null;
if(ping.getDouble("frequency") != freq || ping.getInteger("type") != SonarData.TYPE.SIDESCAN.value()) {
ping = getNextMessageWithFrequency(pingParser, freq);
}
IMCMessage nextPing = getNextMessageWithFrequency(pingParser, freq); // WARNING: This advances the
return generateLine(ping, nextPing, freq, lineWidth, colormap);
}
private SidescanLine generateLine(IMCMessage ping, IMCMessage nextPing, double frequency, int lineWidth, ColorMap colormap) {
// Preparation
BufferedImage line = null;
Image scaledLine = null;
int iData[] = new int[ping.getRawData("data").length];
IMCMessage state = stateParser.getEntryAtOrAfter(ping.getTimestampMillis());
SystemPositionAndAttitude pose;
// try {
// pose = new SystemPositionAndAttitude(new EstimatedState(state));
// }
// catch (Exception e) {
// pose = null; // FIXME
// e.printStackTrace();
// }
pose = new SystemPositionAndAttitude();
pose.setAltitude(state.getDouble("alt"));
pose.getPosition().setLatitudeRads(state.getDouble("lat"));
pose.getPosition().setLongitudeRads(state.getDouble("lon"));
pose.setYaw(state.getDouble("psi"));
pose.getPosition().setOffsetNorth(state.getDouble("x"));
pose.getPosition().setOffsetEast(state.getDouble("y"));
// Null guards
if (ping == null || state == null)
return null;
int range = ping.getInteger("range");
if (range == 0)
range = ping.getInteger("max_range");
int totalsize = 0;
float secondsUntilNextPing = 0;
double speed = 0;
float horizontalScale = (float) ping.getRawData("data").length / (range * 2f);
float verticalScale = horizontalScale;
if (nextPing == null)
return null;
secondsUntilNextPing = (nextPing.getTimestampMillis() - ping.getTimestampMillis()) / 1000f;
speed = state.getDouble("u");
// Finally the 'height' of the ping in pixels
int size = (int) (secondsUntilNextPing * speed * verticalScale);
if (size <= 0 || secondsUntilNextPing > 0.5) {
size = 1;
}
// Image building. Calculate and draw a line, scale it and save it
byte[] data = ping.getRawData("data");
int[] colors = new int[data.length];
line = new BufferedImage(data.length, size, BufferedImage.TYPE_INT_RGB);
// double bottomDistance = state.getDouble("alt");
// double slantIncrement = ((double) range) / (data.length / 2);
for (int c = 0; c < data.length; c++) {
iData[c] = data[c] & 0xFF;
colors[c] = colormap.getColor(iData[c] / 255.0).getRGB();
}
for (int c = 0; c < size; c++) {
line.setRGB(0, c, colors.length, 1, colors, 0, colors.length);
}
double lineScale = (double) lineWidth / (double) data.length;
double lineSize = Math.ceil(Math.max(1, lineScale * size));
scaledLine = ImageUtils.getScaledImage(line, lineWidth, (int) lineSize, true);
totalsize += (int) (lineSize);
SidescanLine l = new SidescanLine(ping.getTimestampMillis(), scaledLine.getWidth(null), (int) lineSize, totalsize, range, pose, scaledLine);
return l;
}
public ArrayList<SidescanLine> getLinesBetween(long timestamp1, long timestamp2, int lineWidth, int subsystem) {
// Preparation
ArrayList<SidescanLine> list = new ArrayList<SidescanLine>();
int[] iData = null;
BufferedImage line = null;
Image scaledLine = null;
pingParser.firstLogEntry();
IMCMessage ping = pingParser.getEntryAtOrAfter(timestamp1);
if (ping == null)
return list;
//FIXME
// if (ping.getDouble("frequency") != freq || ping.getInteger("type") != SonarData.TYPE.SIDESCAN.value()) {
// ping = getNextMessageWithFrequency(pingParser, freq);
// }
if (ping.getInteger("type") != SonarData.TYPE.SIDESCAN.value()) {
ping = getNextMessageWithFrequency(pingParser, 0); //FIXME
}
IMCMessage state = stateParser.getEntryAtOrAfter(ping.getTimestampMillis());
// Null guards
if (ping == null || state == null)
return list;
int range = ping.getInteger("range");
if (range == 0)
range = ping.getInteger("max_range");
int totalsize = 0;
float secondsUntilNextPing = 0;
double speed = 0;
if (iData == null) {
iData = new int[ping.getRawData("data").length];
}
while (ping.getTimestampMillis() <= timestamp2) {
// Null guards
if (ping == null || state == null)
break;
SystemPositionAndAttitude pose;
try {
- pose = new SystemPositionAndAttitude(new EstimatedState(state));
+ pose = new SystemPositionAndAttitude(EstimatedState.clone(state));
}
catch (Exception e) {
e.printStackTrace();
pose = null;
}
float horizontalScale = (float) ping.getRawData("data").length / (range * 2f);
float verticalScale = horizontalScale;
// Time elapsed and speed calculation
IMCMessage nextPing = getNextMessageWithFrequency(pingParser, 0); // WARNING: This advances the
// parser
if (nextPing == null)
break;
secondsUntilNextPing = (nextPing.getTimestampMillis() - ping.getTimestampMillis()) / 1000f;
speed = state.getDouble("u");
// Finally the 'height' of the ping in pixels
int size = (int) (secondsUntilNextPing * speed * verticalScale);
if (size <= 0) {
size = 1;
}
else if (secondsUntilNextPing > 0.5) {
// TODO This is way too much time between shots. Maybe mark it on the plot?
// For now put 1 as ysize
size = 1;
}
// Image building. Calculate and draw a line, scale it and save it
byte[] data = ping.getRawData("data");
int[] colors = new int[data.length];
line = new BufferedImage(data.length, size, BufferedImage.TYPE_INT_RGB);
int pos;
for (int c = 0; c < data.length; c++) {
iData[c] = data[c] & 0xFF;
pos = c;
colors[pos] = colormap.getColor(iData[c] / 255.0).getRGB();
}
for (int c = 0; c < size; c++) {
line.setRGB(0, c, colors.length, 1, colors, 0, colors.length);
}
double lineScale = (double) lineWidth / (double) data.length;
double lineSize = Math.ceil(Math.max(1, lineScale * size));
scaledLine = ImageUtils.getScaledImage(line, lineWidth, (int) lineSize, true);
totalsize += (int) (lineSize);
list.add(new SidescanLine(ping.getTimestampMillis(), scaledLine.getWidth(null), (int) lineSize, totalsize, range, pose, scaledLine));
ping = pingParser.getCurrentEntry(); // This parser was already advanced so only get current entry
state = stateParser.getEntryAtOrAfter(ping.getTimestampMillis());
}
pingParser.firstLogEntry();
stateParser.firstLogEntry();
return list;
}
public long getCurrentTime() {
return pingParser.currentTimeMillis();
}
public IMCMessage getNextMessageWithFrequency(IMraLog parser, double freq) {
IMCMessage msg;
while((msg = parser.nextLogEntry()) != null) {
if(msg.getInteger("type") == SonarData.TYPE.SIDESCAN.value()) {
return msg;
}
}
return null;
}
// public static void main(String[] args) throws Exception {
// JFrame frame = new JFrame();
// final BufferedImage image = new BufferedImage(1800, 600, BufferedImage.TYPE_INT_RGB);
// ImcSidescanParser parser = new ImcSidescanParser(new LsfLogSource(new File("/home/jqcorreia/lsts/logs/lauv-noptilus-1/20130111/100509_rows_2m_alt/Data.lsf"), null));
//
// long init = parser.pingParser.firstLogEntry().getTimestampMillis();
// int y = 0;
// SidescanLine line = parser.getSidescanLineAt(init + 1000000, 770000, image.getWidth());
// image.getGraphics().drawImage(line.image, 0, 0, null);
// y += line.ysize;
//
// for(int i = 0; i < 1000; i++) {
// line = parser.nextSidescanLine(770000, image.getWidth());
// image.getGraphics().drawImage(line.image, 0, y, null);
// y += line.ysize;
// }
// frame.add(new JLabel() {
// @Override
// protected void paintComponent(Graphics g) {
// super.paintComponent(g);
// g.drawImage(image, 0, 0, null);
// }
// });
//
// frame.setSize(1800,600);
// frame.setVisible(true);
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// }
}
| true | true |
public ArrayList<SidescanLine> getLinesBetween(long timestamp1, long timestamp2, int lineWidth, int subsystem) {
// Preparation
ArrayList<SidescanLine> list = new ArrayList<SidescanLine>();
int[] iData = null;
BufferedImage line = null;
Image scaledLine = null;
pingParser.firstLogEntry();
IMCMessage ping = pingParser.getEntryAtOrAfter(timestamp1);
if (ping == null)
return list;
//FIXME
// if (ping.getDouble("frequency") != freq || ping.getInteger("type") != SonarData.TYPE.SIDESCAN.value()) {
// ping = getNextMessageWithFrequency(pingParser, freq);
// }
if (ping.getInteger("type") != SonarData.TYPE.SIDESCAN.value()) {
ping = getNextMessageWithFrequency(pingParser, 0); //FIXME
}
IMCMessage state = stateParser.getEntryAtOrAfter(ping.getTimestampMillis());
// Null guards
if (ping == null || state == null)
return list;
int range = ping.getInteger("range");
if (range == 0)
range = ping.getInteger("max_range");
int totalsize = 0;
float secondsUntilNextPing = 0;
double speed = 0;
if (iData == null) {
iData = new int[ping.getRawData("data").length];
}
while (ping.getTimestampMillis() <= timestamp2) {
// Null guards
if (ping == null || state == null)
break;
SystemPositionAndAttitude pose;
try {
pose = new SystemPositionAndAttitude(new EstimatedState(state));
}
catch (Exception e) {
e.printStackTrace();
pose = null;
}
float horizontalScale = (float) ping.getRawData("data").length / (range * 2f);
float verticalScale = horizontalScale;
// Time elapsed and speed calculation
IMCMessage nextPing = getNextMessageWithFrequency(pingParser, 0); // WARNING: This advances the
// parser
if (nextPing == null)
break;
secondsUntilNextPing = (nextPing.getTimestampMillis() - ping.getTimestampMillis()) / 1000f;
speed = state.getDouble("u");
// Finally the 'height' of the ping in pixels
int size = (int) (secondsUntilNextPing * speed * verticalScale);
if (size <= 0) {
size = 1;
}
else if (secondsUntilNextPing > 0.5) {
// TODO This is way too much time between shots. Maybe mark it on the plot?
// For now put 1 as ysize
size = 1;
}
// Image building. Calculate and draw a line, scale it and save it
byte[] data = ping.getRawData("data");
int[] colors = new int[data.length];
line = new BufferedImage(data.length, size, BufferedImage.TYPE_INT_RGB);
int pos;
for (int c = 0; c < data.length; c++) {
iData[c] = data[c] & 0xFF;
pos = c;
colors[pos] = colormap.getColor(iData[c] / 255.0).getRGB();
}
for (int c = 0; c < size; c++) {
line.setRGB(0, c, colors.length, 1, colors, 0, colors.length);
}
double lineScale = (double) lineWidth / (double) data.length;
double lineSize = Math.ceil(Math.max(1, lineScale * size));
scaledLine = ImageUtils.getScaledImage(line, lineWidth, (int) lineSize, true);
totalsize += (int) (lineSize);
list.add(new SidescanLine(ping.getTimestampMillis(), scaledLine.getWidth(null), (int) lineSize, totalsize, range, pose, scaledLine));
ping = pingParser.getCurrentEntry(); // This parser was already advanced so only get current entry
state = stateParser.getEntryAtOrAfter(ping.getTimestampMillis());
}
pingParser.firstLogEntry();
stateParser.firstLogEntry();
return list;
}
|
public ArrayList<SidescanLine> getLinesBetween(long timestamp1, long timestamp2, int lineWidth, int subsystem) {
// Preparation
ArrayList<SidescanLine> list = new ArrayList<SidescanLine>();
int[] iData = null;
BufferedImage line = null;
Image scaledLine = null;
pingParser.firstLogEntry();
IMCMessage ping = pingParser.getEntryAtOrAfter(timestamp1);
if (ping == null)
return list;
//FIXME
// if (ping.getDouble("frequency") != freq || ping.getInteger("type") != SonarData.TYPE.SIDESCAN.value()) {
// ping = getNextMessageWithFrequency(pingParser, freq);
// }
if (ping.getInteger("type") != SonarData.TYPE.SIDESCAN.value()) {
ping = getNextMessageWithFrequency(pingParser, 0); //FIXME
}
IMCMessage state = stateParser.getEntryAtOrAfter(ping.getTimestampMillis());
// Null guards
if (ping == null || state == null)
return list;
int range = ping.getInteger("range");
if (range == 0)
range = ping.getInteger("max_range");
int totalsize = 0;
float secondsUntilNextPing = 0;
double speed = 0;
if (iData == null) {
iData = new int[ping.getRawData("data").length];
}
while (ping.getTimestampMillis() <= timestamp2) {
// Null guards
if (ping == null || state == null)
break;
SystemPositionAndAttitude pose;
try {
pose = new SystemPositionAndAttitude(EstimatedState.clone(state));
}
catch (Exception e) {
e.printStackTrace();
pose = null;
}
float horizontalScale = (float) ping.getRawData("data").length / (range * 2f);
float verticalScale = horizontalScale;
// Time elapsed and speed calculation
IMCMessage nextPing = getNextMessageWithFrequency(pingParser, 0); // WARNING: This advances the
// parser
if (nextPing == null)
break;
secondsUntilNextPing = (nextPing.getTimestampMillis() - ping.getTimestampMillis()) / 1000f;
speed = state.getDouble("u");
// Finally the 'height' of the ping in pixels
int size = (int) (secondsUntilNextPing * speed * verticalScale);
if (size <= 0) {
size = 1;
}
else if (secondsUntilNextPing > 0.5) {
// TODO This is way too much time between shots. Maybe mark it on the plot?
// For now put 1 as ysize
size = 1;
}
// Image building. Calculate and draw a line, scale it and save it
byte[] data = ping.getRawData("data");
int[] colors = new int[data.length];
line = new BufferedImage(data.length, size, BufferedImage.TYPE_INT_RGB);
int pos;
for (int c = 0; c < data.length; c++) {
iData[c] = data[c] & 0xFF;
pos = c;
colors[pos] = colormap.getColor(iData[c] / 255.0).getRGB();
}
for (int c = 0; c < size; c++) {
line.setRGB(0, c, colors.length, 1, colors, 0, colors.length);
}
double lineScale = (double) lineWidth / (double) data.length;
double lineSize = Math.ceil(Math.max(1, lineScale * size));
scaledLine = ImageUtils.getScaledImage(line, lineWidth, (int) lineSize, true);
totalsize += (int) (lineSize);
list.add(new SidescanLine(ping.getTimestampMillis(), scaledLine.getWidth(null), (int) lineSize, totalsize, range, pose, scaledLine));
ping = pingParser.getCurrentEntry(); // This parser was already advanced so only get current entry
state = stateParser.getEntryAtOrAfter(ping.getTimestampMillis());
}
pingParser.firstLogEntry();
stateParser.firstLogEntry();
return list;
}
|
diff --git a/magma-js/src/main/java/org/obiba/magma/js/methods/GlobalMethods.java b/magma-js/src/main/java/org/obiba/magma/js/methods/GlobalMethods.java
index 73dd3a6a..e0080880 100644
--- a/magma-js/src/main/java/org/obiba/magma/js/methods/GlobalMethods.java
+++ b/magma-js/src/main/java/org/obiba/magma/js/methods/GlobalMethods.java
@@ -1,455 +1,455 @@
package org.obiba.magma.js.methods;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;
import org.obiba.magma.NoSuchValueSetException;
import org.obiba.magma.Value;
import org.obiba.magma.ValueSequence;
import org.obiba.magma.ValueSet;
import org.obiba.magma.ValueTable;
import org.obiba.magma.ValueType;
import org.obiba.magma.Variable;
import org.obiba.magma.VariableEntity;
import org.obiba.magma.VariableValueSource;
import org.obiba.magma.VectorSource;
import org.obiba.magma.js.JavascriptValueSource.VectorCache;
import org.obiba.magma.js.MagmaContext;
import org.obiba.magma.js.MagmaJsEvaluationRuntimeException;
import org.obiba.magma.js.ScriptableValue;
import org.obiba.magma.js.ScriptableVariable;
import org.obiba.magma.support.MagmaEngineVariableResolver;
import org.obiba.magma.support.VariableEntityBean;
import org.obiba.magma.type.DateTimeType;
import org.obiba.magma.type.TextType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
@SuppressWarnings({ "UnusedDeclaration", "IfMayBeConditional", "ChainOfInstanceofChecks", "OverlyCoupledClass" })
public final class GlobalMethods extends AbstractGlobalMethodProvider {
private static final Logger log = LoggerFactory.getLogger(GlobalMethods.class);
/**
* Set of methods to be exposed as top-level methods (ones that can be invoked anywhere)
*/
private static final Set<String> GLOBAL_METHODS = ImmutableSet
.of("$", "$join", "now", "log", "$var", "$id", "$group", "$groups", "newValue");
@Override
protected Set<String> getExposedMethods() {
return GLOBAL_METHODS;
}
/**
* Creates an instance of {@code ScriptableValue} containing the current date and time.
*
* @return an instance of {@code ScriptableValue} containing the current date and time.
*/
public static ScriptableValue now(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
return new ScriptableValue(thisObj, DateTimeType.get().valueOf(new Date()));
}
/**
* Creates a new value.
* <p/>
* <pre>
* newValue('Foo')
* newValue(123)
* newValue('123','integer')
* </pre>
*
* @return an instance of {@code ScriptableValue}
*/
public static ScriptableValue newValue(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
Object value = args[0];
Value v;
v = args.length > 1 //
? ValueType.Factory.forName((String) args[1]).valueOf(value) //
: ValueType.Factory.newValue((Serializable) value);
return new ScriptableValue(thisObj, v);
}
/**
* Allows invoking {@code VariableValueSource#getValue(ValueSet)} and returns a {@code ScriptableValue}. Accessed as $
* in javascript.
* <p/>
* <pre>
* $('Participant.firstName')
* $('other-collection:SMOKER_STATUS')
* </pre>
*
* @return an instance of {@code ScriptableValue}
*/
@SuppressWarnings("UnusedDeclaration")
public static Scriptable $(Context ctx, Scriptable thisObj, Object[] args, Function funObj) {
if(args.length != 1) {
throw new IllegalArgumentException("$() expects exactly one argument: a variable name.");
}
MagmaContext context = MagmaContext.asMagmaContext(ctx);
String name = (String) args[0];
return valueFromContext(context, thisObj, name);
}
/**
* Allows joining a variable value to another variable value that provides a entity identifier. Accessed as $join in
* javascript.
* <p/>
* <pre>
* $join('medications.Drugs:BRAND_NAME','MEDICATION_1')
* </pre>
*
* @return an instance of {@code ScriptableValue}
*/
public static Scriptable $join(Context ctx, Scriptable thisObj, Object[] args, Function funObj) {
if(args.length != 2) {
throw new IllegalArgumentException(
"$join() expects exactly two arguments: the reference the variable to be joined and the name of the variable holding entity identifiers.");
}
MagmaContext context = MagmaContext.asMagmaContext(ctx);
String joinedName = (String) args[0];
String name = (String) args[1];
ValueTable valueTable = context.peek(ValueTable.class);
Value identifier = valueFromContext(context, thisObj, name).getValue();
// Find the joined named source
MagmaEngineVariableResolver reference = MagmaEngineVariableResolver.valueOf(joinedName);
ValueTable joinedTable = reference.resolveTable(valueTable);
VariableValueSource joinedSource = reference.resolveSource(valueTable);
// Default value is null if joined table has no valueSet (equivalent to a LEFT JOIN)
Value value = joinedSource.getVariable().isRepeatable()
? joinedSource.getValueType().nullSequence()
: joinedSource.getValueType().nullValue();
if(!identifier.isNull()) {
@SuppressWarnings("ConstantConditions")
VariableEntity entity = new VariableEntityBean(joinedTable.getEntityType(), identifier.toString());
if(joinedTable.hasValueSet(entity)) {
value = joinedSource.getValue(joinedTable.getValueSet(entity));
}
}
return new ScriptableValue(thisObj, value, joinedSource.getVariable().getUnit());
}
public static Scriptable $var(Context ctx, Scriptable thisObj, Object[] args, Function funObj) {
if(args.length != 1) {
throw new IllegalArgumentException("$var() expects exactly one argument: a variable name.");
}
MagmaContext context = MagmaContext.asMagmaContext(ctx);
String name = (String) args[0];
return new ScriptableVariable(thisObj, variableFromContext(context, name));
}
/**
* Allows accessing the current entity identifier.
* <p/>
* <pre>
* $id()
* </pre>
*
* @return an instance of {@code ScriptableValue}
*/
public static Scriptable $id(Context ctx, Scriptable thisObj, Object[] args, Function funObj) {
MagmaContext context = MagmaContext.asMagmaContext(ctx);
VariableEntity entity = context.peek(VariableEntity.class);
return new ScriptableValue(thisObj, TextType.get().valueOf(entity.getIdentifier()));
}
/**
* Provides 'info' level logging of messages and variables. Returns a {@code ScriptableValue}. Accessed as 'log' in
* javascript.
* <p/>
* <pre>
* log('My message')
* log(onyx('org.obiba.onyx.lastExportDate'))
* log('The last export date: {}', onyx('org.obiba.onyx.lastExportDate'))
* log('The last export date: {} Days before purge: {}', onyx('org.obiba.onyx.lastExportDate'), onyx('org.obiba.onyx.participant.purge'))
* </pre>
*
* @return an instance of {@code ScriptableValue}
*/
public static Scriptable log(Context ctx, Scriptable thisObj, Object[] args, Function funObj) {
if(args.length < 1) {
throw new UnsupportedOperationException(
"log() expects either one or more arguments. e.g. log('message'), log('var 1 {}', $('var1')), log('var 1 {} var 2 {}', $('var1'), $('var2')).");
}
if(args.length == 1) {
if(args[0] instanceof Exception) {
log.warn("Exception during JS execution", (Throwable) args[0]);
} else {
log.info(args[0].toString());
}
} else {
log.info(args[0].toString(), Arrays.copyOfRange(args, 1, args.length));
}
return thisObj;
}
private static ScriptableValue valueFromContext(MagmaContext context, Scriptable thisObj, String name) {
ValueTable valueTable = context.peek(ValueTable.class);
MagmaEngineVariableResolver reference = MagmaEngineVariableResolver.valueOf(name);
// Find the named source
VariableValueSource source = reference.resolveSource(valueTable);
// Test whether this is a vector-oriented evaluation or a ValueSet-oriented evaluation
return context.has(VectorCache.class) //
? valuesForVector(context, thisObj, reference, source) //
: valueForValueSet(context, thisObj, reference, source);
}
private static ScriptableValue valuesForVector(MagmaContext context, Scriptable thisObj,
MagmaEngineVariableResolver reference, VariableValueSource source) {
VectorSource vectorSource = source.asVectorSource();
if(vectorSource == null) {
throw new IllegalArgumentException("source cannot provide vectors (" + source.getClass().getName() + ")");
}
// Load the vector
VectorCache cache = context.peek(VectorCache.class);
return new ScriptableValue(thisObj, cache.get(context, vectorSource), source.getVariable().getUnit());
}
private static ScriptableValue valueForValueSet(MagmaContext context, Scriptable thisObj,
MagmaEngineVariableResolver reference, VariableValueSource source) {
ValueSet valueSet = context.peek(ValueSet.class);
// Tests whether this valueSet is in the same table as the referenced ValueTable
if(reference.isJoin(valueSet)) {
// Resolve the joined valueSet
try {
valueSet = reference.join(valueSet);
} catch(NoSuchValueSetException e) {
// Entity does not have a ValueSet in joined collection
// Return a null value
return new ScriptableValue(thisObj, source.getValueType().nullValue(), source.getVariable().getUnit());
}
}
Value value = source.getValue(valueSet);
return new ScriptableValue(thisObj, value, source.getVariable().getUnit());
}
/**
* Get first occurrence group matching criteria and returns a map (variable name/{@code ScriptableValue}).
* <p/>
* <pre>
* $group('StageName','StageA')['StageDuration']
* $group('NumVar', function(value) {
* return value.ge(10);
* })['AnotherVar']
* </pre>
*
* @return a javascript object that maps variable names to {@code ScriptableValue}
*/
public static NativeObject $group(Context ctx, Scriptable thisObj, Object[] args, Function funObj)
throws MagmaJsEvaluationRuntimeException {
if(args.length != 2) {
throw new IllegalArgumentException(
"$group() expects exactly two arguments: a variable name and a matching criteria (i.e. a value or a function).");
}
List<NativeObject> valueMaps = getGroups(ctx, thisObj, args, funObj, true);
return valueMaps.isEmpty() ? new NativeObject() : valueMaps.get(0);
}
/**
* Get all occurrence group matching criteria and returns an array of maps (variable name/{@code ScriptableValue}).
* <p/>
* <pre>
* $groups('StageName','StageA')[0]['StageDuration']
* $groups('NumVar', function(value) {
* return value.ge(10);
* })[0]['AnotherVar']
* </pre>
*
* @return a javascript object that maps variable names to {@code ScriptableValue}
*/
public static NativeArray $groups(Context ctx, Scriptable thisObj, Object[] args, Function funObj)
throws MagmaJsEvaluationRuntimeException {
if(args.length != 2) {
throw new IllegalArgumentException(
"$groups() expects exactly two arguments: a variable name and a matching criteria (i.e. a value or a function).");
}
return new NativeArray(getGroups(ctx, thisObj, args, funObj, false).toArray());
}
@SuppressWarnings({ "OverlyLongMethod", "PMD.NcssMethodCount" })
private static List<NativeObject> getGroups(Context ctx, Scriptable thisObj, Object[] args, Function funObj,
boolean stopAtFirst) {
String name = (String) args[0];
Object criteria = args[1];
MagmaContext context = MagmaContext.asMagmaContext(ctx);
ScriptableValue sv = valueFromContext(context, thisObj, name);
Variable variable = variableFromContext(context, name);
ValueTable valueTable = valueTableFromContext(context);
List<NativeObject> valueMaps = new ArrayList<NativeObject>();
if(sv.getValue().isNull() || !sv.getValue().isSequence()) {
// just map itself
NativeObject valueMap = new NativeObject();
valueMaps.add(valueMap);
- valueMap.put(variable.getName(), null, sv);
+ valueMap.put(variable.getName(), valueMap, sv);
} else {
Predicate<Value> predicate = getPredicate(ctx, sv.getParentScope(), thisObj, variable, criteria);
Iterable<Variable> variables = getVariablesFromOccurrenceGroup(valueTable, variable);
ValueSequence valueSequence = sv.getValue().asSequence();
int index = -1;
//noinspection ConstantConditions
for(Value value : valueSequence.getValue()) {
index++;
if(predicate.apply(value)) {
NativeObject valueMap = new NativeObject();
valueMaps.add(valueMap);
// map itself
valueMap.put(variable.getName(), valueMap, new ScriptableValue(thisObj, value));
// get variables of the same occurrence group and map values
mapValues(context, thisObj, valueMap, variables, index);
if(stopAtFirst) {
break;
}
}
}
}
return valueMaps;
}
@Nullable
private static ValueTable valueTableFromContext(MagmaContext context) {
ValueTable valueTable = null;
if(context.has(ValueTable.class)) {
valueTable = context.peek(ValueTable.class);
}
return valueTable;
}
private static Variable variableFromContext(MagmaContext context, String name) {
MagmaEngineVariableResolver reference = MagmaEngineVariableResolver.valueOf(name);
VariableValueSource source = context.has(ValueTable.class)
? reference.resolveSource(context.peek(ValueTable.class))
: reference.resolveSource();
return source.getVariable();
}
private static Predicate<Value> getPredicate(Context ctx, Scriptable scope, Scriptable thisObj, Variable variable,
Object criteria) {
Predicate<Value> predicate;
if(criteria instanceof ScriptableValue) {
predicate = new ValuePredicate(((ScriptableValue) criteria).getValue());
} else if(criteria instanceof Function) {
predicate = new FunctionPredicate(ctx, scope, thisObj, (Function) criteria);
} else {
predicate = new ValuePredicate(variable.getValueType().valueOf(criteria));
}
return predicate;
}
private static Iterable<Variable> getVariablesFromOccurrenceGroup(@Nullable ValueTable valueTable,
@Nonnull final Variable variable) {
if(variable.getOccurrenceGroup() == null || valueTable == null) {
return ImmutableList.<Variable>builder().build();
}
return Iterables.filter(valueTable.getVariables(), new Predicate<Variable>() {
@Override
public boolean apply(@Nullable Variable input) {
return input != null && variable.getOccurrenceGroup().equals(input.getOccurrenceGroup());
}
});
}
private static void mapValues(MagmaContext context, Scriptable thisObj, Scriptable valueMap,
Iterable<Variable> variables, int index) {
if(index < 0) return;
for(Variable var : variables) {
ScriptableValue svalue = valueFromContext(context, thisObj, var.getName());
Value val = var.getValueType().nullValue();
if(!svalue.getValue().isNull()) {
ValueSequence valSeq = svalue.getValue().asSequence();
if(index < valSeq.getSize()) {
val = valSeq.get(index);
}
}
valueMap.put(var.getName(), valueMap, new ScriptableValue(thisObj, val));
}
}
/**
* Predicate based on a function call.
*/
private static final class FunctionPredicate implements Predicate<Value> {
private final Context ctx;
private final Scriptable scope;
private final Scriptable thisObj;
private final Function criteriaFunction;
private FunctionPredicate(Context ctx, Scriptable scope, Scriptable thisObj, Function criteriaFunction) {
this.ctx = ctx;
this.scope = scope;
this.thisObj = thisObj;
this.criteriaFunction = criteriaFunction;
}
@Override
public boolean apply(@Nullable Value input) {
if(input == null) return false;
Object rval = criteriaFunction
.call(ctx, scope, thisObj, new ScriptableValue[] { new ScriptableValue(thisObj, input) });
if(rval instanceof ScriptableValue) {
rval = ((ScriptableValue) rval).getValue().getValue();
}
return rval == null ? false : (Boolean) rval;
}
}
/**
* Predicate based on the equality with a value.
*/
private static final class ValuePredicate implements Predicate<Value> {
@Nonnull
private final Value criteriaValue;
private ValuePredicate(@Nonnull Value criteriaValue) {
this.criteriaValue = criteriaValue;
}
@Override
public boolean apply(@Nullable Value input) {
return Objects.equal(input, criteriaValue);
}
}
}
| true | true |
private static List<NativeObject> getGroups(Context ctx, Scriptable thisObj, Object[] args, Function funObj,
boolean stopAtFirst) {
String name = (String) args[0];
Object criteria = args[1];
MagmaContext context = MagmaContext.asMagmaContext(ctx);
ScriptableValue sv = valueFromContext(context, thisObj, name);
Variable variable = variableFromContext(context, name);
ValueTable valueTable = valueTableFromContext(context);
List<NativeObject> valueMaps = new ArrayList<NativeObject>();
if(sv.getValue().isNull() || !sv.getValue().isSequence()) {
// just map itself
NativeObject valueMap = new NativeObject();
valueMaps.add(valueMap);
valueMap.put(variable.getName(), null, sv);
} else {
Predicate<Value> predicate = getPredicate(ctx, sv.getParentScope(), thisObj, variable, criteria);
Iterable<Variable> variables = getVariablesFromOccurrenceGroup(valueTable, variable);
ValueSequence valueSequence = sv.getValue().asSequence();
int index = -1;
//noinspection ConstantConditions
for(Value value : valueSequence.getValue()) {
index++;
if(predicate.apply(value)) {
NativeObject valueMap = new NativeObject();
valueMaps.add(valueMap);
// map itself
valueMap.put(variable.getName(), valueMap, new ScriptableValue(thisObj, value));
// get variables of the same occurrence group and map values
mapValues(context, thisObj, valueMap, variables, index);
if(stopAtFirst) {
break;
}
}
}
}
return valueMaps;
}
|
private static List<NativeObject> getGroups(Context ctx, Scriptable thisObj, Object[] args, Function funObj,
boolean stopAtFirst) {
String name = (String) args[0];
Object criteria = args[1];
MagmaContext context = MagmaContext.asMagmaContext(ctx);
ScriptableValue sv = valueFromContext(context, thisObj, name);
Variable variable = variableFromContext(context, name);
ValueTable valueTable = valueTableFromContext(context);
List<NativeObject> valueMaps = new ArrayList<NativeObject>();
if(sv.getValue().isNull() || !sv.getValue().isSequence()) {
// just map itself
NativeObject valueMap = new NativeObject();
valueMaps.add(valueMap);
valueMap.put(variable.getName(), valueMap, sv);
} else {
Predicate<Value> predicate = getPredicate(ctx, sv.getParentScope(), thisObj, variable, criteria);
Iterable<Variable> variables = getVariablesFromOccurrenceGroup(valueTable, variable);
ValueSequence valueSequence = sv.getValue().asSequence();
int index = -1;
//noinspection ConstantConditions
for(Value value : valueSequence.getValue()) {
index++;
if(predicate.apply(value)) {
NativeObject valueMap = new NativeObject();
valueMaps.add(valueMap);
// map itself
valueMap.put(variable.getName(), valueMap, new ScriptableValue(thisObj, value));
// get variables of the same occurrence group and map values
mapValues(context, thisObj, valueMap, variables, index);
if(stopAtFirst) {
break;
}
}
}
}
return valueMaps;
}
|
diff --git a/swing-application-api/src/main/java/org/cytoscape/application/swing/AbstractCyAction.java b/swing-application-api/src/main/java/org/cytoscape/application/swing/AbstractCyAction.java
index c34b5e2e..b8d1430d 100644
--- a/swing-application-api/src/main/java/org/cytoscape/application/swing/AbstractCyAction.java
+++ b/swing-application-api/src/main/java/org/cytoscape/application/swing/AbstractCyAction.java
@@ -1,507 +1,507 @@
/*
File: AbstractCyAction.java
Copyright (c) 2006, 2010-2011, The Cytoscape Consortium (www.cytoscape.org)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. See
the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package org.cytoscape.application.swing;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNode;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.work.TaskFactoryPredicate;
import org.cytoscape.work.TaskFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.KeyStroke;
import javax.swing.event.MenuEvent;
import javax.swing.event.PopupMenuEvent;
import java.net.URL;
import java.net.MalformedURLException;
/**
* An abstract implementation of the CyAction interface. Instead of using this
* class directly you should (strongly) consider implementing a
* {@link org.cytoscape.work.TaskFactory}/{@link org.cytoscape.work.Task} pair. Doing so will
* allow your action to be used outside of a Swing specific application (which
* the CyAction interface binds you to)!
* @CyAPI.Abstract.Class
*/
public abstract class AbstractCyAction extends AbstractAction implements CyAction {
private static final long serialVersionUID = -2245672104075936952L;
private static final Logger logger = LoggerFactory.getLogger(AbstractCyAction.class);
/**
* The name describing the preferred menu for the action.
*/
protected String preferredMenu = null;
/**
* The float value placing the action within the menu.
* Value of 0.0 is the beginning and 100.0 means end of menu.
*/
protected float menuGravity = 100.0f;
/**
* The float value placing the action within the toolbar.
* Value of 0.0 is the beginning and 100.0 means end of menu.
*/
protected float toolbarGravity = 100.0f;
/**
* Indicates whether accelerator keys have been set for the action.
*/
protected boolean acceleratorSet = false;
/**
* The accelerator keystroke, if set.
*/
protected KeyStroke acceleratorKeyStroke = null;
/**
* Indicates whether to use a checkbox menu item.
*/
protected boolean useCheckBoxMenuItem = false;
/**
* Indicates whether the action is in the toolbar.
*/
protected boolean inToolBar = false;
/**
* Indicates whether the action is in a menu.
*/
protected boolean inMenuBar = true;
/**
* The string defining the possible system states that the
* action is enabled for.
*/
protected String enableFor = null;
/**
* The name of the action.
*/
protected String name;
/**
* A support class for deciding whether the action should be enabled.
*/
private final AbstractEnableSupport enabler;
/**
* Creates a new AbstractCyAction object.
* @param name The name of the action.
*/
public AbstractCyAction(final String name) {
super(name);
this.enabler = new AlwaysEnabledEnableSupport(this);
}
/**
* Creates a new AbstractCyAction object.
*
* @param name The name of the action.
* @param applicationManager The application manager providing context for this action.
* @param enableFor A string declaring which states this action should be enabled for.
*/
public AbstractCyAction(final String name, final CyApplicationManager applicationManager, String enableFor) {
super(name);
this.enabler = new StringEnableSupport(this,enableFor,applicationManager);
}
/**
* Creates a new AbstractCyAction object.
*
* @param configProps
* A String-String Map of configuration metadata. This will
* usually be the Map provided by the OSGi service
* configuration. Available configuration keys include:
* <ul>
* <li>title - (The title of the menu.)</li>
* <li>preferredMenu - (The preferred menu for the action.)</li>
* <li>largeIconURL - (The icon to be used for the toolbar.)</li>
* <li>smallIconURL - (The icon to be used for the menu.)</li>
* <li>tooltip - (The toolbar or menu tooltip.)</li>
* <li>inToolBar - (Whether the action should be in the toolbar.)</li>
* <li>inMenuBar - (Whether the action should be in a menu.)</li>
* <li>enableFor - (System state that the action should be enabled for. See {@link StringEnableSupport} for more detail.)</li>
* <li>accelerator - (Accelerator key bindings.)</li>
* <li>menuGravity - (Float value between 0.0 [top] and 100.0 [bottom] placing the action in the menu.)</li>
* <li>toolBarGravity - (Float value between 0.0 [top] and 100.0 [bottom] placing the action in the toolbar.)</li>
* </ul>
* @param applicationManager
* The application manager providing context for this action.
*/
public AbstractCyAction(final Map<String, String> configProps,
final CyApplicationManager applicationManager) {
this(configProps.get("title"), applicationManager, configProps.get("enableFor"));
configFromProps( configProps );
}
/**
* Creates a new AbstractCyAction object.
*
* @param configProps
* A String-String Map of configuration metadata. This will
* usually be the Map provided by the OSGi service
* configuration. Available configuration keys include:
* <ul>
* <li>title - (The title of the menu.)</li>
* <li>preferredMenu - (The preferred menu for the action.)</li>
* <li>largeIconURL - (The icon to be used for the toolbar.)</li>
* <li>smallIconURL - (The icon to be used for the menu.)</li>
* <li>tooltip - (The toolbar or menu tooltip.)</li>
* <li>inToolBar - (Whether the action should be in the toolbar.)</li>
* <li>inMenuBar - (Whether the action should be in a menu.)</li>
* <li>enableFor - (<i>Ingored in this constructor and TaskFactoryPredicate is used instead!</i>)</li>
* <li>accelerator - (Accelerator key bindings.)</li>
* <li>menuGravity - (Float value between 0.0 [top] and 100.0 [bottom] placing the action in the menu.)</li>
* <li>toolBarGravity - (Float value between 0.0 [top] and 100.0 [bottom] placing the action in the toolbar.)</li>
* </ul>
* @param predicate
* The task factory predicate that indicates whether or not this
* action should be enabled.
*/
public AbstractCyAction(final Map<String, String> configProps,
final TaskFactoryPredicate predicate) {
super(configProps.get("title"));
this.enabler = new TaskFactoryEnableSupport(this,predicate);
configFromProps( configProps );
}
/**
* Creates a new AbstractCyAction object.
*
* @param configProps
* A String-String Map of configuration metadata. This will
* usually be the Map provided by the OSGi service
* configuration. Available configuration keys include:
* <ul>
* <li>title - (The title of the menu.)</li>
* <li>preferredMenu - (The preferred menu for the action.)</li>
* <li>largeIconURL - (The icon to be used for the toolbar.)</li>
* <li>smallIconURL - (The icon to be used for the menu.)</li>
* <li>tooltip - (The toolbar or menu tooltip.)</li>
* <li>inToolBar - (Whether the action should be in the toolbar.)</li>
* <li>inMenuBar - (Whether the action should be in a menu.)</li>
* <li>enableFor - (<i>Will only use this value if the TaskFactory is not a TaskFactoryPredicate!</i>
* See {@link StringEnableSupport} for more detail.)</li>
* <li>accelerator - (Accelerator key bindings.)</li>
* <li>menuGravity - (Float value between 0.0 [top] and 100.0 [bottom] placing the action in the menu.)</li>
* <li>toolBarGravity - (Float value between 0.0 [top] and 100.0 [bottom] placing the action in the toolbar.)</li>
* </ul>
* @param applicationManager
* The application manager providing context for this action.
* @param factory
* The task factory that may or may not be a TaskFactoryPredicate. If it is a predicate,
* it will be used to indicate whether or not this action should be enabled. This
* TaskFactory is not used by the AbstractCyAction in any other way. Any execution of tasks
* from this TaskFactory must be handled by a subclass.
*/
public AbstractCyAction(final Map<String, String> configProps,
final CyApplicationManager applicationManager,
final TaskFactory factory) {
super(configProps.get("title"));
if ( factory instanceof TaskFactoryPredicate )
this.enabler = new TaskFactoryEnableSupport(this,(TaskFactoryPredicate)factory);
else
this.enabler = new StringEnableSupport(this,configProps.get("enableFor"),applicationManager);
configFromProps( configProps );
}
private void configFromProps(final Map<String, String> configProps) {
logger.debug("New CyAction with title: " + configProps.get("title"));
final String prefMenu = configProps.get("preferredMenu");
if (prefMenu != null)
setPreferredMenu(prefMenu);
final URL largeIconURL = getURL( configProps.get("largeIconURL") );
if ( largeIconURL != null )
putValue(LARGE_ICON_KEY, new ImageIcon(largeIconURL));
final URL smallIconURL = getURL( configProps.get("smallIconURL") );
if ( smallIconURL != null )
putValue(SMALL_ICON, new ImageIcon(smallIconURL));
final String tooltip = configProps.get("tooltip");
if (tooltip != null)
putValue(SHORT_DESCRIPTION, tooltip);
final String foundInToolBar = configProps.get("inToolBar");
- if (foundInToolBar != null)
+ if (foundInToolBar != null && Boolean.parseBoolean(foundInToolBar))
inToolBar = true;
final String foundInMenuBar = configProps.get("inMenuBar");
- if (foundInMenuBar != null)
+ if (foundInMenuBar != null && Boolean.parseBoolean(foundInMenuBar))
inMenuBar = true;
final String keyComboString = configProps.get("accelerator");
if (keyComboString != null) {
final KeyStroke command = AcceleratorParser.parse(keyComboString);
if (command != null)
setAcceleratorKeyStroke(command);
}
final String menuGravityString = configProps.get("menuGravity");
if (menuGravityString != null) {
try {
menuGravity = Float.valueOf(menuGravityString);
} catch (NumberFormatException nfe) {
logger.warn("failed to set menuGravity with: " + menuGravityString, nfe);
}
}
final String toolbarGravityString = configProps.get("toolBarGravity");
if (toolbarGravityString != null) {
try {
toolbarGravity = Float.valueOf(toolbarGravityString);
} catch (NumberFormatException nfe) {
logger.warn("failed to set toolBarGravity with: " + toolbarGravityString, nfe);
}
}
setEnabled(true);
}
/**
* Sets the name of the action.
*
* @param name The name of the action.
*/
public void setName(String name) {
this.name = name;
}
/**
* {@inheritDoc}
*/
public String getName() {
return name;
}
/**
* By default all CytoscapeActions wish to be included in the menu bar at
* the 'preferredMenuName' location is specified and the 'Tools' menu not.
*
* @return true if this CyAction should be included in menu bar.
*/
public boolean isInMenuBar() {
return inMenuBar;
}
/**
* By default no CytoscapeActions will be included in the toolbar.
*
* @return true if this Action should be included in the toolbar.
*/
public boolean isInToolBar() {
return inToolBar;
}
/**
* Sets the gravity used to order this action in the menu bar.
*
* @param gravity The gravity for ordering menu bar actions.
*/
public void setMenuGravity(float gravity) {
menuGravity = gravity;
}
/**
* {@inheritDoc}
*/
public float getMenuGravity() {
return menuGravity;
}
/**
* Sets the gravity used to order this action in the toolbar.
*
* @param gravity The gravity for ordering toolbar actions.
*/
public void setToolbarGravity(float gravity) {
toolbarGravity = gravity;
}
/**
* {@inheritDoc}
*/
public float getToolbarGravity() {
return toolbarGravity;
}
/**
* Sets the accelerator KeyStroke for this action.
*
* @param ks The KeyStroke to be used as an accelerator for this action.
* This parameter may be null, in which case no accelerator is
* defined.
*/
public void setAcceleratorKeyStroke(KeyStroke ks) {
acceleratorKeyStroke = ks;
}
/**
* {@inheritDoc}
*/
public KeyStroke getAcceleratorKeyStroke() {
return acceleratorKeyStroke;
}
/**
* {@inheritDoc}
*/
public String getPreferredMenu() {
return preferredMenu;
}
/**
* Sets the preferredMenuString. See the {@link #getPreferredMenu}
* description for formatting description.
*
* @param newPreferredMenu The string describing the preferred menu name.
*/
public void setPreferredMenu(String newPreferredMenu) {
preferredMenu = newPreferredMenu;
}
/**
* {@inheritDoc}
*/
public boolean useCheckBoxMenuItem() {
return useCheckBoxMenuItem;
}
/**
* This method can be used at your discretion, but otherwise does nothing.
*
* @param e The triggering event.
*/
public void menuCanceled(MenuEvent e) {
enabler.updateEnableState();
}
/**
* This method can be used at your discretion, but otherwise does nothing.
*
* @param e The triggering event.
*/
public void menuDeselected(MenuEvent e) {
enabler.updateEnableState();
}
/**
* This method can be overridden by individual actions to set the state of
* menu items based on whatever unique circumstances that menu option cares
* about. By default it sets the state of the menu based on the "enableFor"
* property found in the properties used to construct the action. The valid
* options for "enableFor" are "network", "networkAndView", and
* "selectedNetworkObjs".
*
* @param e The triggering event.
*/
public void menuSelected(MenuEvent e) {
enabler.updateEnableState();
}
/**
* This method can be overridden by individual actions to set the state of
* menu items based on whatever unique circumstances that menu option cares
* about. By default it sets the state of the menu based on the "enableFor"
* property found in the properties used to construct the action. The valid
* options for "enableFor" are "network", "networkAndView", and
* "selectedNetworkObjs".
*
* @param e The triggering event.
*/
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
enabler.updateEnableState();
}
/**
* This method can be used at your discretion, but otherwise does nothing.
*
* @param e The triggering event.
*/
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
/**
* This method can be used at your discretion, but otherwise does nothing.
*
* @param e The triggering event.
*/
public void popupMenuCanceled(PopupMenuEvent e) {
}
/**
* Triggers the enable state of the action to be updated based
* on the enableFor state of the action and the state of the
* system.
*/
public void updateEnableState() {
enabler.updateEnableState();
}
private URL getURL(String s) {
if ( s == null )
return null;
try {
URL u = new URL(s);
return u;
} catch (MalformedURLException e) {
logger.warn("Incorrectly formatted URL string: '" + s +"'",e);
}
return null;
}
}
| false | true |
private void configFromProps(final Map<String, String> configProps) {
logger.debug("New CyAction with title: " + configProps.get("title"));
final String prefMenu = configProps.get("preferredMenu");
if (prefMenu != null)
setPreferredMenu(prefMenu);
final URL largeIconURL = getURL( configProps.get("largeIconURL") );
if ( largeIconURL != null )
putValue(LARGE_ICON_KEY, new ImageIcon(largeIconURL));
final URL smallIconURL = getURL( configProps.get("smallIconURL") );
if ( smallIconURL != null )
putValue(SMALL_ICON, new ImageIcon(smallIconURL));
final String tooltip = configProps.get("tooltip");
if (tooltip != null)
putValue(SHORT_DESCRIPTION, tooltip);
final String foundInToolBar = configProps.get("inToolBar");
if (foundInToolBar != null)
inToolBar = true;
final String foundInMenuBar = configProps.get("inMenuBar");
if (foundInMenuBar != null)
inMenuBar = true;
final String keyComboString = configProps.get("accelerator");
if (keyComboString != null) {
final KeyStroke command = AcceleratorParser.parse(keyComboString);
if (command != null)
setAcceleratorKeyStroke(command);
}
final String menuGravityString = configProps.get("menuGravity");
if (menuGravityString != null) {
try {
menuGravity = Float.valueOf(menuGravityString);
} catch (NumberFormatException nfe) {
logger.warn("failed to set menuGravity with: " + menuGravityString, nfe);
}
}
final String toolbarGravityString = configProps.get("toolBarGravity");
if (toolbarGravityString != null) {
try {
toolbarGravity = Float.valueOf(toolbarGravityString);
} catch (NumberFormatException nfe) {
logger.warn("failed to set toolBarGravity with: " + toolbarGravityString, nfe);
}
}
setEnabled(true);
}
|
private void configFromProps(final Map<String, String> configProps) {
logger.debug("New CyAction with title: " + configProps.get("title"));
final String prefMenu = configProps.get("preferredMenu");
if (prefMenu != null)
setPreferredMenu(prefMenu);
final URL largeIconURL = getURL( configProps.get("largeIconURL") );
if ( largeIconURL != null )
putValue(LARGE_ICON_KEY, new ImageIcon(largeIconURL));
final URL smallIconURL = getURL( configProps.get("smallIconURL") );
if ( smallIconURL != null )
putValue(SMALL_ICON, new ImageIcon(smallIconURL));
final String tooltip = configProps.get("tooltip");
if (tooltip != null)
putValue(SHORT_DESCRIPTION, tooltip);
final String foundInToolBar = configProps.get("inToolBar");
if (foundInToolBar != null && Boolean.parseBoolean(foundInToolBar))
inToolBar = true;
final String foundInMenuBar = configProps.get("inMenuBar");
if (foundInMenuBar != null && Boolean.parseBoolean(foundInMenuBar))
inMenuBar = true;
final String keyComboString = configProps.get("accelerator");
if (keyComboString != null) {
final KeyStroke command = AcceleratorParser.parse(keyComboString);
if (command != null)
setAcceleratorKeyStroke(command);
}
final String menuGravityString = configProps.get("menuGravity");
if (menuGravityString != null) {
try {
menuGravity = Float.valueOf(menuGravityString);
} catch (NumberFormatException nfe) {
logger.warn("failed to set menuGravity with: " + menuGravityString, nfe);
}
}
final String toolbarGravityString = configProps.get("toolBarGravity");
if (toolbarGravityString != null) {
try {
toolbarGravity = Float.valueOf(toolbarGravityString);
} catch (NumberFormatException nfe) {
logger.warn("failed to set toolBarGravity with: " + toolbarGravityString, nfe);
}
}
setEnabled(true);
}
|
diff --git a/WEB-INF/src/edu/wustl/catissuecore/bizlogic/SpecimenArrayBizLogic.java b/WEB-INF/src/edu/wustl/catissuecore/bizlogic/SpecimenArrayBizLogic.java
index 1fe7e9308..082e44c59 100644
--- a/WEB-INF/src/edu/wustl/catissuecore/bizlogic/SpecimenArrayBizLogic.java
+++ b/WEB-INF/src/edu/wustl/catissuecore/bizlogic/SpecimenArrayBizLogic.java
@@ -1,437 +1,437 @@
/*
* <p>Title: SpecimenArrayBizLogic Class </p>
* <p>Description:This class performs business level logic for Specimen Array</p>
* Copyright: Copyright (c) year 2006
* Company: Washington University, School of Medicine, St. Louis.
* @version 1.1
* Created on Aug 28,2006
*/
package edu.wustl.catissuecore.bizlogic;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import edu.wustl.catissuecore.domain.CellSpecimen;
import edu.wustl.catissuecore.domain.FluidSpecimen;
import edu.wustl.catissuecore.domain.MolecularSpecimen;
import edu.wustl.catissuecore.domain.QuantityInMicrogram;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenArray;
import edu.wustl.catissuecore.domain.SpecimenArrayContent;
import edu.wustl.catissuecore.domain.SpecimenArrayType;
import edu.wustl.catissuecore.domain.TissueSpecimen;
import edu.wustl.catissuecore.util.ApiSearchUtil;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.bizlogic.DefaultBizLogic;
import edu.wustl.common.dao.DAO;
import edu.wustl.common.security.exceptions.UserNotAuthorizedException;
import edu.wustl.common.util.dbManager.DAOException;
/**
* <p>This class initializes the fields of SpecimenArrayBizLogic.java</p>
* @author Ashwin Gupta
* @version 1.1
*/
public class SpecimenArrayBizLogic extends DefaultBizLogic
{
/**
* @see edu.wustl.common.bizlogic.AbstractBizLogic#insert(java.lang.Object, edu.wustl.common.dao.DAO, edu.wustl.common.beans.SessionDataBean)
*/
protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean)
throws DAOException, UserNotAuthorizedException
{
SpecimenArray specimenArray = (SpecimenArray) obj;
doUpdateSpecimenArrayContents(specimenArray, dao, sessionDataBean, true);
dao.insert(specimenArray.getCapacity(), sessionDataBean, true, false);
dao.insert(specimenArray, sessionDataBean, true, false);
SpecimenArrayContent specimenArrayContent = null;
// TODO move this method to HibernateDAOImpl for common use (for collection insertion)
for (Iterator iter = specimenArray.getSpecimenArrayContentCollection().iterator(); iter
.hasNext();)
{
specimenArrayContent = (SpecimenArrayContent) iter.next();
specimenArrayContent.setSpecimenArray(specimenArray);
dao.insert(specimenArrayContent, sessionDataBean, true, false);
}
}
/**
* @see edu.wustl.common.bizlogic.AbstractBizLogic#update(edu.wustl.common.dao.DAO, java.lang.Object, java.lang.Object, edu.wustl.common.beans.SessionDataBean)
*/
protected void update(DAO dao, Object obj, Object oldObj, SessionDataBean sessionDataBean)
throws DAOException, UserNotAuthorizedException
{
SpecimenArray specimenArray = (SpecimenArray) obj;
doUpdateSpecimenArrayContents(specimenArray, dao, sessionDataBean, false);
dao.update(specimenArray.getCapacity(), sessionDataBean, true, false, false);
dao.update(specimenArray, sessionDataBean, true, false, false);
SpecimenArrayContent specimenArrayContent = null;
//SpecimenArray oldSpecimenArray = (SpecimenArray) oldObj;
Collection oldSpecArrayContents = ((SpecimenArray) oldObj)
.getSpecimenArrayContentCollection();
for (Iterator iter = specimenArray.getSpecimenArrayContentCollection().iterator(); iter
.hasNext();)
{
specimenArrayContent = (SpecimenArrayContent) iter.next();
specimenArrayContent.setSpecimenArray(specimenArray);
// increment by 1 because of array index starts from 0.
if (specimenArrayContent.getPositionDimensionOne() != null)
{
specimenArrayContent.setPositionDimensionOne(new Integer(specimenArrayContent
.getPositionDimensionOne().intValue() + 1));
specimenArrayContent.setPositionDimensionTwo(new Integer(specimenArrayContent
.getPositionDimensionTwo().intValue() + 1));
}
if (isNewSpecimenArrayContent(specimenArrayContent, oldSpecArrayContents))
{
dao.insert(specimenArrayContent, sessionDataBean, true, false);
}
else
{
dao.update(specimenArrayContent, sessionDataBean, true, false, false);
}
}
}
/**
* @param specimenArrayContent array contents
* @param oldSpecArrayContents old spec array contents
* @return whether it is new or old
*/
private boolean isNewSpecimenArrayContent(SpecimenArrayContent specimenArrayContent,
Collection oldSpecArrayContents)
{
boolean isNew = true;
SpecimenArrayContent arrayContent = null;
for (Iterator iter = oldSpecArrayContents.iterator(); iter.hasNext();)
{
arrayContent = (SpecimenArrayContent) iter.next();
if (specimenArrayContent.getId() == null)
{
isNew = true;
break;
}
else if (arrayContent.getId().longValue() == specimenArrayContent.getId().longValue())
{
isNew = false;
break;
}
}
return isNew;
}
/**
* @param specimenArray specimen array
* @param dao dao
* @param sessionDataBean session data bean
* @param isInsertOperation is insert operation
* @throws DAOException
* @throws UserNotAuthorizedException
*/
private void doUpdateSpecimenArrayContents(SpecimenArray specimenArray, DAO dao,
SessionDataBean sessionDataBean, boolean isInsertOperation) throws DAOException,
UserNotAuthorizedException
{
Collection specimenArrayContentCollection = specimenArray
.getSpecimenArrayContentCollection();
Collection updatedSpecArrayContentCollection = new HashSet();
SpecimenArrayContent specimenArrayContent = null;
Specimen specimen = null;
if (specimenArrayContentCollection != null && !specimenArrayContentCollection.isEmpty())
{
double quantity = 0.0;
// fetch array type to check specimen class
List arrayTypes = dao.retrieve(SpecimenArrayType.class.getName(),
Constants.SYSTEM_IDENTIFIER, specimenArray.getSpecimenArrayType().getId());
SpecimenArrayType arrayType = null;
if ((arrayTypes != null) && (!arrayTypes.isEmpty()))
{
arrayType = (SpecimenArrayType) arrayTypes.get(0);
}
for (Iterator iter = specimenArrayContentCollection.iterator(); iter.hasNext();)
{
specimenArrayContent = (SpecimenArrayContent) iter.next();
/**
* Start: Change for API Search --- Jitendra 06/10/2006
* In Case of Api Search, previoulsy it was failing since there was default class level initialization
* on domain object. For example in User object, it was initialized as protected String lastName="";
* So we removed default class level initialization on domain object and are initializing in method
* setAllValues() of domain object. But in case of Api Search, default values will not get set
* since setAllValues() method of domainObject will not get called. To avoid null pointer exception,
* we are setting the default values same as we were setting in setAllValues() method of domainObject.
*/
- ApiSearchUtil.setSpecimenArrayContentDefault(specimenArrayContent);
+ //ApiSearchUtil.setSpecimenArrayContentDefault(specimenArrayContent);
//End:- Change for API Search
specimen = getSpecimen(dao, specimenArrayContent);
if (specimen != null)
{
// check whether array & specimen are compatible on the basis of class
if (!isArrayAndSpecimenCompatibile(arrayType, specimen))
{
throw new DAOException(
Constants.ARRAY_SPEC_NOT_COMPATIBLE_EXCEPTION_MESSAGE);
}
// set quantity object to null when there is no value.. [due to Hibernate exception]
if (specimenArrayContent.getInitialQuantity() != null)
{
if (specimenArrayContent.getInitialQuantity().getValue() == null)
{
specimenArrayContent.setInitialQuantity(null);
}
}
// if molecular then check available quantity
if (specimen instanceof MolecularSpecimen)
{
if (specimenArrayContent.getInitialQuantity() != null)
{
quantity = specimenArrayContent.getInitialQuantity().getValue()
.doubleValue();
// incase if specimenArray is created from aliquot page, then skip the Available quantity of specimen.
if (!specimenArray.isAliquot())
{
if (!isAvailableQty(specimen, quantity))
{
throw new DAOException(
" Quantity '"
+ quantity
+ "' should be less than current Distributed Quantity '"
+ specimen.getAvailableQuantity().getValue()
.doubleValue() + "' of specimen :: "
+ specimen.getLabel());
}
}
if (specimenArrayContent.getInitialQuantity().getId() == null)
{
dao.insert(specimenArrayContent.getInitialQuantity(),
sessionDataBean, true, false);
}
else
{
dao.update(specimenArrayContent.getInitialQuantity(),
sessionDataBean, true, false, false);
}
}
else
{
throw new DAOException(Constants.ARRAY_MOLECULAR_QUAN_EXCEPTION_MESSAGE
+ specimen.getLabel());
}
}
specimenArrayContent.setSpecimen(specimen);
updatedSpecArrayContentCollection.add(specimenArrayContent);
}
}
// There should be at least one valid specimen in array
if (updatedSpecArrayContentCollection.isEmpty())
{
throw new DAOException(Constants.ARRAY_NO_SPECIMEN__EXCEPTION_MESSAGE);
}
}
specimenArray.setSpecimenArrayContentCollection(updatedSpecArrayContentCollection);
}
/**
* @param specimen specimen
* @param quantity quantity
* @return whether the quantity is available.
*/
private boolean isAvailableQty(Specimen specimen, double quantity)
{
if (specimen instanceof MolecularSpecimen)
{
MolecularSpecimen molecularSpecimen = (MolecularSpecimen) specimen;
double availabeQty = Double.parseDouble(molecularSpecimen.getAvailableQuantity()
.toString());//molecularSpecimen.getAvailableQuantityInMicrogram().doubleValue();
if (quantity > availabeQty)
return false;
else
{
availabeQty = availabeQty - quantity;
molecularSpecimen.setAvailableQuantity(new QuantityInMicrogram(availabeQty));//molecularSpecimen.setAvailableQuantityInMicrogram(new Double(availabeQty));
}
}
return true;
}
/**
* @param dao dao
* @param arrayContent
* @return
* @throws DAOException
*/
private Specimen getSpecimen(DAO dao, SpecimenArrayContent arrayContent) throws DAOException
{
//get list of Participant's names
Specimen specimen = arrayContent.getSpecimen();
if (specimen != null)
{
String columnName = null;
String columnValue = null;
if ((specimen.getLabel() != null) && (!specimen.getLabel().trim().equals("")))
{
columnName = Constants.SPECIMEN_LABEL_COLUMN_NAME;
columnValue = specimen.getLabel();
}
else if ((specimen.getBarcode() != null) && (!specimen.getBarcode().trim().equals("")))
{
columnName = Constants.SPECIMEN_BARCODE_COLUMN_NAME;
columnValue = specimen.getBarcode();
}
else
{
return null;
}
String sourceObjectName = Specimen.class.getName();
String whereColumnName = columnName;
String whereColumnValue = columnValue;
List list = dao.retrieve(sourceObjectName, whereColumnName, whereColumnValue);
if (!list.isEmpty())
{
specimen = (Specimen) list.get(0);
//return specimenCollectionGroup;
}
else
{
throw new DAOException(Constants.ARRAY_SPECIMEN_DOES_NOT_EXIST_EXCEPTION_MESSAGE
+ columnValue);
}
}
return specimen;
}
/**
* @param array array
* @param specimen specimen
* @return true if compatible else false
* |
* |
* ----- on the basis of specimen class
*/
private boolean isArrayAndSpecimenCompatibile(SpecimenArrayType arrayType, Specimen specimen)
{
boolean compatible = false;
String arraySpecimenClassName = arrayType.getSpecimenClass();
String specSpecimenClassName = getClassName(specimen);
if (arraySpecimenClassName.equals(specSpecimenClassName))
{
compatible = true;
}
return compatible;
}
/**
* This function returns the actual type of the specimen i.e Cell / Fluid / Molecular / Tissue.
*/
public final String getClassName(Specimen specimen)
{
String className = "";
if (specimen instanceof CellSpecimen)
{
className = Constants.CELL;
}
else if (specimen instanceof MolecularSpecimen)
{
className = Constants.MOLECULAR;
}
else if (specimen instanceof FluidSpecimen)
{
className = Constants.FLUID;
}
else if (specimen instanceof TissueSpecimen)
{
className = Constants.TISSUE;
}
return className;
}
/**
* Overriding the parent class's method to validate the enumerated attribute values
*/
protected boolean validate(Object obj, DAO dao, String operation) throws DAOException
{
SpecimenArray specimenArray = (SpecimenArray) obj;
/**
* Start: Change for API Search --- Jitendra 06/10/2006
* In Case of Api Search, previoulsy it was failing since there was default class level initialization
* on domain object. For example in User object, it was initialized as protected String lastName="";
* So we removed default class level initialization on domain object and are initializing in method
* setAllValues() of domain object. But in case of Api Search, default values will not get set
* since setAllValues() method of domainObject will not get called. To avoid null pointer exception,
* we are setting the default values same as we were setting in setAllValues() method of domainObject.
*/
ApiSearchUtil.setSpecimenArrayDefault(specimenArray);
//End:- Change for API Search
return true;
}
// Added by Ashish
/*
protected boolean validate(Object obj, DAO dao, String operation) throws DAOException
{
SpecimenArray specimenArray = (SpecimenArray) obj;
if (specimenArray == null)
throw new DAOException("domain.object.null.err.msg", new String[]{"Specimen Array"});
Validator validator = new Validator();
if (specimenArray.getSpecimenArrayType().getId() == -1)
{
String message = ApplicationProperties.getValue("array.arrayType");
throw new DAOException("errors.item.required", new String[]{message});
}
// validate name of array
if (validator.isEmpty(specimenArray.getName()))
{
String message = ApplicationProperties.getValue("array.arrayLabel");
throw new DAOException("errors.item.required", new String[]{message});
}
// validate storage position
if (!validator.isNumeric(String.valueOf(specimenArray.getPositionDimensionOne()), 1)
|| !validator.isNumeric(String.valueOf(specimenArray.getPositionDimensionTwo()), 1)
|| !validator.isNumeric(
String.valueOf(specimenArray.getStorageContainer().getId()), 1))
{
String message = ApplicationProperties.getValue("array.positionInStorageContainer");
throw new DAOException("errors.item.format", new String[]{message});
}
// validate user
if (!validator.isValidOption(String.valueOf(specimenArray.getCreatedBy().getId())))
{
String message = ApplicationProperties.getValue("array.user");
throw new DAOException("errors.item.required", new String[]{message});
}
return true;
}
*/
//END
}
| true | true |
private void doUpdateSpecimenArrayContents(SpecimenArray specimenArray, DAO dao,
SessionDataBean sessionDataBean, boolean isInsertOperation) throws DAOException,
UserNotAuthorizedException
{
Collection specimenArrayContentCollection = specimenArray
.getSpecimenArrayContentCollection();
Collection updatedSpecArrayContentCollection = new HashSet();
SpecimenArrayContent specimenArrayContent = null;
Specimen specimen = null;
if (specimenArrayContentCollection != null && !specimenArrayContentCollection.isEmpty())
{
double quantity = 0.0;
// fetch array type to check specimen class
List arrayTypes = dao.retrieve(SpecimenArrayType.class.getName(),
Constants.SYSTEM_IDENTIFIER, specimenArray.getSpecimenArrayType().getId());
SpecimenArrayType arrayType = null;
if ((arrayTypes != null) && (!arrayTypes.isEmpty()))
{
arrayType = (SpecimenArrayType) arrayTypes.get(0);
}
for (Iterator iter = specimenArrayContentCollection.iterator(); iter.hasNext();)
{
specimenArrayContent = (SpecimenArrayContent) iter.next();
/**
* Start: Change for API Search --- Jitendra 06/10/2006
* In Case of Api Search, previoulsy it was failing since there was default class level initialization
* on domain object. For example in User object, it was initialized as protected String lastName="";
* So we removed default class level initialization on domain object and are initializing in method
* setAllValues() of domain object. But in case of Api Search, default values will not get set
* since setAllValues() method of domainObject will not get called. To avoid null pointer exception,
* we are setting the default values same as we were setting in setAllValues() method of domainObject.
*/
ApiSearchUtil.setSpecimenArrayContentDefault(specimenArrayContent);
//End:- Change for API Search
specimen = getSpecimen(dao, specimenArrayContent);
if (specimen != null)
{
// check whether array & specimen are compatible on the basis of class
if (!isArrayAndSpecimenCompatibile(arrayType, specimen))
{
throw new DAOException(
Constants.ARRAY_SPEC_NOT_COMPATIBLE_EXCEPTION_MESSAGE);
}
// set quantity object to null when there is no value.. [due to Hibernate exception]
if (specimenArrayContent.getInitialQuantity() != null)
{
if (specimenArrayContent.getInitialQuantity().getValue() == null)
{
specimenArrayContent.setInitialQuantity(null);
}
}
// if molecular then check available quantity
if (specimen instanceof MolecularSpecimen)
{
if (specimenArrayContent.getInitialQuantity() != null)
{
quantity = specimenArrayContent.getInitialQuantity().getValue()
.doubleValue();
// incase if specimenArray is created from aliquot page, then skip the Available quantity of specimen.
if (!specimenArray.isAliquot())
{
if (!isAvailableQty(specimen, quantity))
{
throw new DAOException(
" Quantity '"
+ quantity
+ "' should be less than current Distributed Quantity '"
+ specimen.getAvailableQuantity().getValue()
.doubleValue() + "' of specimen :: "
+ specimen.getLabel());
}
}
if (specimenArrayContent.getInitialQuantity().getId() == null)
{
dao.insert(specimenArrayContent.getInitialQuantity(),
sessionDataBean, true, false);
}
else
{
dao.update(specimenArrayContent.getInitialQuantity(),
sessionDataBean, true, false, false);
}
}
else
{
throw new DAOException(Constants.ARRAY_MOLECULAR_QUAN_EXCEPTION_MESSAGE
+ specimen.getLabel());
}
}
specimenArrayContent.setSpecimen(specimen);
updatedSpecArrayContentCollection.add(specimenArrayContent);
}
}
// There should be at least one valid specimen in array
if (updatedSpecArrayContentCollection.isEmpty())
{
throw new DAOException(Constants.ARRAY_NO_SPECIMEN__EXCEPTION_MESSAGE);
}
}
specimenArray.setSpecimenArrayContentCollection(updatedSpecArrayContentCollection);
}
|
private void doUpdateSpecimenArrayContents(SpecimenArray specimenArray, DAO dao,
SessionDataBean sessionDataBean, boolean isInsertOperation) throws DAOException,
UserNotAuthorizedException
{
Collection specimenArrayContentCollection = specimenArray
.getSpecimenArrayContentCollection();
Collection updatedSpecArrayContentCollection = new HashSet();
SpecimenArrayContent specimenArrayContent = null;
Specimen specimen = null;
if (specimenArrayContentCollection != null && !specimenArrayContentCollection.isEmpty())
{
double quantity = 0.0;
// fetch array type to check specimen class
List arrayTypes = dao.retrieve(SpecimenArrayType.class.getName(),
Constants.SYSTEM_IDENTIFIER, specimenArray.getSpecimenArrayType().getId());
SpecimenArrayType arrayType = null;
if ((arrayTypes != null) && (!arrayTypes.isEmpty()))
{
arrayType = (SpecimenArrayType) arrayTypes.get(0);
}
for (Iterator iter = specimenArrayContentCollection.iterator(); iter.hasNext();)
{
specimenArrayContent = (SpecimenArrayContent) iter.next();
/**
* Start: Change for API Search --- Jitendra 06/10/2006
* In Case of Api Search, previoulsy it was failing since there was default class level initialization
* on domain object. For example in User object, it was initialized as protected String lastName="";
* So we removed default class level initialization on domain object and are initializing in method
* setAllValues() of domain object. But in case of Api Search, default values will not get set
* since setAllValues() method of domainObject will not get called. To avoid null pointer exception,
* we are setting the default values same as we were setting in setAllValues() method of domainObject.
*/
//ApiSearchUtil.setSpecimenArrayContentDefault(specimenArrayContent);
//End:- Change for API Search
specimen = getSpecimen(dao, specimenArrayContent);
if (specimen != null)
{
// check whether array & specimen are compatible on the basis of class
if (!isArrayAndSpecimenCompatibile(arrayType, specimen))
{
throw new DAOException(
Constants.ARRAY_SPEC_NOT_COMPATIBLE_EXCEPTION_MESSAGE);
}
// set quantity object to null when there is no value.. [due to Hibernate exception]
if (specimenArrayContent.getInitialQuantity() != null)
{
if (specimenArrayContent.getInitialQuantity().getValue() == null)
{
specimenArrayContent.setInitialQuantity(null);
}
}
// if molecular then check available quantity
if (specimen instanceof MolecularSpecimen)
{
if (specimenArrayContent.getInitialQuantity() != null)
{
quantity = specimenArrayContent.getInitialQuantity().getValue()
.doubleValue();
// incase if specimenArray is created from aliquot page, then skip the Available quantity of specimen.
if (!specimenArray.isAliquot())
{
if (!isAvailableQty(specimen, quantity))
{
throw new DAOException(
" Quantity '"
+ quantity
+ "' should be less than current Distributed Quantity '"
+ specimen.getAvailableQuantity().getValue()
.doubleValue() + "' of specimen :: "
+ specimen.getLabel());
}
}
if (specimenArrayContent.getInitialQuantity().getId() == null)
{
dao.insert(specimenArrayContent.getInitialQuantity(),
sessionDataBean, true, false);
}
else
{
dao.update(specimenArrayContent.getInitialQuantity(),
sessionDataBean, true, false, false);
}
}
else
{
throw new DAOException(Constants.ARRAY_MOLECULAR_QUAN_EXCEPTION_MESSAGE
+ specimen.getLabel());
}
}
specimenArrayContent.setSpecimen(specimen);
updatedSpecArrayContentCollection.add(specimenArrayContent);
}
}
// There should be at least one valid specimen in array
if (updatedSpecArrayContentCollection.isEmpty())
{
throw new DAOException(Constants.ARRAY_NO_SPECIMEN__EXCEPTION_MESSAGE);
}
}
specimenArray.setSpecimenArrayContentCollection(updatedSpecArrayContentCollection);
}
|
diff --git a/common/src/main/java/com/cqlybest/common/service/DictService.java b/common/src/main/java/com/cqlybest/common/service/DictService.java
index 6d73498..9c70afa 100644
--- a/common/src/main/java/com/cqlybest/common/service/DictService.java
+++ b/common/src/main/java/com/cqlybest/common/service/DictService.java
@@ -1,35 +1,35 @@
package com.cqlybest.common.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cqlybest.common.Cn2Spell;
import com.cqlybest.common.bean.Dict;
import com.cqlybest.common.dao.DictDao;
@Service
public class DictService {
@Autowired
private DictDao dictDao;
public void addDict(Dict dict) {
dict.setPinyin(Cn2Spell.converterToSpell(dict.getName()));
dict.setPy(Cn2Spell.converterToFirstSpell(dict.getName()));
dictDao.saveOrUpdate(dict);
}
public void deleteDict(Dict dict) {
Dict _dict = dictDao.findById(dict.getClass(), dict.getId());
if (_dict != null) {
- dictDao.delete(dict);
+ dictDao.delete(_dict);
}
}
public <T extends Dict> List<T> getDict(Class<T> cls) {
return dictDao.findAllDict(cls);
}
}
| true | true |
public void deleteDict(Dict dict) {
Dict _dict = dictDao.findById(dict.getClass(), dict.getId());
if (_dict != null) {
dictDao.delete(dict);
}
}
|
public void deleteDict(Dict dict) {
Dict _dict = dictDao.findById(dict.getClass(), dict.getId());
if (_dict != null) {
dictDao.delete(_dict);
}
}
|
diff --git a/melati/src/test/java/org/melati/app/test/TemplateAppTest.java b/melati/src/test/java/org/melati/app/test/TemplateAppTest.java
index 1b18f59d2..ec223d67d 100644
--- a/melati/src/test/java/org/melati/app/test/TemplateAppTest.java
+++ b/melati/src/test/java/org/melati/app/test/TemplateAppTest.java
@@ -1,321 +1,322 @@
package org.melati.app.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;
import org.melati.Melati;
import org.melati.app.InvalidArgumentsException;
import org.melati.app.TemplateApp;
import org.melati.app.UnhandledExceptionException;
import org.melati.util.ConfigException;
import org.melati.util.MelatiConfigurationException;
import junit.framework.TestCase;
/**
* Generated code for the test suite <b>TemplateAppTest</b> located at
* <i>/melati/src/test/java/org/melati/app/test/TemplateAppTest.testsuite</i>.
*
*/
public class TemplateAppTest extends TestCase {
/**
* Constructor for TemplateAppTest.
*
* @param name
*/
public TemplateAppTest(String name) {
super(name);
}
/**
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
}
/**
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
//System.gc();
}
/**
* @see org.melati.app.TemplateApp#init(String[])
*/
public void testInit() throws Exception {
TemplateApp ta = new TemplateApp();
String[] args = { "appjunit", "user", "0", "method", "field", "value" };
Melati m = ta.init(args);
assertEquals("appjunit", m.getDatabase().getName());
Hashtable f = (Hashtable)m.getTemplateContext().get("Form");
assertEquals("value", f.get("field"));
}
/**
* @see org.melati.app.TemplateApp#init(String[])
*/
public void testInitWithUnmatcheArgs0() throws Exception {
TemplateApp ta = new TemplateApp();
String[] args = { "appjunit", "user", "0", "method", "field", "value",
"unmatched" };
try {
ta.init(args);
fail("Should have bombed");
} catch (InvalidArgumentsException e) {
e = null;
}
}
/**
* @see org.melati.app.TemplateApp#main(String[])
*/
public void testMain() throws Exception {
String fileName = "t.tmp";
String[] args = { "appjunit", "user", "0",
"org/melati/app/TemplateApp", "field", "value", "-o", fileName };
TemplateApp.main(args);
String output = "";
File fileIn = new File(fileName);
BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(fileIn)));
while (in.ready()) {
output += in.readLine();
}
in.close();
fileIn.delete();
assertEquals("Hello _guest_" +
"You have expanded template org/melati/app/TemplateApp" +
"Your melati contains:" +
"Database : jdbc:hsqldb:mem:appjunit " +
"Table : user (from the data structure definition) " +
"Object : _guest_ " +
"Troid : 0 " +
"Method : org/melati/app/TemplateApp " +
"System Users" +
"============" +
" Melati guest user" +
" Melati database administrator" +
"Form settings" +
"=============" +
" field value", output);
}
/**
* @see org.melati.app.TemplateApp#main(String[])
*/
public void testMainOneArg() throws Exception {
String fileName = "tttt.tmp";
String[] args = { "appjunit", "-o", fileName };
TemplateApp it = new TemplateApp();
it.run(args);
String output = "";
File fileIn = new File(fileName);
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(fileIn)));
while (in.ready()) {
output += in.readLine();
}
in.close();
fileIn.delete();
System.err.println(output);
assertEquals("Hello _guest_" +
"You have expanded template org/melati/app/TemplateApp" +
"Your melati contains:" +
"Database : jdbc:hsqldb:mem:appjunit " +
"Table : null " +
"Object : null " +
"Troid : null " +
"Method : null " +
"System Users" +
"============" +
" Melati guest user" +
" Melati database administrator",output);
}
/**
* @see org.melati.app.TemplateApp#main(String[])
*/
public void testMainTwoArgs() throws Exception {
String fileName = "t25555.tmp";
String[] args = { "appjunit", "user", "-o", fileName };
TemplateApp it = new TemplateApp();
try {
it.run(args);
fail("Should have blown up");
} catch (UnhandledExceptionException e) {
e.printStackTrace();
- assertEquals("org.melati.template.NotFoundException: Could not find template user.wm",
- e.subException.getMessage());
+ // Message is slightly different between WM and velocity
+ assertTrue(e.subException.getMessage().
+ startsWith("org.melati.template.NotFoundException: Could not find template user"));
e = null;
}
File fileIn = new File(fileName);
assertTrue(fileIn.delete());
fileName = "t2a.tmp";
args = new String[] { "appjunit", "org/melati/app/TemplateApp", "-o", fileName };
TemplateApp.main(args);
String output = "";
fileIn = new File(fileName);
BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(fileIn)));
while (in.ready()) {
output += in.readLine();
}
in.close();
fileIn.delete();
assertEquals("Hello _guest_" +
"You have expanded template org/melati/app/TemplateApp" +
"Your melati contains:" +
"Database : jdbc:hsqldb:mem:appjunit " +
"Table : null " +
"Object : null " +
"Troid : null " +
"Method : org/melati/app/TemplateApp " +
"System Users" +
"============" +
" Melati guest user" +
" Melati database administrator", output);
}
/**
* @see org.melati.app.TemplateApp#main(String[])
*/
public void testMainThreeArgs() throws Exception {
String fileName = "t3.tmp";
String[] args = { "appjunit", "user", "0",
"-o", fileName };
TemplateApp it = new TemplateApp();
it.run(args);
String output = "";
File fileIn = new File(fileName);
BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(fileIn)));
while (in.ready()) {
output += in.readLine();
}
in.close();
fileIn.delete();
assertEquals("Hello _guest_" +
"You have expanded template org/melati/app/TemplateApp" +
"Your melati contains:" +
"Database : jdbc:hsqldb:mem:appjunit " +
"Table : user (from the data structure definition) " +
"Object : _guest_ " +
"Troid : 0 " +
"Method : null " +
"System Users" +
"============" +
" Melati guest user" +
" Melati database administrator" , output);
}
/**
* Also covers .wm extension.
* @see org.melati.app.TemplateApp#main(String[])
*/
public void testMainFourArgs() throws Exception {
String fileName = "t4.tmp";
String[] args = { "appjunit", "user", "0",
"org/melati/app/TemplateApp", "-o", fileName };
TemplateApp it = new TemplateApp();
it.run(args);
String output = "";
File fileIn = new File(fileName);
BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(fileIn)));
while (in.ready()) {
output += in.readLine();
}
in.close();
fileIn.delete();
assertEquals("Hello _guest_" +
"You have expanded template org/melati/app/TemplateApp" +
"Your melati contains:" +
"Database : jdbc:hsqldb:mem:appjunit " +
"Table : user (from the data structure definition) " +
"Object : _guest_ " +
"Troid : 0 " +
"Method : org/melati/app/TemplateApp " +
"System Users" +
"============" +
" Melati guest user" +
" Melati database administrator" , output);
}
/**
* @see org.melati.app.TemplateApp#main(String[])
*/
public void testMainZeroArgs() throws Exception {
String fileName = "t0.tmp";
String[] args = { "-o", fileName };
TemplateApp it = new TemplateApp();
try {
it.run(args);
fail("Should have bombed");
} catch (ConfigException e) {
e = null;
}
File fileIn = new File(fileName);
assertTrue(fileIn.delete());
}
/**
* @throws Exception
*/
public void testLogin() throws Exception {
String fileName = "t.tmp";
String[] args = { "appjunit", "user", "0",
"org/melati/app/TemplateApp", "-u", "_administrator_","-p", "FIXME","-o", fileName};
TemplateApp it = new ConfiguredTemplateApp();
it.run(args);
String output = "";
File fileIn = new File(fileName);
BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(fileIn)));
while (in.ready()) {
output += in.readLine();
}
in.close();
fileIn.delete();
assertEquals("Hello _administrator_" +
"You have expanded template org/melati/app/TemplateApp" +
"Your melati contains:" +
"Database : jdbc:hsqldb:mem:appjunit " +
"Table : user (from the data structure definition) " +
"Object : _guest_ " +
"Troid : 0 " +
"Method : org/melati/app/TemplateApp " +
"System Users" +
"============" +
" Melati guest user" +
" Melati database administrator" +
"Form settings============= -u _administrator_ -p FIXME", output);
}
/**
* Test no configured template engine.
*/
public void testNoTemplateEngineConfigured() throws Exception {
String fileName = "junitTest99.tmp";
String[] args = { "appjunit", "user", "0",
"org/melati/app/TemplateApp", "-u", "_administrator_","-p", "FIXME","-o", fileName};
TemplateApp it = new MisConfiguredTemplateApp();
try {
it.run(args);
fail("Should have blown up");
} catch (MelatiConfigurationException e) {
System.err.println(e.getMessage());
assertEquals("org.melati.util.MelatiConfigurationException: " +
"Have you configured a template engine? " +
"org.melati.MelatiConfig.templateEngine currently set to " +
"org.melati.template.NoTemplateEngine",
e.getMessage());
e = null;
}
File fileIn = new File(fileName);
assertTrue(fileIn.delete());
}
}
| true | true |
public void testMainTwoArgs() throws Exception {
String fileName = "t25555.tmp";
String[] args = { "appjunit", "user", "-o", fileName };
TemplateApp it = new TemplateApp();
try {
it.run(args);
fail("Should have blown up");
} catch (UnhandledExceptionException e) {
e.printStackTrace();
assertEquals("org.melati.template.NotFoundException: Could not find template user.wm",
e.subException.getMessage());
e = null;
}
File fileIn = new File(fileName);
assertTrue(fileIn.delete());
fileName = "t2a.tmp";
args = new String[] { "appjunit", "org/melati/app/TemplateApp", "-o", fileName };
TemplateApp.main(args);
String output = "";
fileIn = new File(fileName);
BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(fileIn)));
while (in.ready()) {
output += in.readLine();
}
in.close();
fileIn.delete();
assertEquals("Hello _guest_" +
"You have expanded template org/melati/app/TemplateApp" +
"Your melati contains:" +
"Database : jdbc:hsqldb:mem:appjunit " +
"Table : null " +
"Object : null " +
"Troid : null " +
"Method : org/melati/app/TemplateApp " +
"System Users" +
"============" +
" Melati guest user" +
" Melati database administrator", output);
}
|
public void testMainTwoArgs() throws Exception {
String fileName = "t25555.tmp";
String[] args = { "appjunit", "user", "-o", fileName };
TemplateApp it = new TemplateApp();
try {
it.run(args);
fail("Should have blown up");
} catch (UnhandledExceptionException e) {
e.printStackTrace();
// Message is slightly different between WM and velocity
assertTrue(e.subException.getMessage().
startsWith("org.melati.template.NotFoundException: Could not find template user"));
e = null;
}
File fileIn = new File(fileName);
assertTrue(fileIn.delete());
fileName = "t2a.tmp";
args = new String[] { "appjunit", "org/melati/app/TemplateApp", "-o", fileName };
TemplateApp.main(args);
String output = "";
fileIn = new File(fileName);
BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(fileIn)));
while (in.ready()) {
output += in.readLine();
}
in.close();
fileIn.delete();
assertEquals("Hello _guest_" +
"You have expanded template org/melati/app/TemplateApp" +
"Your melati contains:" +
"Database : jdbc:hsqldb:mem:appjunit " +
"Table : null " +
"Object : null " +
"Troid : null " +
"Method : org/melati/app/TemplateApp " +
"System Users" +
"============" +
" Melati guest user" +
" Melati database administrator", output);
}
|
diff --git a/src/uk/co/harcourtprogramming/mewler/Mewler.java b/src/uk/co/harcourtprogramming/mewler/Mewler.java
index a6d9c05..460663b 100644
--- a/src/uk/co/harcourtprogramming/mewler/Mewler.java
+++ b/src/uk/co/harcourtprogramming/mewler/Mewler.java
@@ -1,291 +1,291 @@
package uk.co.harcourtprogramming.mewler;
import uk.co.harcourtprogramming.mewler.servermesasges.IrcMessage;
import uk.co.harcourtprogramming.mewler.servermesasges.AbstractIrcMessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import uk.co.harcourtprogramming.mewler.servermesasges.IrcPingMessage;
import uk.co.harcourtprogramming.mewler.servermesasges.IrcResponseCode;
import uk.co.harcourtprogramming.mewler.servermesasges.User;
/**
*
*/
public class Mewler
{
private final static Logger LOG = Logger.getLogger("InternetRelatCats.Mewler");
static
{
Handler h = new ConsoleHandler();
h.setFormatter(new Formatter()
{
@Override
public String format(LogRecord l)
{
Calendar time = Calendar.getInstance();
time.setTimeInMillis(l.getMillis());
return String.format("[%2$tR %1$s] %3$s\n",
l.getLevel().getLocalizedName(), time, formatMessage(l));
}
@Override
public synchronized String formatMessage(LogRecord record)
{
if (record.getMessage() == null)
{
if (record.getThrown() == null)
{
return String.format("null log from <%3s>%1s::%2s", record.getSourceClassName(), record.getSourceMethodName(), Thread.currentThread().getName());
}
else
{
Throwable thrown = record.getThrown();
return String.format("%s <%s>%s::%s\n\t%s",
thrown.getClass().getName(),
Thread.currentThread().getName(),
record.getSourceClassName(),
record.getSourceMethodName(),
thrown.getLocalizedMessage()
);
}
}
if (record.getThrown() == null)
{
return super.formatMessage(record);
}
Throwable thrown = record.getThrown();
return String.format("%s <%s>%s::%s\n\t%s\n\t%s",
thrown.getClass().getName(),
Thread.currentThread().getName(),
record.getSourceClassName(),
record.getSourceMethodName(),
super.formatMessage(record),
thrown.getLocalizedMessage()
);
}
});
LOG.addHandler(h);
LOG.setUseParentHandlers(false);
}
private final MewlerOut outputThread;
private final MewlerIn inputThread;
private String nick = null;
public Mewler(final InputStream input, final OutputStream output, final ThreadGroup tg)
{
if (input == null) throw new IllegalArgumentException("InputStream must be a valid, active stream");
try
{
input.available();
}
catch (IOException ex)
{
throw new IllegalArgumentException("InputStream must be a valid, active stream");
}
if (input == null) throw new IllegalArgumentException("InputStream must be a valid, active stream");
try
{
input.available();
}
catch (IOException ex)
{
throw new IllegalArgumentException("InputStream must be a valid, active stream");
}
outputThread = new MewlerOut(output, tg);
inputThread = new MewlerIn(new BufferedReader(new InputStreamReader(input)), tg, this);
}
public synchronized void connect(final String nick, final String password, final String realName) throws IOException
{
if (inputThread.isAlive() && !inputThread.isDead())
return; // TODO: Do we want to throw an exception here
if (nick == null || !nick.matches("[\\w<\\-\\[\\]\\^{}]+"))
{
throw new IllegalArgumentException("Supplied nick is null or not a valid nickname");
}
if (password != null && password.length() != 0)
{
String passCommand = IrcCommands.createCommandString(
IrcCommands.PASS, password);
outputThread.send(passCommand);
}
String commandString;
int nicksTried = 0;
BufferedReader inputFromIrc = inputThread.inputStream;
// Try and register a nick name
commandString = IrcCommands.createCommandString(IrcCommands.NICK, nick);
outputThread.send(commandString);
String currNick = nick;
// Send the user data
commandString = IrcCommands.createCommandString(IrcCommands.USER,
nick, 0, "*", realName == null ? "Mewler-Bot" : realName);
outputThread.send(commandString);
while(true)
{
String line = inputFromIrc.readLine();
if (line == null)
{
dispose();
- throw new Error("Error whilst trying to connect: null message");
+ throw new IOException("Error whilst trying to connect: null message");
}
AbstractIrcMessage mess = AbstractIrcMessage.parse(line, currNick);
if (mess instanceof IrcPingMessage)
{
LOG.log(Level.FINER, ">> {0}", mess.toString());
outputThread.send(((IrcPingMessage)mess).reply());
}
else if (mess instanceof IrcMessage)
{
final IrcMessage message = (IrcMessage)mess;
LOG.log(Level.FINER, ">> {0}", mess.toString());
if (message.getMessageType().equals("ERROR"))
{
dispose();
- throw new Error("Error whilst trying to connect: " + message.getPayload());
+ throw new IOException("Error whilst trying to connect: " + message.getPayload());
}
}
else if (mess instanceof IrcResponseCode)
{
final IrcResponseCode message = (IrcResponseCode)mess;
switch (message.getCode())
{
case ERR_NICKNAMEINUSE:
case ERR_NICKCOLLISION:
LOG.log(Level.FINE, ">> Nick in use, trying again");
currNick = nick + "-" + nicksTried;
commandString = IrcCommands.createCommandString(IrcCommands.NICK, currNick);
outputThread.send(commandString);
break;
case RPL_MOTDSTART:
case RPL_MOTD:
LOG.log(Level.FINE, "Sucessfully connected!!!");
this.nick = currNick;
inputThread.start();
outputThread.start();
return;
default:
LOG.log(Level.FINER, ">> {0}", mess.toString());
// TODO: do something with messages of other codes
}
}
else
{
LOG.log(Level.FINER, ">> {0}", mess.toString());
}
}
}
public void message(final String target, final String message)
{
StringBuilder rawMessage = new StringBuilder(100 + message.length());
for (String line : message.split("[\r\n]+"))
{
rawMessage.append(IrcCommands.createCommandString(IrcCommands.MESS,
target, line));
}
outputThread.queue(rawMessage.toString());
}
public void act(final String target, final String message)
{
String mess = IrcCommands.createCommandString(IrcCommands.ACTION,
target, message.split("[\r\n]+")[0]);
outputThread.queue(mess);
}
public void join(String channel)
{
String command = IrcCommands.createCommandString(IrcCommands.JOIN, channel);
outputThread.queue(command);
}
public void part(String channel)
{
String command = IrcCommands.createCommandString(IrcCommands.PART, channel);
outputThread.queue(command);
}
public void quit()
{
String command = IrcCommands.createCommandString(IrcCommands.QUIT, "Mewler");
outputThread.queue(command);
}
@Override
protected void finalize() throws Throwable
{
dispose();
super.finalize();
}
public void dispose()
{
outputThread.interrupt();
inputThread.interrupt();
}
public String getNick()
{
return nick;
}
protected void onMessage(String nick, User sender, String channel, String message)
{
// Nothing to see here. Move along, citizen!
}
protected void onAction(String nick, User sender, String channel, String action)
{
// Nothing to see here. Move along, citizen!
}
protected void onDisconnect()
{
// Nothing to see here. Move along, citizen!
}
protected void onPing(IrcPingMessage ping)
{
try
{
outputThread.send(ping.reply());
}
catch (IOException ex)
{
LOG.log(Level.SEVERE, "Exception when replying to PING", ex);
}
}
protected boolean isAlive()
{
return (inputThread.isAlive() || outputThread.isAlive());
}
}
| false | true |
public synchronized void connect(final String nick, final String password, final String realName) throws IOException
{
if (inputThread.isAlive() && !inputThread.isDead())
return; // TODO: Do we want to throw an exception here
if (nick == null || !nick.matches("[\\w<\\-\\[\\]\\^{}]+"))
{
throw new IllegalArgumentException("Supplied nick is null or not a valid nickname");
}
if (password != null && password.length() != 0)
{
String passCommand = IrcCommands.createCommandString(
IrcCommands.PASS, password);
outputThread.send(passCommand);
}
String commandString;
int nicksTried = 0;
BufferedReader inputFromIrc = inputThread.inputStream;
// Try and register a nick name
commandString = IrcCommands.createCommandString(IrcCommands.NICK, nick);
outputThread.send(commandString);
String currNick = nick;
// Send the user data
commandString = IrcCommands.createCommandString(IrcCommands.USER,
nick, 0, "*", realName == null ? "Mewler-Bot" : realName);
outputThread.send(commandString);
while(true)
{
String line = inputFromIrc.readLine();
if (line == null)
{
dispose();
throw new Error("Error whilst trying to connect: null message");
}
AbstractIrcMessage mess = AbstractIrcMessage.parse(line, currNick);
if (mess instanceof IrcPingMessage)
{
LOG.log(Level.FINER, ">> {0}", mess.toString());
outputThread.send(((IrcPingMessage)mess).reply());
}
else if (mess instanceof IrcMessage)
{
final IrcMessage message = (IrcMessage)mess;
LOG.log(Level.FINER, ">> {0}", mess.toString());
if (message.getMessageType().equals("ERROR"))
{
dispose();
throw new Error("Error whilst trying to connect: " + message.getPayload());
}
}
else if (mess instanceof IrcResponseCode)
{
final IrcResponseCode message = (IrcResponseCode)mess;
switch (message.getCode())
{
case ERR_NICKNAMEINUSE:
case ERR_NICKCOLLISION:
LOG.log(Level.FINE, ">> Nick in use, trying again");
currNick = nick + "-" + nicksTried;
commandString = IrcCommands.createCommandString(IrcCommands.NICK, currNick);
outputThread.send(commandString);
break;
case RPL_MOTDSTART:
case RPL_MOTD:
LOG.log(Level.FINE, "Sucessfully connected!!!");
this.nick = currNick;
inputThread.start();
outputThread.start();
return;
default:
LOG.log(Level.FINER, ">> {0}", mess.toString());
// TODO: do something with messages of other codes
}
}
else
{
LOG.log(Level.FINER, ">> {0}", mess.toString());
}
}
}
|
public synchronized void connect(final String nick, final String password, final String realName) throws IOException
{
if (inputThread.isAlive() && !inputThread.isDead())
return; // TODO: Do we want to throw an exception here
if (nick == null || !nick.matches("[\\w<\\-\\[\\]\\^{}]+"))
{
throw new IllegalArgumentException("Supplied nick is null or not a valid nickname");
}
if (password != null && password.length() != 0)
{
String passCommand = IrcCommands.createCommandString(
IrcCommands.PASS, password);
outputThread.send(passCommand);
}
String commandString;
int nicksTried = 0;
BufferedReader inputFromIrc = inputThread.inputStream;
// Try and register a nick name
commandString = IrcCommands.createCommandString(IrcCommands.NICK, nick);
outputThread.send(commandString);
String currNick = nick;
// Send the user data
commandString = IrcCommands.createCommandString(IrcCommands.USER,
nick, 0, "*", realName == null ? "Mewler-Bot" : realName);
outputThread.send(commandString);
while(true)
{
String line = inputFromIrc.readLine();
if (line == null)
{
dispose();
throw new IOException("Error whilst trying to connect: null message");
}
AbstractIrcMessage mess = AbstractIrcMessage.parse(line, currNick);
if (mess instanceof IrcPingMessage)
{
LOG.log(Level.FINER, ">> {0}", mess.toString());
outputThread.send(((IrcPingMessage)mess).reply());
}
else if (mess instanceof IrcMessage)
{
final IrcMessage message = (IrcMessage)mess;
LOG.log(Level.FINER, ">> {0}", mess.toString());
if (message.getMessageType().equals("ERROR"))
{
dispose();
throw new IOException("Error whilst trying to connect: " + message.getPayload());
}
}
else if (mess instanceof IrcResponseCode)
{
final IrcResponseCode message = (IrcResponseCode)mess;
switch (message.getCode())
{
case ERR_NICKNAMEINUSE:
case ERR_NICKCOLLISION:
LOG.log(Level.FINE, ">> Nick in use, trying again");
currNick = nick + "-" + nicksTried;
commandString = IrcCommands.createCommandString(IrcCommands.NICK, currNick);
outputThread.send(commandString);
break;
case RPL_MOTDSTART:
case RPL_MOTD:
LOG.log(Level.FINE, "Sucessfully connected!!!");
this.nick = currNick;
inputThread.start();
outputThread.start();
return;
default:
LOG.log(Level.FINER, ">> {0}", mess.toString());
// TODO: do something with messages of other codes
}
}
else
{
LOG.log(Level.FINER, ">> {0}", mess.toString());
}
}
}
|
diff --git a/omod/src/main/java/org/openmrs/module/billing/web/controller/main/BillableServiceBillEditController.java b/omod/src/main/java/org/openmrs/module/billing/web/controller/main/BillableServiceBillEditController.java
index dbb6fcf..cc2e51f 100644
--- a/omod/src/main/java/org/openmrs/module/billing/web/controller/main/BillableServiceBillEditController.java
+++ b/omod/src/main/java/org/openmrs/module/billing/web/controller/main/BillableServiceBillEditController.java
@@ -1,231 +1,236 @@
/**
* Copyright 2009 Society for Health Information Systems Programmes, India (HISP India)
*
* This file is part of Billing module.
*
* Billing module is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Billing module is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Billing module. If not, see <http://www.gnu.org/licenses/>.
*
**/
package org.openmrs.module.billing.web.controller.main;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Concept;
import org.openmrs.Order;
import org.openmrs.Patient;
import org.openmrs.api.context.Context;
import org.openmrs.module.billing.includable.billcalculator.BillCalculatorService;
import org.openmrs.module.hospitalcore.BillingService;
import org.openmrs.module.hospitalcore.model.BillableService;
import org.openmrs.module.hospitalcore.model.PatientServiceBill;
import org.openmrs.module.hospitalcore.model.PatientServiceBillItem;
import org.openmrs.module.hospitalcore.util.HospitalCoreUtils;
import org.openmrs.module.hospitalcore.util.Money;
import org.openmrs.module.hospitalcore.util.PatientUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
*
*/
@Controller
@RequestMapping("/module/billing/editPatientServiceBill.form")
public class BillableServiceBillEditController {
private Log logger = LogFactory.getLog(getClass());
@RequestMapping(method = RequestMethod.GET)
public String viewForm(Model model, @RequestParam("billId") Integer billId,
@RequestParam("patientId") Integer patientId) {
BillingService billingService = Context
.getService(BillingService.class);
List<BillableService> services = billingService.getAllServices();
Map<Integer, BillableService> mapServices = new HashMap<Integer, BillableService>();
for (BillableService ser : services) {
mapServices.put(ser.getConceptId(), ser);
}
Integer conceptId = Integer.valueOf(Context.getAdministrationService()
.getGlobalProperty("billing.rootServiceConceptId"));
Concept concept = Context.getConceptService().getConcept(conceptId);
model.addAttribute("tabs",
billingService.traversTab(concept, mapServices, 1));
model.addAttribute("patientId", patientId);
PatientServiceBill bill = billingService
.getPatientServiceBillById(billId);
model.addAttribute("bill", bill);
return "/module/billing/main/billableServiceBillEdit";
}
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(Model model, Object command,
BindingResult bindingResult, HttpServletRequest request,
@RequestParam("cons") Integer[] cons,
@RequestParam("patientId") Integer patientId,
@RequestParam("billId") Integer billId,
@RequestParam("action") String action,
@RequestParam(value = "description", required = false) String description) {
validate(cons, bindingResult, request);
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "module/billing/main/patientServiceBillEdit";
}
BillingService billingService = Context
.getService(BillingService.class);
PatientServiceBill bill = billingService
.getPatientServiceBillById(billId);
// Get the BillCalculator to calculate the rate of bill item the patient
// has to pay
Patient patient = Context.getPatientService().getPatient(patientId);
Map<String, String> attributes = PatientUtils.getAttributes(patient);
BillCalculatorService calculator = new BillCalculatorService();
if(!"".equals( description ))
bill.setDescription(description);
if ("void".equalsIgnoreCase(action)) {
bill.setVoided(true);
bill.setVoidedDate(new Date());
for (PatientServiceBillItem item : bill.getBillItems()) {
item.setVoided(true);
item.setVoidedDate(new Date());
}
billingService.savePatientServiceBill(bill);
return "redirect:/module/billing/patientServiceBill.list?patientId="
+ patientId;
}
// void old items and reset amount
Map<Integer, PatientServiceBillItem> mapOldItems = new HashMap<Integer, PatientServiceBillItem>();
for (PatientServiceBillItem item : bill.getBillItems()) {
item.setVoided(true);
item.setVoidedDate(new Date());
//ghanshyam-kesav 16-08-2012 Bug #323 [BILLING] When a bill with a lab\radiology order is edited the order is re-sent
Order ord=item.getOrder();
+ /*ghanshyam 18-08-2012 [Billing - Bug #337] [3.2.7 snap shot][billing(DDU,DDU SDMX,Tanda,mohali)]error in edit bill.
+ the problem was while we are editing the bill of other than lab and radiology.
+ */
+ if(ord!=null){
ord.setDateVoided(new Date());
+ }
item.setOrder(ord);
mapOldItems.put(item.getPatientServiceBillItemId(), item);
}
bill.setAmount(BigDecimal.ZERO);
bill.setPrinted(false);
PatientServiceBillItem item;
int quantity = 0;
Money itemAmount;
Money mUnitPrice;
Money totalAmount = new Money(BigDecimal.ZERO);
BigDecimal totalActualAmount = new BigDecimal(0);
BigDecimal unitPrice;
String name;
BillableService service;
for (int conceptId : cons) {
unitPrice = NumberUtils.createBigDecimal(request
.getParameter(conceptId + "_unitPrice"));
quantity = NumberUtils.createInteger(request.getParameter(conceptId
+ "_qty"));
name = request.getParameter(conceptId + "_name");
service = billingService.getServiceByConceptId(conceptId);
mUnitPrice = new Money(unitPrice);
itemAmount = mUnitPrice.times(quantity);
totalAmount = totalAmount.plus(itemAmount);
String sItemId = request.getParameter(conceptId + "_itemId");
if (sItemId == null) {
item = new PatientServiceBillItem();
// Get the ratio for each bill item
Map<String, Object> parameters = HospitalCoreUtils
.buildParameters("patient", patient, "attributes",
attributes, "billItem", item);
BigDecimal rate = calculator.getRate(parameters);
item.setAmount(itemAmount.getAmount());
item.setActualAmount(item.getAmount().multiply(rate));
totalActualAmount = totalActualAmount.add(item
.getActualAmount());
item.setCreatedDate(new Date());
item.setName(name);
item.setPatientServiceBill(bill);
item.setQuantity(quantity);
item.setService(service);
item.setUnitPrice(unitPrice);
bill.addBillItem(item);
} else {
item = mapOldItems.get(Integer.parseInt(sItemId));
// Get the ratio for each bill item
Map<String, Object> parameters = HospitalCoreUtils
.buildParameters("patient", patient, "attributes",
attributes, "billItem", item);
BigDecimal rate = calculator.getRate(parameters);
item.setVoided(false);
item.setVoidedDate(null);
item.setQuantity(quantity);
item.setAmount(itemAmount.getAmount());
item.setActualAmount(item.getAmount().multiply(rate));
totalActualAmount = totalActualAmount.add(item
.getActualAmount());
}
}
bill.setAmount(totalAmount.getAmount());
bill.setActualAmount(totalActualAmount);
// Determine whether the bill is free or not
bill.setFreeBill(calculator.isFreeBill(HospitalCoreUtils
.buildParameters("attributes", attributes)));
logger.info("Is free bill: " + bill.getFreeBill());
bill = billingService.savePatientServiceBill(bill);
return "redirect:/module/billing/patientServiceBill.list?patientId="
+ patientId + "&billId=" + billId;
}
private void validate(Integer[] ids, BindingResult binding,
HttpServletRequest request) {
for (int id : ids) {
try {
Integer.parseInt(request.getParameter(id + "_qty"));
} catch (Exception e) {
binding.reject("billing.bill.quantity.invalid",
"Quantity is invalid");
return;
}
}
}
}
| false | true |
public String onSubmit(Model model, Object command,
BindingResult bindingResult, HttpServletRequest request,
@RequestParam("cons") Integer[] cons,
@RequestParam("patientId") Integer patientId,
@RequestParam("billId") Integer billId,
@RequestParam("action") String action,
@RequestParam(value = "description", required = false) String description) {
validate(cons, bindingResult, request);
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "module/billing/main/patientServiceBillEdit";
}
BillingService billingService = Context
.getService(BillingService.class);
PatientServiceBill bill = billingService
.getPatientServiceBillById(billId);
// Get the BillCalculator to calculate the rate of bill item the patient
// has to pay
Patient patient = Context.getPatientService().getPatient(patientId);
Map<String, String> attributes = PatientUtils.getAttributes(patient);
BillCalculatorService calculator = new BillCalculatorService();
if(!"".equals( description ))
bill.setDescription(description);
if ("void".equalsIgnoreCase(action)) {
bill.setVoided(true);
bill.setVoidedDate(new Date());
for (PatientServiceBillItem item : bill.getBillItems()) {
item.setVoided(true);
item.setVoidedDate(new Date());
}
billingService.savePatientServiceBill(bill);
return "redirect:/module/billing/patientServiceBill.list?patientId="
+ patientId;
}
// void old items and reset amount
Map<Integer, PatientServiceBillItem> mapOldItems = new HashMap<Integer, PatientServiceBillItem>();
for (PatientServiceBillItem item : bill.getBillItems()) {
item.setVoided(true);
item.setVoidedDate(new Date());
//ghanshyam-kesav 16-08-2012 Bug #323 [BILLING] When a bill with a lab\radiology order is edited the order is re-sent
Order ord=item.getOrder();
ord.setDateVoided(new Date());
item.setOrder(ord);
mapOldItems.put(item.getPatientServiceBillItemId(), item);
}
bill.setAmount(BigDecimal.ZERO);
bill.setPrinted(false);
PatientServiceBillItem item;
int quantity = 0;
Money itemAmount;
Money mUnitPrice;
Money totalAmount = new Money(BigDecimal.ZERO);
BigDecimal totalActualAmount = new BigDecimal(0);
BigDecimal unitPrice;
String name;
BillableService service;
for (int conceptId : cons) {
unitPrice = NumberUtils.createBigDecimal(request
.getParameter(conceptId + "_unitPrice"));
quantity = NumberUtils.createInteger(request.getParameter(conceptId
+ "_qty"));
name = request.getParameter(conceptId + "_name");
service = billingService.getServiceByConceptId(conceptId);
mUnitPrice = new Money(unitPrice);
itemAmount = mUnitPrice.times(quantity);
totalAmount = totalAmount.plus(itemAmount);
String sItemId = request.getParameter(conceptId + "_itemId");
if (sItemId == null) {
item = new PatientServiceBillItem();
// Get the ratio for each bill item
Map<String, Object> parameters = HospitalCoreUtils
.buildParameters("patient", patient, "attributes",
attributes, "billItem", item);
BigDecimal rate = calculator.getRate(parameters);
item.setAmount(itemAmount.getAmount());
item.setActualAmount(item.getAmount().multiply(rate));
totalActualAmount = totalActualAmount.add(item
.getActualAmount());
item.setCreatedDate(new Date());
item.setName(name);
item.setPatientServiceBill(bill);
item.setQuantity(quantity);
item.setService(service);
item.setUnitPrice(unitPrice);
bill.addBillItem(item);
} else {
item = mapOldItems.get(Integer.parseInt(sItemId));
// Get the ratio for each bill item
Map<String, Object> parameters = HospitalCoreUtils
.buildParameters("patient", patient, "attributes",
attributes, "billItem", item);
BigDecimal rate = calculator.getRate(parameters);
item.setVoided(false);
item.setVoidedDate(null);
item.setQuantity(quantity);
item.setAmount(itemAmount.getAmount());
item.setActualAmount(item.getAmount().multiply(rate));
totalActualAmount = totalActualAmount.add(item
.getActualAmount());
}
}
bill.setAmount(totalAmount.getAmount());
bill.setActualAmount(totalActualAmount);
// Determine whether the bill is free or not
bill.setFreeBill(calculator.isFreeBill(HospitalCoreUtils
.buildParameters("attributes", attributes)));
logger.info("Is free bill: " + bill.getFreeBill());
bill = billingService.savePatientServiceBill(bill);
return "redirect:/module/billing/patientServiceBill.list?patientId="
+ patientId + "&billId=" + billId;
}
|
public String onSubmit(Model model, Object command,
BindingResult bindingResult, HttpServletRequest request,
@RequestParam("cons") Integer[] cons,
@RequestParam("patientId") Integer patientId,
@RequestParam("billId") Integer billId,
@RequestParam("action") String action,
@RequestParam(value = "description", required = false) String description) {
validate(cons, bindingResult, request);
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "module/billing/main/patientServiceBillEdit";
}
BillingService billingService = Context
.getService(BillingService.class);
PatientServiceBill bill = billingService
.getPatientServiceBillById(billId);
// Get the BillCalculator to calculate the rate of bill item the patient
// has to pay
Patient patient = Context.getPatientService().getPatient(patientId);
Map<String, String> attributes = PatientUtils.getAttributes(patient);
BillCalculatorService calculator = new BillCalculatorService();
if(!"".equals( description ))
bill.setDescription(description);
if ("void".equalsIgnoreCase(action)) {
bill.setVoided(true);
bill.setVoidedDate(new Date());
for (PatientServiceBillItem item : bill.getBillItems()) {
item.setVoided(true);
item.setVoidedDate(new Date());
}
billingService.savePatientServiceBill(bill);
return "redirect:/module/billing/patientServiceBill.list?patientId="
+ patientId;
}
// void old items and reset amount
Map<Integer, PatientServiceBillItem> mapOldItems = new HashMap<Integer, PatientServiceBillItem>();
for (PatientServiceBillItem item : bill.getBillItems()) {
item.setVoided(true);
item.setVoidedDate(new Date());
//ghanshyam-kesav 16-08-2012 Bug #323 [BILLING] When a bill with a lab\radiology order is edited the order is re-sent
Order ord=item.getOrder();
/*ghanshyam 18-08-2012 [Billing - Bug #337] [3.2.7 snap shot][billing(DDU,DDU SDMX,Tanda,mohali)]error in edit bill.
the problem was while we are editing the bill of other than lab and radiology.
*/
if(ord!=null){
ord.setDateVoided(new Date());
}
item.setOrder(ord);
mapOldItems.put(item.getPatientServiceBillItemId(), item);
}
bill.setAmount(BigDecimal.ZERO);
bill.setPrinted(false);
PatientServiceBillItem item;
int quantity = 0;
Money itemAmount;
Money mUnitPrice;
Money totalAmount = new Money(BigDecimal.ZERO);
BigDecimal totalActualAmount = new BigDecimal(0);
BigDecimal unitPrice;
String name;
BillableService service;
for (int conceptId : cons) {
unitPrice = NumberUtils.createBigDecimal(request
.getParameter(conceptId + "_unitPrice"));
quantity = NumberUtils.createInteger(request.getParameter(conceptId
+ "_qty"));
name = request.getParameter(conceptId + "_name");
service = billingService.getServiceByConceptId(conceptId);
mUnitPrice = new Money(unitPrice);
itemAmount = mUnitPrice.times(quantity);
totalAmount = totalAmount.plus(itemAmount);
String sItemId = request.getParameter(conceptId + "_itemId");
if (sItemId == null) {
item = new PatientServiceBillItem();
// Get the ratio for each bill item
Map<String, Object> parameters = HospitalCoreUtils
.buildParameters("patient", patient, "attributes",
attributes, "billItem", item);
BigDecimal rate = calculator.getRate(parameters);
item.setAmount(itemAmount.getAmount());
item.setActualAmount(item.getAmount().multiply(rate));
totalActualAmount = totalActualAmount.add(item
.getActualAmount());
item.setCreatedDate(new Date());
item.setName(name);
item.setPatientServiceBill(bill);
item.setQuantity(quantity);
item.setService(service);
item.setUnitPrice(unitPrice);
bill.addBillItem(item);
} else {
item = mapOldItems.get(Integer.parseInt(sItemId));
// Get the ratio for each bill item
Map<String, Object> parameters = HospitalCoreUtils
.buildParameters("patient", patient, "attributes",
attributes, "billItem", item);
BigDecimal rate = calculator.getRate(parameters);
item.setVoided(false);
item.setVoidedDate(null);
item.setQuantity(quantity);
item.setAmount(itemAmount.getAmount());
item.setActualAmount(item.getAmount().multiply(rate));
totalActualAmount = totalActualAmount.add(item
.getActualAmount());
}
}
bill.setAmount(totalAmount.getAmount());
bill.setActualAmount(totalActualAmount);
// Determine whether the bill is free or not
bill.setFreeBill(calculator.isFreeBill(HospitalCoreUtils
.buildParameters("attributes", attributes)));
logger.info("Is free bill: " + bill.getFreeBill());
bill = billingService.savePatientServiceBill(bill);
return "redirect:/module/billing/patientServiceBill.list?patientId="
+ patientId + "&billId=" + billId;
}
|
diff --git a/util/src/test/java/uk/ac/imperial/presage2/util/location/TestLocation2D.java b/util/src/test/java/uk/ac/imperial/presage2/util/location/TestLocation2D.java
index 091b062..4088114 100644
--- a/util/src/test/java/uk/ac/imperial/presage2/util/location/TestLocation2D.java
+++ b/util/src/test/java/uk/ac/imperial/presage2/util/location/TestLocation2D.java
@@ -1,208 +1,208 @@
/**
* Copyright (C) 2011 Sam Macbeth <sm1106 [at] imperial [dot] ac [dot] uk>
*
* This file is part of Presage2.
*
* Presage2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Presage2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with Presage2. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.ac.imperial.presage2.util.location;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import uk.ac.imperial.presage2.core.util.random.Random;
/**
* @author Sam Macbeth
*
*/
public class TestLocation2D {
/**
* Test creation of a {@link Continuous2DLocation}
*/
@Test
public void testContinuousLocation2D() {
final double x = Random.randomDouble();
final double y = Random.randomDouble();
Location l = new Location(x, y);
assertNotNull(l);
assertEquals(x, l.getX(), 0);
assertEquals(y, l.getY(), 0);
assertSame(l, l.getLocation());
}
@Test
public void testDiscreteLocation2D() {
final int x = Random.randomInt();
final int y = Random.randomInt();
Location l = new Location(x, y);
assertNotNull(l);
assertEquals(x, l.getX(), 0);
assertEquals(y, l.getY(), 0);
assertSame(l, l.getLocation());
}
@Test
@SuppressWarnings("ObjectEqualsNull")
public void testEquals() {
// create actual locations
final double x1 = Random.randomDouble();
final double y1 = Random.randomDouble();
Location l1 = new Location(x1, y1);
final int x2 = Random.randomInt();
final int y2 = Random.randomInt();
Location l2 = new Location(x2, y2);
// test null comparisons
assertFalse(l1.equals(null));
assertFalse(l2.equals(null));
// test same object comparison
assertTrue(l1.equals(l1));
assertTrue(l2.equals(l2));
// test same object comparison with Object cast
assertTrue(l1.equals((Object)l1));
assertTrue(l2.equals((Object)l2));
- assertTrue((Object)(l1).equals(l1));
- assertTrue((Object)(l2).equals(l2));
- assertTrue((Object)(l1).equals((Object)l1));
- assertTrue((Object)(l2).equals((Object)l2));
+ assertTrue(((Object)l1).equals(l1));
+ assertTrue(((Object)l2).equals(l2));
+ assertTrue(((Object)l1).equals((Object)l1));
+ assertTrue(((Object)l2).equals((Object)l2));
// test equal but different object
assertTrue(l1.equals(new Location(x1, y1)));
assertTrue(l1.equals(new Location(x1, y1)));
assertTrue(l2.equals(new Location(x2, y2)));
assertTrue(l2.equals(new Location(x2, y2)));
assertTrue(new Location(x1, y1).equals(l1));
assertTrue(new Location(x2, y2).equals(l2));
// test same type but not equal
assertFalse(l1.equals(new Location(Random.randomDouble(), Random.randomDouble())));
assertFalse(new Location(Random.randomDouble(), Random.randomDouble()).equals(l1));
assertFalse(l2.equals(new Location(Random.randomInt(), Random.randomInt())));
assertFalse(new Location(Random.randomInt(), Random.randomInt()).equals(l2));
// test l1 - l2 comparison
assertFalse(l1.equals(l2));
assertFalse(l2.equals(l1));
}
@Test
public void testContinuousDistanceTo() {
final double x1 = Random.randomDouble();
final double y1 = Random.randomDouble();
final Location l1 = new Location(x1, y1);
final double x2 = Random.randomDouble();
final double y2 = Random.randomDouble();
final Location l2 = new Location(x2, y2);
final double distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
assertEquals(0, l1.distanceTo(l1), 0);
assertEquals(0, l2.distanceTo(l2), 0);
assertEquals(distance, l1.distanceTo(l2), 0);
assertEquals(distance, l2.distanceTo(l1), 0);
}
@Test
public void testDiscreteDistanceTo() {
final int x1 = Random.randomInt(100);
final int y1 = Random.randomInt(100);
final Location l1 = new Location(x1, y1);
final int x2 = Random.randomInt(100);
final int y2 = Random.randomInt(100);
final Location l2 = new Location(x2, y2);
final double distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
assertEquals(0, l1.distanceTo(l1), 0);
assertEquals(0, l2.distanceTo(l2), 0);
assertEquals(distance, l1.distanceTo(l2), 0);
assertEquals(distance, l2.distanceTo(l1), 0);
assertEquals(distance, l1.distanceTo(l2), 0);
assertEquals(distance, l2.distanceTo(l1), 0);
}
@Test
public void testDiscreteGetMoveTo() {
final int x = Random.randomInt();
final int y = Random.randomInt();
final Location l1 = new Location(x, y);
final int dx = Random.randomInt(10) - 5;
final int dy = Random.randomInt(10) - 5;
final Location l2 = new Location(x + dx, y + dy);
final Move m = l1.getMoveTo(l2);
assertEquals(dx, m.getX(), 0);
assertEquals(dy, m.getY(), 0);
}
@Test
public void testContinuousGetMoveTo() {
final double x = Random.randomDouble() * Random.randomInt();
final double y = Random.randomDouble() * Random.randomInt();
final Location l1 = new Location(x, y);
final double dx = Random.randomDouble() * Random.randomInt();
final double dy = Random.randomDouble() * Random.randomInt();
final Location l2 = new Location(x + dx, y + dy);
final Move m = l1.getMoveTo(l2);
assertEquals(dx, m.getX(), 0.000001);
assertEquals(dy, m.getY(), 0.000001);
}
@Test
public void testDiscreteGetMoveToWithSpeed() {
final int x = Random.randomInt();
final int y = Random.randomInt();
final Location l1 = new Location(x, y);
final int dx = Random.randomInt(10) - 5;
final int dy = Random.randomInt(10) - 5;
final Location l2 = new Location(x + dx, y + dy);
final double highSpeed = Math.sqrt(dx * dx + dy * dy) + Random.randomInt(5);
final Move m1 = l1.getMoveTo(l2, highSpeed);
assertEquals(dx, m1.getX(), 0);
assertEquals(dy, m1.getY(), 0);
final double lowSpeed = Math.sqrt(dx * dx + dy * dy)
- Random.randomInt((int) Math.max(Math.floor(Math.sqrt(dx * dx + dy * dy)), 1));
final Move m2 = l1.getMoveTo(l2, lowSpeed);
assertEquals(lowSpeed, m2.getNorm(), 0.0001);
assertEquals(0, Location.angle(m1, m2), 0);
}
}
| true | true |
public void testEquals() {
// create actual locations
final double x1 = Random.randomDouble();
final double y1 = Random.randomDouble();
Location l1 = new Location(x1, y1);
final int x2 = Random.randomInt();
final int y2 = Random.randomInt();
Location l2 = new Location(x2, y2);
// test null comparisons
assertFalse(l1.equals(null));
assertFalse(l2.equals(null));
// test same object comparison
assertTrue(l1.equals(l1));
assertTrue(l2.equals(l2));
// test same object comparison with Object cast
assertTrue(l1.equals((Object)l1));
assertTrue(l2.equals((Object)l2));
assertTrue((Object)(l1).equals(l1));
assertTrue((Object)(l2).equals(l2));
assertTrue((Object)(l1).equals((Object)l1));
assertTrue((Object)(l2).equals((Object)l2));
// test equal but different object
assertTrue(l1.equals(new Location(x1, y1)));
assertTrue(l1.equals(new Location(x1, y1)));
assertTrue(l2.equals(new Location(x2, y2)));
assertTrue(l2.equals(new Location(x2, y2)));
assertTrue(new Location(x1, y1).equals(l1));
assertTrue(new Location(x2, y2).equals(l2));
// test same type but not equal
assertFalse(l1.equals(new Location(Random.randomDouble(), Random.randomDouble())));
assertFalse(new Location(Random.randomDouble(), Random.randomDouble()).equals(l1));
assertFalse(l2.equals(new Location(Random.randomInt(), Random.randomInt())));
assertFalse(new Location(Random.randomInt(), Random.randomInt()).equals(l2));
// test l1 - l2 comparison
assertFalse(l1.equals(l2));
assertFalse(l2.equals(l1));
}
|
public void testEquals() {
// create actual locations
final double x1 = Random.randomDouble();
final double y1 = Random.randomDouble();
Location l1 = new Location(x1, y1);
final int x2 = Random.randomInt();
final int y2 = Random.randomInt();
Location l2 = new Location(x2, y2);
// test null comparisons
assertFalse(l1.equals(null));
assertFalse(l2.equals(null));
// test same object comparison
assertTrue(l1.equals(l1));
assertTrue(l2.equals(l2));
// test same object comparison with Object cast
assertTrue(l1.equals((Object)l1));
assertTrue(l2.equals((Object)l2));
assertTrue(((Object)l1).equals(l1));
assertTrue(((Object)l2).equals(l2));
assertTrue(((Object)l1).equals((Object)l1));
assertTrue(((Object)l2).equals((Object)l2));
// test equal but different object
assertTrue(l1.equals(new Location(x1, y1)));
assertTrue(l1.equals(new Location(x1, y1)));
assertTrue(l2.equals(new Location(x2, y2)));
assertTrue(l2.equals(new Location(x2, y2)));
assertTrue(new Location(x1, y1).equals(l1));
assertTrue(new Location(x2, y2).equals(l2));
// test same type but not equal
assertFalse(l1.equals(new Location(Random.randomDouble(), Random.randomDouble())));
assertFalse(new Location(Random.randomDouble(), Random.randomDouble()).equals(l1));
assertFalse(l2.equals(new Location(Random.randomInt(), Random.randomInt())));
assertFalse(new Location(Random.randomInt(), Random.randomInt()).equals(l2));
// test l1 - l2 comparison
assertFalse(l1.equals(l2));
assertFalse(l2.equals(l1));
}
|
diff --git a/branches/last-2.x/Crux/src/br/com/sysmap/crux/core/rebind/screen/config/WidgetConfig.java b/branches/last-2.x/Crux/src/br/com/sysmap/crux/core/rebind/screen/config/WidgetConfig.java
index 7ae79548d..a213818db 100644
--- a/branches/last-2.x/Crux/src/br/com/sysmap/crux/core/rebind/screen/config/WidgetConfig.java
+++ b/branches/last-2.x/Crux/src/br/com/sysmap/crux/core/rebind/screen/config/WidgetConfig.java
@@ -1,187 +1,190 @@
/*
* Copyright 2009 Sysmap Solutions Software e Consultoria Ltda.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package br.com.sysmap.crux.core.rebind.screen.config;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import br.com.sysmap.crux.core.client.screen.WidgetFactory;
import br.com.sysmap.crux.core.i18n.MessagesFactory;
import br.com.sysmap.crux.core.server.ServerMessages;
import br.com.sysmap.crux.core.server.scan.ClassScanner;
/**
*
* @author Thiago da Rosa de Bustamante
*
*/
public class WidgetConfig
{
private static Map<String, Class<? extends WidgetFactory<?>>> config = null;
private static Map<String, String> widgets = null;
private static Map<String, Set<String>> registeredLibraries = null;
private static ServerMessages messages = (ServerMessages)MessagesFactory.getMessages(ServerMessages.class);
private static final Log logger = LogFactory.getLog(WidgetConfig.class);
private static final Lock lock = new ReentrantLock();
/**
*
*/
public static void initialize()
{
if (config != null)
{
return;
}
try
{
lock.lock();
if (config != null)
{
return;
}
initializeWidgetConfig();
}
finally
{
lock.unlock();
}
}
@SuppressWarnings("unchecked")
protected static void initializeWidgetConfig()
{
config = new HashMap<String, Class<? extends WidgetFactory<?>>>(100);
widgets = new HashMap<String, String>();
registeredLibraries = new HashMap<String, Set<String>>();
Set<String> factoriesNames = ClassScanner.searchClassesByAnnotation(br.com.sysmap.crux.core.client.declarative.DeclarativeFactory.class);
if (factoriesNames != null)
{
for (String name : factoriesNames)
{
try
{
Class<? extends WidgetFactory<?>> factoryClass = (Class<? extends WidgetFactory<?>>)Class.forName(name);
br.com.sysmap.crux.core.client.declarative.DeclarativeFactory annot =
factoryClass.getAnnotation(br.com.sysmap.crux.core.client.declarative.DeclarativeFactory.class);
if (!registeredLibraries.containsKey(annot.library()))
{
registeredLibraries.put(annot.library(), new HashSet<String>());
}
registeredLibraries.get(annot.library()).add(annot.id());
String widgetType = annot.library() + "_" + annot.id();
config.put(widgetType, factoryClass);
Type type = ((ParameterizedType)factoryClass.getGenericSuperclass()).getActualTypeArguments()[0];
if (type instanceof ParameterizedType)
{
Type rawType = ((ParameterizedType) type).getRawType();
if (rawType instanceof Class)
{
widgets.put(((Class<?>)rawType).getCanonicalName(), widgetType);
}
}
- widgets.put(((Class<?>)type).getCanonicalName(), widgetType);
+ if (type instanceof Class)
+ {
+ widgets.put(((Class<?>)type).getCanonicalName(), widgetType);
+ }
}
catch (ClassNotFoundException e)
{
throw new WidgetConfigException(messages.widgetConfigInitializeError(e.getLocalizedMessage()),e);
}
}
}
if (logger.isInfoEnabled())
{
logger.info(messages.widgetCongigWidgetsRegistered());
}
}
/**
*
* @param id
* @return
*/
public static Class<? extends WidgetFactory<?>> getClientClass(String id)
{
if (config == null)
{
initializeWidgetConfig();
}
return config.get(id);
}
/**
*
* @param library
* @param id
* @return
*/
public static Class<? extends WidgetFactory<?>> getClientClass(String library, String id)
{
if (config == null)
{
initializeWidgetConfig();
}
return config.get(library+"_"+id);
}
/**
*
* @return
*/
public static Set<String> getRegisteredLibraries()
{
if (registeredLibraries == null)
{
initializeWidgetConfig();
}
return registeredLibraries.keySet();
}
/**
*
* @param library
* @return
*/
public static Set<String> getRegisteredLibraryFactories(String library)
{
if (registeredLibraries == null)
{
initializeWidgetConfig();
}
return registeredLibraries.get(library);
}
public static String getWidgetType(Class<?> widgetClass)
{
if (widgets == null)
{
initializeWidgetConfig();
}
return widgets.get(widgetClass.getCanonicalName());
}
}
| true | true |
protected static void initializeWidgetConfig()
{
config = new HashMap<String, Class<? extends WidgetFactory<?>>>(100);
widgets = new HashMap<String, String>();
registeredLibraries = new HashMap<String, Set<String>>();
Set<String> factoriesNames = ClassScanner.searchClassesByAnnotation(br.com.sysmap.crux.core.client.declarative.DeclarativeFactory.class);
if (factoriesNames != null)
{
for (String name : factoriesNames)
{
try
{
Class<? extends WidgetFactory<?>> factoryClass = (Class<? extends WidgetFactory<?>>)Class.forName(name);
br.com.sysmap.crux.core.client.declarative.DeclarativeFactory annot =
factoryClass.getAnnotation(br.com.sysmap.crux.core.client.declarative.DeclarativeFactory.class);
if (!registeredLibraries.containsKey(annot.library()))
{
registeredLibraries.put(annot.library(), new HashSet<String>());
}
registeredLibraries.get(annot.library()).add(annot.id());
String widgetType = annot.library() + "_" + annot.id();
config.put(widgetType, factoryClass);
Type type = ((ParameterizedType)factoryClass.getGenericSuperclass()).getActualTypeArguments()[0];
if (type instanceof ParameterizedType)
{
Type rawType = ((ParameterizedType) type).getRawType();
if (rawType instanceof Class)
{
widgets.put(((Class<?>)rawType).getCanonicalName(), widgetType);
}
}
widgets.put(((Class<?>)type).getCanonicalName(), widgetType);
}
catch (ClassNotFoundException e)
{
throw new WidgetConfigException(messages.widgetConfigInitializeError(e.getLocalizedMessage()),e);
}
}
}
if (logger.isInfoEnabled())
{
logger.info(messages.widgetCongigWidgetsRegistered());
}
}
|
protected static void initializeWidgetConfig()
{
config = new HashMap<String, Class<? extends WidgetFactory<?>>>(100);
widgets = new HashMap<String, String>();
registeredLibraries = new HashMap<String, Set<String>>();
Set<String> factoriesNames = ClassScanner.searchClassesByAnnotation(br.com.sysmap.crux.core.client.declarative.DeclarativeFactory.class);
if (factoriesNames != null)
{
for (String name : factoriesNames)
{
try
{
Class<? extends WidgetFactory<?>> factoryClass = (Class<? extends WidgetFactory<?>>)Class.forName(name);
br.com.sysmap.crux.core.client.declarative.DeclarativeFactory annot =
factoryClass.getAnnotation(br.com.sysmap.crux.core.client.declarative.DeclarativeFactory.class);
if (!registeredLibraries.containsKey(annot.library()))
{
registeredLibraries.put(annot.library(), new HashSet<String>());
}
registeredLibraries.get(annot.library()).add(annot.id());
String widgetType = annot.library() + "_" + annot.id();
config.put(widgetType, factoryClass);
Type type = ((ParameterizedType)factoryClass.getGenericSuperclass()).getActualTypeArguments()[0];
if (type instanceof ParameterizedType)
{
Type rawType = ((ParameterizedType) type).getRawType();
if (rawType instanceof Class)
{
widgets.put(((Class<?>)rawType).getCanonicalName(), widgetType);
}
}
if (type instanceof Class)
{
widgets.put(((Class<?>)type).getCanonicalName(), widgetType);
}
}
catch (ClassNotFoundException e)
{
throw new WidgetConfigException(messages.widgetConfigInitializeError(e.getLocalizedMessage()),e);
}
}
}
if (logger.isInfoEnabled())
{
logger.info(messages.widgetCongigWidgetsRegistered());
}
}
|
diff --git a/src/net/sickill/off/OffPanel.java b/src/net/sickill/off/OffPanel.java
index 705d2d9..3ec9049 100644
--- a/src/net/sickill/off/OffPanel.java
+++ b/src/net/sickill/off/OffPanel.java
@@ -1,212 +1,213 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.sickill.off;
import net.sickill.off.netbeans.ProjectItem;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
import net.sickill.off.netbeans.NetbeansProject;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ui.OpenProjects;
/**
*
* @author kill
*/
public class OffPanel extends JPanel implements ItemListener {
// UI
private OffTextField patternInput;
private OffList resultsList;
private OffListModel listModel;
private JLabel statusBar;
private JComboBox projectChooser;
// providers
private ActionsProvider actionsProvider;
private Settings settings;
private AbstractProject project;
private Timer timer;
public OffPanel(Settings s, AbstractProject p) {
this.settings = s;
this.project = p;
build();
}
void setIndexing(boolean indexing) {
if (indexing) {
patternInput.setEnabled(false);
statusBar.setText("Indexing project files, please wait...");
} else {
patternInput.setEnabled(true);
statusBar.setText("Indexing finished");
}
}
private void build() {
setLayout(new BorderLayout());
setBorder(new EmptyBorder(5, 5, 5, 5));
patternInput = new OffTextField(this);
// Below steps are used to receive notifications of the
// KeyStrokes we are interested in unlike
// ActionListener/KeyListener
// which is fired irrespective of the kind of KeyStroke.
JPanel pnlNorth = new JPanel(new BorderLayout());
URL url = OffPanel.class.getResource("search.png");
JLabel searchIcon = new JLabel(new ImageIcon(url));
pnlNorth.add(searchIcon, BorderLayout.WEST);
pnlNorth.add(patternInput, BorderLayout.CENTER);
add(pnlNorth, BorderLayout.NORTH);
// status bar
JPanel pnlSouth = new JPanel(new BorderLayout());
statusBar = new JLabel(" ");
- pnlSouth.add(statusBar, BorderLayout.EAST);
+ pnlSouth.add(statusBar, BorderLayout.SOUTH);
add(pnlSouth, BorderLayout.SOUTH);
listModel = new OffListModel(settings, this);
project.init(listModel);
resultsList = new OffList(this, listModel);
JScrollPane scroller = new JScrollPane(resultsList);
add(scroller, BorderLayout.CENTER);
+ pnlSouth.add(new JLabel("Project "), BorderLayout.WEST);
// projects combo
projectChooser = new JComboBox();
- add(projectChooser, BorderLayout.SOUTH);
+ pnlSouth.add(projectChooser, BorderLayout.CENTER);
projectChooser.addItemListener(this);
// Add escape-key event handling to widgets
KeyHandler keyHandler = new KeyHandler();
addKeyListener(keyHandler);
patternInput.addKeyListener(keyHandler);
resultsList.addKeyListener(keyHandler);
}
public void setActionsProvider(ActionsProvider ap) {
this.actionsProvider = ap;
}
private void closeMainWindow() {
actionsProvider.closeWindow();
}
public OffList getResultsList() {
return resultsList;
}
public void openSelected() {
// For enter keys pressed inside txtfilename
closeMainWindow();
for (Object o : resultsList.getSelectedValues()) {
// int lineNo = getLineNumber();
ProjectFile pf = ((OffListElement)o).getFile();
listModel.incrementAccessCounter(pf);
actionsProvider.openFile(pf);
}
}
void startSearching() {
if (timer == null) {
timer = new Timer((int)(settings.getSearchDelay() * 1000.0), new SearchAction());
timer.setRepeats(false);
timer.start();
} else {
timer.restart();
}
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
NetbeansProject.getInstance().setSelectedProject(((ProjectItem)e.getItem()).getProject());
patternInput.requestFocus();
}
}
public void focusOnDefaultComponent() {
Project selected = NetbeansProject.getInstance().getSelectedProject();
projectChooser.removeAllItems();
projectChooser.removeItemListener(this);
for (Project p : OpenProjects.getDefault().getOpenProjects()) {
ProjectItem item = new ProjectItem(p);
projectChooser.addItem(item);
if (selected == p) {
projectChooser.setSelectedItem(item);
}
}
projectChooser.addItemListener(this);
if (settings.isClearOnOpen()) {
patternInput.setText("");
} else {
patternInput.selectAll();
patternInput.requestFocus();
}
}
private String getFilePattern() {
String[] parts = patternInput.getText().split(":", 2);
return parts[0];
}
private int getLineNumber() {
String[] parts = patternInput.getText().split(":", 2);
int lineNo;
try {
lineNo = parts.length > 1 ? Integer.parseInt(parts[1]) : -1;
} catch (NumberFormatException e) {
lineNo = -1;
}
return lineNo;
}
private void search() {
if (listModel.setFilter(getFilePattern())) {
patternInput.setSearchSuccess(true);
resultsList.setSelectedIndex(0);
} else {
patternInput.setSearchSuccess(false);
}
statusBar.setText("Found " + listModel.getSize() + " files");
}
class SearchAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
search();
timer = null;
}
}
class KeyHandler extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
closeMainWindow();
evt.consume();
}
}
}
}
| false | true |
private void build() {
setLayout(new BorderLayout());
setBorder(new EmptyBorder(5, 5, 5, 5));
patternInput = new OffTextField(this);
// Below steps are used to receive notifications of the
// KeyStrokes we are interested in unlike
// ActionListener/KeyListener
// which is fired irrespective of the kind of KeyStroke.
JPanel pnlNorth = new JPanel(new BorderLayout());
URL url = OffPanel.class.getResource("search.png");
JLabel searchIcon = new JLabel(new ImageIcon(url));
pnlNorth.add(searchIcon, BorderLayout.WEST);
pnlNorth.add(patternInput, BorderLayout.CENTER);
add(pnlNorth, BorderLayout.NORTH);
// status bar
JPanel pnlSouth = new JPanel(new BorderLayout());
statusBar = new JLabel(" ");
pnlSouth.add(statusBar, BorderLayout.EAST);
add(pnlSouth, BorderLayout.SOUTH);
listModel = new OffListModel(settings, this);
project.init(listModel);
resultsList = new OffList(this, listModel);
JScrollPane scroller = new JScrollPane(resultsList);
add(scroller, BorderLayout.CENTER);
// projects combo
projectChooser = new JComboBox();
add(projectChooser, BorderLayout.SOUTH);
projectChooser.addItemListener(this);
// Add escape-key event handling to widgets
KeyHandler keyHandler = new KeyHandler();
addKeyListener(keyHandler);
patternInput.addKeyListener(keyHandler);
resultsList.addKeyListener(keyHandler);
}
|
private void build() {
setLayout(new BorderLayout());
setBorder(new EmptyBorder(5, 5, 5, 5));
patternInput = new OffTextField(this);
// Below steps are used to receive notifications of the
// KeyStrokes we are interested in unlike
// ActionListener/KeyListener
// which is fired irrespective of the kind of KeyStroke.
JPanel pnlNorth = new JPanel(new BorderLayout());
URL url = OffPanel.class.getResource("search.png");
JLabel searchIcon = new JLabel(new ImageIcon(url));
pnlNorth.add(searchIcon, BorderLayout.WEST);
pnlNorth.add(patternInput, BorderLayout.CENTER);
add(pnlNorth, BorderLayout.NORTH);
// status bar
JPanel pnlSouth = new JPanel(new BorderLayout());
statusBar = new JLabel(" ");
pnlSouth.add(statusBar, BorderLayout.SOUTH);
add(pnlSouth, BorderLayout.SOUTH);
listModel = new OffListModel(settings, this);
project.init(listModel);
resultsList = new OffList(this, listModel);
JScrollPane scroller = new JScrollPane(resultsList);
add(scroller, BorderLayout.CENTER);
pnlSouth.add(new JLabel("Project "), BorderLayout.WEST);
// projects combo
projectChooser = new JComboBox();
pnlSouth.add(projectChooser, BorderLayout.CENTER);
projectChooser.addItemListener(this);
// Add escape-key event handling to widgets
KeyHandler keyHandler = new KeyHandler();
addKeyListener(keyHandler);
patternInput.addKeyListener(keyHandler);
resultsList.addKeyListener(keyHandler);
}
|
diff --git a/src/main/java/uk/ac/ebi/ae15/servlets/DownloadServlet.java b/src/main/java/uk/ac/ebi/ae15/servlets/DownloadServlet.java
index 1e457e2d..580e4c17 100644
--- a/src/main/java/uk/ac/ebi/ae15/servlets/DownloadServlet.java
+++ b/src/main/java/uk/ac/ebi/ae15/servlets/DownloadServlet.java
@@ -1,117 +1,117 @@
package uk.ac.ebi.ae15.servlets;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import uk.ac.ebi.ae15.app.ApplicationServlet;
import uk.ac.ebi.ae15.components.DownloadableFilesRegistry;
import uk.ac.ebi.ae15.components.Experiments;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DownloadServlet extends ApplicationServlet
{
// logging machinery
private final Log log = LogFactory.getLog(getClass());
// buffer size
private final int TRANSFER_BUFFER_SIZE = 8 * 1024 * 1024;
// Respond to HTTP GET requests from browsers.
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
log.debug(
new StringBuilder("Processing request: ")
.append(request.getRequestURL())
.append("?")
.append(request.getQueryString())
);
Pattern p = Pattern.compile("/([^/]+)$");
Matcher m = p.matcher(request.getRequestURL());
String filename;
try {
if (m.find()) {
filename = m.group(1);
sendFile(filename, response);
} else {
log.error("Unable to get a filename from [" + request.getRequestURL() + "]");
throw (new Exception());
}
} catch ( Throwable x ) {
String name = x.getClass().getName();
if (name.equals("org.apache.catalina.connector.ClientAbortException")) {
// generate log entry for client abortion
log.warn("Download aborted");
} else {
log.debug("Caught an exception:", x);
if (!response.isCommitted())
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
}
private void sendFile( String filename, HttpServletResponse response ) throws IOException
{
log.info("Requested download of [" + filename + "]");
DownloadableFilesRegistry filesRegistry = (DownloadableFilesRegistry) getComponent("DownloadableFilesRegistry");
Experiments experiments = (Experiments) getComponent("Experiments");
if (!filesRegistry.doesExist(filename)) {
log.error("File [" + filename + "] is not in files registry");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
String fileLocation = filesRegistry.getLocation(filename);
String contentType = getServletContext().getMimeType(fileLocation);
if (null != contentType) {
log.debug("Setting content type to [" + contentType + "]");
response.setContentType(contentType);
} else {
log.warn("Download servlet was unable to determine content type for [" + fileLocation + "]");
}
log.debug("Checking file [" + fileLocation + "]");
File file = new File(fileLocation);
if (!file.exists()) {
log.error("File [" + fileLocation + "] does not exist");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else if (!experiments.isFilePublic(fileLocation)) {
log.error("Attempting to download file for the experiment that is not present in the index");
response.sendError(HttpServletResponse.SC_FORBIDDEN);
} else {
FileInputStream fileInputStream = null;
ServletOutputStream servletOutStream = null;
try {
fileInputStream = new FileInputStream(file);
int size = fileInputStream.available();
response.setContentLength(size);
servletOutStream = response.getOutputStream();
int bytesRead;
byte[] buffer = new byte[TRANSFER_BUFFER_SIZE];
while ( true ) {
bytesRead = fileInputStream.read(buffer, 0, TRANSFER_BUFFER_SIZE);
if (bytesRead == -1) break;
servletOutStream.write(buffer, 0, bytesRead);
servletOutStream.flush();
- log.info("Download of [" + filename + "] completed, sent [" + size + "] bytes");
}
+ log.info("Download of [" + filename + "] completed, sent [" + size + "] bytes");
} finally {
if (null != fileInputStream)
fileInputStream.close();
if (null != servletOutStream)
servletOutStream.close();
}
}
}
}
}
| false | true |
private void sendFile( String filename, HttpServletResponse response ) throws IOException
{
log.info("Requested download of [" + filename + "]");
DownloadableFilesRegistry filesRegistry = (DownloadableFilesRegistry) getComponent("DownloadableFilesRegistry");
Experiments experiments = (Experiments) getComponent("Experiments");
if (!filesRegistry.doesExist(filename)) {
log.error("File [" + filename + "] is not in files registry");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
String fileLocation = filesRegistry.getLocation(filename);
String contentType = getServletContext().getMimeType(fileLocation);
if (null != contentType) {
log.debug("Setting content type to [" + contentType + "]");
response.setContentType(contentType);
} else {
log.warn("Download servlet was unable to determine content type for [" + fileLocation + "]");
}
log.debug("Checking file [" + fileLocation + "]");
File file = new File(fileLocation);
if (!file.exists()) {
log.error("File [" + fileLocation + "] does not exist");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else if (!experiments.isFilePublic(fileLocation)) {
log.error("Attempting to download file for the experiment that is not present in the index");
response.sendError(HttpServletResponse.SC_FORBIDDEN);
} else {
FileInputStream fileInputStream = null;
ServletOutputStream servletOutStream = null;
try {
fileInputStream = new FileInputStream(file);
int size = fileInputStream.available();
response.setContentLength(size);
servletOutStream = response.getOutputStream();
int bytesRead;
byte[] buffer = new byte[TRANSFER_BUFFER_SIZE];
while ( true ) {
bytesRead = fileInputStream.read(buffer, 0, TRANSFER_BUFFER_SIZE);
if (bytesRead == -1) break;
servletOutStream.write(buffer, 0, bytesRead);
servletOutStream.flush();
log.info("Download of [" + filename + "] completed, sent [" + size + "] bytes");
}
} finally {
if (null != fileInputStream)
fileInputStream.close();
if (null != servletOutStream)
servletOutStream.close();
}
}
}
}
|
private void sendFile( String filename, HttpServletResponse response ) throws IOException
{
log.info("Requested download of [" + filename + "]");
DownloadableFilesRegistry filesRegistry = (DownloadableFilesRegistry) getComponent("DownloadableFilesRegistry");
Experiments experiments = (Experiments) getComponent("Experiments");
if (!filesRegistry.doesExist(filename)) {
log.error("File [" + filename + "] is not in files registry");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
String fileLocation = filesRegistry.getLocation(filename);
String contentType = getServletContext().getMimeType(fileLocation);
if (null != contentType) {
log.debug("Setting content type to [" + contentType + "]");
response.setContentType(contentType);
} else {
log.warn("Download servlet was unable to determine content type for [" + fileLocation + "]");
}
log.debug("Checking file [" + fileLocation + "]");
File file = new File(fileLocation);
if (!file.exists()) {
log.error("File [" + fileLocation + "] does not exist");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else if (!experiments.isFilePublic(fileLocation)) {
log.error("Attempting to download file for the experiment that is not present in the index");
response.sendError(HttpServletResponse.SC_FORBIDDEN);
} else {
FileInputStream fileInputStream = null;
ServletOutputStream servletOutStream = null;
try {
fileInputStream = new FileInputStream(file);
int size = fileInputStream.available();
response.setContentLength(size);
servletOutStream = response.getOutputStream();
int bytesRead;
byte[] buffer = new byte[TRANSFER_BUFFER_SIZE];
while ( true ) {
bytesRead = fileInputStream.read(buffer, 0, TRANSFER_BUFFER_SIZE);
if (bytesRead == -1) break;
servletOutStream.write(buffer, 0, bytesRead);
servletOutStream.flush();
}
log.info("Download of [" + filename + "] completed, sent [" + size + "] bytes");
} finally {
if (null != fileInputStream)
fileInputStream.close();
if (null != servletOutStream)
servletOutStream.close();
}
}
}
}
|
diff --git a/org.eclipse.xtext.xdoc.ui/src/org/eclipse/xtext/xdoc/ui/builder/XdocBuilderParticipant.java b/org.eclipse.xtext.xdoc.ui/src/org/eclipse/xtext/xdoc/ui/builder/XdocBuilderParticipant.java
index 5dd602c..f0f535e 100644
--- a/org.eclipse.xtext.xdoc.ui/src/org/eclipse/xtext/xdoc/ui/builder/XdocBuilderParticipant.java
+++ b/org.eclipse.xtext.xdoc.ui/src/org/eclipse/xtext/xdoc/ui/builder/XdocBuilderParticipant.java
@@ -1,112 +1,114 @@
package org.eclipse.xtext.xdoc.ui.builder;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xpand2.XpandExecutionContextImpl;
import org.eclipse.xpand2.XpandFacade;
import org.eclipse.xpand2.output.FileHandle;
import org.eclipse.xpand2.output.Outlet;
import org.eclipse.xpand2.output.OutputImpl;
import org.eclipse.xpand2.output.VetoException;
import org.eclipse.xtend.expression.Variable;
import org.eclipse.xtend.type.impl.java.JavaBeansMetaModel;
import org.eclipse.xtext.builder.IXtextBuilderParticipant;
import org.eclipse.xtext.resource.IResourceDescription;
import org.eclipse.xtext.util.Wrapper;
public class XdocBuilderParticipant implements IXtextBuilderParticipant {
private final Logger logger = Logger.getLogger(this.getClass());
public void build(final IBuildContext context, IProgressMonitor monitor)
throws CoreException {
final Wrapper<IFolder> folder = Wrapper.wrap(null);
OutputImpl output = new OutputImpl();
Outlet outlet = new Outlet() {
@Override
public FileHandle createFileHandle(String fileName)
throws VetoException {
IFile file = folder.get().getFile(new Path(fileName));
return new EclipseBasedFileHandle(file, this);
}
};
output.addOutlet(outlet);
Map<String, Variable> globalVars = new HashMap<String, Variable>();
// FIXME resource loading
XpandExecutionContextImpl ctx = new XpandExecutionContextImpl(output,
null, null, null, null);
ctx.registerMetaModel(new JavaBeansMetaModel());
String projectName = context.getBuiltProject().getName();
for (IResourceDescription.Delta delta : context.getDeltas()) {
// handle deletion
String projectSegment = delta.getUri().segment(1);
if (projectName.equals(projectSegment)) {
if (delta.getUri().fileExtension().equals("xdoc")) {
IFolder contentsFolder = context.getBuiltProject().getFolder("contents");
if (folder.get() == null) {
if (!contentsFolder.exists())
contentsFolder.create(true, true, monitor);
folder.set(contentsFolder);
}
if (delta.getNew() == null) {
IFile file = folder.get().getFile(delta.getUri().lastSegment()+".html");
if (file.exists())
file.delete(true, monitor);
} else {
Resource resource = context.getResourceSet().getResource(
delta.getUri(), true);
EObject object = resource.getContents().get(0);
// set directories for CopyUtil to be able to copy referenced images
String baseDir = context.getBuiltProject().getLocation() + File.separator +
concatSegments(2, delta.getUri().segmentCount() - 1, delta.getUri());
Variable var = new Variable("srcDir", baseDir);
globalVars.put("srcDir", var);
var = new Variable("dir", contentsFolder.getLocation().toString());
globalVars.put("dir", var);
ctx.getGlobalVariables().putAll(globalVars);
generate(object, ctx, context);
}
}
}
}
if(context.getBuildType().equals(BuildType.CLEAN)) {
- IFile file = folder.get().getFile("toc.xml");
- if (file.exists())
- file.delete(true, monitor);
+ if (folder.get() != null) {
+ IFile file = folder.get().getFile("toc.xml");
+ if (file.exists())
+ file.delete(true, monitor);
+ }
}
}
private String concatSegments(int i, int segmentCount, URI uri) {
StringBuilder sb = new StringBuilder();
for(; i < segmentCount; i++){
sb.append(uri.segment(i));
sb.append(File.separatorChar);
}
return sb.toString();
}
protected void generate(EObject eObject, XpandExecutionContextImpl ctx,
IBuildContext context) {
try {
XpandFacade.create(ctx).evaluate(
"templates::eclipsehelp::Main::main", eObject);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
}
| true | true |
public void build(final IBuildContext context, IProgressMonitor monitor)
throws CoreException {
final Wrapper<IFolder> folder = Wrapper.wrap(null);
OutputImpl output = new OutputImpl();
Outlet outlet = new Outlet() {
@Override
public FileHandle createFileHandle(String fileName)
throws VetoException {
IFile file = folder.get().getFile(new Path(fileName));
return new EclipseBasedFileHandle(file, this);
}
};
output.addOutlet(outlet);
Map<String, Variable> globalVars = new HashMap<String, Variable>();
// FIXME resource loading
XpandExecutionContextImpl ctx = new XpandExecutionContextImpl(output,
null, null, null, null);
ctx.registerMetaModel(new JavaBeansMetaModel());
String projectName = context.getBuiltProject().getName();
for (IResourceDescription.Delta delta : context.getDeltas()) {
// handle deletion
String projectSegment = delta.getUri().segment(1);
if (projectName.equals(projectSegment)) {
if (delta.getUri().fileExtension().equals("xdoc")) {
IFolder contentsFolder = context.getBuiltProject().getFolder("contents");
if (folder.get() == null) {
if (!contentsFolder.exists())
contentsFolder.create(true, true, monitor);
folder.set(contentsFolder);
}
if (delta.getNew() == null) {
IFile file = folder.get().getFile(delta.getUri().lastSegment()+".html");
if (file.exists())
file.delete(true, monitor);
} else {
Resource resource = context.getResourceSet().getResource(
delta.getUri(), true);
EObject object = resource.getContents().get(0);
// set directories for CopyUtil to be able to copy referenced images
String baseDir = context.getBuiltProject().getLocation() + File.separator +
concatSegments(2, delta.getUri().segmentCount() - 1, delta.getUri());
Variable var = new Variable("srcDir", baseDir);
globalVars.put("srcDir", var);
var = new Variable("dir", contentsFolder.getLocation().toString());
globalVars.put("dir", var);
ctx.getGlobalVariables().putAll(globalVars);
generate(object, ctx, context);
}
}
}
}
if(context.getBuildType().equals(BuildType.CLEAN)) {
IFile file = folder.get().getFile("toc.xml");
if (file.exists())
file.delete(true, monitor);
}
}
|
public void build(final IBuildContext context, IProgressMonitor monitor)
throws CoreException {
final Wrapper<IFolder> folder = Wrapper.wrap(null);
OutputImpl output = new OutputImpl();
Outlet outlet = new Outlet() {
@Override
public FileHandle createFileHandle(String fileName)
throws VetoException {
IFile file = folder.get().getFile(new Path(fileName));
return new EclipseBasedFileHandle(file, this);
}
};
output.addOutlet(outlet);
Map<String, Variable> globalVars = new HashMap<String, Variable>();
// FIXME resource loading
XpandExecutionContextImpl ctx = new XpandExecutionContextImpl(output,
null, null, null, null);
ctx.registerMetaModel(new JavaBeansMetaModel());
String projectName = context.getBuiltProject().getName();
for (IResourceDescription.Delta delta : context.getDeltas()) {
// handle deletion
String projectSegment = delta.getUri().segment(1);
if (projectName.equals(projectSegment)) {
if (delta.getUri().fileExtension().equals("xdoc")) {
IFolder contentsFolder = context.getBuiltProject().getFolder("contents");
if (folder.get() == null) {
if (!contentsFolder.exists())
contentsFolder.create(true, true, monitor);
folder.set(contentsFolder);
}
if (delta.getNew() == null) {
IFile file = folder.get().getFile(delta.getUri().lastSegment()+".html");
if (file.exists())
file.delete(true, monitor);
} else {
Resource resource = context.getResourceSet().getResource(
delta.getUri(), true);
EObject object = resource.getContents().get(0);
// set directories for CopyUtil to be able to copy referenced images
String baseDir = context.getBuiltProject().getLocation() + File.separator +
concatSegments(2, delta.getUri().segmentCount() - 1, delta.getUri());
Variable var = new Variable("srcDir", baseDir);
globalVars.put("srcDir", var);
var = new Variable("dir", contentsFolder.getLocation().toString());
globalVars.put("dir", var);
ctx.getGlobalVariables().putAll(globalVars);
generate(object, ctx, context);
}
}
}
}
if(context.getBuildType().equals(BuildType.CLEAN)) {
if (folder.get() != null) {
IFile file = folder.get().getFile("toc.xml");
if (file.exists())
file.delete(true, monitor);
}
}
}
|
diff --git a/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/reconciler/XtextReconcilerUnitOfWork.java b/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/reconciler/XtextReconcilerUnitOfWork.java
index 763c25269..a5058de27 100644
--- a/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/reconciler/XtextReconcilerUnitOfWork.java
+++ b/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/reconciler/XtextReconcilerUnitOfWork.java
@@ -1,61 +1,65 @@
/*******************************************************************************
* Copyright (c) 2008 itemis AG (http://www.itemis.eu) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.xtext.ui.core.editor.reconciler;
import org.apache.log4j.Logger;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.xtext.concurrent.IUnitOfWork;
import org.eclipse.xtext.resource.XtextResource;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
class XtextReconcilerUnitOfWork extends IUnitOfWork.Void<XtextResource> {
private static final Logger log = Logger.getLogger(XtextReconcilerUnitOfWork.class);
private IRegion region;
private IDocument document;
/**
* @param region
* @param document
*/
public XtextReconcilerUnitOfWork(IRegion region, IDocument document) {
super();
this.document = document;
this.region = region;
}
@Override
public void process(XtextResource resource) throws Exception {
if (log.isDebugEnabled())
log.debug("Preparing reconciliation.");
try {
if (!(region instanceof ReplaceRegion)) {
throw new IllegalArgumentException("Region to be reconciled must be a ReplaceRegion");
}
ReplaceRegion replaceRegionToBeProcessed = (ReplaceRegion) region;
if (log.isTraceEnabled())
log.trace("Parsing replace region '" + replaceRegionToBeProcessed.getText() + "'.");
resource.update(replaceRegionToBeProcessed.getOffset(), replaceRegionToBeProcessed.getLength(),
replaceRegionToBeProcessed.getText());
EcoreUtil.resolveAll(resource);
}
- catch (Throwable t) {
+ catch (Exception t) {
if (log.isDebugEnabled())
log.debug("Partial parsing failed. Performing full reparse", t);
- resource.reparse(document.get());
+ try {
+ resource.reparse(document.get());
+ } catch (Exception e) {
+ log.error("Parsing in reconciler failed.", e);
+ }
}
}
}
| false | true |
public void process(XtextResource resource) throws Exception {
if (log.isDebugEnabled())
log.debug("Preparing reconciliation.");
try {
if (!(region instanceof ReplaceRegion)) {
throw new IllegalArgumentException("Region to be reconciled must be a ReplaceRegion");
}
ReplaceRegion replaceRegionToBeProcessed = (ReplaceRegion) region;
if (log.isTraceEnabled())
log.trace("Parsing replace region '" + replaceRegionToBeProcessed.getText() + "'.");
resource.update(replaceRegionToBeProcessed.getOffset(), replaceRegionToBeProcessed.getLength(),
replaceRegionToBeProcessed.getText());
EcoreUtil.resolveAll(resource);
}
catch (Throwable t) {
if (log.isDebugEnabled())
log.debug("Partial parsing failed. Performing full reparse", t);
resource.reparse(document.get());
}
}
|
public void process(XtextResource resource) throws Exception {
if (log.isDebugEnabled())
log.debug("Preparing reconciliation.");
try {
if (!(region instanceof ReplaceRegion)) {
throw new IllegalArgumentException("Region to be reconciled must be a ReplaceRegion");
}
ReplaceRegion replaceRegionToBeProcessed = (ReplaceRegion) region;
if (log.isTraceEnabled())
log.trace("Parsing replace region '" + replaceRegionToBeProcessed.getText() + "'.");
resource.update(replaceRegionToBeProcessed.getOffset(), replaceRegionToBeProcessed.getLength(),
replaceRegionToBeProcessed.getText());
EcoreUtil.resolveAll(resource);
}
catch (Exception t) {
if (log.isDebugEnabled())
log.debug("Partial parsing failed. Performing full reparse", t);
try {
resource.reparse(document.get());
} catch (Exception e) {
log.error("Parsing in reconciler failed.", e);
}
}
}
|
diff --git a/core/src/main/java/com/google/bitcoin/core/MemoryPool.java b/core/src/main/java/com/google/bitcoin/core/MemoryPool.java
index 955c5cf..1c19375 100644
--- a/core/src/main/java/com/google/bitcoin/core/MemoryPool.java
+++ b/core/src/main/java/com/google/bitcoin/core/MemoryPool.java
@@ -1,320 +1,319 @@
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.core;
import com.google.bitcoin.utils.Locks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* <p>Tracks transactions that are being announced across the network. Typically one is created for you by a
* {@link PeerGroup} and then given to each Peer to update. The current purpose is to let Peers update the confidence
* (number of peers broadcasting). It helps address an attack scenario in which a malicious remote peer (or several)
* feeds you invalid transactions, eg, ones that spend coins which don't exist. If you don't see most of the peers
* announce the transaction within a reasonable time, it may be that the TX is not valid. Alternatively, an attacker
* may control your entire internet connection: in this scenario counting broadcasting peers does not help you.</p>
*
* <p>It is <b>not</b> at this time directly equivalent to the Satoshi clients memory pool, which tracks
* all transactions not currently included in the best chain - it's simply a cache.</p>
*/
public class MemoryPool {
private static final Logger log = LoggerFactory.getLogger(MemoryPool.class);
protected ReentrantLock lock = Locks.lock("mempool");
// For each transaction we may have seen:
// - only its hash in an inv packet
// - the full transaction itself, if we asked for it to be sent to us (or a peer sent it regardless)
//
// Before we see the full transaction, we need to track how many peers advertised it, so we can estimate its
// confidence pre-chain inclusion assuming an un-tampered with network connection. After we see the full transaction
// we need to switch from tracking that data in the Entry to tracking it in the TransactionConfidence object itself.
private static class WeakTransactionReference extends WeakReference<Transaction> {
public Sha256Hash hash;
public WeakTransactionReference(Transaction tx, ReferenceQueue<Transaction> queue) {
super(tx, queue);
hash = tx.getHash();
}
}
private static class Entry {
// Invariants: one of the two fields must be null, to indicate which is used.
Set<PeerAddress> addresses;
// We keep a weak reference to the transaction. This means that if no other bit of code finds the transaction
// worth keeping around it will drop out of memory and we will, at some point, forget about it, which means
// both addresses and tx.get() will be null. When this happens the WeakTransactionReference appears in the queue
// allowing us to delete the associated entry (the tx itself has already gone away).
WeakTransactionReference tx;
}
private LinkedHashMap<Sha256Hash, Entry> memoryPool;
// This ReferenceQueue gets entries added to it when they are only weakly reachable, ie, the MemoryPool is the
// only thing that is tracking the transaction anymore. We check it from time to time and delete memoryPool entries
// corresponding to expired transactions. In this way memory usage of the system is in line with however many
// transactions you actually care to track the confidence of. We can still end up with lots of hashes being stored
// if our peers flood us with invs but the MAX_SIZE param caps this.
private ReferenceQueue<Transaction> referenceQueue;
/** The max size of a memory pool created with the no-args constructor. */
public static final int MAX_SIZE = 1000;
/**
* Creates a memory pool that will track at most the given number of transactions (allowing you to bound memory
* usage).
* @param size Max number of transactions to track. The pool will fill up to this size then stop growing.
*/
public MemoryPool(final int size) {
memoryPool = new LinkedHashMap<Sha256Hash, Entry>() {
@Override
protected boolean removeEldestEntry(Map.Entry<Sha256Hash, Entry> entry) {
// An arbitrary choice to stop the memory used by tracked transactions getting too huge in the event
// of some kind of DoS attack.
return size() > size;
}
};
referenceQueue = new ReferenceQueue<Transaction>();
}
/**
* Creates a memory pool that will track at most {@link MemoryPool#MAX_SIZE} entries. You should normally use
* this constructor.
*/
public MemoryPool() {
this(MAX_SIZE);
}
/**
* If any transactions have expired due to being only weakly reachable through us, go ahead and delete their
* memoryPool entries - it means we downloaded the transaction and sent it to various event listeners, none of
* which bothered to keep a reference. Typically, this is because the transaction does not involve any keys that
* are relevant to any of our wallets.
*/
private void cleanPool() {
lock.lock();
try {
Reference<? extends Transaction> ref;
while ((ref = referenceQueue.poll()) != null) {
// Find which transaction got deleted by the GC.
WeakTransactionReference txRef = (WeakTransactionReference) ref;
// And remove the associated map entry so the other bits of memory can also be reclaimed.
memoryPool.remove(txRef.hash);
}
} finally {
lock.unlock();
}
}
/**
* Returns the number of peers that have seen the given hash recently.
*/
public int numBroadcastPeers(Sha256Hash txHash) {
lock.lock();
try {
cleanPool();
Entry entry = memoryPool.get(txHash);
if (entry == null) {
// No such TX known.
return 0;
} else if (entry.tx == null) {
// We've seen at least one peer announce with an inv.
checkNotNull(entry.addresses);
return entry.addresses.size();
} else {
final Transaction tx = entry.tx.get();
if (tx == null) {
// We previously downloaded this transaction, but nothing cared about it so the garbage collector threw
// it away. We also deleted the set that tracked which peers had seen it. Treat this case as a zero and
// just delete it from the map.
memoryPool.remove(txHash);
return 0;
} else {
checkState(entry.addresses == null);
return tx.getConfidence().numBroadcastPeers();
}
}
} finally {
lock.unlock();
}
}
/**
* Called by peers when they receive a "tx" message containing a valid serialized transaction.
* @param tx The TX deserialized from the wire.
* @param byPeer The Peer that received it.
* @return An object that is semantically the same TX but may be a different object instance.
*/
public Transaction seen(Transaction tx, PeerAddress byPeer) {
+ boolean skipUnlock = false;
lock.lock();
try {
cleanPool();
Entry entry = memoryPool.get(tx.getHash());
if (entry != null) {
// This TX or its hash have been previously announced.
if (entry.tx != null) {
// We already downloaded it.
checkState(entry.addresses == null);
// We only want one canonical object instance for a transaction no matter how many times it is
// deserialized.
Transaction transaction = entry.tx.get();
if (transaction == null) {
// We previously downloaded this transaction, but the garbage collector threw it away because
// no other part of the system cared enough to keep it around (it's not relevant to us).
// Given the lack of interest last time we probably don't need to track it this time either.
log.info("{}: Provided with a transaction that we previously threw away: {}", byPeer, tx.getHash());
} else {
// We saw it before and kept it around. Hand back the canonical copy.
tx = transaction;
log.info("{}: Provided with a transaction downloaded before: [{}] {}",
new Object[]{byPeer, tx.getConfidence().numBroadcastPeers(), tx.getHash()});
}
markBroadcast(byPeer, tx);
return tx;
} else {
// We received a transaction that we have previously seen announced but not downloaded until now.
checkNotNull(entry.addresses);
entry.tx = new WeakTransactionReference(tx, referenceQueue);
+ Set<PeerAddress> addrs = entry.addresses;
+ entry.addresses = null;
// Copy the previously announced peers into the confidence and then clear it out. Unlock here
// because markBroadcastBy can trigger event listeners and thus inversions.
+ TransactionConfidence confidence = tx.getConfidence();
+ log.debug("{}: Adding tx [{}] {} to the memory pool",
+ new Object[]{byPeer, confidence.numBroadcastPeers(), tx.getHashAsString()});
lock.unlock();
- try {
- TransactionConfidence confidence = tx.getConfidence();
- for (PeerAddress a : entry.addresses) {
- confidence.markBroadcastBy(a);
- }
- entry.addresses = null;
- log.debug("{}: Adding tx [{}] {} to the memory pool",
- new Object[]{byPeer, confidence.numBroadcastPeers(), tx.getHashAsString()});
- } finally {
- lock.lock();
+ skipUnlock = true;
+ for (PeerAddress a : addrs) {
+ confidence.markBroadcastBy(a);
}
return tx;
}
} else {
// This often happens when we are downloading a Bloom filtered chain, or recursively downloading
// dependencies of a relevant transaction (see Peer.downloadDependencies).
log.debug("{}: Provided with a downloaded transaction we didn't see announced yet: {}",
byPeer, tx.getHashAsString());
entry = new Entry();
entry.tx = new WeakTransactionReference(tx, referenceQueue);
memoryPool.put(tx.getHash(), entry);
markBroadcast(byPeer, tx);
return tx;
}
} finally {
- lock.unlock();
+ if (!skipUnlock) lock.unlock();
}
}
/**
* Called by peers when they see a transaction advertised in an "inv" message. It either will increase the
* confidence of the pre-existing transaction or will just keep a record of the address for future usage.
*/
public void seen(Sha256Hash hash, PeerAddress byPeer) {
lock.lock();
try {
cleanPool();
Entry entry = memoryPool.get(hash);
if (entry != null) {
// This TX or its hash have been previously announced.
if (entry.tx != null) {
checkState(entry.addresses == null);
Transaction tx = entry.tx.get();
if (tx != null) {
markBroadcast(byPeer, tx);
log.debug("{}: Announced transaction we have seen before [{}] {}",
new Object[]{byPeer, tx.getConfidence().numBroadcastPeers(), tx.getHashAsString()});
} else {
// The inv is telling us about a transaction that we previously downloaded, and threw away because
// nothing found it interesting enough to keep around. So do nothing.
}
} else {
checkNotNull(entry.addresses);
entry.addresses.add(byPeer);
log.debug("{}: Announced transaction we have seen announced before [{}] {}",
new Object[]{byPeer, entry.addresses.size(), hash});
}
} else {
// This TX has never been seen before.
entry = new Entry();
// TODO: Using hashsets here is inefficient compared to just having an array.
entry.addresses = new HashSet<PeerAddress>();
entry.addresses.add(byPeer);
memoryPool.put(hash, entry);
log.info("{}: Announced new transaction [1] {}", byPeer, hash);
}
} finally {
lock.unlock();
}
}
private void markBroadcast(PeerAddress byPeer, Transaction tx) {
// Marking a TX as broadcast by a peer can run event listeners that might call back into Peer or PeerGroup.
// Thus we unlock ourselves here to avoid potential inversions.
checkState(lock.isLocked());
lock.unlock();
try {
tx.getConfidence().markBroadcastBy(byPeer);
} finally {
lock.lock();
}
}
/**
* Returns the {@link Transaction} for the given hash if we have downloaded it, or null if that hash is unknown or
* we only saw advertisements for it yet or it has been downloaded but garbage collected due to nowhere else
* holding a reference to it.
*/
public Transaction get(Sha256Hash hash) {
lock.lock();
try {
Entry entry = memoryPool.get(hash);
if (entry == null) return null; // Unknown.
if (entry.tx == null) return null; // Seen but only in advertisements.
if (entry.tx.get() == null) return null; // Was downloaded but garbage collected.
Transaction tx = entry.tx.get();
checkNotNull(tx);
return tx;
} finally {
lock.unlock();
}
}
/**
* Returns true if the TX identified by hash has been seen before (ie, in an inv). Note that a transaction that
* was broadcast, downloaded and nothing kept a reference to it will eventually be cleared out by the garbage
* collector and wasSeen() will return false - it does not keep a permanent record of every hash ever broadcast.
*/
public boolean maybeWasSeen(Sha256Hash hash) {
lock.lock();
try {
Entry entry = memoryPool.get(hash);
return entry != null;
} finally {
lock.unlock();
}
}
}
| false | true |
public Transaction seen(Transaction tx, PeerAddress byPeer) {
lock.lock();
try {
cleanPool();
Entry entry = memoryPool.get(tx.getHash());
if (entry != null) {
// This TX or its hash have been previously announced.
if (entry.tx != null) {
// We already downloaded it.
checkState(entry.addresses == null);
// We only want one canonical object instance for a transaction no matter how many times it is
// deserialized.
Transaction transaction = entry.tx.get();
if (transaction == null) {
// We previously downloaded this transaction, but the garbage collector threw it away because
// no other part of the system cared enough to keep it around (it's not relevant to us).
// Given the lack of interest last time we probably don't need to track it this time either.
log.info("{}: Provided with a transaction that we previously threw away: {}", byPeer, tx.getHash());
} else {
// We saw it before and kept it around. Hand back the canonical copy.
tx = transaction;
log.info("{}: Provided with a transaction downloaded before: [{}] {}",
new Object[]{byPeer, tx.getConfidence().numBroadcastPeers(), tx.getHash()});
}
markBroadcast(byPeer, tx);
return tx;
} else {
// We received a transaction that we have previously seen announced but not downloaded until now.
checkNotNull(entry.addresses);
entry.tx = new WeakTransactionReference(tx, referenceQueue);
// Copy the previously announced peers into the confidence and then clear it out. Unlock here
// because markBroadcastBy can trigger event listeners and thus inversions.
lock.unlock();
try {
TransactionConfidence confidence = tx.getConfidence();
for (PeerAddress a : entry.addresses) {
confidence.markBroadcastBy(a);
}
entry.addresses = null;
log.debug("{}: Adding tx [{}] {} to the memory pool",
new Object[]{byPeer, confidence.numBroadcastPeers(), tx.getHashAsString()});
} finally {
lock.lock();
}
return tx;
}
} else {
// This often happens when we are downloading a Bloom filtered chain, or recursively downloading
// dependencies of a relevant transaction (see Peer.downloadDependencies).
log.debug("{}: Provided with a downloaded transaction we didn't see announced yet: {}",
byPeer, tx.getHashAsString());
entry = new Entry();
entry.tx = new WeakTransactionReference(tx, referenceQueue);
memoryPool.put(tx.getHash(), entry);
markBroadcast(byPeer, tx);
return tx;
}
} finally {
lock.unlock();
}
}
|
public Transaction seen(Transaction tx, PeerAddress byPeer) {
boolean skipUnlock = false;
lock.lock();
try {
cleanPool();
Entry entry = memoryPool.get(tx.getHash());
if (entry != null) {
// This TX or its hash have been previously announced.
if (entry.tx != null) {
// We already downloaded it.
checkState(entry.addresses == null);
// We only want one canonical object instance for a transaction no matter how many times it is
// deserialized.
Transaction transaction = entry.tx.get();
if (transaction == null) {
// We previously downloaded this transaction, but the garbage collector threw it away because
// no other part of the system cared enough to keep it around (it's not relevant to us).
// Given the lack of interest last time we probably don't need to track it this time either.
log.info("{}: Provided with a transaction that we previously threw away: {}", byPeer, tx.getHash());
} else {
// We saw it before and kept it around. Hand back the canonical copy.
tx = transaction;
log.info("{}: Provided with a transaction downloaded before: [{}] {}",
new Object[]{byPeer, tx.getConfidence().numBroadcastPeers(), tx.getHash()});
}
markBroadcast(byPeer, tx);
return tx;
} else {
// We received a transaction that we have previously seen announced but not downloaded until now.
checkNotNull(entry.addresses);
entry.tx = new WeakTransactionReference(tx, referenceQueue);
Set<PeerAddress> addrs = entry.addresses;
entry.addresses = null;
// Copy the previously announced peers into the confidence and then clear it out. Unlock here
// because markBroadcastBy can trigger event listeners and thus inversions.
TransactionConfidence confidence = tx.getConfidence();
log.debug("{}: Adding tx [{}] {} to the memory pool",
new Object[]{byPeer, confidence.numBroadcastPeers(), tx.getHashAsString()});
lock.unlock();
skipUnlock = true;
for (PeerAddress a : addrs) {
confidence.markBroadcastBy(a);
}
return tx;
}
} else {
// This often happens when we are downloading a Bloom filtered chain, or recursively downloading
// dependencies of a relevant transaction (see Peer.downloadDependencies).
log.debug("{}: Provided with a downloaded transaction we didn't see announced yet: {}",
byPeer, tx.getHashAsString());
entry = new Entry();
entry.tx = new WeakTransactionReference(tx, referenceQueue);
memoryPool.put(tx.getHash(), entry);
markBroadcast(byPeer, tx);
return tx;
}
} finally {
if (!skipUnlock) lock.unlock();
}
}
|
diff --git a/src/ScheduleClientConnection.java b/src/ScheduleClientConnection.java
index 44c7b75..0a21064 100644
--- a/src/ScheduleClientConnection.java
+++ b/src/ScheduleClientConnection.java
@@ -1,321 +1,321 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.PriorityQueue;
public class ScheduleClientConnection implements Runnable {
private Socket clientSocket;
private String line;
BufferedReader in;
PrintStream out;
private HashMap<CurrentDate, Day> calStorage;
ScheduleClientConnection(Socket server, HashMap<CurrentDate, Day> calStorage) {
clientSocket = server;
this.calStorage = calStorage;
}
/*
* The server takes 4 ints separated by spaces this is somewhat sanitized,
* but don't test it
*
* the format for input is month day year time
*
* year and time must be four digits, the time must be in 24 hr format
*
* it returns two lines, the first line is the current period given the time
*
* the second line is the next period
*
* these lines each give the period number and then the start and end times
* separated by spaces
*
* ex 10 11 2012 1051 <-- input A 4 1050 1205 <-output 6 1305 1405
*
* key to output anything >0 is the period number -1 is break -2 assembly -3
* class meeting -4 advisory -5 clubs -7 lunch
*/
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintStream(clientSocket.getOutputStream());
while ((line = in.readLine()) != null && !line.equals(".")) {
String[] temp = line.split(" ");
if (temp.length != 4) {
out.println("Please enter the time and date in the following format: month day year time");
// out.println(".");
} else {
CurrentDate today = new CurrentDate(Integer.parseInt(temp[0]), Integer.parseInt(temp[1]),
Integer.parseInt(temp[2]));
Day thing = null;
for (Entry<CurrentDate, Day> c : calStorage.entrySet()) {
if (c.getKey().equals(today)) {
thing = c.getValue();
}
}
if (thing != null) {
if (thing.getD().size() <= 7) {
thing = buildDay(today);
}
int currentTime = Integer.parseInt(temp[3]);
currentTime = adjustTime(currentTime, today, 1);
// System.out.println(currentTime);
// System.out.println(thing);
String stuff = "";
if (thing != null) {
Period tp;
if (currentTime < thing.getD().peek().getStartTime()) {
stuff += thing.getDayType() + "--";
stuff += "-9--";
tp = thing.getD().peek();
stuff += tp.getNumber() + "--" + adjustTime(tp.getStartTime(), today, -1) + "--"
+ adjustTime(tp.getEndTime(), today, -1);
} else {
if ((tp = thing.currentPeriod(currentTime)) != null) {
stuff += thing.getDayType() + "--";
stuff += tp.getNumber() + "--" + adjustTime(tp.getStartTime(), today, -1) + "--"
+ adjustTime(tp.getEndTime(), today, -1) + "--";
} else {
stuff += "-8--";
}
if ((tp = thing.nextPeriod(currentTime)) != null) {
stuff += tp.getNumber() + "--" + adjustTime(tp.getStartTime(), today, -1) + "--"
+ adjustTime(tp.getEndTime(), today, -1);
} else if (((tp = thing.nextPeriod(currentTime - 10)) != null && (thing.getD().peek()
.getStartTime() == adjustTime(800, today, 1)
&& currentTime < adjustTime(1410, today, 1) || (thing.getD().peek()
.getStartTime() == adjustTime(900, today, 1) && currentTime < adjustTime(1425,
today, 1))))) {
stuff += tp.getNumber() + "--" + adjustTime(tp.getStartTime(), today, -1) + "--"
+ adjustTime(tp.getEndTime(), today, -1);
} else
stuff += "-8";
}
out.println(stuff);
// out.println(".");
}
} else {
out.println('X');
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
public int adjustTime(int time, CurrentDate today, int direction) {
int currentTime = time;
if (today.isBefore(new CurrentDate(11, 4, 2012)) || today.isAfterOrEqual(new CurrentDate(3, 10, 2013))) {
currentTime += 600 * direction;
} else {
currentTime += 700 * direction;
}
return currentTime;
}
public Day buildDay(CurrentDate today) {
Period tp = new Period();
Period tp2 = new Period();
Period lunch = new Period();
Day temp = null;
for (Entry<CurrentDate, Day> c : calStorage.entrySet()) {
if (c.getKey().equals(today)) {
temp = c.getValue();
}
}
if (temp != null) {
int firstPeriod = temp.getD().peek().getNumber();
PriorityQueue<Period> tempQueue = new PriorityQueue<Period>();
int breakStart;
for (Period p : temp.getD()) {
tempQueue.offer(p);
}
if (temp.getD().peek().getStartTime() == adjustTime(900, today, 1)) {
switch (firstPeriod) {
case 1:
temp.setDayType('A');
break;
case 2:
temp.setDayType('B');
break;
case 3:
temp.setDayType('C');
break;
case 4:
temp.setDayType('D');
break;
case 5:
temp.setDayType('E');
break;
case 6:
temp.setDayType('F');
break;
case 7:
temp.setDayType('G');
break;
default:
break;
}
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 60);
tp.setNumber(-1);
temp.add(tp);
lunch.setStartTime(adjustTime(1230, today, 1));
- lunch.setEndTime(adjustTime(1330, today, 1));
+ lunch.setEndTime(adjustTime(1325, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
return temp;
}
switch (firstPeriod) {
case 1:
temp.setDayType('A');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-2);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 2:
temp.setDayType('B');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
breakStart = tempQueue.poll().getEndTime();
tp2.setStartTime(breakStart + 5);
tp2.setEndTime(breakStart + 65);
tp2.setNumber(-5);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 3:
temp.setDayType('C');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-3);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 4:
temp.setDayType('D');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-4);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 5:
temp.setDayType('E');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-2);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 6:
temp.setDayType('F');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-4);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 7:
temp.setDayType('G');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
breakStart = tempQueue.poll().getEndTime();
tp2.setStartTime(breakStart + 5);
tp2.setEndTime(breakStart + 65);
tp2.setNumber(-5);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
default:
break;
}
}
return temp;
}
}
| true | true |
public Day buildDay(CurrentDate today) {
Period tp = new Period();
Period tp2 = new Period();
Period lunch = new Period();
Day temp = null;
for (Entry<CurrentDate, Day> c : calStorage.entrySet()) {
if (c.getKey().equals(today)) {
temp = c.getValue();
}
}
if (temp != null) {
int firstPeriod = temp.getD().peek().getNumber();
PriorityQueue<Period> tempQueue = new PriorityQueue<Period>();
int breakStart;
for (Period p : temp.getD()) {
tempQueue.offer(p);
}
if (temp.getD().peek().getStartTime() == adjustTime(900, today, 1)) {
switch (firstPeriod) {
case 1:
temp.setDayType('A');
break;
case 2:
temp.setDayType('B');
break;
case 3:
temp.setDayType('C');
break;
case 4:
temp.setDayType('D');
break;
case 5:
temp.setDayType('E');
break;
case 6:
temp.setDayType('F');
break;
case 7:
temp.setDayType('G');
break;
default:
break;
}
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 60);
tp.setNumber(-1);
temp.add(tp);
lunch.setStartTime(adjustTime(1230, today, 1));
lunch.setEndTime(adjustTime(1330, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
return temp;
}
switch (firstPeriod) {
case 1:
temp.setDayType('A');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-2);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 2:
temp.setDayType('B');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
breakStart = tempQueue.poll().getEndTime();
tp2.setStartTime(breakStart + 5);
tp2.setEndTime(breakStart + 65);
tp2.setNumber(-5);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 3:
temp.setDayType('C');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-3);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 4:
temp.setDayType('D');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-4);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 5:
temp.setDayType('E');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-2);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 6:
temp.setDayType('F');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-4);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 7:
temp.setDayType('G');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
breakStart = tempQueue.poll().getEndTime();
tp2.setStartTime(breakStart + 5);
tp2.setEndTime(breakStart + 65);
tp2.setNumber(-5);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
default:
break;
}
}
return temp;
}
|
public Day buildDay(CurrentDate today) {
Period tp = new Period();
Period tp2 = new Period();
Period lunch = new Period();
Day temp = null;
for (Entry<CurrentDate, Day> c : calStorage.entrySet()) {
if (c.getKey().equals(today)) {
temp = c.getValue();
}
}
if (temp != null) {
int firstPeriod = temp.getD().peek().getNumber();
PriorityQueue<Period> tempQueue = new PriorityQueue<Period>();
int breakStart;
for (Period p : temp.getD()) {
tempQueue.offer(p);
}
if (temp.getD().peek().getStartTime() == adjustTime(900, today, 1)) {
switch (firstPeriod) {
case 1:
temp.setDayType('A');
break;
case 2:
temp.setDayType('B');
break;
case 3:
temp.setDayType('C');
break;
case 4:
temp.setDayType('D');
break;
case 5:
temp.setDayType('E');
break;
case 6:
temp.setDayType('F');
break;
case 7:
temp.setDayType('G');
break;
default:
break;
}
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 60);
tp.setNumber(-1);
temp.add(tp);
lunch.setStartTime(adjustTime(1230, today, 1));
lunch.setEndTime(adjustTime(1325, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
return temp;
}
switch (firstPeriod) {
case 1:
temp.setDayType('A');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-2);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 2:
temp.setDayType('B');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
breakStart = tempQueue.poll().getEndTime();
tp2.setStartTime(breakStart + 5);
tp2.setEndTime(breakStart + 65);
tp2.setNumber(-5);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 3:
temp.setDayType('C');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-3);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 4:
temp.setDayType('D');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-4);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 5:
temp.setDayType('E');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-2);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 6:
temp.setDayType('F');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
tp2.setStartTime(breakStart + 20);
tp2.setEndTime(breakStart + 40);
tp2.setNumber(-4);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
case 7:
temp.setDayType('G');
tempQueue.poll();
breakStart = tempQueue.poll().getEndTime();
tp.setStartTime(breakStart);
tp.setEndTime(breakStart + 20);
tp.setNumber(-1);
temp.add(tp);
breakStart = tempQueue.poll().getEndTime();
tp2.setStartTime(breakStart + 5);
tp2.setEndTime(breakStart + 65);
tp2.setNumber(-5);
temp.add(tp2);
lunch.setStartTime(adjustTime(1205, today, 1));
lunch.setEndTime(adjustTime(1305, today, 1));
lunch.setNumber(-7);
temp.add(lunch);
break;
default:
break;
}
}
return temp;
}
|
diff --git a/src/com/dmdirc/WritableFrameContainer.java b/src/com/dmdirc/WritableFrameContainer.java
index 75fa916c9..c0b9e02e7 100644
--- a/src/com/dmdirc/WritableFrameContainer.java
+++ b/src/com/dmdirc/WritableFrameContainer.java
@@ -1,324 +1,341 @@
/*
* Copyright (c) 2006-2010 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc;
import com.dmdirc.actions.ActionManager;
import com.dmdirc.actions.interfaces.ActionType;
import com.dmdirc.config.ConfigManager;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.ui.WindowManager;
import com.dmdirc.ui.interfaces.InputWindow;
import com.dmdirc.ui.interfaces.Window;
import java.util.ArrayList;
import java.util.List;
/**
* The writable frame container adds additional methods to the frame container
* class that allow the sending of lines back to whatever the container's
* data source is (e.g. an IRC channel or server).
*
* @author chris
*/
public abstract class WritableFrameContainer extends FrameContainer {
/** The name of the server notification target. */
protected static final String NOTIFICATION_SERVER = "server".intern();
/** The name of the channel notification target. */
protected static final String NOTIFICATION_CHANNEL = "channel".intern();
/**
* Creates a new WritableFrameContainer.
*
* @param icon The icon to use for this container
* @param name The name of this container
* @param config The config manager for this container
* @since 0.6.3m2
*/
public WritableFrameContainer(final String icon, final String name, final ConfigManager config) {
super(icon, name, config);
}
/**
* Sends a line of text to this container's source.
*
* @param line The line to be sent
*/
public abstract void sendLine(String line);
/**
* Returns the internal frame associated with this object.
*
* @return The internal frame associated with this object
*/
@Override
public abstract InputWindow getFrame();
/**
* Returns the maximum length that a line passed to sendLine() should be,
* in order to prevent it being truncated or causing protocol violations.
*
* @return The maximum line length for this container
*/
public abstract int getMaxLineLength();
/**
* Splits the specified line into chunks that contain a number of bytes
* less than or equal to the value returned by {@link #getMaxLineLength()}.
*
* @param line The line to be split
* @return An ordered list of chunks of the desired length
*/
protected List<String> splitLine(final String line) {
final List<String> result = new ArrayList<String>();
if (line.indexOf('\n') > -1) {
for (String part : line.split("\n")) {
result.addAll(splitLine(part));
}
} else {
final StringBuilder remaining = new StringBuilder(line);
while (getMaxLineLength() > -1 && remaining.toString().getBytes().length
> getMaxLineLength()) {
int number = Math.min(remaining.length(), getMaxLineLength());
while (remaining.substring(0, number).getBytes().length > getMaxLineLength()) {
number--;
}
result.add(remaining.substring(0, number));
remaining.delete(0, number);
}
result.add(remaining.toString());
}
return result;
}
/**
* Returns the number of lines that the specified string would be sent as.
*
* @param line The string to be split and sent
* @return The number of lines required to send the specified string
*/
public final int getNumLines(final String line) {
final String[] splitLines = line.split("(\n|\r\n|\r)", Integer.MAX_VALUE);
int lines = 0;
for (String splitLine : splitLines) {
if (getMaxLineLength() <= 0) {
lines++;
} else {
lines += (int) Math.ceil(splitLine.getBytes().length
/ (double) getMaxLineLength());
}
}
return lines;
}
/**
* Processes and displays a notification.
*
* @param messageType The name of the formatter to be used for the message
* @param actionType The action type to be used
* @param args The arguments for the message
*/
public void doNotification(final String messageType,
final ActionType actionType, final Object... args) {
final List<Object> messageArgs = new ArrayList<Object>();
final List<Object> actionArgs = new ArrayList<Object>();
final StringBuffer buffer = new StringBuffer(messageType);
actionArgs.add(this);
for (Object arg : args) {
actionArgs.add(arg);
if (!processNotificationArg(arg, messageArgs)) {
messageArgs.add(arg);
}
}
modifyNotificationArgs(actionArgs, messageArgs);
ActionManager.processEvent(actionType, buffer, actionArgs.toArray());
handleNotification(buffer.toString(), messageArgs.toArray());
}
/**
* Allows subclasses to modify the lists of arguments for notifications.
*
* @param actionArgs The list of arguments to be passed to the actions system
* @param messageArgs The list of arguments to be passed to the formatter
*/
protected void modifyNotificationArgs(final List<Object> actionArgs,
final List<Object> messageArgs) {
// Do nothing
}
/**
* Allows subclasses to process specific types of notification arguments.
*
* @param arg The argument to be processed
* @param args The list of arguments that any data should be appended to
* @return True if the arg has been processed, false otherwise
*/
protected boolean processNotificationArg(final Object arg, final List<Object> args) {
return false;
}
/**
* Handles general server notifications (i.e., ones not tied to a
* specific window). The user can select where the notifications should
* go in their config.
*
* @param messageType The type of message that is being sent
* @param args The arguments for the message
*/
public void handleNotification(final String messageType, final Object... args) {
despatchNotification(messageType, getConfigManager().hasOptionString("notifications",
messageType) ? getConfigManager().getOption("notifications", messageType)
: "self", args);
}
/**
* Despatches a notification of the specified type to the specified target.
*
* @param messageType The type of the message that is being sent
* @param messageTarget The target of the message
* @param args The arguments for the message
*/
protected void despatchNotification(final String messageType,
final String messageTarget, final Object... args) {
String target = messageTarget;
String format = messageType;
if (target.startsWith("format:")) {
format = target.substring(7);
format = format.substring(0, format.indexOf(':'));
target = target.substring(8 + format.length());
}
if (target.startsWith("group:")) {
target = getConfigManager().hasOptionString("notifications", target.substring(6))
? getConfigManager().getOption("notifications", target.substring(6))
: "self";
}
if (target.startsWith("fork:")) {
for (String newtarget : target.substring(5).split("\\|")) {
despatchNotification(format, newtarget, args);
}
return;
}
if ("self".equals(target)) {
addLine(format, args);
} else if (NOTIFICATION_SERVER.equals(target)) {
getServer().addLine(format, args);
} else if ("all".equals(target)) {
getServer().addLineToAll(format, args);
} else if ("active".equals(target)) {
getServer().addLineToActive(format, args);
} else if (target.startsWith("window:")) {
final String windowName = target.substring(7);
Window targetWindow = WindowManager.findCustomWindow(getServer().getFrame(),
windowName);
if (targetWindow == null) {
targetWindow = new CustomWindow(windowName, windowName,
getServer().getFrame()).getFrame();
}
targetWindow.addLine(format, args);
} else if (target.startsWith("lastcommand:")) {
final Object[] escapedargs = new Object[args.length];
for (int i = 0; i < args.length; i++) {
escapedargs[i] = "\\Q" + args[i] + "\\E";
}
final String command = String.format(target.substring(12), escapedargs);
WritableFrameContainer best = this;
long besttime = 0;
final List<WritableFrameContainer> containers
= new ArrayList<WritableFrameContainer>();
containers.add(getServer());
containers.addAll(getServer().getChildren());
for (WritableFrameContainer container : containers) {
final long time
= container.getFrame().getCommandParser().getCommandTime(command);
if (time > besttime) {
besttime = time;
best = container;
}
}
best.addLine(format, args);
} else if (target.startsWith(NOTIFICATION_CHANNEL + ":")) {
- final String channel = String.format(target.substring(8), args);
+ final int sp = target.indexOf(' ');
+ final String channel = String.format(
+ target.substring(8, sp > -1 ? sp : target.length()), args);
if (getServer().hasChannel(channel)) {
getServer().getChannel(channel).addLine(messageType, args);
+ } else if (sp > -1) {
+ // They specified a fallback
+ despatchNotification(format, target.substring(sp + 1), args);
} else {
+ // No fallback specified
addLine(format, args);
Logger.userError(ErrorLevel.LOW,
"Invalid notification target for type " + messageType
+ ": channel " + channel + " doesn't exist");
}
} else if (target.startsWith("comchans:")) {
- final String user = String.format(target.substring(9), args);
+ final int sp = target.indexOf(' ');
+ final String user = String.format(
+ target.substring(9, sp > -1 ? sp : target.length()), args);
boolean found = false;
for (String channelName : getServer().getChannels()) {
final Channel channel = getServer().getChannel(channelName);
if (channel.getChannelInfo().getChannelClient(user) != null) {
channel.addLine(messageType, args);
found = true;
}
}
if (!found) {
- addLine(messageType, args);
+ if (sp > -1) {
+ // They specified a fallback
+ despatchNotification(format, target.substring(sp + 1), args);
+ } else {
+ // No fallback specified
+ addLine(messageType, args);
+ Logger.userError(ErrorLevel.LOW,
+ "Invalid notification target for type " + messageType
+ + ": no common channels with " + user);
+ }
}
} else if (!"none".equals(target)) {
addLine(format, args);
Logger.userError(ErrorLevel.MEDIUM,
"Invalid notification target for type " + messageType + ": " + target);
}
}
}
| false | true |
protected void despatchNotification(final String messageType,
final String messageTarget, final Object... args) {
String target = messageTarget;
String format = messageType;
if (target.startsWith("format:")) {
format = target.substring(7);
format = format.substring(0, format.indexOf(':'));
target = target.substring(8 + format.length());
}
if (target.startsWith("group:")) {
target = getConfigManager().hasOptionString("notifications", target.substring(6))
? getConfigManager().getOption("notifications", target.substring(6))
: "self";
}
if (target.startsWith("fork:")) {
for (String newtarget : target.substring(5).split("\\|")) {
despatchNotification(format, newtarget, args);
}
return;
}
if ("self".equals(target)) {
addLine(format, args);
} else if (NOTIFICATION_SERVER.equals(target)) {
getServer().addLine(format, args);
} else if ("all".equals(target)) {
getServer().addLineToAll(format, args);
} else if ("active".equals(target)) {
getServer().addLineToActive(format, args);
} else if (target.startsWith("window:")) {
final String windowName = target.substring(7);
Window targetWindow = WindowManager.findCustomWindow(getServer().getFrame(),
windowName);
if (targetWindow == null) {
targetWindow = new CustomWindow(windowName, windowName,
getServer().getFrame()).getFrame();
}
targetWindow.addLine(format, args);
} else if (target.startsWith("lastcommand:")) {
final Object[] escapedargs = new Object[args.length];
for (int i = 0; i < args.length; i++) {
escapedargs[i] = "\\Q" + args[i] + "\\E";
}
final String command = String.format(target.substring(12), escapedargs);
WritableFrameContainer best = this;
long besttime = 0;
final List<WritableFrameContainer> containers
= new ArrayList<WritableFrameContainer>();
containers.add(getServer());
containers.addAll(getServer().getChildren());
for (WritableFrameContainer container : containers) {
final long time
= container.getFrame().getCommandParser().getCommandTime(command);
if (time > besttime) {
besttime = time;
best = container;
}
}
best.addLine(format, args);
} else if (target.startsWith(NOTIFICATION_CHANNEL + ":")) {
final String channel = String.format(target.substring(8), args);
if (getServer().hasChannel(channel)) {
getServer().getChannel(channel).addLine(messageType, args);
} else {
addLine(format, args);
Logger.userError(ErrorLevel.LOW,
"Invalid notification target for type " + messageType
+ ": channel " + channel + " doesn't exist");
}
} else if (target.startsWith("comchans:")) {
final String user = String.format(target.substring(9), args);
boolean found = false;
for (String channelName : getServer().getChannels()) {
final Channel channel = getServer().getChannel(channelName);
if (channel.getChannelInfo().getChannelClient(user) != null) {
channel.addLine(messageType, args);
found = true;
}
}
if (!found) {
addLine(messageType, args);
}
} else if (!"none".equals(target)) {
addLine(format, args);
Logger.userError(ErrorLevel.MEDIUM,
"Invalid notification target for type " + messageType + ": " + target);
}
}
|
protected void despatchNotification(final String messageType,
final String messageTarget, final Object... args) {
String target = messageTarget;
String format = messageType;
if (target.startsWith("format:")) {
format = target.substring(7);
format = format.substring(0, format.indexOf(':'));
target = target.substring(8 + format.length());
}
if (target.startsWith("group:")) {
target = getConfigManager().hasOptionString("notifications", target.substring(6))
? getConfigManager().getOption("notifications", target.substring(6))
: "self";
}
if (target.startsWith("fork:")) {
for (String newtarget : target.substring(5).split("\\|")) {
despatchNotification(format, newtarget, args);
}
return;
}
if ("self".equals(target)) {
addLine(format, args);
} else if (NOTIFICATION_SERVER.equals(target)) {
getServer().addLine(format, args);
} else if ("all".equals(target)) {
getServer().addLineToAll(format, args);
} else if ("active".equals(target)) {
getServer().addLineToActive(format, args);
} else if (target.startsWith("window:")) {
final String windowName = target.substring(7);
Window targetWindow = WindowManager.findCustomWindow(getServer().getFrame(),
windowName);
if (targetWindow == null) {
targetWindow = new CustomWindow(windowName, windowName,
getServer().getFrame()).getFrame();
}
targetWindow.addLine(format, args);
} else if (target.startsWith("lastcommand:")) {
final Object[] escapedargs = new Object[args.length];
for (int i = 0; i < args.length; i++) {
escapedargs[i] = "\\Q" + args[i] + "\\E";
}
final String command = String.format(target.substring(12), escapedargs);
WritableFrameContainer best = this;
long besttime = 0;
final List<WritableFrameContainer> containers
= new ArrayList<WritableFrameContainer>();
containers.add(getServer());
containers.addAll(getServer().getChildren());
for (WritableFrameContainer container : containers) {
final long time
= container.getFrame().getCommandParser().getCommandTime(command);
if (time > besttime) {
besttime = time;
best = container;
}
}
best.addLine(format, args);
} else if (target.startsWith(NOTIFICATION_CHANNEL + ":")) {
final int sp = target.indexOf(' ');
final String channel = String.format(
target.substring(8, sp > -1 ? sp : target.length()), args);
if (getServer().hasChannel(channel)) {
getServer().getChannel(channel).addLine(messageType, args);
} else if (sp > -1) {
// They specified a fallback
despatchNotification(format, target.substring(sp + 1), args);
} else {
// No fallback specified
addLine(format, args);
Logger.userError(ErrorLevel.LOW,
"Invalid notification target for type " + messageType
+ ": channel " + channel + " doesn't exist");
}
} else if (target.startsWith("comchans:")) {
final int sp = target.indexOf(' ');
final String user = String.format(
target.substring(9, sp > -1 ? sp : target.length()), args);
boolean found = false;
for (String channelName : getServer().getChannels()) {
final Channel channel = getServer().getChannel(channelName);
if (channel.getChannelInfo().getChannelClient(user) != null) {
channel.addLine(messageType, args);
found = true;
}
}
if (!found) {
if (sp > -1) {
// They specified a fallback
despatchNotification(format, target.substring(sp + 1), args);
} else {
// No fallback specified
addLine(messageType, args);
Logger.userError(ErrorLevel.LOW,
"Invalid notification target for type " + messageType
+ ": no common channels with " + user);
}
}
} else if (!"none".equals(target)) {
addLine(format, args);
Logger.userError(ErrorLevel.MEDIUM,
"Invalid notification target for type " + messageType + ": " + target);
}
}
|
diff --git a/src/com/timsu/astrid/sync/SynchronizationService.java b/src/com/timsu/astrid/sync/SynchronizationService.java
index fcf922b3c..ad1941b24 100644
--- a/src/com/timsu/astrid/sync/SynchronizationService.java
+++ b/src/com/timsu/astrid/sync/SynchronizationService.java
@@ -1,139 +1,137 @@
package com.timsu.astrid.sync;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import com.timsu.astrid.utilities.Preferences;
/**
* SynchronizationService is the service that performs Astrid's background
* synchronization with online task managers. Starting this service launches
* the timer, which handles timing for synchronization.
*
* @author Tim Su
*
*/
public class SynchronizationService extends Service {
/** miniumum time before an auto-sync */
private static final long AUTO_SYNC_MIN_OFFSET = 5*60*1000L;
/** Service timer */
private Timer timer = new Timer();
/** Service activity */
private static Context context;
/** Set the activity for this service */
public static void setContext(Context context) {
SynchronizationService.context = context;
}
// --- utility methods
public static void start() {
if(Preferences.getSyncAutoSyncFrequency(context) == null)
return;
Intent service = new Intent(context, SynchronizationService.class);
context.startService(service);
}
public static void stop() {
Intent service = new Intent(context, SynchronizationService.class);
context.stopService(service);
}
// ---
@Override
public IBinder onBind(Intent arg0) {
return null; // unused
}
@Override
public void onCreate() {
super.onCreate();
// init the service here
startService();
}
@Override
public void onDestroy() {
super.onDestroy();
shutdownService();
}
/** Start the timer that runs the service */
private void startService() {
if(context == null)
return;
// figure out synchronization frequency
Integer syncFrequencySeconds = Preferences.getSyncAutoSyncFrequency(context);
if(syncFrequencySeconds == null) {
shutdownService();
return;
}
long interval = 1000L * syncFrequencySeconds;
// figure out last synchronize time
Date lastSyncDate = Preferences.getSyncLastSync(context);
Date lastAutoSyncDate = Preferences.getSyncLastSyncAttempt(context);
// if user never synchronized, give them a full offset period before bg sync
long latestSyncMillis = System.currentTimeMillis();
if(lastSyncDate != null)
latestSyncMillis = lastSyncDate.getTime();
if(lastAutoSyncDate != null && lastAutoSyncDate.getTime() > latestSyncMillis)
latestSyncMillis = lastAutoSyncDate.getTime();
long offset = 0;
if(latestSyncMillis != 0)
- offset = Math.min(offset, Math.max(0, latestSyncMillis + interval -
- System.currentTimeMillis()));
+ offset = Math.max(0, latestSyncMillis + interval - System.currentTimeMillis());
// give a little padding
offset = Math.max(offset, AUTO_SYNC_MIN_OFFSET);
- offset = AUTO_SYNC_MIN_OFFSET;
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
performSynchronization();
}
}, offset, interval);
Log.i("astrid", "Synchronization Service Started, Offset: " + offset/1000 +
"s Interval: " + interval/1000);
}
/** Stop the timer that runs the service */
private void shutdownService() {
if (timer != null)
timer.cancel();
Log.i("astrid", "Synchronization Service Stopped");
}
/** Perform the actual synchronization */
private void performSynchronization() {
if(context == null || context.getResources() == null)
return;
Log.i("astrid", "Automatic Synchronize Initiated.");
Preferences.setSyncLastSyncAttempt(context, new Date());
Synchronizer sync = new Synchronizer(true);
sync.synchronize(context, null);
}
}
| false | true |
private void startService() {
if(context == null)
return;
// figure out synchronization frequency
Integer syncFrequencySeconds = Preferences.getSyncAutoSyncFrequency(context);
if(syncFrequencySeconds == null) {
shutdownService();
return;
}
long interval = 1000L * syncFrequencySeconds;
// figure out last synchronize time
Date lastSyncDate = Preferences.getSyncLastSync(context);
Date lastAutoSyncDate = Preferences.getSyncLastSyncAttempt(context);
// if user never synchronized, give them a full offset period before bg sync
long latestSyncMillis = System.currentTimeMillis();
if(lastSyncDate != null)
latestSyncMillis = lastSyncDate.getTime();
if(lastAutoSyncDate != null && lastAutoSyncDate.getTime() > latestSyncMillis)
latestSyncMillis = lastAutoSyncDate.getTime();
long offset = 0;
if(latestSyncMillis != 0)
offset = Math.min(offset, Math.max(0, latestSyncMillis + interval -
System.currentTimeMillis()));
// give a little padding
offset = Math.max(offset, AUTO_SYNC_MIN_OFFSET);
offset = AUTO_SYNC_MIN_OFFSET;
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
performSynchronization();
}
}, offset, interval);
Log.i("astrid", "Synchronization Service Started, Offset: " + offset/1000 +
"s Interval: " + interval/1000);
}
|
private void startService() {
if(context == null)
return;
// figure out synchronization frequency
Integer syncFrequencySeconds = Preferences.getSyncAutoSyncFrequency(context);
if(syncFrequencySeconds == null) {
shutdownService();
return;
}
long interval = 1000L * syncFrequencySeconds;
// figure out last synchronize time
Date lastSyncDate = Preferences.getSyncLastSync(context);
Date lastAutoSyncDate = Preferences.getSyncLastSyncAttempt(context);
// if user never synchronized, give them a full offset period before bg sync
long latestSyncMillis = System.currentTimeMillis();
if(lastSyncDate != null)
latestSyncMillis = lastSyncDate.getTime();
if(lastAutoSyncDate != null && lastAutoSyncDate.getTime() > latestSyncMillis)
latestSyncMillis = lastAutoSyncDate.getTime();
long offset = 0;
if(latestSyncMillis != 0)
offset = Math.max(0, latestSyncMillis + interval - System.currentTimeMillis());
// give a little padding
offset = Math.max(offset, AUTO_SYNC_MIN_OFFSET);
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
performSynchronization();
}
}, offset, interval);
Log.i("astrid", "Synchronization Service Started, Offset: " + offset/1000 +
"s Interval: " + interval/1000);
}
|
diff --git a/src/Graphing/GraphLayer.java b/src/Graphing/GraphLayer.java
index f3b08c0..c613a63 100644
--- a/src/Graphing/GraphLayer.java
+++ b/src/Graphing/GraphLayer.java
@@ -1,236 +1,236 @@
/* OpenLogViewer
*
* Copyright 2011
*
* This file is part of the OpenLogViewer project.
*
* OpenLogViewer software is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenLogViewer software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with any OpenLogViewer software. If not, see http://www.gnu.org/licenses/
*
* I ask that if you make any changes to this file you fork the code on github.com!
*
*/
package Graphing;
import GenericLog.GenericDataElement;
import OpenLogViewer.OpenLogViewerApp;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.HierarchyBoundsListener;
import java.awt.event.HierarchyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.LinkedList;
import javax.swing.JPanel;
/**
*
* @author Bryan
*/
public class GraphLayer extends JPanel implements HierarchyBoundsListener,PropertyChangeListener {
private GenericDataElement GDE;
private LinkedList<Double> drawnData;
private LayeredGraph.Zoom zoom;
private int nullData;
public GraphLayer() {
this.setOpaque(false);
this.setLayout(null);
this.GDE = null;
drawnData = new LinkedList<Double>();
this.nullData = 0;
}
private int getCurrent() {
LayeredGraph lg = (LayeredGraph) this.getParent();
return lg.getCurrent();
}
@Override
public void ancestorMoved(HierarchyEvent e) {
}
@Override
public void ancestorResized(HierarchyEvent e) {
if (e.getID() == HierarchyEvent.ANCESTOR_RESIZED) {
sizeGraph();
}
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equalsIgnoreCase("Split")){
sizeGraph();
}
}
@Override
public void paint(Graphics g) { // overridden paint because there will be no other painting other than this
if (!this.getParent().getSize().equals(this.getSize())) {
}
Dimension d = this.getSize();
Graphics2D g2d = (Graphics2D) g;
if (drawnData != null && drawnData.size() > 0) {
g2d.setColor(GDE.getColor());
Iterator dat = drawnData.iterator();
int i = 0;
Double chartNum = 0.0;
try {
chartNum = (Double) dat.next();
- int a = chartNumber(chartNum, d.height, GDE.getMinValue(), GDE.getMaxValue());
+ int a = chartNumber(chartNum, (int)(d.height*0.95), GDE.getMinValue(), GDE.getMaxValue());
while (dat.hasNext()) {
chartNum = (Double) dat.next();
int b = chartNumber(chartNum, (int)(d.height*0.95), GDE.getMinValue(), GDE.getMaxValue());
if (i >= nullData * zoom.getZoom()) {
if (zoom.getZoom() > 5) {
g2d.fillOval(i - 2, a - 2, 4, 4);
}
g2d.drawLine(i, a, i + zoom.getZoom(), b);
}
a = b;
i += zoom.getZoom();
}
} catch (ConcurrentModificationException CME) {
System.out.println(this.getClass().toString() + " " + CME.getMessage());
}
}
}
private int chartNumber(Double elemData, int height, double minValue, double maxValue) {
int point = 0;
if (maxValue != minValue) {
point = (int) (height - (height * ((elemData - minValue) / (maxValue - minValue))));
}
return point;
}
public void setData(GenericDataElement GDE) {
this.GDE = GDE;
sizeGraph();
initGraph();
}
public GenericDataElement getData() {
return GDE;
}
public Double getMouseInfo(int i) {
LayeredGraph lg = (LayeredGraph) this.getParent();
int getIt = (i / zoom.getZoom()) + lg.getCurrent() - ((this.getSize().width / 2) / zoom.getZoom());
if (getIt < GDE.size() && getIt >= 0) {
return GDE.get(getIt);
} else {
return 0.0;
}
}
public Color getColor() {
return GDE.getColor();
}
public void setColor(Color c) {
GDE.setColor(c);
}
public void initGraph() {
if (GDE != null) {
LayeredGraph lg = (LayeredGraph) this.getParent();
Dimension d = this.getSize();
drawnData = new LinkedList<Double>();
int zoomFactor = ((d.width + zoom.getZoom()) / zoom.getZoom()) / 2; // add two datapoints to be drawn due to zoom clipping at the ends
if ((double) d.width / 2 > zoom.getZoom() * (double) (zoomFactor)) {
zoomFactor++;// without this certain zoom factors will cause data to be misdrawn on screen
}
if (lg.getCurrent() <= zoomFactor) {
int x = 0;
int fill = (zoomFactor) - lg.getCurrent();
nullData = fill;
while (x < fill) {
drawnData.add(0.0);
x++;
}
int to = 0;
if (GDE.size() - 1 < (d.width / zoom.getZoom()) - x + 2) {// get the whole array because its stupid short
to = (GDE.size() - 1);
} else { // get the first width-zoom-x
to = (d.width / zoom.getZoom()) - x + 2;
}
drawnData.addAll(GDE.subList(0, to));
} else if ((zoomFactor + lg.getCurrent() + 2) < GDE.size()) {
nullData = 0;
drawnData.addAll(GDE.subList(lg.getCurrent() - zoomFactor, zoomFactor + 2 + lg.getCurrent()));
} else {
nullData = 0;
drawnData.addAll(GDE.subList(lg.getCurrent() - zoomFactor, GDE.size()));
}
}
}
public void sizeGraph() {
LayeredGraph lg = OpenLogViewerApp.getInstance().getLayeredGraph();
// Dimension d = lg.getSize();
int wherePixel = 0 ;
if (lg.getTotalSplits() > 1) {
if (GDE.getSplitNumber() <= lg.getTotalSplits()) {
wherePixel += lg.getHeight() / lg.getTotalSplits() * GDE.getSplitNumber() - (lg.getHeight() / lg.getTotalSplits());
} else {
wherePixel += lg.getHeight() / lg.getTotalSplits() * lg.getTotalSplits() - (lg.getHeight() / lg.getTotalSplits());
}
}
this.setBounds(0, wherePixel, lg.getWidth(), lg.getHeight() / (lg.getTotalSplits()));
initGraph();
}
public void advanceGraph() {
if (GDE != null) {
LayeredGraph lg = (LayeredGraph) this.getParent();
Dimension d = this.getSize();
int zoomFactor = (d.width / 2) / zoom.getZoom();
if ((lg.getCurrent() + zoomFactor) < GDE.size()) {
drawnData.add(GDE.get(lg.getCurrent() + zoomFactor));
if (nullData > 0) {
nullData--;
}
}
if (drawnData.size() > zoomFactor + 1) {
drawnData.remove(0);
} else {
lg.stop();
}
}
}
public int graphSize() {
return GDE.size();
}
public void setZoom(LayeredGraph.Zoom z) {
zoom = z;
}
}
| true | true |
public void paint(Graphics g) { // overridden paint because there will be no other painting other than this
if (!this.getParent().getSize().equals(this.getSize())) {
}
Dimension d = this.getSize();
Graphics2D g2d = (Graphics2D) g;
if (drawnData != null && drawnData.size() > 0) {
g2d.setColor(GDE.getColor());
Iterator dat = drawnData.iterator();
int i = 0;
Double chartNum = 0.0;
try {
chartNum = (Double) dat.next();
int a = chartNumber(chartNum, d.height, GDE.getMinValue(), GDE.getMaxValue());
while (dat.hasNext()) {
chartNum = (Double) dat.next();
int b = chartNumber(chartNum, (int)(d.height*0.95), GDE.getMinValue(), GDE.getMaxValue());
if (i >= nullData * zoom.getZoom()) {
if (zoom.getZoom() > 5) {
g2d.fillOval(i - 2, a - 2, 4, 4);
}
g2d.drawLine(i, a, i + zoom.getZoom(), b);
}
a = b;
i += zoom.getZoom();
}
} catch (ConcurrentModificationException CME) {
System.out.println(this.getClass().toString() + " " + CME.getMessage());
}
}
}
|
public void paint(Graphics g) { // overridden paint because there will be no other painting other than this
if (!this.getParent().getSize().equals(this.getSize())) {
}
Dimension d = this.getSize();
Graphics2D g2d = (Graphics2D) g;
if (drawnData != null && drawnData.size() > 0) {
g2d.setColor(GDE.getColor());
Iterator dat = drawnData.iterator();
int i = 0;
Double chartNum = 0.0;
try {
chartNum = (Double) dat.next();
int a = chartNumber(chartNum, (int)(d.height*0.95), GDE.getMinValue(), GDE.getMaxValue());
while (dat.hasNext()) {
chartNum = (Double) dat.next();
int b = chartNumber(chartNum, (int)(d.height*0.95), GDE.getMinValue(), GDE.getMaxValue());
if (i >= nullData * zoom.getZoom()) {
if (zoom.getZoom() > 5) {
g2d.fillOval(i - 2, a - 2, 4, 4);
}
g2d.drawLine(i, a, i + zoom.getZoom(), b);
}
a = b;
i += zoom.getZoom();
}
} catch (ConcurrentModificationException CME) {
System.out.println(this.getClass().toString() + " " + CME.getMessage());
}
}
}
|
diff --git a/src/com/google/videoeditor/widgets/PlayheadView.java b/src/com/google/videoeditor/widgets/PlayheadView.java
index 16d3172..30eb822 100755
--- a/src/com/google/videoeditor/widgets/PlayheadView.java
+++ b/src/com/google/videoeditor/widgets/PlayheadView.java
@@ -1,196 +1,197 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.videoeditor.widgets;
import com.google.videoeditor.R;
import com.google.videoeditor.service.VideoEditorProject;
import com.google.videoeditor.util.StringUtils;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
/**
* The view which displays the scroll position
*/
public class PlayheadView extends View {
// Instance variables
private final Paint mLinePaint;
private final Paint mTextPaint;
private final int mTicksHeight;
private final int mScreenWidth;
private final ScrollViewListener mScrollListener;
private int mScrollX;
private VideoEditorProject mProject;
/*
* {@inheritDoc}
*/
public PlayheadView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final Resources resources = context.getResources();
// Prepare the Paint used to draw the tick marks
mLinePaint = new Paint();
mLinePaint.setColor(resources.getColor(R.color.playhead_tick_color));
mLinePaint.setStrokeWidth(2);
mLinePaint.setStyle(Paint.Style.STROKE);
// Prepare the Paint used to draw the text
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setColor(resources.getColor(R.color.playhead_tick_color));
mTextPaint.setTextSize(18);
// The ticks height
mTicksHeight = (int)resources.getDimension(R.dimen.playhead_tick_height);
// Get the screen width
final Display display = ((WindowManager)context.getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
final DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScreenWidth = metrics.widthPixels;
// Listen to scroll events and repaint this view as needed
mScrollListener = new ScrollViewListener() {
/*
* {@inheritDoc}
*/
public void onScrollBegin(View view, int scrollX, int scrollY, boolean appScroll) {
}
/*
* {@inheritDoc}
*/
public void onScrollProgress(View view, int scrollX, int scrollY, boolean appScroll) {
mScrollX = scrollX;
+ invalidate();
}
/*
* {@inheritDoc}
*/
public void onScrollEnd(View view, int scrollX, int scrollY, boolean appScroll) {
mScrollX = scrollX;
invalidate();
}
};
}
/*
* {@inheritDoc}
*/
public PlayheadView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/*
* {@inheritDoc}
*/
public PlayheadView(Context context) {
this(context, null, 0);
}
/*
* {@inheritDoc}
*/
@Override
protected void onAttachedToWindow() {
final TimelineHorizontalScrollView scrollView =
(TimelineHorizontalScrollView)((View)getParent()).getParent();
mScrollX = scrollView.getScrollX();
scrollView.addScrollListener(mScrollListener);
}
/*
* {@inheritDoc}
*/
@Override
protected void onDetachedFromWindow() {
final TimelineHorizontalScrollView scrollView =
(TimelineHorizontalScrollView)((View)getParent()).getParent();
scrollView.removeScrollListener(mScrollListener);
}
/**
* @param project The project
*/
public void setProject(VideoEditorProject project) {
mProject = project;
}
/*
* {@inheritDoc}
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mProject == null) {
return;
}
final long durationMs = mProject.computeDuration();
final long durationSec = durationMs / 1000;
if (durationMs == 0 || durationSec == 0) {
final String timeText = StringUtils.getSimpleTimestampAsString(getContext(), 0);
canvas.drawText(timeText, (getWidth() / 2) - 35, 28, mTextPaint);
return;
}
final int width = getWidth() - mScreenWidth;
// Compute the number of pixels per second
final int pixelsPerSec = (int)(width / durationSec);
// Compute the distance between ticks
final long tickMs;
if (pixelsPerSec < 4) {
tickMs = 240000;
} else if (pixelsPerSec < 6) {
tickMs = 120000;
} else if (pixelsPerSec < 10) {
tickMs = 60000;
} else if (pixelsPerSec < 50) {
tickMs = 10000;
} else if (pixelsPerSec < 200) {
tickMs = 5000;
} else {
tickMs = 1000;
}
final float spacing = ((float)(width * tickMs) / (float)durationMs);
final float startX = Math.max(mScrollX - (((mScrollX - (mScreenWidth / 2)) % spacing)),
mScreenWidth / 2);
float startMs = ((tickMs * (startX - (mScreenWidth / 2))) / spacing);
startMs = Math.round(startMs);
startMs -= (startMs % tickMs);
final float endX = Math.min(mScrollX + mScreenWidth, getWidth() - (mScreenWidth / 2));
for (float i = startX; i <= endX; i += spacing, startMs += tickMs) {
final String timeText = StringUtils.getSimpleTimestampAsString(getContext(),
(long)startMs);
canvas.drawText(timeText, i - 35, 28, mTextPaint);
canvas.drawLine(i, 0, i, mTicksHeight, mLinePaint);
}
}
}
| true | true |
public PlayheadView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final Resources resources = context.getResources();
// Prepare the Paint used to draw the tick marks
mLinePaint = new Paint();
mLinePaint.setColor(resources.getColor(R.color.playhead_tick_color));
mLinePaint.setStrokeWidth(2);
mLinePaint.setStyle(Paint.Style.STROKE);
// Prepare the Paint used to draw the text
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setColor(resources.getColor(R.color.playhead_tick_color));
mTextPaint.setTextSize(18);
// The ticks height
mTicksHeight = (int)resources.getDimension(R.dimen.playhead_tick_height);
// Get the screen width
final Display display = ((WindowManager)context.getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
final DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScreenWidth = metrics.widthPixels;
// Listen to scroll events and repaint this view as needed
mScrollListener = new ScrollViewListener() {
/*
* {@inheritDoc}
*/
public void onScrollBegin(View view, int scrollX, int scrollY, boolean appScroll) {
}
/*
* {@inheritDoc}
*/
public void onScrollProgress(View view, int scrollX, int scrollY, boolean appScroll) {
mScrollX = scrollX;
}
/*
* {@inheritDoc}
*/
public void onScrollEnd(View view, int scrollX, int scrollY, boolean appScroll) {
mScrollX = scrollX;
invalidate();
}
};
}
|
public PlayheadView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final Resources resources = context.getResources();
// Prepare the Paint used to draw the tick marks
mLinePaint = new Paint();
mLinePaint.setColor(resources.getColor(R.color.playhead_tick_color));
mLinePaint.setStrokeWidth(2);
mLinePaint.setStyle(Paint.Style.STROKE);
// Prepare the Paint used to draw the text
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setColor(resources.getColor(R.color.playhead_tick_color));
mTextPaint.setTextSize(18);
// The ticks height
mTicksHeight = (int)resources.getDimension(R.dimen.playhead_tick_height);
// Get the screen width
final Display display = ((WindowManager)context.getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
final DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScreenWidth = metrics.widthPixels;
// Listen to scroll events and repaint this view as needed
mScrollListener = new ScrollViewListener() {
/*
* {@inheritDoc}
*/
public void onScrollBegin(View view, int scrollX, int scrollY, boolean appScroll) {
}
/*
* {@inheritDoc}
*/
public void onScrollProgress(View view, int scrollX, int scrollY, boolean appScroll) {
mScrollX = scrollX;
invalidate();
}
/*
* {@inheritDoc}
*/
public void onScrollEnd(View view, int scrollX, int scrollY, boolean appScroll) {
mScrollX = scrollX;
invalidate();
}
};
}
|
diff --git a/src/org/encog/neural/pattern/BAMPattern.java b/src/org/encog/neural/pattern/BAMPattern.java
index 59b563001..4712596e8 100644
--- a/src/org/encog/neural/pattern/BAMPattern.java
+++ b/src/org/encog/neural/pattern/BAMPattern.java
@@ -1,175 +1,175 @@
/*
* Encog Artificial Intelligence Framework v2.x
* Java Version
* http://www.heatonresearch.com/encog/
* http://code.google.com/p/encog-java/
*
* Copyright 2008-2009, Heaton Research Inc., and individual contributors.
* See the copyright.txt in the distribution for a full listing of
* individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.encog.neural.pattern;
import org.encog.neural.activation.ActivationBiPolar;
import org.encog.neural.activation.ActivationFunction;
import org.encog.neural.networks.BasicNetwork;
import org.encog.neural.networks.layers.BasicLayer;
import org.encog.neural.networks.layers.Layer;
import org.encog.neural.networks.logic.BAMLogic;
import org.encog.neural.networks.synapse.Synapse;
import org.encog.neural.networks.synapse.WeightedSynapse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Construct a Bidirectional Access Memory (BAM) neural network. This
* neural network type learns to associate one pattern with another. The
* two patterns do not need to be of the same length. This network has two
* that are connected to each other. Though they are labeled as input and
* output layers to Encog, they are both equal, and should simply be thought
* of as the two layers that make up the net.
*
*/
public class BAMPattern implements NeuralNetworkPattern {
public final static String TAG_F1 = "F1";
public final static String TAG_F2 = "F2";
/**
* The number of neurons in the first layer.
*/
private int f1Neurons;
/**
* The number of neurons in the second layer.
*/
private int f2Neurons;
/**
* The logging object.
*/
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* Unused, a BAM has no hidden layers.
* @param count Not used.
*/
public void addHiddenLayer(int count) {
final String str = "A BAM network has no hidden layers.";
if (this.logger.isErrorEnabled()) {
this.logger.error(str);
}
throw new PatternError(str);
}
/**
* Clear any settings on the pattern.
*/
public void clear() {
this.f1Neurons = this.f2Neurons = 0;
}
/**
* @return The generated network.
*/
public BasicNetwork generate() {
BasicNetwork network = new BasicNetwork(new BAMLogic());
Layer f1Layer = new BasicLayer(new ActivationBiPolar(), false,
f1Neurons);
Layer f2Layer = new BasicLayer(new ActivationBiPolar(), false,
f2Neurons);
Synapse synapseInputToOutput = new WeightedSynapse(f1Layer,
f2Layer);
Synapse synapseOutputToInput = new WeightedSynapse(f2Layer,
f1Layer);
f1Layer.addSynapse(synapseInputToOutput);
f2Layer.addSynapse(synapseOutputToInput);
- network.tagLayer(BAMPattern.TAG_F1, f2Layer);
- network.tagLayer(BAMPattern.TAG_F1, f2Layer);
+ network.tagLayer(BAMPattern.TAG_F1, f1Layer);
+ network.tagLayer(BAMPattern.TAG_F2, f2Layer);
network.getStructure().finalizeStructure();
network.getStructure().finalizeStructure();
f1Layer.setY(PatternConst.START_Y);
f2Layer.setY(PatternConst.START_Y);
f1Layer.setX(PatternConst.START_X);
f2Layer.setX(PatternConst.INDENT_X);
return network;
}
/**
* Not used, the BAM uses a bipoloar activation function.
* @param activation Not used.
*/
public void setActivationFunction(ActivationFunction activation) {
final String str = "A BAM network can't specify a custom activation function.";
if (this.logger.isErrorEnabled()) {
this.logger.error(str);
}
throw new PatternError(str);
}
/**
* Set the F1 neurons. The BAM really does not have an input and output
* layer, so this is simply setting the number of neurons that are in the
* first layer.
* @param count The number of neurons in the first layer.
*/
public void setF1Neurons(int count) {
this.f1Neurons = count;
}
/**
* Set the output neurons. The BAM really does not have an input and output
* layer, so this is simply setting the number of neurons that are in the
* second layer.
* @param count The number of neurons in the second layer.
*/
public void setF2Neurons(int count) {
this.f2Neurons = count;
}
@Override
public void setInputNeurons(int count) {
final String str = "A BAM network has no input layer, consider setting F1 layer.";
if (this.logger.isErrorEnabled()) {
this.logger.error(str);
}
throw new PatternError(str);
}
@Override
public void setOutputNeurons(int count) {
final String str = "A BAM network has no output layer, consider setting F2 layer.";
if (this.logger.isErrorEnabled()) {
this.logger.error(str);
}
throw new PatternError(str);
}
}
| true | true |
public BasicNetwork generate() {
BasicNetwork network = new BasicNetwork(new BAMLogic());
Layer f1Layer = new BasicLayer(new ActivationBiPolar(), false,
f1Neurons);
Layer f2Layer = new BasicLayer(new ActivationBiPolar(), false,
f2Neurons);
Synapse synapseInputToOutput = new WeightedSynapse(f1Layer,
f2Layer);
Synapse synapseOutputToInput = new WeightedSynapse(f2Layer,
f1Layer);
f1Layer.addSynapse(synapseInputToOutput);
f2Layer.addSynapse(synapseOutputToInput);
network.tagLayer(BAMPattern.TAG_F1, f2Layer);
network.tagLayer(BAMPattern.TAG_F1, f2Layer);
network.getStructure().finalizeStructure();
network.getStructure().finalizeStructure();
f1Layer.setY(PatternConst.START_Y);
f2Layer.setY(PatternConst.START_Y);
f1Layer.setX(PatternConst.START_X);
f2Layer.setX(PatternConst.INDENT_X);
return network;
}
|
public BasicNetwork generate() {
BasicNetwork network = new BasicNetwork(new BAMLogic());
Layer f1Layer = new BasicLayer(new ActivationBiPolar(), false,
f1Neurons);
Layer f2Layer = new BasicLayer(new ActivationBiPolar(), false,
f2Neurons);
Synapse synapseInputToOutput = new WeightedSynapse(f1Layer,
f2Layer);
Synapse synapseOutputToInput = new WeightedSynapse(f2Layer,
f1Layer);
f1Layer.addSynapse(synapseInputToOutput);
f2Layer.addSynapse(synapseOutputToInput);
network.tagLayer(BAMPattern.TAG_F1, f1Layer);
network.tagLayer(BAMPattern.TAG_F2, f2Layer);
network.getStructure().finalizeStructure();
network.getStructure().finalizeStructure();
f1Layer.setY(PatternConst.START_Y);
f2Layer.setY(PatternConst.START_Y);
f1Layer.setX(PatternConst.START_X);
f2Layer.setX(PatternConst.INDENT_X);
return network;
}
|
diff --git a/src/org/pentaho/agilebi/pdi/perspective/PublisherHelper.java b/src/org/pentaho/agilebi/pdi/perspective/PublisherHelper.java
index a4c5dfa..87da66f 100644
--- a/src/org/pentaho/agilebi/pdi/perspective/PublisherHelper.java
+++ b/src/org/pentaho/agilebi/pdi/perspective/PublisherHelper.java
@@ -1,159 +1,159 @@
package org.pentaho.agilebi.pdi.perspective;
import java.io.File;
import org.pentaho.agilebi.pdi.modeler.BiServerConnection;
import org.pentaho.agilebi.pdi.modeler.ModelServerPublish;
import org.pentaho.agilebi.pdi.modeler.ModelerException;
import org.pentaho.agilebi.pdi.modeler.ModelerWorkspace;
import org.pentaho.agilebi.pdi.modeler.XulDialogPublish;
import org.pentaho.agilebi.pdi.modeler.XulUI;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.gui.SpoonFactory;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.modules.parser.bundle.writer.BundleWriter;
import org.pentaho.reporting.engine.classic.extensions.datasources.pmd.PmdDataFactory;
import org.pentaho.reporting.libraries.base.util.StringUtils;
import org.pentaho.ui.xul.XulException;
public class PublisherHelper {
public static void publish(ModelerWorkspace workspace, String publishingFile,
String comment, int treeDepth, DatabaseMeta databaseMeta, String filename, boolean checkDatasources,
boolean showServerSelection, boolean showFolders, boolean showCurrentFolder, String serverPathTemplate, String extension, String databaseName ) throws ModelerException {
try {
if (StringUtils.isEmpty(publishingFile)) {
SpoonFactory.getInstance().messageBox(BaseMessages.getString(XulUI.class,"ModelServerPublish.Publish.UnsavedModel"), //$NON-NLS-1$
"Dialog Error", false, Const.ERROR); //$NON-NLS-1$
return;
}
ModelServerPublish publisher = new ModelServerPublish();
publisher.setModel(workspace);
Spoon spoon = ((Spoon) SpoonFactory.getInstance());
try {
XulDialogPublish publishDialog = new XulDialogPublish(spoon.getShell());
publishDialog.setFolderTreeDepth(treeDepth);
publishDialog.setComment(comment);
publishDialog.setDatabaseMeta(databaseMeta);
publishDialog.setFilename(filename);
publishDialog.setCheckDatasources(checkDatasources);
publishDialog.setShowLocation(showServerSelection, showFolders, showCurrentFolder);
publishDialog.setPathTemplate(serverPathTemplate);
publishDialog.showDialog();
if (publishDialog.isAccepted()) {
// now try to publish
String selectedPath = publishDialog.getPath();
// we always publish to {solution}/resources/metadata
BiServerConnection biServerConnection = publishDialog.getBiServerConnection();
publisher.setBiServerConnection(biServerConnection);
boolean publishDatasource = publishDialog.isPublishDataSource();
String repositoryPath = null;
if(serverPathTemplate != null) {
String selectedSolution = null;
if(selectedPath.indexOf("/") != -1) { //$NON-NLS-1$
selectedSolution = selectedPath.substring(0, selectedPath.indexOf("/")); //$NON-NLS-1$
} else {
selectedSolution = selectedPath;
}
repositoryPath = serverPathTemplate.replace("{path}", selectedSolution); //$NON-NLS-1$
}
if(publishingFile.endsWith(".xmi")) { //$NON-NLS-1$
selectedPath = repositoryPath;
}
filename = publishDialog.getFilename();
publisher
.publishToServer(
filename + extension, databaseName, filename, repositoryPath, selectedPath, publishDatasource, true, publishDialog.isExistentDatasource(), publishingFile);
}
} catch (XulException e) {
e.printStackTrace();
SpoonFactory.getInstance().messageBox("Could not create dialog: " + e.getLocalizedMessage(), "Dialog Error", //$NON-NLS-1$ //$NON-NLS-2$
false, Const.ERROR);
}
} catch (Exception e) {
throw new ModelerException(e);
}
}
public static void publishPrpt(MasterReport report, ModelerWorkspace workspace, String xmi, String prpt,
String comment, int treeDepth, DatabaseMeta databaseMeta, String modelName, boolean checkDatasources,
boolean showServerSelection, boolean showFolders, boolean showCurrentFolder, String serverPathTemplate, String databaseName ) throws ModelerException {
try {
if (StringUtils.isEmpty(prpt)) {
SpoonFactory.getInstance().messageBox(BaseMessages.getString(XulUI.class,"ModelServerPublish.Publish.UnsavedModel"), //$NON-NLS-1$
"Dialog Error", false, Const.ERROR); //$NON-NLS-1$
return;
}
ModelServerPublish publisher = new ModelServerPublish();
publisher.setModel(workspace);
Spoon spoon = ((Spoon) SpoonFactory.getInstance());
try {
XulDialogPublish publishDialog = new XulDialogPublish(spoon.getShell());
publishDialog.setFolderTreeDepth(treeDepth);
publishDialog.setComment(comment);
publishDialog.setDatabaseMeta(databaseMeta);
publishDialog.setFilename(modelName);
publishDialog.setCheckDatasources(checkDatasources);
publishDialog.setShowLocation(showServerSelection, showFolders, showCurrentFolder);
publishDialog.setPathTemplate(serverPathTemplate);
publishDialog.showDialog();
if (publishDialog.isAccepted()) {
// now try to publish
String thePrptPublishingPath = publishDialog.getPath();
// we always publish to {solution}/resources/metadata
BiServerConnection biServerConnection = publishDialog.getBiServerConnection();
publisher.setBiServerConnection(biServerConnection);
boolean publishDatasource = publishDialog.isPublishDataSource();
String theXmiPublishingPath = null;
if(serverPathTemplate != null) {
String theSolution = null;
- if(thePrptPublishingPath.indexOf("/") != -1) { //$NON-NLS-1$
- theSolution = thePrptPublishingPath.substring(0, thePrptPublishingPath.indexOf("/")); //$NON-NLS-1$
+ if(thePrptPublishingPath.indexOf(File.pathSeparator) != -1) { //$NON-NLS-1$
+ theSolution = thePrptPublishingPath.substring(0, thePrptPublishingPath.indexOf(File.pathSeparator)); //$NON-NLS-1$
} else {
theSolution = thePrptPublishingPath;
}
theXmiPublishingPath = serverPathTemplate.replace("{path}", theSolution); //$NON-NLS-1$
}
// Set the domain id to the xmi.
- String theXmiFile = xmi.substring(xmi.lastIndexOf("\\") + 1, xmi.length()); //$NON-NLS-1$
+ String theXmiFile = xmi.substring(xmi.lastIndexOf(File.pathSeparator) + 1, xmi.length()); //$NON-NLS-1$
PmdDataFactory thePmdDataFactory = (PmdDataFactory) report.getDataFactory();
String theDomainId = theXmiPublishingPath + "/" + theXmiFile; //$NON-NLS-1$
thePmdDataFactory.setDomainId(theDomainId);
// Point the mql query to the xmi instead of default.
String theMQLQuery = thePmdDataFactory.getQuery("default"); //$NON-NLS-1$
String theQuery = theMQLQuery.substring(0, theMQLQuery.lastIndexOf("default")) //$NON-NLS-1$
+ theDomainId + theMQLQuery.substring(theMQLQuery.lastIndexOf("default") + 7, theMQLQuery.length()); //$NON-NLS-1$
thePmdDataFactory.setQuery("default", theQuery); //$NON-NLS-1$
try {
BundleWriter.writeReportToZipFile(report, new File(prpt));
} catch (Exception e) {
throw new ModelerException(e);
}
publisher.publishPrptToServer(theXmiPublishingPath, thePrptPublishingPath, publishDatasource, publishDialog.isExistentDatasource(), xmi, prpt);
thePmdDataFactory.setQuery("default", theMQLQuery); //$NON-NLS-1$
}
} catch (XulException e) {
e.printStackTrace();
SpoonFactory.getInstance().messageBox("Could not create dialog: " + e.getLocalizedMessage(), "Dialog Error", //$NON-NLS-1$ //$NON-NLS-2$
false, Const.ERROR);
}
} catch (Exception e) {
throw new ModelerException(e);
}
}
}
| false | true |
public static void publishPrpt(MasterReport report, ModelerWorkspace workspace, String xmi, String prpt,
String comment, int treeDepth, DatabaseMeta databaseMeta, String modelName, boolean checkDatasources,
boolean showServerSelection, boolean showFolders, boolean showCurrentFolder, String serverPathTemplate, String databaseName ) throws ModelerException {
try {
if (StringUtils.isEmpty(prpt)) {
SpoonFactory.getInstance().messageBox(BaseMessages.getString(XulUI.class,"ModelServerPublish.Publish.UnsavedModel"), //$NON-NLS-1$
"Dialog Error", false, Const.ERROR); //$NON-NLS-1$
return;
}
ModelServerPublish publisher = new ModelServerPublish();
publisher.setModel(workspace);
Spoon spoon = ((Spoon) SpoonFactory.getInstance());
try {
XulDialogPublish publishDialog = new XulDialogPublish(spoon.getShell());
publishDialog.setFolderTreeDepth(treeDepth);
publishDialog.setComment(comment);
publishDialog.setDatabaseMeta(databaseMeta);
publishDialog.setFilename(modelName);
publishDialog.setCheckDatasources(checkDatasources);
publishDialog.setShowLocation(showServerSelection, showFolders, showCurrentFolder);
publishDialog.setPathTemplate(serverPathTemplate);
publishDialog.showDialog();
if (publishDialog.isAccepted()) {
// now try to publish
String thePrptPublishingPath = publishDialog.getPath();
// we always publish to {solution}/resources/metadata
BiServerConnection biServerConnection = publishDialog.getBiServerConnection();
publisher.setBiServerConnection(biServerConnection);
boolean publishDatasource = publishDialog.isPublishDataSource();
String theXmiPublishingPath = null;
if(serverPathTemplate != null) {
String theSolution = null;
if(thePrptPublishingPath.indexOf("/") != -1) { //$NON-NLS-1$
theSolution = thePrptPublishingPath.substring(0, thePrptPublishingPath.indexOf("/")); //$NON-NLS-1$
} else {
theSolution = thePrptPublishingPath;
}
theXmiPublishingPath = serverPathTemplate.replace("{path}", theSolution); //$NON-NLS-1$
}
// Set the domain id to the xmi.
String theXmiFile = xmi.substring(xmi.lastIndexOf("\\") + 1, xmi.length()); //$NON-NLS-1$
PmdDataFactory thePmdDataFactory = (PmdDataFactory) report.getDataFactory();
String theDomainId = theXmiPublishingPath + "/" + theXmiFile; //$NON-NLS-1$
thePmdDataFactory.setDomainId(theDomainId);
// Point the mql query to the xmi instead of default.
String theMQLQuery = thePmdDataFactory.getQuery("default"); //$NON-NLS-1$
String theQuery = theMQLQuery.substring(0, theMQLQuery.lastIndexOf("default")) //$NON-NLS-1$
+ theDomainId + theMQLQuery.substring(theMQLQuery.lastIndexOf("default") + 7, theMQLQuery.length()); //$NON-NLS-1$
thePmdDataFactory.setQuery("default", theQuery); //$NON-NLS-1$
try {
BundleWriter.writeReportToZipFile(report, new File(prpt));
} catch (Exception e) {
throw new ModelerException(e);
}
publisher.publishPrptToServer(theXmiPublishingPath, thePrptPublishingPath, publishDatasource, publishDialog.isExistentDatasource(), xmi, prpt);
thePmdDataFactory.setQuery("default", theMQLQuery); //$NON-NLS-1$
}
} catch (XulException e) {
e.printStackTrace();
SpoonFactory.getInstance().messageBox("Could not create dialog: " + e.getLocalizedMessage(), "Dialog Error", //$NON-NLS-1$ //$NON-NLS-2$
false, Const.ERROR);
}
} catch (Exception e) {
throw new ModelerException(e);
}
}
|
public static void publishPrpt(MasterReport report, ModelerWorkspace workspace, String xmi, String prpt,
String comment, int treeDepth, DatabaseMeta databaseMeta, String modelName, boolean checkDatasources,
boolean showServerSelection, boolean showFolders, boolean showCurrentFolder, String serverPathTemplate, String databaseName ) throws ModelerException {
try {
if (StringUtils.isEmpty(prpt)) {
SpoonFactory.getInstance().messageBox(BaseMessages.getString(XulUI.class,"ModelServerPublish.Publish.UnsavedModel"), //$NON-NLS-1$
"Dialog Error", false, Const.ERROR); //$NON-NLS-1$
return;
}
ModelServerPublish publisher = new ModelServerPublish();
publisher.setModel(workspace);
Spoon spoon = ((Spoon) SpoonFactory.getInstance());
try {
XulDialogPublish publishDialog = new XulDialogPublish(spoon.getShell());
publishDialog.setFolderTreeDepth(treeDepth);
publishDialog.setComment(comment);
publishDialog.setDatabaseMeta(databaseMeta);
publishDialog.setFilename(modelName);
publishDialog.setCheckDatasources(checkDatasources);
publishDialog.setShowLocation(showServerSelection, showFolders, showCurrentFolder);
publishDialog.setPathTemplate(serverPathTemplate);
publishDialog.showDialog();
if (publishDialog.isAccepted()) {
// now try to publish
String thePrptPublishingPath = publishDialog.getPath();
// we always publish to {solution}/resources/metadata
BiServerConnection biServerConnection = publishDialog.getBiServerConnection();
publisher.setBiServerConnection(biServerConnection);
boolean publishDatasource = publishDialog.isPublishDataSource();
String theXmiPublishingPath = null;
if(serverPathTemplate != null) {
String theSolution = null;
if(thePrptPublishingPath.indexOf(File.pathSeparator) != -1) { //$NON-NLS-1$
theSolution = thePrptPublishingPath.substring(0, thePrptPublishingPath.indexOf(File.pathSeparator)); //$NON-NLS-1$
} else {
theSolution = thePrptPublishingPath;
}
theXmiPublishingPath = serverPathTemplate.replace("{path}", theSolution); //$NON-NLS-1$
}
// Set the domain id to the xmi.
String theXmiFile = xmi.substring(xmi.lastIndexOf(File.pathSeparator) + 1, xmi.length()); //$NON-NLS-1$
PmdDataFactory thePmdDataFactory = (PmdDataFactory) report.getDataFactory();
String theDomainId = theXmiPublishingPath + "/" + theXmiFile; //$NON-NLS-1$
thePmdDataFactory.setDomainId(theDomainId);
// Point the mql query to the xmi instead of default.
String theMQLQuery = thePmdDataFactory.getQuery("default"); //$NON-NLS-1$
String theQuery = theMQLQuery.substring(0, theMQLQuery.lastIndexOf("default")) //$NON-NLS-1$
+ theDomainId + theMQLQuery.substring(theMQLQuery.lastIndexOf("default") + 7, theMQLQuery.length()); //$NON-NLS-1$
thePmdDataFactory.setQuery("default", theQuery); //$NON-NLS-1$
try {
BundleWriter.writeReportToZipFile(report, new File(prpt));
} catch (Exception e) {
throw new ModelerException(e);
}
publisher.publishPrptToServer(theXmiPublishingPath, thePrptPublishingPath, publishDatasource, publishDialog.isExistentDatasource(), xmi, prpt);
thePmdDataFactory.setQuery("default", theMQLQuery); //$NON-NLS-1$
}
} catch (XulException e) {
e.printStackTrace();
SpoonFactory.getInstance().messageBox("Could not create dialog: " + e.getLocalizedMessage(), "Dialog Error", //$NON-NLS-1$ //$NON-NLS-2$
false, Const.ERROR);
}
} catch (Exception e) {
throw new ModelerException(e);
}
}
|
diff --git a/src/lib/com/izforge/izpack/panels/PathSelectionPanel.java b/src/lib/com/izforge/izpack/panels/PathSelectionPanel.java
index 83e238139..709c28a0d 100644
--- a/src/lib/com/izforge/izpack/panels/PathSelectionPanel.java
+++ b/src/lib/com/izforge/izpack/panels/PathSelectionPanel.java
@@ -1,211 +1,211 @@
/*
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2004 Klaus Bartz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.izforge.izpack.panels;
import com.izforge.izpack.gui.ButtonFactory;
import com.izforge.izpack.gui.IzPanelConstraints;
import com.izforge.izpack.gui.IzPanelLayout;
import com.izforge.izpack.gui.LayoutConstants;
import com.izforge.izpack.installer.InstallData;
import com.izforge.izpack.installer.IzPanel;
import com.izforge.izpack.installer.LayoutHelper;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
/**
* This is a sub panel which contains a text field and a browse button for path selection. This is
* NOT an IzPanel, else it is made to use in an IzPanel for any path selection. If the IzPanel
* parent implements ActionListener, the ActionPerformed method will be called, if
* PathSelectionPanel.ActionPerformed was called with a source other than the browse button. This
* can be used to perform parentFrame.navigateNext in the IzPanel parent. An example implementation
* is done in com.izforge.izpack.panels.PathInputPanel.
*
* @author Klaus Bartz
*/
public class PathSelectionPanel extends JPanel implements ActionListener, LayoutConstants
{
/**
*
*/
private static final long serialVersionUID = 3618700794577105718L;
/**
* The text field for the path.
*/
private JTextField textField;
/**
* The 'browse' button.
*/
private JButton browseButton;
/**
* IzPanel parent (not the InstallerFrame).
*/
private IzPanel parent;
/**
* The installer internal data.
*/
private InstallData idata;
/**
* The constructor. Be aware, parent is the parent IzPanel, not the installer frame.
*
* @param parent The parent IzPanel.
* @param idata The installer internal data.
*/
public PathSelectionPanel(IzPanel parent, InstallData idata)
{
super();
this.parent = parent;
this.idata = idata;
createLayout();
}
/**
* Creates the layout for this sub panel.
*/
protected void createLayout()
{
// We would use the IzPanelLayout also in this "sub" panel.
// In an IzPanel there is support for this layout manager in
// more than one place, but not in this panel so we have
// to make all things needed.
// First create a layout helper.
LayoutHelper layoutHelper = new LayoutHelper(this);
// Start the layout.
layoutHelper.startLayout(new IzPanelLayout());
// One of the rare points we need explicit a constraints.
IzPanelConstraints ipc = IzPanelLayout.getDefaultConstraint(TEXT_CONSTRAINT);
// The text field should be stretched.
ipc.setXStretch(1.0);
textField = new JTextField(idata.getInstallPath(), 10);
textField.addActionListener(this);
parent.setInitialFocus(textField);
add(textField, ipc);
// We would have place between text field and button.
add(IzPanelLayout.createHorizontalFiller(3));
// No explicit constraints for the button (else implicit) because
// defaults are OK.
browseButton = ButtonFactory.createButton(parent.getInstallerFrame().langpack
.getString("TargetPanel.browse"), parent.getInstallerFrame().icons
.getImageIcon("open"), idata.buttonsHColor);
browseButton.addActionListener(this);
add(browseButton);
}
// There are problems with the size if no other component needs the
// full size. Sometimes directly, somtimes only after a back step.
public Dimension getMinimumSize()
{
Dimension ss = super.getPreferredSize();
Dimension retval = parent.getSize();
retval.height = ss.height;
return (retval);
}
/**
* Actions-handling method.
*
* @param e The event.
*/
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == browseButton)
{
// The user wants to browse its filesystem
// Prepares the file chooser
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(textField.getText()));
fc.setMultiSelectionEnabled(false);
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.addChoosableFileFilter(fc.getAcceptAllFileFilter());
// Shows it
- if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
+ if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
{
String path = fc.getSelectedFile().getAbsolutePath();
textField.setText(path);
}
}
else
{
if (parent instanceof ActionListener)
{
((ActionListener) parent).actionPerformed(e);
}
}
}
/**
* Returns the chosen path.
*
* @return the chosen path
*/
public String getPath()
{
return (textField.getText());
}
/**
* Sets the contents of the text field to the given path.
*
* @param path the path to be set
*/
public void setPath(String path)
{
textField.setText(path);
}
/**
* Returns the text input field for the path. This methode can be used to differ in a
* ActionPerformed method of the parent between the browse button and the text field.
*
* @return the text input field for the path
*/
public JTextField getPathInputField()
{
return textField;
}
/**
* Returns the browse button object for modification or for use with a different ActionListener.
*
* @return the browse button to open the JFileChooser
*/
public JButton getBrowseButton()
{
return browseButton;
}
}
| true | true |
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == browseButton)
{
// The user wants to browse its filesystem
// Prepares the file chooser
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(textField.getText()));
fc.setMultiSelectionEnabled(false);
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.addChoosableFileFilter(fc.getAcceptAllFileFilter());
// Shows it
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
String path = fc.getSelectedFile().getAbsolutePath();
textField.setText(path);
}
}
else
{
if (parent instanceof ActionListener)
{
((ActionListener) parent).actionPerformed(e);
}
}
}
|
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == browseButton)
{
// The user wants to browse its filesystem
// Prepares the file chooser
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(textField.getText()));
fc.setMultiSelectionEnabled(false);
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.addChoosableFileFilter(fc.getAcceptAllFileFilter());
// Shows it
if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
{
String path = fc.getSelectedFile().getAbsolutePath();
textField.setText(path);
}
}
else
{
if (parent instanceof ActionListener)
{
((ActionListener) parent).actionPerformed(e);
}
}
}
|
diff --git a/preptool/model/layout/manager/RenderingUtils.java b/preptool/model/layout/manager/RenderingUtils.java
index 828dab8a..d31e936b 100644
--- a/preptool/model/layout/manager/RenderingUtils.java
+++ b/preptool/model/layout/manager/RenderingUtils.java
@@ -1,958 +1,958 @@
/**
* This file is part of VoteBox.
*
* VoteBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as published by
* the Free Software Foundation.
*
* You should have received a copy of the GNU General Public License
* along with VoteBox, found in the root of any distribution or
* repository containing all or part of VoteBox.
*
* THIS SOFTWARE IS PROVIDED BY WILLIAM MARSH RICE UNIVERSITY, HOUSTON,
* TX AND IS PROVIDED 'AS IS' AND WITHOUT ANY EXPRESS, IMPLIED OR
* STATUTORY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF
* ACCURACY, COMPLETENESS, AND NONINFRINGEMENT. THE SOFTWARE USER SHALL
* INDEMNIFY, DEFEND AND HOLD HARMLESS RICE UNIVERSITY AND ITS FACULTY,
* STAFF AND STUDENTS FROM ANY AND ALL CLAIMS, ACTIONS, DAMAGES, LOSSES,
* LIABILITIES, COSTS AND EXPENSES, INCLUDING ATTORNEYS' FEES AND COURT
* COSTS, DIRECTLY OR INDIRECTLY ARISING OUR OF OR IN CONNECTION WITH
* ACCESS OR USE OF THE SOFTWARE.
*/
package preptool.model.layout.manager;
import printer.PrintImageUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import printer.PrintImageUtils;
/**
* A set of static functions useful for rendering different types of layout
* components. These methods are independent of implementation as they take many
* customization parameters.
* @author cshaw, ttorous
*/
public class RenderingUtils {
/**
* Max dimensions for buttons. Longer text will be clipped.
*/
public static final int MAX_BUTTON_WIDTH = 600;
public static final int MAX_BUTTON_HEIGHT = 100;
/**
* Scaling factor for high dpi printed images
* Choose this value based on a 360 dpi printer and the fact that java's default is 72 dpi and 360/72 is a whole number
*/
public static final int DPI_SCALE_FACTOR = Math.round(1.0f*300/72);
/**
* The dimensions of the selection box.
*/
public static final int SELECTION_BOX_WIDTH = 15*DPI_SCALE_FACTOR;
public static final int SELECTION_BOX_HEIGHT = 10*DPI_SCALE_FACTOR;
/**
* The standard font to use
*/
public static final String FONT_NAME = "Arial Unicode";
/**
* A dummy 1x1 image used for getting the sizes of components
*/
private static final BufferedImage DUMMY_IMAGE = new BufferedImage(1, 1,
BufferedImage.TYPE_INT_ARGB);
/**
* Copies a buffered Image. Borrowed 100% from
* http://cui.unige.ch/~deriazm/javasources/ImgTools.java I really can't
* think of a better way of writing this code - so i just used theirs
*/
public static BufferedImage copy(BufferedImage bImage) {
int w = bImage.getWidth(null);
int h = bImage.getHeight(null);
BufferedImage bImage2 = new BufferedImage(w, h,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = bImage2.createGraphics();
g2.drawImage(bImage, 0, 0, null);
return bImage2;
}
/**
* Calculates the size of a button.<br>
* Note: Buttons do not automatically wrap - must be wrapped w/ a \n in the
* text of the button
* @param text the text of the button
* @param fontsize the size of the font to use
* @param bold whether the button has bold text
* @return the size of the Button
*/
public static Dimension getButtonSize(String text, int fontsize,
boolean bold) {
Font font = new Font(FONT_NAME, (bold) ? Font.BOLD : Font.PLAIN,
fontsize);
BufferedImage wrappedImage = DUMMY_IMAGE;
Graphics2D graphs = wrappedImage.createGraphics();
graphs.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
graphs.setFont(font);
int baseline = graphs.getFontMetrics().getAscent();
String[] words = text.split(" ");
int padding = 10;
int heightPos = padding + baseline;
int lineWidth = padding;
int maxWidth = 0; // the max width of any line
for (String word : words) // For each word try placing it on the line,
// if not jump down a line and then write it
{
Rectangle2D measurement = font.getStringBounds(word + " ",
new FontRenderContext(null, true, true));
int wordWidth = (int) measurement.getWidth();
int wordHeight = (int) measurement.getHeight();
lineWidth += wordWidth;
if (word.equals("\n")) {
maxWidth = Math.max(lineWidth, maxWidth);
heightPos += wordHeight;
lineWidth = padding;
}
}
maxWidth = Math.max(lineWidth, maxWidth);
return new Dimension(maxWidth, heightPos + padding);
}
/**
* Calculates the size of a Label.
* @param title is the text to be outputted
* @param instructions are any instructions to be italized, such as '(please
* select one)'
* @param description are any descriptions (such as those used on
* propositions)
* @param fontsize the size of the font
* @param wrappingWidth is the width at which the label should wrap
* @param bold whether the label is bold
* @param titleCentered is a boolean flag as to whether or not the text
* should be centered
* @return the size of the Label
*/
public static Dimension getLabelSize(String title, String instructions,
String description, int fontsize, int wrappingWidth, boolean bold,
boolean titleCentered) {
Font font = new Font(FONT_NAME, (bold) ? Font.BOLD : Font.PLAIN,
fontsize);
Font italicFont = new Font(FONT_NAME, Font.ITALIC, fontsize);
Font bigBoldFont = new Font(FONT_NAME, Font.BOLD, fontsize + 4);
BufferedImage wrappedImage = DUMMY_IMAGE;
Graphics2D graphs = wrappedImage.createGraphics();
graphs.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
graphs.setFont(font);
int baseline = graphs.getFontMetrics().getAscent();
String[] titleWords = title.split(" ");
int padding = 10;
int heightPos = padding + baseline;
int lineWidth = padding;
int maxWidth = 0; // the max width of any line
if (titleCentered) {
graphs.setFont(bigBoldFont);
String[][] splitText = spliteOnNewLineAndSpace(title);
for (int y = 0; y < splitText.length; y++) {
heightPos += lineHeight("line", bigBoldFont);
}
} else {
for (String word : titleWords) // For each word try placing it on
// the line,
// if not jump down a line and then write it
{
Rectangle2D measurement = font
.getStringBounds(word + " ", new FontRenderContext(
new AffineTransform(), true, true));
int wordWidth = (int) measurement.getWidth();
int wordHeight = (int) measurement.getHeight();
lineWidth += wordWidth;
if (word.equals("\n") || word.equals("<newline>")) {
maxWidth = Math.max(lineWidth, maxWidth);
heightPos += wordHeight;
lineWidth = padding;
}
}
}
if (!instructions.equals("")) // write instructions on how to use
{
String[][] splitText = spliteOnNewLineAndSpace(instructions);
for (int y = 0; y < splitText.length; y++) {
heightPos += lineHeight("line", italicFont);
}
}
if (!description.equals("")) // write description on how to use
{
heightPos += lineHeight("text", font);
description = addInNewLines(description, font, wrappingWidth,
padding);
String[][] splitText = spliteOnNewLineAndSpace(description);
for (int y = 0; y < splitText.length; y++) {
heightPos += lineHeight("line", font);
}
}
maxWidth = Math.max(lineWidth, maxWidth);
if (wrappingWidth != 0) // then wrap at the wrappingWidth or maxWidth
maxWidth = Math.max(maxWidth, wrappingWidth);
return new Dimension(maxWidth, heightPos + padding);
}
/**
* Calculates the size of a ToggleButton.<br>
* ToggleButton does not wrap unless indicated to do so w/ \n. Also if two
* names are used the second name appears at an offset. And since this is a
* togglebutton a box and possible check mark in the box are added
* @param text is the text of the togglebutton
* @param text2 is the second text of the toggle button - added on a
* secondline and indented
* @param party is the party of the candidate in the toggle button - right
* aligned on first line of button
* @param fontsize the size of the font
* @param wrappingWidth width of the button
* @param bold whether the button is bold
* @return the size of the ToggleButton
*/
public static Dimension getToggleButtonSize(String text, String text2,
String party, int fontsize, int wrappingWidth, boolean bold) {
Font font = new Font(FONT_NAME, (bold) ? Font.BOLD : Font.PLAIN,
fontsize);
BufferedImage wrappedImage = DUMMY_IMAGE;
Graphics2D graphs = wrappedImage.createGraphics();
graphs.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
graphs.setFont(font);
int baseline = graphs.getFontMetrics().getAscent();
int padding = 10;
int heightPos = padding + baseline;
int lineWidth = padding;
int maxWidth = 0; // the max width of any line
if (!text2.equals("")) {
heightPos += lineHeight(text, font);
}
maxWidth = Math.max(lineWidth, maxWidth);
return new Dimension(wrappingWidth, heightPos + padding);
}
/**
* Renders a Button and returns it as a BufferedImage.<br>
* Buttons do not automatically wrap - must be wrapped w/ a \n in the text
* of the button
* @param text is the text of the button
* @param fontsize is the size of the font
* @param bold is whether the button is bold
* @param boxed whether the button is boxed
* @param backGroundColor is the background color of the button
* @param preferredWidth desired width of the button, honored if possible
* @return the rendered Button
*/
public static BufferedImage renderButton(String text, int fontsize,
boolean bold, boolean boxed, int preferredWidth,
Color backGroundColor) {
Font font = new Font(FONT_NAME, (bold) ? Font.BOLD : Font.PLAIN,
fontsize);
BufferedImage wrappedImage = new BufferedImage(
MAX_BUTTON_WIDTH, MAX_BUTTON_HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphs = wrappedImage.createGraphics();
graphs.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
graphs.setFont(font);
graphs.setPaint(backGroundColor);
graphs.fillRect(0, 0, MAX_BUTTON_WIDTH, MAX_BUTTON_HEIGHT);
graphs.setColor(Color.BLACK); // Could make this a variable
int baseline = graphs.getFontMetrics().getAscent();
String[] words = text.split(" ");
int padding = 10;
int leading = 1;
int heightPos = padding + baseline;
int writePos = padding;
int lineWidth = padding;
int maxWidth = 0; // the max width of any line
for (String word : words) // For each word try placing it on the line,
// if not jump down a line and then write it
{
//Rectangle2D measurement = font.getStringBounds(word + " ", new FontRenderContext(new AffineTransform(), true, true));
String spacedWord = word + " ";
int wordWidth = lineWidth(spacedWord.split("$"), font);
writePos = lineWidth;
lineWidth += wordWidth;
if (word.equals("\n")) {
maxWidth = Math.max(lineWidth, maxWidth);
heightPos += baseline + leading;
writePos = padding;
lineWidth = padding;
}
graphs.drawString(word + " ", writePos, heightPos);
}
maxWidth = Math.max(lineWidth, maxWidth);
if (preferredWidth > 0) maxWidth = preferredWidth;
if (boxed) {
graphs.setColor(Color.BLACK);
graphs.setStroke(new BasicStroke(padding / 2));
graphs.drawRect(0, 0, maxWidth - 1, heightPos + padding - 1);
}
// Cut the image down to the correct size
wrappedImage = wrappedImage.getSubimage(0, 0, maxWidth, heightPos
+ padding);
return copy(wrappedImage);
}
/**
* Renders a Label and returns it as a BufferedImage.
* @param title is the text to be outputted
* @param instructions are any instructions to be italicized, such as '(please
* select one)'
* @param description are any descriptions (such as those used on
* propositions)
* @param fontsize the size of the font
* @param wrappingWidth is the width at which the label should wrap
* @param bold whether the label is bold
* @param color is the color of the text
* @param boxed is a boolean flag to determine whether or a box should be
* placed around the label
* @param titleCentered is a boolean flag as to whether or not the text
* should be centered
* @return the rendered Label
*/
public static BufferedImage renderLabel(String title, String instructions,
String description, int fontsize, int wrappingWidth, Color color,
boolean bold, boolean boxed, boolean titleCentered) {
Font font = new Font(FONT_NAME, (bold) ? Font.BOLD : Font.PLAIN,
fontsize);
Font italicFont = new Font(FONT_NAME, Font.ITALIC, fontsize);
Font bigBoldFont = new Font(FONT_NAME, Font.BOLD, fontsize + 4);
BufferedImage wrappedImage = new BufferedImage(1000, 1000,
BufferedImage.TYPE_INT_ARGB);
Graphics2D graphs = wrappedImage.createGraphics();
graphs.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
graphs.setFont(font);
graphs.setColor(color);
int baseline = graphs.getFontMetrics().getAscent();
String[] titleWords = title.split(" ");
int padding = 10;
int heightPos = padding + baseline;
int writePos = padding;
int lineWidth = padding;
int maxWidth = 0; // the max width of any line
if (titleCentered) {
graphs.setFont(bigBoldFont);
String[][] splitText = spliteOnNewLineAndSpace(title);
for (int y = 0; y < splitText.length; y++) {
String[] line = splitText[y];
int margin = (wrappingWidth - 2 * padding - lineWidth(line,
bigBoldFont)) / 2;
graphs.drawString(stringArrayToString(line), writePos + margin,
heightPos);
heightPos += lineHeight("line", bigBoldFont);
}
} else {
for (String word : titleWords) // For each word try placing it on
// the line,
// if not jump down a line and then write it
{
Rectangle2D measurement = font
.getStringBounds(word + " ", new FontRenderContext(
new AffineTransform(), true, true));
int wordWidth = (int) measurement.getWidth();
int wordHeight = (int) measurement.getHeight();
writePos = lineWidth;
lineWidth += wordWidth;
// TODO: this code does do what the comment above says it does!
// It doesn't jump down a line on it's own! add this!
// if the width of our word is longer than the entire line space,
// break it up.
if(wordWidth > wrappedImage.getWidth()) {
String remainingStr = word;
while(remainingStr.length() > wrappedImage.getWidth()) {
graphs.drawString(remainingStr.substring(0, wrappedImage.getWidth()),
writePos, heightPos);
remainingStr= remainingStr.substring(wrappedImage.getWidth());
// we've just written one whole line. put our position variables back
// at the beginning
heightPos+= wordHeight;
writePos= padding;
lineWidth= padding;
}
} else if (word.equals("\n") || word.equals("<newline>")) {
maxWidth = Math.max(lineWidth, maxWidth);
heightPos += wordHeight;
writePos = padding;
lineWidth = padding;
}
graphs.drawString(word + " ", writePos, heightPos);
}
}
if (!instructions.equals("")) // write instructions on how to use
{
// heightPos+= lineHeight(instructions.split(" "), italicFont);
String[][] splitText = spliteOnNewLineAndSpace(instructions);
for (int y = 0; y < splitText.length; y++) {
String[] line = splitText[y];
int margin = (wrappingWidth - 2 * padding - lineWidth(line,
italicFont)) / 2;
graphs.setFont(italicFont);
graphs.drawString(stringArrayToString(line), writePos + margin,
heightPos);
heightPos += lineHeight("line", italicFont);
}
}
if (!description.equals("")) // write description on how to use
{
heightPos += lineHeight("text", font);
description = addInNewLines(description, font, wrappingWidth,
padding);
String[][] splitText = spliteOnNewLineAndSpace(description);
graphs.setFont(font);
for (int y = 0; y < splitText.length; y++) {
String[] line = splitText[y];
graphs.drawString(stringArrayToString(line), writePos,
heightPos);
heightPos += lineHeight("line", font);
}
}
maxWidth = Math.max(lineWidth, maxWidth);
if (wrappingWidth != 0) // then wrap at the wrappingWidth or maxWidth
maxWidth = Math.max(maxWidth, wrappingWidth);
if (boxed) {
graphs.setColor(Color.BLACK);
graphs.setStroke(new BasicStroke(padding / 2));
graphs.drawRect(0, 0, maxWidth - 1, heightPos + padding - 1);
}
if(maxWidth < wrappedImage.getWidth()) {
wrappedImage = wrappedImage.getSubimage(0, 0, maxWidth, heightPos
+ padding);
}
else {
wrappedImage = wrappedImage.getSubimage(0, 0, wrappedImage.getWidth(), heightPos);
}
return copy(wrappedImage);
}
/**
* Renders a ToggleButton and returns it as a BufferedImage. ToggleButton
* does not wrap unless indicated to do so with \n. Also if two names are used
* the second name appears at an offset. And since this is a togglebutton a
* box and possible check mark in the box are added
* @param text is the text of the togglebutton
* @param text2 is the second text of the toggle button - added on a
* secondline and indented
* @param party is the party of the candidate in the toggle button - right
* aligned on first line of button
* @param fontsize the size of the font
* @param wrappingWidth is not used
* @param bold whether the button is bold
* @param selected is whether or not the toggleButton should have a check
* mark in its box
* @return the rendered ToggleButton
*/
public static BufferedImage renderToggleButton(String text, String text2,
String party, int fontsize, int wrappingWidth, boolean bold,
boolean selected) {
Font font = new Font(FONT_NAME, (bold) ? Font.BOLD : Font.PLAIN,
fontsize);
String box = "\u25a1"; // box character
String filledSelection = "\u2713"; // check mark character
BufferedImage wrappedImage = new BufferedImage(1000, 1000,
BufferedImage.TYPE_INT_ARGB);
Graphics2D graphs = wrappedImage.createGraphics();
graphs.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
graphs.setFont(font);
graphs.setColor(Color.BLACK); // Could make this a variable
int baseline = graphs.getFontMetrics().getAscent();
int padding = 10;
int heightPos = padding + baseline;
int writePos = padding;
int lineWidth = padding;
int boxPos = wrappingWidth - 30;
int partyLength = lineWidth(party.split(" "), font);
int partyPos = boxPos - 10 - partyLength;
graphs.drawString(text, writePos, heightPos);
graphs.drawString(box, boxPos, heightPos);
if (selected) {
Font checkFont = new Font(FONT_NAME, Font.PLAIN,
(int) (fontsize - 4 + ((fontsize - 4) * 1.1)));
graphs.setColor(new Color(0, 165, 80));
graphs.setFont(checkFont);
graphs.drawString(filledSelection, boxPos, heightPos);
graphs.setFont(font);
graphs.setColor(Color.BLACK);
}
if (!party.equals("")) {
graphs.drawString(party, partyPos, heightPos);
}
if (!text2.equals("")) {
heightPos += lineHeight(text, font);
graphs.drawString(" " + text2, writePos, heightPos);
}
graphs.setColor(Color.BLACK);
graphs.setStroke(new BasicStroke(padding / 2));
// start this rectangle off the top of our visible area so we don't see
// the top border
graphs.drawRect(0, -padding, wrappingWidth - 1, heightPos + 2*padding - 1);
wrappedImage = wrappedImage.getSubimage(0, 0, wrappingWidth, heightPos
+ padding);
return copy(wrappedImage);
}
public static BufferedImage renderPrintButton(String uid, String text, String text2,
String party, int fontsize, int wrappingWidth, boolean bold,
boolean selected) {
//System.out.println("Image with UID: "+ uid + " Text1: " + text + " has wrapping width " + wrappingWidth);
//System.out.println("Wrapping Width:\tUID:\tText1:");
//System.out.println(wrappingWidth + "\t" + uid + "\t" + text);
/* This is never true.
if (wrappingWidth == 600 && !uid.contains("_printable"))
System.out.println(">>>>>>>> " + uid);
*/
fontsize *= DPI_SCALE_FACTOR;
Font font = new Font(FONT_NAME, (bold) ? Font.BOLD : Font.PLAIN,
fontsize);
if(text.equals("NO SELECTION")){
selected = false;
}
//Scale the wrapping width
wrappingWidth *= DPI_SCALE_FACTOR;
Font nf = new Font("OCR A Extended", Font.PLAIN, 12*DPI_SCALE_FACTOR);
String box = "\u25a1"; // box character
String filledSelection = "\u25a8"; // filled box character
int selectionLength = lineWidth(text.split(""), nf);
int imageLength = Math.max(1000, selectionLength);
BufferedImage wrappedImage = new BufferedImage(1000*DPI_SCALE_FACTOR, 1000*DPI_SCALE_FACTOR,
BufferedImage.TYPE_INT_ARGB);
Graphics2D graphs = wrappedImage.createGraphics();
graphs.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
graphs.setFont(nf);
graphs.setColor(Color.BLACK); // Could make this a variable
int baseline = graphs.getFontMetrics().getAscent()*DPI_SCALE_FACTOR;
/* Useful data attributes. */
int padding = 10*DPI_SCALE_FACTOR;
int presidentNameLength = lineWidth(text.split("$"), nf);
int vicePresidentNameLength = lineWidth(text2.split("$"), nf);
int heightPos = padding + baseline;
int writePos = padding;
int boxPos = wrappingWidth - SELECTION_BOX_WIDTH - DPI_SCALE_FACTOR;
int candidateNameEndPos = boxPos - 2*DPI_SCALE_FACTOR;
String selection = "";
int drawPosition = 0;
if (!text2.equals("")) { // If the selection represents a Presidential election.
if (!party.equals("")) {
selection = text2 + " - " + party;
selectionLength = lineWidth(selection.split("$"), nf);
}
graphs.drawString(text, candidateNameEndPos - (selectionLength - vicePresidentNameLength) - presidentNameLength, heightPos);
heightPos += lineHeight(text, nf);
}
else {
if (!party.equals("")) {
selection += text + " - " + party;
}
else{
selection = text;
}
}
graphs.setFont(nf);
//If this is a race name and not a candidate
if (uid.contains("L"))
{
wrappingWidth = 250*DPI_SCALE_FACTOR; //Arbitrary size!
Font temp = font.deriveFont(12.0f*DPI_SCALE_FACTOR);
String[] split = selection.split("\n");
text = split[0];
if(split.length > 1) //if there is a newline character, there are two titles
text2 = split[1];
selectionLength = lineWidth(selection.split("$"), font);
graphs.setFont(temp);
if (!text2.equals("")) { // If the selection represents a Presidential election.
graphs.drawString(text + ":", padding, heightPos);
heightPos += lineHeight(text, font);
selection = text2;
}
graphs.drawString(selection, padding, heightPos); //height based on an appropriate spacing of up to a 3 digit number
graphs.setFont(font);
wrappedImage = wrappedImage.getSubimage(0, 0, Math.max(wrappingWidth,selectionLength), 2 * heightPos);
//Trim the image.
wrappedImage = PrintImageUtils.trimImageVertically(wrappedImage, false, Integer.MAX_VALUE); // Above
wrappedImage = PrintImageUtils.trimImageVertically(wrappedImage, true, Integer.MAX_VALUE); // Below
// No Left/Right trimming, because it is done in the Printer class.
return copy(wrappedImage);
}
//Get rid of all underscores and letters in UID's
if(uid.contains("_"))
uid = uid.substring(1, uid.indexOf("_"));
else
uid = uid.substring(1);
graphs.drawString(uid, writePos, heightPos);
/* This is where the box is being drawn. */
drawBox(graphs, boxPos, (heightPos - SELECTION_BOX_HEIGHT), SELECTION_BOX_WIDTH, SELECTION_BOX_HEIGHT, selected, padding/8);
graphs.setFont(nf);
drawPosition = Math.max(0, candidateNameEndPos - lineWidth(selection.split("$"), nf));
graphs.drawString(selection, drawPosition, heightPos); //height based on an appropriate spacing of up to a 3 digit number
graphs.setColor(Color.BLACK);
graphs.setStroke(new BasicStroke(padding / 4));
//split "1" because it gives a nice line width. It's sort of a hack...
- graphs.drawLine(writePos + lineWidth(("1").split(""), nf), heightPos + fontsize/2, Math.max(wrappingWidth,selectionLength), heightPos + fontsize/2);
+ graphs.drawLine(writePos + lineWidth(("1").split(""), nf), heightPos + fontsize/2, wrappingWidth/*Math.max(wrappingWidth,selectionLength)*/, heightPos + fontsize/2);
//This should automatically trim the image, sadly, it doesn't
- wrappedImage = wrappedImage.getSubimage(0, 0, Math.max(wrappingWidth,selectionLength), heightPos + padding);
+ wrappedImage = wrappedImage.getSubimage(0, 0, wrappingWidth/*Math.max(wrappingWidth,selectionLength)*/, heightPos + padding);
//Need to also remove whitespace above and below the image.
wrappedImage = PrintImageUtils.trimImageVertically(wrappedImage, false, Integer.MAX_VALUE);
wrappedImage = PrintImageUtils.trimImageVertically(wrappedImage, true, Integer.MAX_VALUE); // Below
return copy(wrappedImage);
}
/**
* A private helper to add in tags of where new lines should be added when a
* text is rendered with at given font with a set wrappingWidth and padding
* @param text the text to be rendered
* @param font the font to render with
* @param wrappingWidth the width at which to wrap
* @param padding the padding that should be on the text
* @return the text with appropriate <newline> tags added in
*/
private static String addInNewLines(String text, Font font,
int wrappingWidth, int padding) {
String copy = new String("");
String[] splitText = text.split(" ");
int currentLineWidth = padding;
for (String word : splitText) {
Rectangle2D measurement = font.getStringBounds(word + " ",
new FontRenderContext(new AffineTransform(), true, true));
currentLineWidth += measurement.getWidth();
if (currentLineWidth + padding > wrappingWidth) {
currentLineWidth = (int) measurement.getWidth() + padding;
copy = copy.concat(" <newline>");
}
copy = copy.concat(word + " ");
}
return copy;
}
/**
* Calculates the line height at a given font, by looking at the height of
* the first word
* @param line is the line
* @param font is the font
* @return the height
*/
private static int lineHeight(String line, Font font) {
Rectangle2D measurement = font.getStringBounds(line + " ",
new FontRenderContext(new AffineTransform(), true, true));
return (int) measurement.getHeight();
}
/**
* Calculates the line width at a given font
* @param line is the line
* @param font is the font
* @return the width
*/
private static int lineWidth(String[] line, Font font) {
int width = 0;
for (String word : line) {
Rectangle2D measurement = font.getStringBounds(word + " ",
new FontRenderContext(new AffineTransform(), true, true));
width += measurement.getWidth();
}
return width;
}
/**
* Splits text on new line and then on white space
* @param text the text to be split
* @return the split text
*/
private static String[][] spliteOnNewLineAndSpace(String text) {
String[] splitOnNewLine = text.split("<newline>");
String[][] splitText = new String[splitOnNewLine.length][0];
for (int x = 0; x < splitOnNewLine.length; x++) {
splitText[x] = splitOnNewLine[x].split(" ");
}
return splitText;
}
/**
* Transforms an array of Strings to one string w/ appropriate spacing added
* in between. Also trims the string to remove useless white sapce
* @param array the array to be transformed
* @return the array as a string
*/
private static String stringArrayToString(String[] array) {
String currentString = new String(" ");
for (int x = 0; x < array.length; x++) {
currentString = currentString.concat(array[x] + " ");
}
return currentString.trim();
}
/**
* This method draws a box in a given context, with the upper left corner at the location given.
* @param graphicsObject - the context (graphics object) on which to draw the box
* @param upperLeftX - the X coordinate of the upper-left corner
* @param upperLeftY - the Y coordinate of the upper-left corner
* @param width - the width of the box
* @param height - the height of the box
* @param selected - whether or not the box should be filled in
* @param thickness - the line thickness of the box
*/
public static void drawBox(Graphics2D graphicsObject, int upperLeftX, int upperLeftY, int width, int height, Boolean selected, int thickness)
{
graphicsObject.setStroke(new BasicStroke(thickness));
// Drawing the empty box.
graphicsObject.drawRect(upperLeftX, upperLeftY, width, height);
if (selected)
{
//determines how many lines get drawn in the box
int denominator = 3;
float slope = (1.0f*height)/width;
ArrayList<Integer> startXs = new ArrayList<Integer> ();
ArrayList<Integer> startYs = new ArrayList<Integer> ();
ArrayList<Integer> endXs = new ArrayList<Integer> ();
ArrayList<Integer> endYs = new ArrayList<Integer> ();
// Building the list of start positions for the fill lines.
int offsetX = 0;
int offsetY = 0;
while (offsetX < width)
{
startXs.add(new Integer(upperLeftX+offsetX));
startYs.add(new Integer(upperLeftY+offsetY));
offsetX += width/denominator;
}
while (offsetY < height)
{
startXs.add(new Integer(upperLeftX+offsetX));
startYs.add(new Integer(upperLeftY+offsetY));
offsetY += height/denominator;
}
// Building the list of end positions for the fill lines.
offsetX = 0;
offsetY = 0;
while (offsetY < height)
{
endXs.add(new Integer(upperLeftX+offsetX));
endYs.add(new Integer(upperLeftY+offsetY));
offsetY += height/denominator;
}
while (offsetX < width)
{
int endX = new Integer(upperLeftX+offsetX);
int endY = new Integer(upperLeftY+offsetY);
endXs.add(endX);
endYs.add(endY);
offsetX += width/denominator;
}
// Drawing the fill lines.
for (int i = 0; i < startXs.size(); i++)
{
int startX = startXs.get(i);
int startY = startYs.get(i);
int endX = endXs.get(i);
int endY = endYs.get(i);
//Correct for overflow vertically
if(endY > upperLeftY + height){
int newY = upperLeftY + height;
int newX = Math.round((endY - newY)/slope) + endX;
endX = newX;
endY = newY;
}
//Correct for overflow horizontally (note that there should never be overflow in both cases)
else if(endX > upperLeftX + width){
int newX = upperLeftX + width;
int newY = Math.round((endX - newX)/slope) + endY;
endX = newX;
endY = newY;
}
graphicsObject.drawLine(startX, startY, endX, endY);
}
}
}
}
| false | true |
public static BufferedImage renderPrintButton(String uid, String text, String text2,
String party, int fontsize, int wrappingWidth, boolean bold,
boolean selected) {
//System.out.println("Image with UID: "+ uid + " Text1: " + text + " has wrapping width " + wrappingWidth);
//System.out.println("Wrapping Width:\tUID:\tText1:");
//System.out.println(wrappingWidth + "\t" + uid + "\t" + text);
/* This is never true.
if (wrappingWidth == 600 && !uid.contains("_printable"))
System.out.println(">>>>>>>> " + uid);
*/
fontsize *= DPI_SCALE_FACTOR;
Font font = new Font(FONT_NAME, (bold) ? Font.BOLD : Font.PLAIN,
fontsize);
if(text.equals("NO SELECTION")){
selected = false;
}
//Scale the wrapping width
wrappingWidth *= DPI_SCALE_FACTOR;
Font nf = new Font("OCR A Extended", Font.PLAIN, 12*DPI_SCALE_FACTOR);
String box = "\u25a1"; // box character
String filledSelection = "\u25a8"; // filled box character
int selectionLength = lineWidth(text.split(""), nf);
int imageLength = Math.max(1000, selectionLength);
BufferedImage wrappedImage = new BufferedImage(1000*DPI_SCALE_FACTOR, 1000*DPI_SCALE_FACTOR,
BufferedImage.TYPE_INT_ARGB);
Graphics2D graphs = wrappedImage.createGraphics();
graphs.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
graphs.setFont(nf);
graphs.setColor(Color.BLACK); // Could make this a variable
int baseline = graphs.getFontMetrics().getAscent()*DPI_SCALE_FACTOR;
/* Useful data attributes. */
int padding = 10*DPI_SCALE_FACTOR;
int presidentNameLength = lineWidth(text.split("$"), nf);
int vicePresidentNameLength = lineWidth(text2.split("$"), nf);
int heightPos = padding + baseline;
int writePos = padding;
int boxPos = wrappingWidth - SELECTION_BOX_WIDTH - DPI_SCALE_FACTOR;
int candidateNameEndPos = boxPos - 2*DPI_SCALE_FACTOR;
String selection = "";
int drawPosition = 0;
if (!text2.equals("")) { // If the selection represents a Presidential election.
if (!party.equals("")) {
selection = text2 + " - " + party;
selectionLength = lineWidth(selection.split("$"), nf);
}
graphs.drawString(text, candidateNameEndPos - (selectionLength - vicePresidentNameLength) - presidentNameLength, heightPos);
heightPos += lineHeight(text, nf);
}
else {
if (!party.equals("")) {
selection += text + " - " + party;
}
else{
selection = text;
}
}
graphs.setFont(nf);
//If this is a race name and not a candidate
if (uid.contains("L"))
{
wrappingWidth = 250*DPI_SCALE_FACTOR; //Arbitrary size!
Font temp = font.deriveFont(12.0f*DPI_SCALE_FACTOR);
String[] split = selection.split("\n");
text = split[0];
if(split.length > 1) //if there is a newline character, there are two titles
text2 = split[1];
selectionLength = lineWidth(selection.split("$"), font);
graphs.setFont(temp);
if (!text2.equals("")) { // If the selection represents a Presidential election.
graphs.drawString(text + ":", padding, heightPos);
heightPos += lineHeight(text, font);
selection = text2;
}
graphs.drawString(selection, padding, heightPos); //height based on an appropriate spacing of up to a 3 digit number
graphs.setFont(font);
wrappedImage = wrappedImage.getSubimage(0, 0, Math.max(wrappingWidth,selectionLength), 2 * heightPos);
//Trim the image.
wrappedImage = PrintImageUtils.trimImageVertically(wrappedImage, false, Integer.MAX_VALUE); // Above
wrappedImage = PrintImageUtils.trimImageVertically(wrappedImage, true, Integer.MAX_VALUE); // Below
// No Left/Right trimming, because it is done in the Printer class.
return copy(wrappedImage);
}
//Get rid of all underscores and letters in UID's
if(uid.contains("_"))
uid = uid.substring(1, uid.indexOf("_"));
else
uid = uid.substring(1);
graphs.drawString(uid, writePos, heightPos);
/* This is where the box is being drawn. */
drawBox(graphs, boxPos, (heightPos - SELECTION_BOX_HEIGHT), SELECTION_BOX_WIDTH, SELECTION_BOX_HEIGHT, selected, padding/8);
graphs.setFont(nf);
drawPosition = Math.max(0, candidateNameEndPos - lineWidth(selection.split("$"), nf));
graphs.drawString(selection, drawPosition, heightPos); //height based on an appropriate spacing of up to a 3 digit number
graphs.setColor(Color.BLACK);
graphs.setStroke(new BasicStroke(padding / 4));
//split "1" because it gives a nice line width. It's sort of a hack...
graphs.drawLine(writePos + lineWidth(("1").split(""), nf), heightPos + fontsize/2, Math.max(wrappingWidth,selectionLength), heightPos + fontsize/2);
//This should automatically trim the image, sadly, it doesn't
wrappedImage = wrappedImage.getSubimage(0, 0, Math.max(wrappingWidth,selectionLength), heightPos + padding);
//Need to also remove whitespace above and below the image.
wrappedImage = PrintImageUtils.trimImageVertically(wrappedImage, false, Integer.MAX_VALUE);
wrappedImage = PrintImageUtils.trimImageVertically(wrappedImage, true, Integer.MAX_VALUE); // Below
return copy(wrappedImage);
}
|
public static BufferedImage renderPrintButton(String uid, String text, String text2,
String party, int fontsize, int wrappingWidth, boolean bold,
boolean selected) {
//System.out.println("Image with UID: "+ uid + " Text1: " + text + " has wrapping width " + wrappingWidth);
//System.out.println("Wrapping Width:\tUID:\tText1:");
//System.out.println(wrappingWidth + "\t" + uid + "\t" + text);
/* This is never true.
if (wrappingWidth == 600 && !uid.contains("_printable"))
System.out.println(">>>>>>>> " + uid);
*/
fontsize *= DPI_SCALE_FACTOR;
Font font = new Font(FONT_NAME, (bold) ? Font.BOLD : Font.PLAIN,
fontsize);
if(text.equals("NO SELECTION")){
selected = false;
}
//Scale the wrapping width
wrappingWidth *= DPI_SCALE_FACTOR;
Font nf = new Font("OCR A Extended", Font.PLAIN, 12*DPI_SCALE_FACTOR);
String box = "\u25a1"; // box character
String filledSelection = "\u25a8"; // filled box character
int selectionLength = lineWidth(text.split(""), nf);
int imageLength = Math.max(1000, selectionLength);
BufferedImage wrappedImage = new BufferedImage(1000*DPI_SCALE_FACTOR, 1000*DPI_SCALE_FACTOR,
BufferedImage.TYPE_INT_ARGB);
Graphics2D graphs = wrappedImage.createGraphics();
graphs.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
graphs.setFont(nf);
graphs.setColor(Color.BLACK); // Could make this a variable
int baseline = graphs.getFontMetrics().getAscent()*DPI_SCALE_FACTOR;
/* Useful data attributes. */
int padding = 10*DPI_SCALE_FACTOR;
int presidentNameLength = lineWidth(text.split("$"), nf);
int vicePresidentNameLength = lineWidth(text2.split("$"), nf);
int heightPos = padding + baseline;
int writePos = padding;
int boxPos = wrappingWidth - SELECTION_BOX_WIDTH - DPI_SCALE_FACTOR;
int candidateNameEndPos = boxPos - 2*DPI_SCALE_FACTOR;
String selection = "";
int drawPosition = 0;
if (!text2.equals("")) { // If the selection represents a Presidential election.
if (!party.equals("")) {
selection = text2 + " - " + party;
selectionLength = lineWidth(selection.split("$"), nf);
}
graphs.drawString(text, candidateNameEndPos - (selectionLength - vicePresidentNameLength) - presidentNameLength, heightPos);
heightPos += lineHeight(text, nf);
}
else {
if (!party.equals("")) {
selection += text + " - " + party;
}
else{
selection = text;
}
}
graphs.setFont(nf);
//If this is a race name and not a candidate
if (uid.contains("L"))
{
wrappingWidth = 250*DPI_SCALE_FACTOR; //Arbitrary size!
Font temp = font.deriveFont(12.0f*DPI_SCALE_FACTOR);
String[] split = selection.split("\n");
text = split[0];
if(split.length > 1) //if there is a newline character, there are two titles
text2 = split[1];
selectionLength = lineWidth(selection.split("$"), font);
graphs.setFont(temp);
if (!text2.equals("")) { // If the selection represents a Presidential election.
graphs.drawString(text + ":", padding, heightPos);
heightPos += lineHeight(text, font);
selection = text2;
}
graphs.drawString(selection, padding, heightPos); //height based on an appropriate spacing of up to a 3 digit number
graphs.setFont(font);
wrappedImage = wrappedImage.getSubimage(0, 0, Math.max(wrappingWidth,selectionLength), 2 * heightPos);
//Trim the image.
wrappedImage = PrintImageUtils.trimImageVertically(wrappedImage, false, Integer.MAX_VALUE); // Above
wrappedImage = PrintImageUtils.trimImageVertically(wrappedImage, true, Integer.MAX_VALUE); // Below
// No Left/Right trimming, because it is done in the Printer class.
return copy(wrappedImage);
}
//Get rid of all underscores and letters in UID's
if(uid.contains("_"))
uid = uid.substring(1, uid.indexOf("_"));
else
uid = uid.substring(1);
graphs.drawString(uid, writePos, heightPos);
/* This is where the box is being drawn. */
drawBox(graphs, boxPos, (heightPos - SELECTION_BOX_HEIGHT), SELECTION_BOX_WIDTH, SELECTION_BOX_HEIGHT, selected, padding/8);
graphs.setFont(nf);
drawPosition = Math.max(0, candidateNameEndPos - lineWidth(selection.split("$"), nf));
graphs.drawString(selection, drawPosition, heightPos); //height based on an appropriate spacing of up to a 3 digit number
graphs.setColor(Color.BLACK);
graphs.setStroke(new BasicStroke(padding / 4));
//split "1" because it gives a nice line width. It's sort of a hack...
graphs.drawLine(writePos + lineWidth(("1").split(""), nf), heightPos + fontsize/2, wrappingWidth/*Math.max(wrappingWidth,selectionLength)*/, heightPos + fontsize/2);
//This should automatically trim the image, sadly, it doesn't
wrappedImage = wrappedImage.getSubimage(0, 0, wrappingWidth/*Math.max(wrappingWidth,selectionLength)*/, heightPos + padding);
//Need to also remove whitespace above and below the image.
wrappedImage = PrintImageUtils.trimImageVertically(wrappedImage, false, Integer.MAX_VALUE);
wrappedImage = PrintImageUtils.trimImageVertically(wrappedImage, true, Integer.MAX_VALUE); // Below
return copy(wrappedImage);
}
|
diff --git a/src/com/dmdirc/addons/ui_swing/components/NickList.java b/src/com/dmdirc/addons/ui_swing/components/NickList.java
index 34c543d64..398884dc8 100644
--- a/src/com/dmdirc/addons/ui_swing/components/NickList.java
+++ b/src/com/dmdirc/addons/ui_swing/components/NickList.java
@@ -1,290 +1,289 @@
/*
*
* Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.addons.ui_swing.components;
import com.dmdirc.addons.ui_swing.components.frames.ChannelFrame;
import com.dmdirc.addons.ui_swing.components.renderers.NicklistRenderer;
import com.dmdirc.addons.ui_swing.textpane.ClickType;
import com.dmdirc.config.ConfigManager;
import com.dmdirc.interfaces.ConfigChangeListener;
import com.dmdirc.parser.interfaces.ChannelClientInfo;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Collection;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
/**
* Nicklist class.
*/
public class NickList extends JScrollPane implements ConfigChangeListener,
MouseListener {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 10;
/** Nick list. */
private JList nickList;
private final ChannelFrame frame;
/** Config. */
private final ConfigManager config;
/** Nick list model. */
private final NicklistListModel nicklistModel;
/**
* Creates a nicklist.
*
* @param frame Frame
* @param config Config
*/
public NickList(final ChannelFrame frame, final ConfigManager config) {
super();
this.frame = frame;
this.config = config;
nickList = new JList();
nickList.setBackground(config.getOptionColour(
"ui", "nicklistbackgroundcolour",
"ui", "backgroundcolour"));
nickList.setForeground(config.getOptionColour(
"ui", "nicklistforegroundcolour",
"ui", "foregroundcolour"));
config.addChangeListener("ui", "nicklistforegroundcolour", this);
config.addChangeListener("ui", "foregroundcolour", this);
config.addChangeListener("ui", "nicklistbackgroundcolour", this);
config.addChangeListener("ui", "backgroundcolour", this);
config.addChangeListener("ui", "nickListAltBackgroundColour", this);
- nickList = new JList();
nickList.setCellRenderer(new NicklistRenderer(config, nickList));
nickList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
nickList.addMouseListener(this);
nicklistModel = new NicklistListModel(config);
nickList.setModel(nicklistModel);
setViewportView(nickList);
final int splitPanePosition = config.getOptionInt("ui",
"channelSplitPanePosition");
setPreferredSize(new Dimension(splitPanePosition, 0));
setMinimumSize(new Dimension(75, 0));
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseClicked(final MouseEvent e) {
processMouseEvent(e);
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mousePressed(final MouseEvent e) {
processMouseEvent(e);
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseReleased(final MouseEvent e) {
processMouseEvent(e);
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseEntered(MouseEvent e) {
//Ignore
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseExited(final MouseEvent e) {
//Ignore
}
/**
* Processes every mouse button event to check for a popup trigger.
*
* @param e mouse event
*/
@Override
public void processMouseEvent(final MouseEvent e) {
if (e.getSource() == nickList && nickList.getMousePosition() != null &&
getMousePosition() != null) {
if (checkCursorInSelectedCell() || selectNickUnderCursor()) {
if (e.isPopupTrigger()) {
frame.showPopupMenu(ClickType.NICKNAME, new Point(e.
getXOnScreen(), e.getYOnScreen()),
((ChannelClientInfo) nickList.getSelectedValue()).
getClient().getNickname());
}
} else {
nickList.clearSelection();
}
}
super.processMouseEvent(e);
}
/**
* Checks whether the mouse cursor is currently over a cell in the nicklist
* which has been previously selected.
*
* @return True if the cursor is over a selected cell, false otherwise
*/
private boolean checkCursorInSelectedCell() {
boolean showMenu = false;
final Point mousePos = nickList.getMousePosition();
if (mousePos != null) {
for (int i = 0; i < nickList.getModel().getSize(); i++) {
if (nickList.getCellBounds(i, i) != null && nickList.
getCellBounds(i, i).
contains(mousePos) && nickList.isSelectedIndex(i)) {
showMenu = true;
break;
}
}
}
return showMenu;
}
/**
* If the mouse cursor is over a nicklist cell, sets that cell to be
* selected and returns true. If the mouse is not over any cell, the
* selection is unchanged and the method returns false.
*
* @return True if an item was selected
*/
private boolean selectNickUnderCursor() {
boolean suceeded = false;
final Point mousePos = nickList.getMousePosition();
if (mousePos != null) {
for (int i = 0; i < nickList.getModel().getSize(); i++) {
if (nickList.getCellBounds(i, i) != null && nickList.
getCellBounds(i, i).
contains(mousePos)) {
nickList.setSelectedIndex(i);
suceeded = true;
break;
}
}
}
return suceeded;
}
/** {@inheritDoc} */
@Override
public void configChanged(final String domain, final String key) {
if ("nickListAltBackgroundColour".equals(key) ||
"nicklistbackgroundcolour".equals(key) ||
"backgroundcolour".equals(key) ||
"nicklistforegroundcolour".equals(key) ||
"foregroundcolour".equals(key)) {
nickList.setBackground(config.getOptionColour(
"ui", "nicklistbackgroundcolour",
"ui", "backgroundcolour"));
nickList.setForeground(config.getOptionColour(
"ui", "nicklistforegroundcolour",
"ui", "foregroundcolour"));
nickList.repaint();
}
nickList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
public void updateNames(final Collection<ChannelClientInfo> clients) {
SwingUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
nicklistModel.replace(clients);
}
});
}
public void updateNames() {
SwingUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
nicklistModel.sort();
}
});
}
public void addName(final ChannelClientInfo client) {
SwingUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
nicklistModel.add(client);
}
});
}
public void removeName(final ChannelClientInfo client) {
SwingUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
nicklistModel.remove(client);
}
});
}
}
| true | true |
public NickList(final ChannelFrame frame, final ConfigManager config) {
super();
this.frame = frame;
this.config = config;
nickList = new JList();
nickList.setBackground(config.getOptionColour(
"ui", "nicklistbackgroundcolour",
"ui", "backgroundcolour"));
nickList.setForeground(config.getOptionColour(
"ui", "nicklistforegroundcolour",
"ui", "foregroundcolour"));
config.addChangeListener("ui", "nicklistforegroundcolour", this);
config.addChangeListener("ui", "foregroundcolour", this);
config.addChangeListener("ui", "nicklistbackgroundcolour", this);
config.addChangeListener("ui", "backgroundcolour", this);
config.addChangeListener("ui", "nickListAltBackgroundColour", this);
nickList = new JList();
nickList.setCellRenderer(new NicklistRenderer(config, nickList));
nickList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
nickList.addMouseListener(this);
nicklistModel = new NicklistListModel(config);
nickList.setModel(nicklistModel);
setViewportView(nickList);
final int splitPanePosition = config.getOptionInt("ui",
"channelSplitPanePosition");
setPreferredSize(new Dimension(splitPanePosition, 0));
setMinimumSize(new Dimension(75, 0));
}
|
public NickList(final ChannelFrame frame, final ConfigManager config) {
super();
this.frame = frame;
this.config = config;
nickList = new JList();
nickList.setBackground(config.getOptionColour(
"ui", "nicklistbackgroundcolour",
"ui", "backgroundcolour"));
nickList.setForeground(config.getOptionColour(
"ui", "nicklistforegroundcolour",
"ui", "foregroundcolour"));
config.addChangeListener("ui", "nicklistforegroundcolour", this);
config.addChangeListener("ui", "foregroundcolour", this);
config.addChangeListener("ui", "nicklistbackgroundcolour", this);
config.addChangeListener("ui", "backgroundcolour", this);
config.addChangeListener("ui", "nickListAltBackgroundColour", this);
nickList.setCellRenderer(new NicklistRenderer(config, nickList));
nickList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
nickList.addMouseListener(this);
nicklistModel = new NicklistListModel(config);
nickList.setModel(nicklistModel);
setViewportView(nickList);
final int splitPanePosition = config.getOptionInt("ui",
"channelSplitPanePosition");
setPreferredSize(new Dimension(splitPanePosition, 0));
setMinimumSize(new Dimension(75, 0));
}
|
diff --git a/src/main/java/org/glite/authz/common/config/AbstractIniConfigurationParser.java b/src/main/java/org/glite/authz/common/config/AbstractIniConfigurationParser.java
index 9d6d004..b51f1db 100644
--- a/src/main/java/org/glite/authz/common/config/AbstractIniConfigurationParser.java
+++ b/src/main/java/org/glite/authz/common/config/AbstractIniConfigurationParser.java
@@ -1,297 +1,297 @@
/*
* Copyright (c) Members of the EGEE Collaboration. 2006-2010.
* See http://www.eu-egee.org/partners/ for details on the copyright holders.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.glite.authz.common.config;
import java.io.IOException;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;
import net.jcip.annotations.ThreadSafe;
import org.glite.authz.common.util.Files;
import org.ini4j.Ini;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.emi.security.authn.x509.CommonX509TrustManager;
import eu.emi.security.authn.x509.impl.OpensslCertChainValidator;
import eu.emi.security.authn.x509.impl.PEMCredential;
/**
* Base class for configuration parsers that employ an INI file.
*
* @param <ConfigurationType>
* the type of configuration produced by this parser
*/
@ThreadSafe
public abstract class AbstractIniConfigurationParser<ConfigurationType extends AbstractConfiguration>
implements ConfigurationParser<ConfigurationType> {
/**
* The name of the {@value} INI header which contains the property for
* configuring credential/trust information.
*/
public static final String SECURITY_SECTION_HEADER= "SECURITY";
/**
* The name of the {@value} which gives the path to the service's private
* key.
*/
public static final String SERVICE_KEY_PROP= "servicePrivateKey";
/**
* The name of the {@value} which provides the password of the service's
* private key.
*/
public static final String SERVICE_KEY_PASSWORD_PROP= "servicePrivateKeyPassword";
/**
* The name of the {@value} which gives the path to the service's
* certificate.
*/
public static final String SERVICE_CERT_PROP= "serviceCertificate";
/**
* The name of the {@value} which gives the path to directory of PEM-encoded
* trusted X.509 certificates.
*/
public static final String TRUST_INFO_DIR_PROP= "trustInfoDir";
/**
* The name of the {@value} which gives the refresh period, in minutes, for
* the trust information.
*/
public static final String TRUST_INFO_REFRSH_PROP= "trustInfoRefresh";
/**
* The name of the {@value} which gives the maximum number of simultaneous
* requests.
*/
public static final String MAX_REQUESTS_PROP= "maximumRequests";
/** The name of the {@value} which gives the connection timeout, in seconds. */
public static final String CONN_TIMEOUT_PROP= "connectionTimeout";
/**
* The name of the {@value} which gives the size of the receiving message
* buffer, in bytes.
*/
public static final String REC_BUFF_SIZE_PROP= "receiveBufferSize";
/**
* The name of the {@value} which gives the sending message buffer, in
* bytes.
*/
public static final String SEND_BUFF_SIZE_PROP= "sendBufferSize";
/**
* Default value of the {@value #TRUST_INFO_REFRSH_PROP} property: {@value}
* minutes.
*/
public static final int DEFAULT_TRUST_INFO_REFRESH= 60;
/** Default value of the {@value #MAX_REQUESTS_PROP} property: {@value} . */
public static final int DEFAULT_MAX_REQS= 200;
/**
* Default value of the {@value #CONN_TIMEOUT_PROP} property: {@value}
* seconds.
*/
public static final int DEFAULT_CONN_TIMEOUT= 30;
/**
* Default value of the {@value #REC_BUFF_SIZE_PROP} property: {@value}
* kilobytes.
*/
public static final int DEFAULT_REC_BUFF_SIZE= 16384;
/**
* Default value of the {@value #SEND_BUFF_SIZE_PROP} property: {@value}
* kilobytes.
*/
public static final int DEFAULT_SEND_BUFF_SIZE= 16384;
/** Class logger. */
private final Logger log= LoggerFactory.getLogger(AbstractIniConfigurationParser.class);
/**
* Gets the value of the {@value #CONN_TIMEOUT_PROP} property from the
* configuration section. If the property is not present or is not valid the
* default value of {@value #DEFAULT_CONN_TIMEOUT} will be used.
*
* @param configSection
* configuration section from which to extract the value
*
* @return the timeout in milliseconds
*/
protected int getConnectionTimeout(Ini.Section configSection) {
int timeout= IniConfigUtil.getInt(configSection, CONN_TIMEOUT_PROP, DEFAULT_CONN_TIMEOUT, 1, Integer.MAX_VALUE);
return timeout * 1000;
}
/**
* Gets the value of the {@value #MAX_REQUESTS_PROP} property from the
* configuration section. If the property is not present or is not valid the
* default value of {@value #DEFAULT_MAX_REQS} will be used.
*
* @param configSection
* configuration section from which to extract the value
*
* @return the value
*/
protected int getMaximumRequests(Ini.Section configSection) {
return IniConfigUtil.getInt(configSection, MAX_REQUESTS_PROP, DEFAULT_MAX_REQS, 1, Integer.MAX_VALUE);
}
/**
* Gets the value of the {@value #REC_BUFF_SIZE_PROP} property from the
* configuration section. If the property is not present or is not valid the
* default value of {@value #DEFAULT_REC_BUFF_SIZE} will be used.
*
* @param configSection
* configuration section from which to extract the value
*
* @return the value
*/
protected int getReceiveBufferSize(Ini.Section configSection) {
return IniConfigUtil.getInt(configSection, REC_BUFF_SIZE_PROP, DEFAULT_REC_BUFF_SIZE, 1, Integer.MAX_VALUE);
}
/**
* Gets the value of the {@value #SEND_BUFF_SIZE_PROP} property from the
* configuration section. If the property is not present or is not valid the
* default value of {@value #DEFAULT_SEND_BUFF_SIZE} will be used.
*
* @param configSection
* configuration section from which to extract the value
*
* @return the value
*/
protected int getSendBufferSize(Ini.Section configSection) {
return IniConfigUtil.getInt(configSection, SEND_BUFF_SIZE_PROP, DEFAULT_SEND_BUFF_SIZE, 1, Integer.MAX_VALUE);
}
/**
* Gets the value of the {@value #TRUST_INFO_REFRSH_PROP} property from the
* configuration section. If the property is not present or is not valid the
* default value of {@value #DEFAULT_TRUST_INFO_REFRESH} will be used.
*
* @param configSection
* configuration section from which to extract the value
*
* @return the refresh interval in minutes
*/
protected int getTrustMaterialRefreshInterval(Ini.Section configSection) {
return IniConfigUtil.getInt(configSection, TRUST_INFO_REFRSH_PROP, DEFAULT_TRUST_INFO_REFRESH, 1, Integer.MAX_VALUE);
}
/**
* Creates a {@link javax.net.ssl.KeyManager} from the
* {@value #SERVICE_KEY_PROP} and {@value #SERVICE_CERT_PROP} properties, if
* they exist.
*
* @param configSection
* current configuration section being processed
*
* @return the constructed key manager, or null if the required properties
* do not exist
*
* @throws ConfigurationException
* thrown if there is a problem creating the key manager
*/
protected X509KeyManager getX509KeyManager(Ini.Section configSection)
throws ConfigurationException {
if (configSection == null) {
return null;
}
String name= configSection.getName();
String privateKeyFilePath= IniConfigUtil.getString(configSection, SERVICE_KEY_PROP, null);
if (privateKeyFilePath == null) {
log.info("{}: No service private key file provided, no service credential will be used.", name);
return null;
}
String privateKeyPassword= IniConfigUtil.getString(configSection, SERVICE_KEY_PASSWORD_PROP, null);
String certificateFilePath= IniConfigUtil.getString(configSection, SERVICE_CERT_PROP, null);
if (certificateFilePath == null) {
log.info("{}: No service certificate file provided, no service credential will be used.", name);
return null;
}
log.info("{}: service credential will use private key {} and certificate {}", new Object[] {
name, privateKeyFilePath, certificateFilePath });
try {
PEMCredential credential= new PEMCredential(privateKeyFilePath, certificateFilePath, (privateKeyPassword != null) ? privateKeyPassword.toCharArray() : null);
return credential.getKeyManager();
} catch (Exception e) {
log.error("Unable to create service key manager", e);
throw new ConfigurationException("Unable to read service credential information", e);
}
}
/**
* Creates a {@link PKIStore} from the {@value #TRUST_INFO_DIR_PROP}
* property, if they exist. This store holds the material used to validate
* X.509 certificates.
*
* @param configSection
* current configuration section being processed
*
* @return the constructed trust material store, or null if the required
* attribute did not exist
*
* @throws ConfigurationException
* thrown if there is a problem creating the trust manager
*/
protected X509TrustManager getX509TrustManager(Ini.Section configSection)
throws ConfigurationException {
if (configSection == null) {
return null;
}
String name= configSection.getName();
String trustStoreDir= IniConfigUtil.getString(configSection, TRUST_INFO_DIR_PROP, null);
if (trustStoreDir == null) {
log.info("{}: No truststore directory given, no trust manager will be used", name);
return null;
}
try {
Files.getFile(trustStoreDir, false, true, true, false);
} catch (IOException e) {
log.error("Unable to read truststore directory " + trustStoreDir, e);
throw new ConfigurationException(e.getMessage());
}
log.info("{}: X.509 trust information directory: {}", name, trustStoreDir);
int refreshInterval= getTrustMaterialRefreshInterval(configSection) * 60 * 1000;
log.info("{}: X.509 trust information refresh interval: {}ms", name, refreshInterval);
try {
OpensslCertChainValidator validator= new OpensslCertChainValidator(trustStoreDir);
validator.setUpdateInterval(refreshInterval);
X509TrustManager trustManager= new CommonX509TrustManager(validator);
return trustManager;
} catch (Exception e) {
- log.error("Unable to create X.509 trust material store", e);
- throw new ConfigurationException("Unable to create X.509 trust material store", e);
+ log.error("Unable to create X.509 trust store", e);
+ throw new ConfigurationException("Unable to create X.509 trust store", e);
}
}
}
| true | true |
protected X509TrustManager getX509TrustManager(Ini.Section configSection)
throws ConfigurationException {
if (configSection == null) {
return null;
}
String name= configSection.getName();
String trustStoreDir= IniConfigUtil.getString(configSection, TRUST_INFO_DIR_PROP, null);
if (trustStoreDir == null) {
log.info("{}: No truststore directory given, no trust manager will be used", name);
return null;
}
try {
Files.getFile(trustStoreDir, false, true, true, false);
} catch (IOException e) {
log.error("Unable to read truststore directory " + trustStoreDir, e);
throw new ConfigurationException(e.getMessage());
}
log.info("{}: X.509 trust information directory: {}", name, trustStoreDir);
int refreshInterval= getTrustMaterialRefreshInterval(configSection) * 60 * 1000;
log.info("{}: X.509 trust information refresh interval: {}ms", name, refreshInterval);
try {
OpensslCertChainValidator validator= new OpensslCertChainValidator(trustStoreDir);
validator.setUpdateInterval(refreshInterval);
X509TrustManager trustManager= new CommonX509TrustManager(validator);
return trustManager;
} catch (Exception e) {
log.error("Unable to create X.509 trust material store", e);
throw new ConfigurationException("Unable to create X.509 trust material store", e);
}
}
|
protected X509TrustManager getX509TrustManager(Ini.Section configSection)
throws ConfigurationException {
if (configSection == null) {
return null;
}
String name= configSection.getName();
String trustStoreDir= IniConfigUtil.getString(configSection, TRUST_INFO_DIR_PROP, null);
if (trustStoreDir == null) {
log.info("{}: No truststore directory given, no trust manager will be used", name);
return null;
}
try {
Files.getFile(trustStoreDir, false, true, true, false);
} catch (IOException e) {
log.error("Unable to read truststore directory " + trustStoreDir, e);
throw new ConfigurationException(e.getMessage());
}
log.info("{}: X.509 trust information directory: {}", name, trustStoreDir);
int refreshInterval= getTrustMaterialRefreshInterval(configSection) * 60 * 1000;
log.info("{}: X.509 trust information refresh interval: {}ms", name, refreshInterval);
try {
OpensslCertChainValidator validator= new OpensslCertChainValidator(trustStoreDir);
validator.setUpdateInterval(refreshInterval);
X509TrustManager trustManager= new CommonX509TrustManager(validator);
return trustManager;
} catch (Exception e) {
log.error("Unable to create X.509 trust store", e);
throw new ConfigurationException("Unable to create X.509 trust store", e);
}
}
|
diff --git a/src/main/java/net/pleiades/persistence/PersistentCilibSimulation.java b/src/main/java/net/pleiades/persistence/PersistentCilibSimulation.java
index 147594c..b709802 100644
--- a/src/main/java/net/pleiades/persistence/PersistentCilibSimulation.java
+++ b/src/main/java/net/pleiades/persistence/PersistentCilibSimulation.java
@@ -1,81 +1,81 @@
/* Pleiades
* Copyright (C) 2011 - 2012
* Computational Intelligence Research Group (CIRG@UP)
* Department of Computer Science
* University of Pretoria
* South Africa
*/
package net.pleiades.persistence;
import com.mongodb.BasicDBObject;
import java.util.ArrayList;
import java.util.List;
import net.pleiades.simulations.Simulation;
/**
*
* @author bennie
*/
public class PersistentCilibSimulation extends BasicDBObject {
public PersistentCilibSimulation() {
}
public PersistentCilibSimulation(Simulation s) {
- put("cilibInput", s.getCilibInput());
+ //put("cilibInput", s.getCilibInput());
put("fileKey", s.getFileKey());
put("outputFileName", s.getOutputFileName());
put("outputPath", s.getOutputPath());
put("samples", s.getSamples());
put("owner", s.getOwner());
put("ownerEmail", s.getOwnerEmail());
put("id", s.getID());
put("jobName", s.getJobName());
put("unfinishedTasks", s.unfinishedCount());
- //put("results", s.getResults());
+ put("results", s.getResults());
}
public String cilibInput() {
return (String) get("cilibInput");
}
public String fileKey() {
return (String) get("fileKey");
}
public String outputFileName() {
return (String) get("outputFileName");
}
public String outputPath() {
return (String) get("outputPath");
}
public String owner() {
return (String) get("owner");
}
public String ownerEmail() {
return (String) get("ownerEmail");
}
public String id() {
return (String) get("id");
}
public String jobName() {
return (String) get("jobName");
}
public int samples() {
return (Integer) get("samples");
}
public int unfinishedTasks() {
return (Integer) get("unfinishedTasks");
}
public List<String> results() {
return (ArrayList<String>) get("results");
}
}
| false | true |
public PersistentCilibSimulation(Simulation s) {
put("cilibInput", s.getCilibInput());
put("fileKey", s.getFileKey());
put("outputFileName", s.getOutputFileName());
put("outputPath", s.getOutputPath());
put("samples", s.getSamples());
put("owner", s.getOwner());
put("ownerEmail", s.getOwnerEmail());
put("id", s.getID());
put("jobName", s.getJobName());
put("unfinishedTasks", s.unfinishedCount());
//put("results", s.getResults());
}
|
public PersistentCilibSimulation(Simulation s) {
//put("cilibInput", s.getCilibInput());
put("fileKey", s.getFileKey());
put("outputFileName", s.getOutputFileName());
put("outputPath", s.getOutputPath());
put("samples", s.getSamples());
put("owner", s.getOwner());
put("ownerEmail", s.getOwnerEmail());
put("id", s.getID());
put("jobName", s.getJobName());
put("unfinishedTasks", s.unfinishedCount());
put("results", s.getResults());
}
|
diff --git a/src/main/java/com/totalchange/bunman/jb7/Jb7Catalogue.java b/src/main/java/com/totalchange/bunman/jb7/Jb7Catalogue.java
index ccba72a..3669715 100644
--- a/src/main/java/com/totalchange/bunman/jb7/Jb7Catalogue.java
+++ b/src/main/java/com/totalchange/bunman/jb7/Jb7Catalogue.java
@@ -1,256 +1,255 @@
/*
* Copyright 2013 Ralph Jones
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.totalchange.bunman.jb7;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.totalchange.bunman.Catalogue;
import com.totalchange.bunman.CatalogueSongListener;
import com.totalchange.bunman.cddb.CddbQuerier;
import com.totalchange.bunman.cddb.CddbResult;
final class Jb7Catalogue implements Catalogue {
private static final String CDDB_DATA_CATEGORY = "data";
private static final String SPLITTER_CDDB = "/";
private static final String SPLITTER_DIRNAME = " ";
private static final Logger logger = LoggerFactory
.getLogger(Jb7Catalogue.class);
private IdnFileAlbumCache cache;
private CddbQuerier querier;
private File root;
public Jb7Catalogue(IdnFileAlbumCache cache, CddbQuerier querier, File root) {
this.cache = cache;
this.querier = querier;
this.root = root;
}
private void processAlbumData(CatalogueSongListener listener, Album album,
boolean ignoreTrackNum, File dir, File... ignored) {
FileFinder fileFinder = new FileFinder(dir.listFiles(), ignored);
for (int num = 0; num < album.getTracks().size(); num++) {
String track = album.getTracks().get(num);
File file = fileFinder.findTrackFile(track);
if (file != null) {
int trackNum = -1;
if (!ignoreTrackNum) {
trackNum = num + 1;
}
listener.yetAnotherSong(new Jb7Song(album, trackNum, track,
file));
} else {
// TODO: Internationalise
listener.warn("Couldn't find a file for " + "track '" + track
+ "' from album '" + album.getAlbum() + "' by artist '"
+ album.getArtist() + "' in directory "
+ dir.getAbsolutePath());
}
}
}
private void processIdDir(File dir, File idFile,
CatalogueSongListener listener) {
try {
IdFileAlbum idf = new IdFileAlbum(idFile);
processAlbumData(listener, idf, false, dir, idFile);
} catch (IOException ioEx) {
listener.warn("Couldn''t read ID file " + idFile + ": "
+ ioEx.getLocalizedMessage());
}
}
private String readIdValue(File file) throws IOException {
logger.trace("Reading id string from file {}", file);
BufferedReader in = new BufferedReader(new FileReader(file));
try {
String id = in.readLine();
logger.trace("Raw id value is {}", id);
if (id != null) {
id = id.trim();
}
if (id != null && id.length() <= 0) {
id = null;
}
logger.trace("Parsed id value is {}", id);
return id;
} finally {
in.close();
}
}
private void addItemToQueueAndCacheIt(CatalogueSongListener listener,
File file, String id, IdnFileAlbum idnf) {
cache.putFileIntoCache(id, file.getParentFile().getName(), idnf);
processAlbumData(listener, idnf, false, file.getParentFile(), file);
}
private boolean equalsIgnoreCase(String[] arr1, String[] arr2) {
if (arr1.length != arr2.length) {
return false;
}
for (int num = 0; num < arr1.length; num++) {
if (!arr1[num].equalsIgnoreCase(arr2[num])) {
return false;
}
}
return true;
}
private void processQueryResults(CatalogueSongListener listener, File file,
String id, List<CddbResult> results) {
if (logger.isTraceEnabled()) {
logger.trace("Got CDDB results for file " + file + ", id " + id
+ ": " + results);
}
if (results.size() <= 0) {
logger.trace("No results - need to report as a problem");
// TODO: Internationalise
listener.warn("Failed to find any CDDB info for id " + id
+ " in directory " + file.getParent());
return;
}
if (results.size() == 1) {
logger.trace("Only one result, adding it to the queue");
addItemToQueueAndCacheIt(listener, file, id, new IdnFileAlbum(file,
results.get(0)));
return;
}
// Got more than 1 result - remove any that don't match on artist and
// title (and skip any in the "data" category).
String[] dirSplit = Jb7Utils.splitArtistAlbumBits(file.getParentFile()
.getName(), SPLITTER_DIRNAME);
List<CddbResult> matches = new ArrayList<CddbResult>();
for (CddbResult cddb : results) {
String[] resSplit = Jb7Utils.splitArtistAlbumBits(cddb.getTitle(),
SPLITTER_CDDB);
if (!cddb.getCategory().equalsIgnoreCase(CDDB_DATA_CATEGORY)
&& equalsIgnoreCase(dirSplit, resSplit)) {
matches.add(cddb);
}
}
if (matches.size() >= 1) {
logger.trace("Found a match for {}: {}", (Object[]) dirSplit,
matches);
addItemToQueueAndCacheIt(listener, file, id, new IdnFileAlbum(file,
matches.get(0)));
return;
}
// Bums
- // TODO: sort out a way of flagging multiple possibilities to the user
// TODO: Internationalise
listener.warn("Couldn't find any suitable CDDB info " + "for id " + id
+ " in directory " + file.getParent()
+ " out of possible matches " + results
+ ". Fallen back to file names.");
processAlbumData(listener, new NoFileAlbum(file.getParentFile()), true,
file.getParentFile(), file);
}
private void processIdnFile(final File file,
final CatalogueSongListener listener) {
logger.trace("Processing idn file {}", file);
final String id;
try {
id = readIdValue(file);
} catch (IOException ioEx) {
// TODO: Internationalise
listener.warn("Failed to read an ID value from " + file
+ " with error " + ioEx.getMessage());
return;
}
if (id == null) {
// TODO: Internationalise
listener.warn(file + " does not contain an ID value");
return;
}
logger.trace("Looking up from cache based on id {}", id);
IdnFileAlbum idnf = cache.getFileFromCache(id, file.getParentFile()
.getName());
if (idnf != null) {
logger.trace("Got result {} from cache", idnf);
idnf.setIdnFile(file);
processAlbumData(listener, idnf, false, file.getParentFile(), file);
}
logger.trace("Querying for CDDB results for id {}", id);
querier.query(id, new CddbQuerier.Listener() {
public void response(List<CddbResult> results) {
processQueryResults(listener, file, id, results);
}
public void error(IOException exception) {
listener.warn(exception.getMessage());
}
});
}
private void recurseForIdFiles(File dir, CatalogueSongListener listener) {
File idFile = new File(dir, "id");
if (idFile.exists()) {
processIdDir(dir, idFile, listener);
} else {
File idnFile = new File(dir, "idn");
if (idnFile.exists()) {
processIdnFile(idnFile, listener);
}
}
for (File subDir : dir.listFiles()) {
if (subDir.isDirectory()) {
recurseForIdFiles(subDir, listener);
}
}
}
public void listAllSongs(CatalogueSongListener listener) {
recurseForIdFiles(root, listener);
// Wait for IDN factory to finish any background processing - shouldn't
// really throw an error...
try {
querier.close();
} catch (IOException ioEx) {
listener.warn(ioEx.getMessage());
logger.warn("A problem occurred waiting for the CDDB querier to "
+ "close", ioEx);
}
}
}
| true | true |
private void processQueryResults(CatalogueSongListener listener, File file,
String id, List<CddbResult> results) {
if (logger.isTraceEnabled()) {
logger.trace("Got CDDB results for file " + file + ", id " + id
+ ": " + results);
}
if (results.size() <= 0) {
logger.trace("No results - need to report as a problem");
// TODO: Internationalise
listener.warn("Failed to find any CDDB info for id " + id
+ " in directory " + file.getParent());
return;
}
if (results.size() == 1) {
logger.trace("Only one result, adding it to the queue");
addItemToQueueAndCacheIt(listener, file, id, new IdnFileAlbum(file,
results.get(0)));
return;
}
// Got more than 1 result - remove any that don't match on artist and
// title (and skip any in the "data" category).
String[] dirSplit = Jb7Utils.splitArtistAlbumBits(file.getParentFile()
.getName(), SPLITTER_DIRNAME);
List<CddbResult> matches = new ArrayList<CddbResult>();
for (CddbResult cddb : results) {
String[] resSplit = Jb7Utils.splitArtistAlbumBits(cddb.getTitle(),
SPLITTER_CDDB);
if (!cddb.getCategory().equalsIgnoreCase(CDDB_DATA_CATEGORY)
&& equalsIgnoreCase(dirSplit, resSplit)) {
matches.add(cddb);
}
}
if (matches.size() >= 1) {
logger.trace("Found a match for {}: {}", (Object[]) dirSplit,
matches);
addItemToQueueAndCacheIt(listener, file, id, new IdnFileAlbum(file,
matches.get(0)));
return;
}
// Bums
// TODO: sort out a way of flagging multiple possibilities to the user
// TODO: Internationalise
listener.warn("Couldn't find any suitable CDDB info " + "for id " + id
+ " in directory " + file.getParent()
+ " out of possible matches " + results
+ ". Fallen back to file names.");
processAlbumData(listener, new NoFileAlbum(file.getParentFile()), true,
file.getParentFile(), file);
}
|
private void processQueryResults(CatalogueSongListener listener, File file,
String id, List<CddbResult> results) {
if (logger.isTraceEnabled()) {
logger.trace("Got CDDB results for file " + file + ", id " + id
+ ": " + results);
}
if (results.size() <= 0) {
logger.trace("No results - need to report as a problem");
// TODO: Internationalise
listener.warn("Failed to find any CDDB info for id " + id
+ " in directory " + file.getParent());
return;
}
if (results.size() == 1) {
logger.trace("Only one result, adding it to the queue");
addItemToQueueAndCacheIt(listener, file, id, new IdnFileAlbum(file,
results.get(0)));
return;
}
// Got more than 1 result - remove any that don't match on artist and
// title (and skip any in the "data" category).
String[] dirSplit = Jb7Utils.splitArtistAlbumBits(file.getParentFile()
.getName(), SPLITTER_DIRNAME);
List<CddbResult> matches = new ArrayList<CddbResult>();
for (CddbResult cddb : results) {
String[] resSplit = Jb7Utils.splitArtistAlbumBits(cddb.getTitle(),
SPLITTER_CDDB);
if (!cddb.getCategory().equalsIgnoreCase(CDDB_DATA_CATEGORY)
&& equalsIgnoreCase(dirSplit, resSplit)) {
matches.add(cddb);
}
}
if (matches.size() >= 1) {
logger.trace("Found a match for {}: {}", (Object[]) dirSplit,
matches);
addItemToQueueAndCacheIt(listener, file, id, new IdnFileAlbum(file,
matches.get(0)));
return;
}
// Bums
// TODO: Internationalise
listener.warn("Couldn't find any suitable CDDB info " + "for id " + id
+ " in directory " + file.getParent()
+ " out of possible matches " + results
+ ". Fallen back to file names.");
processAlbumData(listener, new NoFileAlbum(file.getParentFile()), true,
file.getParentFile(), file);
}
|
diff --git a/Proyecto/src/SongInterfaz.java b/Proyecto/src/SongInterfaz.java
index ce23762..2adc1ae 100644
--- a/Proyecto/src/SongInterfaz.java
+++ b/Proyecto/src/SongInterfaz.java
@@ -1,129 +1,135 @@
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.util.*;
import javax.swing.event.*;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javazoom.jlgui.basicplayer.BasicPlayerException;
import bibliotecaXML.Track;
import com.sun.awt.AWTUtilities;
public class SongInterfaz extends JFrame{
private JFrame principal;
private JList listado;
private Dimension pantalla = null;
private Dimension ventana = null;
private JScrollPane scroll=null;
private BotonAvanzado minButton = null;
private ImageIcon minIcon1 = new ImageIcon("images/skin1/minIcon1.jpg");
private ImageIcon minIcon2 = new ImageIcon("images/skin1/minIcon2.jpg");
private InterfazAvanzada interfazAvanzada= null;
public SongInterfaz(String[] temas, InterfazAvanzada interfazAvanzada){
super("Listado de Canciones");
this.interfazAvanzada = interfazAvanzada;
pantalla = Toolkit.getDefaultToolkit().getScreenSize();
ventana = this.getSize();
principal = this;
this.setSize(200, pantalla.height-200);
this.centrarVentana();
//this.setResizable(false); //En la otra principal
this.getContentPane().setLayout(new BorderLayout());
this.setUndecorated(true);
this.getContentPane().setBackground(Color.black);
this.scroll = new JScrollPane();
this.getContentPane().add(scroll,BorderLayout.EAST);
this.setEnabled(true);
listado=getListado(temas);
this.getContentPane().add(listado, BorderLayout.CENTER);
this.setAlwaysOnTop(true);
this.minButton = getMinButton();
this.getContentPane().add(minButton, BorderLayout.SOUTH);
this.setVisible(true);
//JFrame.setDefaultLookAndFeelDecorated(true);
AWTUtilities.setWindowOpacity(this, (float) 0.3);
}
private JList getListado(String[] temas){
listado = new JList(temas);
listado.setSize(100, pantalla.height);
listado.setBackground(Color.black);
listado.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
AWTUtilities.setWindowOpacity(principal, (float)0.9);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
AWTUtilities.setWindowOpacity(principal, (float) 0.3);
}
});
+ listado.addListSelectionListener(new ListSelectionListener() {
+ public void valueChanged(ListSelectionEvent evt) {
+ if (evt.getValueIsAdjusting())
+ interfazAvanzada.setTrackNumber(listado.getSelectedIndex());
+ }
+ });
- listado.addMouseListener(new java.awt.event.MouseAdapter()
+ /*listado.addMouseListener(new java.awt.event.MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
jList1_mouseClicked(e);
}
private void jList1_mouseClicked(MouseEvent e)
{
interfazAvanzada.setTrackNumber(listado.getSelectedIndex());
}
- });
+ }); */
return listado;
}
/*protected void this_windowOpened(WindowEvent e) {
centrarVentana();
}*/
public void actualizaTemas(String[] temas){
listado.setListData(temas);
}
private BotonAvanzado getMinButton(){
minButton = new BotonAvanzado(minIcon1,minIcon2);
minButton.addMouseListener(new java.awt.event.MouseAdapter() {
@SuppressWarnings("deprecation")
public void mouseReleased(java.awt.event.MouseEvent evt) {
setExtendedState(JFrame.CROSSHAIR_CURSOR);
// TODO
};
});
return minButton;
}
private void centrarVentana() {
// Se obtienen las dimensiones en pixels de la pantalla.
Dimension pantalla = Toolkit.getDefaultToolkit().getScreenSize();
// Se obtienen las dimensiones en pixels de la ventana.
Dimension ventana = this.getSize();
// Una cuenta para situar la ventana en el centro de la pantalla.
this.setLocation((pantalla.width)-200,
(pantalla.height - ventana.height) / 2);
}
}
| false | true |
private JList getListado(String[] temas){
listado = new JList(temas);
listado.setSize(100, pantalla.height);
listado.setBackground(Color.black);
listado.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
AWTUtilities.setWindowOpacity(principal, (float)0.9);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
AWTUtilities.setWindowOpacity(principal, (float) 0.3);
}
});
listado.addMouseListener(new java.awt.event.MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
jList1_mouseClicked(e);
}
private void jList1_mouseClicked(MouseEvent e)
{
interfazAvanzada.setTrackNumber(listado.getSelectedIndex());
}
});
return listado;
}
|
private JList getListado(String[] temas){
listado = new JList(temas);
listado.setSize(100, pantalla.height);
listado.setBackground(Color.black);
listado.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
AWTUtilities.setWindowOpacity(principal, (float)0.9);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
AWTUtilities.setWindowOpacity(principal, (float) 0.3);
}
});
listado.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
if (evt.getValueIsAdjusting())
interfazAvanzada.setTrackNumber(listado.getSelectedIndex());
}
});
/*listado.addMouseListener(new java.awt.event.MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
jList1_mouseClicked(e);
}
private void jList1_mouseClicked(MouseEvent e)
{
interfazAvanzada.setTrackNumber(listado.getSelectedIndex());
}
}); */
return listado;
}
|
diff --git a/driver-core/src/main/java/com/datastax/driver/core/Connection.java b/driver-core/src/main/java/com/datastax/driver/core/Connection.java
index 2f9cc7979..de8363579 100644
--- a/driver-core/src/main/java/com/datastax/driver/core/Connection.java
+++ b/driver-core/src/main/java/com/datastax/driver/core/Connection.java
@@ -1,612 +1,612 @@
/*
* Copyright (C) 2012 DataStax Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.driver.core;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.util.concurrent.Uninterruptibles;
import com.datastax.driver.core.exceptions.AuthenticationException;
import com.datastax.driver.core.exceptions.DriverInternalError;
import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.transport.*;
import org.apache.cassandra.transport.messages.*;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.ChannelGroupFuture;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// For LoggingHandler
//import org.jboss.netty.handler.logging.LoggingHandler;
//import org.jboss.netty.logging.InternalLogLevel;
/**
* A connection to a Cassandra Node.
*/
class Connection extends org.apache.cassandra.transport.Connection
{
public static final int MAX_STREAM_PER_CONNECTION = 128;
private static final Logger logger = LoggerFactory.getLogger(Connection.class);
// TODO: that doesn't belong here
private static final String CQL_VERSION = "3.0.0";
private static final org.apache.cassandra.transport.Connection.Tracker EMPTY_TRACKER = new org.apache.cassandra.transport.Connection.Tracker() {
public void addConnection(Channel ch, org.apache.cassandra.transport.Connection connection) {}
public void closeAll() {}
};
public final InetAddress address;
private final String name;
private final Channel channel;
private final Factory factory;
private final Dispatcher dispatcher = new Dispatcher();
// Used by connnection pooling to count how many requests are "in flight" on that connection.
public final AtomicInteger inFlight = new AtomicInteger(0);
private final AtomicInteger writer = new AtomicInteger(0);
private volatile boolean isClosed;
private volatile String keyspace;
private volatile boolean isDefunct;
private volatile ConnectionException exception;
/**
* Create a new connection to a Cassandra node.
*
* The connection is open and initialized by the constructor.
*
* @throws ConnectionException if the connection attempts fails or is
* refused by the server.
*/
private Connection(String name, InetAddress address, Factory factory) throws ConnectionException, InterruptedException {
super(EMPTY_TRACKER);
this.address = address;
this.factory = factory;
this.name = name;
ClientBootstrap bootstrap = factory.newBootstrap();
bootstrap.setPipelineFactory(new PipelineFactory(this));
ChannelFuture future = bootstrap.connect(new InetSocketAddress(address, factory.getPort()));
writer.incrementAndGet();
try {
// Wait until the connection attempt succeeds or fails.
this.channel = future.awaitUninterruptibly().getChannel();
this.factory.allChannels.add(this.channel);
if (!future.isSuccess())
{
if (logger.isDebugEnabled())
logger.debug(String.format("[%s] Error connecting to %s%s", name, address, extractMessage(future.getCause())));
throw new TransportException(address, "Cannot connect", future.getCause());
}
} finally {
writer.decrementAndGet();
}
logger.trace("[{}] Connection opened successfully", name);
initializeTransport();
logger.trace("[{}] Transport initialized and ready", name);
}
private static String extractMessage(Throwable t) {
if (t == null || t.getMessage().isEmpty())
return "";
return " (" + t.getMessage() + ")";
}
private void initializeTransport() throws ConnectionException, InterruptedException {
// TODO: we will need to get fancy about handling protocol version at
// some point, but keep it simple for now.
Map<String, String> options = new HashMap<String, String>() {{
put(StartupMessage.CQL_VERSION, CQL_VERSION);
}};
ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
if (compression != ProtocolOptions.Compression.NONE)
{
options.put(StartupMessage.COMPRESSION, compression.toString());
setCompressor(compression.compressor());
}
StartupMessage startup = new StartupMessage(options);
try {
Message.Response response = write(startup).get();
switch (response.type) {
case READY:
break;
case ERROR:
throw defunct(new TransportException(address, String.format("Error initializing connection: %s", ((ErrorMessage)response).error.getMessage())));
case AUTHENTICATE:
CredentialsMessage creds = new CredentialsMessage();
creds.credentials.putAll(factory.authProvider.getAuthInfo(address));
Message.Response authResponse = write(creds).get();
switch (authResponse.type) {
case READY:
break;
case ERROR:
- throw new AuthenticationException(address, (((ErrorMessage)response).error).getMessage());
+ throw new AuthenticationException(address, (((ErrorMessage)authResponse).error).getMessage());
default:
throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type)));
}
break;
default:
throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type)));
}
} catch (BusyConnectionException e) {
throw new DriverInternalError("Newly created connection should not be busy");
} catch (ExecutionException e) {
throw defunct(new ConnectionException(address, "Unexpected error during transport initialization", e.getCause()));
}
}
public boolean isDefunct() {
return isDefunct;
}
public ConnectionException lastException() {
return exception;
}
ConnectionException defunct(ConnectionException e) {
if (logger.isDebugEnabled())
logger.debug("Defuncting connection to " + address, e);
exception = e;
isDefunct = true;
dispatcher.errorOutAllHandler(e);
return e;
}
public String keyspace() {
return keyspace;
}
public void setKeyspace(String keyspace) throws ConnectionException {
if (keyspace == null)
return;
if (this.keyspace != null && this.keyspace.equals(keyspace))
return;
try {
logger.trace("[{}] Setting keyspace {}", name, keyspace);
Message.Response response = Uninterruptibles.getUninterruptibly(write(new QueryMessage("USE \"" + keyspace + "\"", ConsistencyLevel.DEFAULT_CASSANDRA_CL)));
switch (response.type) {
case RESULT:
this.keyspace = keyspace;
break;
default:
// The code set the keyspace only when a successful 'use'
// has been perform, so there shouldn't be any error here.
// It can happen however that the node we're connecting to
// is not up on the schema yet. In that case, defuncting
// the connection is not a bad choice.
defunct(new ConnectionException(address, String.format("Problem while setting keyspace, got %s as response", response)));
break;
}
} catch (ConnectionException e) {
throw defunct(e);
} catch (BusyConnectionException e) {
logger.error("Tried to set the keyspace on busy connection. This should not happen but is not critical");
} catch (ExecutionException e) {
throw defunct(new ConnectionException(address, "Error while setting keyspace", e));
}
}
/**
* Write a request on this connection.
*
* @param request the request to send
* @return a future on the server response
*
* @throws ConnectionException if the connection is closed
* @throws TransportException if an I/O error while sending the request
*/
public Future write(Message.Request request) throws ConnectionException, BusyConnectionException {
Future future = new Future(request);
write(future);
return future;
}
public void write(ResponseCallback callback) throws ConnectionException, BusyConnectionException {
Message.Request request = callback.request();
if (isDefunct)
throw new ConnectionException(address, "Write attempt on defunct connection");
if (isClosed)
throw new ConnectionException(address, "Connection has been closed");
request.attach(this);
ResponseHandler handler = new ResponseHandler(dispatcher, callback);
dispatcher.add(handler);
request.setStreamId(handler.streamId);
logger.trace("[{}] writing request {}", name, request);
writer.incrementAndGet();
channel.write(request).addListener(writeHandler(request, handler));
}
private ChannelFutureListener writeHandler(final Message.Request request, final ResponseHandler handler) {
return new ChannelFutureListener() {
public void operationComplete(ChannelFuture writeFuture) {
writer.decrementAndGet();
if (!writeFuture.isSuccess()) {
logger.debug("[{}] Error writing request {}", name, request);
// Remove this handler from the dispatcher so it don't get notified of the error
// twice (we will fail that method already)
dispatcher.removeHandler(handler.streamId);
ConnectionException ce;
if (writeFuture.getCause() instanceof java.nio.channels.ClosedChannelException) {
ce = new TransportException(address, "Error writing: Closed channel");
} else {
ce = new TransportException(address, "Error writing", writeFuture.getCause());
}
handler.callback.onException(Connection.this, defunct(ce));
} else {
logger.trace("[{}] request sent successfully", name);
}
}
};
}
public void close() {
try {
close(0, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public boolean close(long timeout, TimeUnit unit) throws InterruptedException {
if (isClosed)
return true;
// Note: there is no guarantee only one thread will reach that point, but executing this
// method multiple time is harmless. If the latter change, we'll have to CAS isClosed to
// make sure this gets executed only once.
logger.trace("[{}] closing connection", name);
// Make sure all new writes are rejected
isClosed = true;
long start = System.currentTimeMillis();
if (!isDefunct) {
// Busy waiting, we just wait for request to be fully written, shouldn't take long
while (writer.get() > 0 && Cluster.timeSince(start, unit) < timeout)
Uninterruptibles.sleepUninterruptibly(1, unit);
}
return channel.close().await(timeout - unit.convert(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS), unit);
// Note: we must not call releaseExternalResources on the bootstrap, because this shutdown the executors, which are shared
}
public boolean isClosed() {
return isClosed;
}
@Override
public String toString() {
return String.format("Connection[%s, inFlight=%d, closed=%b]", name, inFlight.get(), isClosed);
}
// Cruft needed because we reuse server side classes, but we don't care about it
public void validateNewMessage(Message.Type type) {};
public void applyStateTransition(Message.Type requestType, Message.Type responseType) {};
public ClientState clientState() { return null; };
public static class Factory {
private final ExecutorService bossExecutor = Executors.newCachedThreadPool();
private final ExecutorService workerExecutor = Executors.newCachedThreadPool();
private final ChannelFactory channelFactory = new NioClientSocketChannelFactory(bossExecutor, workerExecutor);
private final ChannelGroup allChannels = new DefaultChannelGroup();
private final ConcurrentMap<Host, AtomicInteger> idGenerators = new ConcurrentHashMap<Host, AtomicInteger>();
public final DefaultResponseHandler defaultHandler;
public final Configuration configuration;
public final AuthInfoProvider authProvider;
private volatile boolean isShutdown;
public Factory(Cluster.Manager manager, AuthInfoProvider authProvider) {
this(manager, manager.configuration, authProvider);
}
private Factory(DefaultResponseHandler defaultHandler, Configuration configuration, AuthInfoProvider authProvider) {
this.defaultHandler = defaultHandler;
this.configuration = configuration;
this.authProvider = authProvider;
}
public int getPort() {
return configuration.getProtocolOptions().getPort();
}
/**
* Opens a new connection to the node this factory points to.
*
* @return the newly created (and initialized) connection.
*
* @throws ConnectionException if connection attempt fails.
*/
public Connection open(Host host) throws ConnectionException, InterruptedException {
InetAddress address = host.getAddress();
if (isShutdown)
throw new ConnectionException(address, "Connection factory is shut down");
String name = address.toString() + "-" + getIdGenerator(host).getAndIncrement();
return new Connection(name, address, this);
}
private AtomicInteger getIdGenerator(Host host) {
AtomicInteger g = idGenerators.get(host);
if (g == null) {
g = new AtomicInteger(1);
AtomicInteger old = idGenerators.putIfAbsent(host, g);
if (old != null)
g = old;
}
return g;
}
private ClientBootstrap newBootstrap() {
ClientBootstrap b = new ClientBootstrap(channelFactory);
SocketOptions options = configuration.getSocketOptions();
b.setOption("connectTimeoutMillis", options.getConnectTimeoutMillis());
Boolean keepAlive = options.getKeepAlive();
if (keepAlive != null)
b.setOption("keepAlive", keepAlive);
Boolean reuseAddress = options.getReuseAddress();
if (reuseAddress != null)
b.setOption("reuseAddress", reuseAddress);
Integer soLinger = options.getSoLinger();
if (soLinger != null)
b.setOption("soLinger", soLinger);
Boolean tcpNoDelay = options.getTcpNoDelay();
if (tcpNoDelay != null)
b.setOption("tcpNoDelay", tcpNoDelay);
Integer receiveBufferSize = options.getReceiveBufferSize();
if (receiveBufferSize != null)
b.setOption("receiveBufferSize", receiveBufferSize);
Integer sendBufferSize = options.getSendBufferSize();
if (sendBufferSize != null)
b.setOption("sendBufferSize", sendBufferSize);
return b;
}
public boolean shutdown(long timeout, TimeUnit unit) throws InterruptedException {
// Make sure we skip creating connection from now on.
isShutdown = true;
long start = System.currentTimeMillis();
ChannelGroupFuture future = allChannels.close();
channelFactory.shutdown();
bossExecutor.shutdown();
workerExecutor.shutdown();
return future.await(timeout, unit)
&& bossExecutor.awaitTermination(timeout - Cluster.timeSince(start, unit), unit)
&& workerExecutor.awaitTermination(timeout - Cluster.timeSince(start, unit), unit);
}
}
private class Dispatcher extends SimpleChannelUpstreamHandler {
public final StreamIdGenerator streamIdHandler = new StreamIdGenerator();
private final ConcurrentMap<Integer, ResponseHandler> pending = new ConcurrentHashMap<Integer, ResponseHandler>();
public void add(ResponseHandler handler) {
ResponseHandler old = pending.put(handler.streamId, handler);
assert old == null;
}
public void removeHandler(int streamId) {
pending.remove(streamId);
streamIdHandler.release(streamId);
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
if (!(e.getMessage() instanceof Message.Response)) {
logger.error("[{}] Received unexpected message: {}", name, e.getMessage());
defunct(new TransportException(address, "Unexpected message received: " + e.getMessage()));
} else {
Message.Response response = (Message.Response)e.getMessage();
int streamId = response.getStreamId();
logger.trace("[{}] received: {}", name, e.getMessage());
if (streamId < 0) {
factory.defaultHandler.handle(response);
return;
}
ResponseHandler handler = pending.remove(streamId);
streamIdHandler.release(streamId);
if (handler == null) {
// Note: this is a bug, either us or cassandra. So log it, but I'm not sure it's worth breaking
// the connection for that.
logger.error("[{}] No handler set for stream {} (this is a bug, either of this driver or of Cassandra, you should report it)", name, streamId);
return;
}
handler.callback.onSet(Connection.this, response);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
if (logger.isTraceEnabled())
logger.trace(String.format("[%s] connection error", name), e.getCause());
// Ignore exception while writing, this will be handled by write() directly
if (writer.get() > 0)
return;
defunct(new TransportException(address, "Unexpected exception triggered", e.getCause()));
}
public void errorOutAllHandler(ConnectionException ce) {
Iterator<ResponseHandler> iter = pending.values().iterator();
while (iter.hasNext())
{
iter.next().callback.onException(Connection.this, ce);
iter.remove();
}
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
{
// If we've closed the channel server side then we don't really want to defunct the connection, but
// if there is remaining thread waiting on us, we still want to wake them up
if (isClosed)
errorOutAllHandler(new TransportException(address, "Channel has been closed"));
else
defunct(new TransportException(address, "Channel has been closed"));
}
}
static class Future extends SimpleFuture<Message.Response> implements RequestHandler.Callback {
private final Message.Request request;
private volatile InetAddress address;
public Future(Message.Request request) {
this.request = request;
}
public Message.Request request() {
return request;
}
public void onSet(Connection connection, Message.Response response, ExecutionInfo info) {
onSet(connection, response);
}
public void onSet(Connection connection, Message.Response response) {
this.address = connection.address;
super.set(response);
}
public void onException(Connection connection, Exception exception) {
super.setException(exception);
}
public InetAddress getAddress() {
return address;
}
}
interface ResponseCallback {
public Message.Request request();
public void onSet(Connection connection, Message.Response response);
public void onException(Connection connection, Exception exception);
}
private static class ResponseHandler {
public final int streamId;
public final ResponseCallback callback;
public ResponseHandler(Dispatcher dispatcher, ResponseCallback callback) throws BusyConnectionException {
this.streamId = dispatcher.streamIdHandler.next();
this.callback = callback;
}
}
public interface DefaultResponseHandler {
public void handle(Message.Response response);
}
private static class PipelineFactory implements ChannelPipelineFactory {
// Stateless handlers
private static final Message.ProtocolDecoder messageDecoder = new Message.ProtocolDecoder();
private static final Message.ProtocolEncoder messageEncoder = new Message.ProtocolEncoder();
private static final Frame.Decompressor frameDecompressor = new Frame.Decompressor();
private static final Frame.Compressor frameCompressor = new Frame.Compressor();
private static final Frame.Encoder frameEncoder = new Frame.Encoder();
// One more fallout of using server side classes; not a big deal
private static final org.apache.cassandra.transport.Connection.Tracker tracker;
static {
tracker = new org.apache.cassandra.transport.Connection.Tracker() {
public void addConnection(Channel ch, org.apache.cassandra.transport.Connection connection) {}
public void closeAll() {}
};
}
private final Connection connection;
private final org.apache.cassandra.transport.Connection.Factory cfactory;
public PipelineFactory(final Connection connection) {
this.connection = connection;
this.cfactory = new org.apache.cassandra.transport.Connection.Factory() {
public Connection newConnection(org.apache.cassandra.transport.Connection.Tracker tracker) {
return connection;
}
};
}
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
//pipeline.addLast("debug", new LoggingHandler(InternalLogLevel.INFO));
pipeline.addLast("frameDecoder", new Frame.Decoder(tracker, cfactory));
pipeline.addLast("frameEncoder", frameEncoder);
pipeline.addLast("frameDecompressor", frameDecompressor);
pipeline.addLast("frameCompressor", frameCompressor);
pipeline.addLast("messageDecoder", messageDecoder);
pipeline.addLast("messageEncoder", messageEncoder);
pipeline.addLast("dispatcher", connection.dispatcher);
return pipeline;
}
}
}
| true | true |
private void initializeTransport() throws ConnectionException, InterruptedException {
// TODO: we will need to get fancy about handling protocol version at
// some point, but keep it simple for now.
Map<String, String> options = new HashMap<String, String>() {{
put(StartupMessage.CQL_VERSION, CQL_VERSION);
}};
ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
if (compression != ProtocolOptions.Compression.NONE)
{
options.put(StartupMessage.COMPRESSION, compression.toString());
setCompressor(compression.compressor());
}
StartupMessage startup = new StartupMessage(options);
try {
Message.Response response = write(startup).get();
switch (response.type) {
case READY:
break;
case ERROR:
throw defunct(new TransportException(address, String.format("Error initializing connection: %s", ((ErrorMessage)response).error.getMessage())));
case AUTHENTICATE:
CredentialsMessage creds = new CredentialsMessage();
creds.credentials.putAll(factory.authProvider.getAuthInfo(address));
Message.Response authResponse = write(creds).get();
switch (authResponse.type) {
case READY:
break;
case ERROR:
throw new AuthenticationException(address, (((ErrorMessage)response).error).getMessage());
default:
throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type)));
}
break;
default:
throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type)));
}
} catch (BusyConnectionException e) {
throw new DriverInternalError("Newly created connection should not be busy");
} catch (ExecutionException e) {
throw defunct(new ConnectionException(address, "Unexpected error during transport initialization", e.getCause()));
}
}
|
private void initializeTransport() throws ConnectionException, InterruptedException {
// TODO: we will need to get fancy about handling protocol version at
// some point, but keep it simple for now.
Map<String, String> options = new HashMap<String, String>() {{
put(StartupMessage.CQL_VERSION, CQL_VERSION);
}};
ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
if (compression != ProtocolOptions.Compression.NONE)
{
options.put(StartupMessage.COMPRESSION, compression.toString());
setCompressor(compression.compressor());
}
StartupMessage startup = new StartupMessage(options);
try {
Message.Response response = write(startup).get();
switch (response.type) {
case READY:
break;
case ERROR:
throw defunct(new TransportException(address, String.format("Error initializing connection: %s", ((ErrorMessage)response).error.getMessage())));
case AUTHENTICATE:
CredentialsMessage creds = new CredentialsMessage();
creds.credentials.putAll(factory.authProvider.getAuthInfo(address));
Message.Response authResponse = write(creds).get();
switch (authResponse.type) {
case READY:
break;
case ERROR:
throw new AuthenticationException(address, (((ErrorMessage)authResponse).error).getMessage());
default:
throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type)));
}
break;
default:
throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type)));
}
} catch (BusyConnectionException e) {
throw new DriverInternalError("Newly created connection should not be busy");
} catch (ExecutionException e) {
throw defunct(new ConnectionException(address, "Unexpected error during transport initialization", e.getCause()));
}
}
|
diff --git a/src/com/seanmadden/deepthought/responders/WikiResponder.java b/src/com/seanmadden/deepthought/responders/WikiResponder.java
index 7c4737c..cc1e552 100644
--- a/src/com/seanmadden/deepthought/responders/WikiResponder.java
+++ b/src/com/seanmadden/deepthought/responders/WikiResponder.java
@@ -1,50 +1,51 @@
/*
* WikiResponder.java
*
* $Id $
* Author: smadden
*
* Copyright (C) 2010 Sean Madden
*
* Please see the pertinent documents for licensing information.
*
*/
package com.seanmadden.deepthought.responders;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import com.seanmadden.deepthought.IRCClient;
import com.seanmadden.deepthought.Message;
import com.seanmadden.deepthought.MessageHandler;
public class WikiResponder implements MessageHandler {
@Override
public boolean handleMessage(IRCClient irc, Message m) {
String message = m.getMessage();
if(!message.contains("!wiki")){
return false;
}
String[] args = message.split(" ", 2);
if(args.length < 2){
return false;
}
if(!args[0].equals("!wiki")){
return false;
}
String wiki = "https://secure.wikimedia.org/wikipedia/en/wiki/";
try {
+ args[1] = args[1].replaceAll(" ", "_");
wiki += URLEncoder.encode(args[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Message mesg = new Message(wiki, m.getTarget());
irc.sendMessage(mesg);
return true;
}
}
| true | true |
public boolean handleMessage(IRCClient irc, Message m) {
String message = m.getMessage();
if(!message.contains("!wiki")){
return false;
}
String[] args = message.split(" ", 2);
if(args.length < 2){
return false;
}
if(!args[0].equals("!wiki")){
return false;
}
String wiki = "https://secure.wikimedia.org/wikipedia/en/wiki/";
try {
wiki += URLEncoder.encode(args[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Message mesg = new Message(wiki, m.getTarget());
irc.sendMessage(mesg);
return true;
}
|
public boolean handleMessage(IRCClient irc, Message m) {
String message = m.getMessage();
if(!message.contains("!wiki")){
return false;
}
String[] args = message.split(" ", 2);
if(args.length < 2){
return false;
}
if(!args[0].equals("!wiki")){
return false;
}
String wiki = "https://secure.wikimedia.org/wikipedia/en/wiki/";
try {
args[1] = args[1].replaceAll(" ", "_");
wiki += URLEncoder.encode(args[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Message mesg = new Message(wiki, m.getTarget());
irc.sendMessage(mesg);
return true;
}
|
diff --git a/hw2-wfeely/src/main/java/edu/cmu/deiis/annotators/NgramAnnotator.java b/hw2-wfeely/src/main/java/edu/cmu/deiis/annotators/NgramAnnotator.java
index ce67cbf..76941aa 100644
--- a/hw2-wfeely/src/main/java/edu/cmu/deiis/annotators/NgramAnnotator.java
+++ b/hw2-wfeely/src/main/java/edu/cmu/deiis/annotators/NgramAnnotator.java
@@ -1,112 +1,115 @@
/** NgramAnnotator.java
* @author Weston Feely
*/
package edu.cmu.deiis.annotators;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.uima.analysis_component.JCasAnnotator_ImplBase;
import org.apache.uima.cas.FSIndex;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.cas.FSArray;
import org.apache.uima.tutorial.RoomNumber;
import edu.cmu.deiis.types.*;
/**
* Annotator that creates 1-,2-, and 3-grams from annotated tokens.
*/
public class NgramAnnotator extends JCasAnnotator_ImplBase {
public void process (JCas aJCas) {
// get tokens
FSIndex tokenIndex = aJCas.getAnnotationIndex(Token.type);
// loop over tokens
Iterator tokenIter = tokenIndex.iterator();
Token penult = null;
Token antepenult = null;
while (tokenIter.hasNext()) {
// grab a token
Token token = (Token) tokenIter.next();
// check previous tokens
if (penult == null && antepenult == null) {
// Case 1: Previous two tokens are not set
// set previous token
penult = token;
}
else if (antepenult == null)
{
// Case 2: Penultimate token is set, antepenultimate token is not set
// check whether previous two tokens are from same sentence
if (penult.getSentenceId() == token.getSentenceId())
{
// make a bigram
NGram bigram = new NGram(aJCas);
bigram.setElementType("Bigram");
bigram.setElements(new FSArray(aJCas, 2));
// add tokens to bigram
bigram.setElements(0,penult);
bigram.setElements(1,token);
// set bigram begin and end
bigram.setBegin(penult.getBegin());
bigram.setEnd(token.getEnd());
// add bigram to indexes
bigram.addToIndexes();
}
+ // set previous two tokens
+ antepenult = penult;
+ penult = token;
}
else {
// Case 3: Previous two tokens are set
// check whether previous two tokens are from same sentence
if (penult.getSentenceId() == token.getSentenceId())
{
// make a bigram
NGram bigram = new NGram(aJCas);
bigram.setElementType("Bigram");
bigram.setElements(new FSArray(aJCas, 2));
// add tokens to bigram
bigram.setElements(0,penult);
bigram.setElements(1,token);
// set bigram begin and end
bigram.setBegin(penult.getBegin());
bigram.setEnd(token.getEnd());
// add bigram to indexes
bigram.addToIndexes();
}
// check whether previous three tokens are from same sentence
if (antepenult.getSentenceId() == penult.getSentenceId() &&
penult.getSentenceId() == token.getSentenceId())
{
// make a trigram
NGram trigram = new NGram(aJCas);
trigram.setElementType("Trigram");
trigram.setElements(new FSArray(aJCas, 3));
// add tokens to trigram
trigram.setElements(0,antepenult);
trigram.setElements(1,penult);
trigram.setElements(2,token);
// set trigram begin and end
trigram.setBegin(antepenult.getBegin());
trigram.setEnd(token.getEnd());
// add trigram to indexes
trigram.addToIndexes();
}
// set previous two tokens
antepenult = penult;
penult = token;
}
// set up a unigram
NGram unigram = new NGram(aJCas);
unigram.setElementType("Unigram");
unigram.setElements(new FSArray(aJCas, 1));
// add token to unigram
unigram.setElements(0,token);
// set unigram begin and end
unigram.setBegin(token.getBegin());
unigram.setEnd(token.getEnd());
// add unigram to indexes
unigram.addToIndexes();
}
}
}
| true | true |
public void process (JCas aJCas) {
// get tokens
FSIndex tokenIndex = aJCas.getAnnotationIndex(Token.type);
// loop over tokens
Iterator tokenIter = tokenIndex.iterator();
Token penult = null;
Token antepenult = null;
while (tokenIter.hasNext()) {
// grab a token
Token token = (Token) tokenIter.next();
// check previous tokens
if (penult == null && antepenult == null) {
// Case 1: Previous two tokens are not set
// set previous token
penult = token;
}
else if (antepenult == null)
{
// Case 2: Penultimate token is set, antepenultimate token is not set
// check whether previous two tokens are from same sentence
if (penult.getSentenceId() == token.getSentenceId())
{
// make a bigram
NGram bigram = new NGram(aJCas);
bigram.setElementType("Bigram");
bigram.setElements(new FSArray(aJCas, 2));
// add tokens to bigram
bigram.setElements(0,penult);
bigram.setElements(1,token);
// set bigram begin and end
bigram.setBegin(penult.getBegin());
bigram.setEnd(token.getEnd());
// add bigram to indexes
bigram.addToIndexes();
}
}
else {
// Case 3: Previous two tokens are set
// check whether previous two tokens are from same sentence
if (penult.getSentenceId() == token.getSentenceId())
{
// make a bigram
NGram bigram = new NGram(aJCas);
bigram.setElementType("Bigram");
bigram.setElements(new FSArray(aJCas, 2));
// add tokens to bigram
bigram.setElements(0,penult);
bigram.setElements(1,token);
// set bigram begin and end
bigram.setBegin(penult.getBegin());
bigram.setEnd(token.getEnd());
// add bigram to indexes
bigram.addToIndexes();
}
// check whether previous three tokens are from same sentence
if (antepenult.getSentenceId() == penult.getSentenceId() &&
penult.getSentenceId() == token.getSentenceId())
{
// make a trigram
NGram trigram = new NGram(aJCas);
trigram.setElementType("Trigram");
trigram.setElements(new FSArray(aJCas, 3));
// add tokens to trigram
trigram.setElements(0,antepenult);
trigram.setElements(1,penult);
trigram.setElements(2,token);
// set trigram begin and end
trigram.setBegin(antepenult.getBegin());
trigram.setEnd(token.getEnd());
// add trigram to indexes
trigram.addToIndexes();
}
// set previous two tokens
antepenult = penult;
penult = token;
}
// set up a unigram
NGram unigram = new NGram(aJCas);
unigram.setElementType("Unigram");
unigram.setElements(new FSArray(aJCas, 1));
// add token to unigram
unigram.setElements(0,token);
// set unigram begin and end
unigram.setBegin(token.getBegin());
unigram.setEnd(token.getEnd());
// add unigram to indexes
unigram.addToIndexes();
}
}
|
public void process (JCas aJCas) {
// get tokens
FSIndex tokenIndex = aJCas.getAnnotationIndex(Token.type);
// loop over tokens
Iterator tokenIter = tokenIndex.iterator();
Token penult = null;
Token antepenult = null;
while (tokenIter.hasNext()) {
// grab a token
Token token = (Token) tokenIter.next();
// check previous tokens
if (penult == null && antepenult == null) {
// Case 1: Previous two tokens are not set
// set previous token
penult = token;
}
else if (antepenult == null)
{
// Case 2: Penultimate token is set, antepenultimate token is not set
// check whether previous two tokens are from same sentence
if (penult.getSentenceId() == token.getSentenceId())
{
// make a bigram
NGram bigram = new NGram(aJCas);
bigram.setElementType("Bigram");
bigram.setElements(new FSArray(aJCas, 2));
// add tokens to bigram
bigram.setElements(0,penult);
bigram.setElements(1,token);
// set bigram begin and end
bigram.setBegin(penult.getBegin());
bigram.setEnd(token.getEnd());
// add bigram to indexes
bigram.addToIndexes();
}
// set previous two tokens
antepenult = penult;
penult = token;
}
else {
// Case 3: Previous two tokens are set
// check whether previous two tokens are from same sentence
if (penult.getSentenceId() == token.getSentenceId())
{
// make a bigram
NGram bigram = new NGram(aJCas);
bigram.setElementType("Bigram");
bigram.setElements(new FSArray(aJCas, 2));
// add tokens to bigram
bigram.setElements(0,penult);
bigram.setElements(1,token);
// set bigram begin and end
bigram.setBegin(penult.getBegin());
bigram.setEnd(token.getEnd());
// add bigram to indexes
bigram.addToIndexes();
}
// check whether previous three tokens are from same sentence
if (antepenult.getSentenceId() == penult.getSentenceId() &&
penult.getSentenceId() == token.getSentenceId())
{
// make a trigram
NGram trigram = new NGram(aJCas);
trigram.setElementType("Trigram");
trigram.setElements(new FSArray(aJCas, 3));
// add tokens to trigram
trigram.setElements(0,antepenult);
trigram.setElements(1,penult);
trigram.setElements(2,token);
// set trigram begin and end
trigram.setBegin(antepenult.getBegin());
trigram.setEnd(token.getEnd());
// add trigram to indexes
trigram.addToIndexes();
}
// set previous two tokens
antepenult = penult;
penult = token;
}
// set up a unigram
NGram unigram = new NGram(aJCas);
unigram.setElementType("Unigram");
unigram.setElements(new FSArray(aJCas, 1));
// add token to unigram
unigram.setElements(0,token);
// set unigram begin and end
unigram.setBegin(token.getBegin());
unigram.setEnd(token.getEnd());
// add unigram to indexes
unigram.addToIndexes();
}
}
|
diff --git a/src/au/edu/uts/eng/remotelabs/rigclient/status/StatusUpdater.java b/src/au/edu/uts/eng/remotelabs/rigclient/status/StatusUpdater.java
index dc14326..8822890 100644
--- a/src/au/edu/uts/eng/remotelabs/rigclient/status/StatusUpdater.java
+++ b/src/au/edu/uts/eng/remotelabs/rigclient/status/StatusUpdater.java
@@ -1,401 +1,402 @@
/**
* SAHARA Rig Client
*
* Software abstraction of physical rig to provide rig session control
* and rig device control. Automatically tests rig hardware and reports
* the rig status to ensure rig goodness.
*
* @license See LICENSE in the top level directory for complete license terms.
*
* Copyright (c) 2010, University of Technology, Sydney
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Technology, Sydney nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Michael Diponio (mdiponio)
* @date 23rd February 2010
*/
package au.edu.uts.eng.remotelabs.rigclient.status;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.rmi.RemoteException;
import java.util.Arrays;
import java.util.Calendar;
import org.apache.axis2.AxisFault;
import org.apache.axis2.databinding.types.URI;
import au.edu.uts.eng.remotelabs.rigclient.rig.IRig;
import au.edu.uts.eng.remotelabs.rigclient.status.types.ProviderResponse;
import au.edu.uts.eng.remotelabs.rigclient.status.types.RegisterRig;
import au.edu.uts.eng.remotelabs.rigclient.status.types.RegisterRigResponse;
import au.edu.uts.eng.remotelabs.rigclient.status.types.RegisterRigType;
import au.edu.uts.eng.remotelabs.rigclient.status.types.RemoveRig;
import au.edu.uts.eng.remotelabs.rigclient.status.types.RemoveRigResponse;
import au.edu.uts.eng.remotelabs.rigclient.status.types.RemoveRigType;
import au.edu.uts.eng.remotelabs.rigclient.status.types.StatusType;
import au.edu.uts.eng.remotelabs.rigclient.status.types.UpdateRigStatus;
import au.edu.uts.eng.remotelabs.rigclient.status.types.UpdateRigStatusResponse;
import au.edu.uts.eng.remotelabs.rigclient.status.types.UpdateRigType;
import au.edu.uts.eng.remotelabs.rigclient.type.RigFactory;
import au.edu.uts.eng.remotelabs.rigclient.util.ConfigFactory;
import au.edu.uts.eng.remotelabs.rigclient.util.IConfig;
import au.edu.uts.eng.remotelabs.rigclient.util.ILogger;
import au.edu.uts.eng.remotelabs.rigclient.util.LoggerFactory;
/**
* Registers the rig client with a scheduling server, then periodically
* updates the scheduling server with the rig clients status.
* <br />
* Interrupting the status updater will cause the status updater to
* shutdown by removing the scheduling server's rig client registration.
*/
public class StatusUpdater implements Runnable
{
/** Suffix for the Scheduling Server local rig provider SOAP interface
* end point. */
public static final String SS_URL_SUFFIX = "/SchedulingServer-LocalRigProvider/services/LocalRigProvider";
/** Default status update interval. */
public static final int DEFAULT_UPDATE_PERIOD = 30;
/** Scheduling server SOAP stub. */
private SchedulingServerProviderStub schedServerStub;
/** Scheduling server end point. */
private final String endPoint;
/** The actual rig type class. */
private final IRig rig;
/** The address the rig client is listening on. */
private final URI rigClientAddress;
/** The period to provide status updates. */
private int updatePeriod;
/** The identity tokens from registration. The 0th value is current
* identity token, the 1st identity token is the identity token
* directly before the current identity token. */
private final static String identToks[] = new String[2];
/** Whether the rig client is registered. */
private static boolean isRegistered;
/** Flag to specify the status updater should
/** Logger. */
private final ILogger logger;
public StatusUpdater(String addr) throws Exception
{
this.logger = LoggerFactory.getLoggerInstance();
this.rig = RigFactory.getRigInstance();
this.rigClientAddress = new URI(addr);
/* Load the configuration properties. */
IConfig config = ConfigFactory.getInstance();
/* Generate the end point URL. */
StringBuilder ep = new StringBuilder();
ep.append("http://");
String tmp = config.getProperty("Scheduling_Server_Address");
if (tmp == null || tmp.length() < 1)
{
this.logger.fatal("Unable to load the Scheduling Server address. Ensure the property " +
"'Scheduling_Server_Address' is set with a valid host name or IP address.");
throw new Exception("Unable to load scheduling server address.");
}
this.logger.debug("Loaded scheduling server address ('Scheduling_Server_Address') property as " + tmp + '.');
ep.append(tmp);
tmp = config.getProperty("Scheduling_Server_Port", "8080");
try
{
ep.append(':');
ep.append(Integer.parseInt(tmp)); // Check to ensure the port number is valid
}
catch (NumberFormatException ex)
{
this.logger.fatal("Invalid Scheduling Server port number loaded. Ensure the property " +
"'Scheduling_Server_Port' is either set to a valid port number or not set (defaults to 8080).");
throw new Exception("Invalid port number for scheduling server.");
}
ep.append(StatusUpdater.SS_URL_SUFFIX);
this.endPoint = ep.toString();
this.logger.info("Scheduling server end point address is " + this.endPoint + '.');
tmp = config.getProperty("Scheduling_Server_Update_Period", String.valueOf(StatusUpdater.DEFAULT_UPDATE_PERIOD));
try
{
this.updatePeriod = Integer.parseInt(tmp);
this.logger.info("Going to update the scheduling server every " + this.updatePeriod + " seconds.");
}
catch (NumberFormatException ex)
{
this.logger.warn("Invalid scheduling server status update period set ('Scheduling_Server_Update_Period'), " +
"using the default of every " + StatusUpdater.DEFAULT_UPDATE_PERIOD + " seconds.");
this.updatePeriod = StatusUpdater.DEFAULT_UPDATE_PERIOD;
}
}
@Override
public void run()
{
while (!Thread.interrupted())
{
try
{
if (this.schedServerStub == null)
{
this.schedServerStub = new SchedulingServerProviderStub(this.endPoint);
}
ProviderResponse provResp;
if (StatusUpdater.isRegistered)
{
/* --------------------------------------------------------
* -- Registered - providing status update. --
* ------------------------------------------------------*/
/* 1) Set up message. */
UpdateRigStatus request = new UpdateRigStatus();
UpdateRigType updateType = new UpdateRigType();
request.setUpdateRigStatus(updateType);
updateType.setName(this.rig.getName());
StatusType status = new StatusType();
updateType.setStatus(status);
status.setIsOnline(this.rig.isMonitorStatusGood());
if (!this.rig.isMonitorStatusGood()) status.setOfflineReason(this.rig.getMonitorReason());
/* 2) Send message. */
UpdateRigStatusResponse response = this.schedServerStub.updateRigStatus(request);
provResp = response.getUpdateRigStatusResponse();
}
else
{
/* --------------------------------------------------------
* -- Not registered - attempt to register. --
* ------------------------------------------------------*/
/* 1) Set up message. */
RegisterRig request = new RegisterRig();
RegisterRigType registerType = new RegisterRigType();
request.setRegisterRig(registerType);
registerType.setName(this.rig.getName());
registerType.setType(this.rig.getType());
String caps[] = this.rig.getCapabilities();
StringBuilder capBuilder = new StringBuilder();
for (int i = 0; i < caps.length; i++)
{
capBuilder.append(caps[0]);
if ((i + 1) != caps.length) capBuilder.append(',');
}
registerType.setCapabilities(capBuilder.toString());
registerType.setContactUrl(this.rigClientAddress);
StatusType status = new StatusType();
registerType.setStatus(status);
status.setIsOnline(this.rig.isMonitorStatusGood());
status.setOfflineReason(this.rig.getMonitorReason());
/* 2) Send message. */
RegisterRigResponse response = this.schedServerStub.registerRig(request);
provResp = response.getRegisterRigResponse();
}
/* 3) Check response. */
if (provResp.getSuccessful())
{
this.logger.debug("Successfully communicated with the scheduling server to " +
(StatusUpdater.isRegistered ? "update the rig status." : "register the rig."));
StatusUpdater.isRegistered = true;
String identTok = provResp.getIdentityToken();
if (identTok != null && !identTok.equals(identToks[0]))
{
synchronized (StatusUpdater.class)
{
StatusUpdater.identToks[1] = StatusUpdater.identToks[0];
StatusUpdater.identToks[0] = identTok;
}
this.logger.info("Obtained new identity token with value '" + StatusUpdater.identToks[0] + "'.");
StatusUpdater.isRegistered = true;
}
}
else
{
/* Assuming the Scheduling Server does not have the rig client registered. */
synchronized (StatusUpdater.class)
{
StatusUpdater.identToks[1] = null;
StatusUpdater.identToks[0] = null;
}
this.logger.error("Failed to " + (StatusUpdater.isRegistered ? "update" : "register") + " the " +
"Scheduling Server. The provided reason for failing is '" +
this.getNiceErrorMessage(provResp.getErrorReason()) + "'.");
StatusUpdater.isRegistered = false;
}
}
catch (AxisFault ex)
{
synchronized (StatusUpdater.class)
{
StatusUpdater.identToks[1] = null;
StatusUpdater.identToks[0] = null;
}
StatusUpdater.isRegistered = false;
this.schedServerStub = null;
if (ex.getCause() instanceof ConnectException)
{
this.logger.error("SOAP fault trying to" + (StatusUpdater.isRegistered ? " update the rigs status" :
" register the rig") + ". Fault reason is connection error with reason: " + ex.getMessage() +
". Ensure the Scheduling Server is running and listening on the configured port number.");
}
else if (ex.getCause() instanceof UnknownHostException)
{
this.logger.error("SOAP fault trying to" + (StatusUpdater.isRegistered ? " update the rigs status" :
" register the rig") + ". Fault reason is unknown host " + ex.getMessage() + ". " +
"Configure the scheduling server host as a valid host name.");
}
else
{
this.logger.error("SOAP fault trying to" + (StatusUpdater.isRegistered ? " update the rigs status" :
" register the rig") + ". Fault reason is '" + ex.getReason() + "'.");
}
}
catch (RemoteException ex)
{
synchronized (StatusUpdater.class)
{
StatusUpdater.identToks[1] = null;
StatusUpdater.identToks[0] = null;
}
StatusUpdater.isRegistered = false;
this.schedServerStub = null;
this.logger.error("Remote exception when trying to" + (StatusUpdater.isRegistered ? " update the rigs status" :
" register the rig") + ". Exception message is '" + ex.getMessage() + "'.");
}
try
{
Thread.sleep(this.updatePeriod * 1000);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
/* --------------------------------------------------------------------
* -- 3) Unregister the rig. --
* ------------------------------------------------------------------*/
+ if (!StatusUpdater.isRegistered) return;
this.logger.debug("Received interrupt for the status updater, removing the rig client's registration.");
/* 1) Set up message. */
RemoveRig request = new RemoveRig();
RemoveRigType removeType = new RemoveRigType();
request.setRemoveRig(removeType);
removeType.setName(this.rig.getName());
Calendar cal = Calendar.getInstance();
removeType.setRemovalReason("Shutting down at time " + cal.get(Calendar.HOUR_OF_DAY) + ':' +
cal.get(Calendar.MINUTE) + ':' + cal.get(Calendar.SECOND) + " on " + cal.get(Calendar.DAY_OF_MONTH) +
'/' + (cal.get(Calendar.MONTH) + 1) + '/' + cal.get(Calendar.YEAR) + '.');
/* 2) Send message. */
try
{
RemoveRigResponse response = this.schedServerStub.removeRig(request);
if (response.getRemoveRigResponse().getSuccessful())
{
this.logger.info("Successfully removed the rig client's scheduling server registration.");
}
else
{
this.logger.error("Failed to remove the rig client's scheduling server registration with provided " +
"error '" + this.getNiceErrorMessage(response.getRemoveRigResponse().getErrorReason()) + "'.");
}
}
catch (RemoteException e)
{
this.logger.error("Failed to remove the scheduling servers registration because of remote exception " +
" with error message '" + e.getMessage() + "'.");
}
}
/**
* Returns the current identity token and the identity token directly
* before the current identity token. The 0th value is the current
* identity token and the 1st is the one directly before.
* <br />
* If the rig client is not registered or recently registered, the 0th or
* 1st values may be <code>null</code>.
*
* @return current and last identity token
*/
public static String[] getServerIdentityTokens()
{
synchronized (StatusUpdater.class)
{
return Arrays.copyOf(StatusUpdater.identToks, 2);
}
}
/**
* Returns <tt>true</tt> if the rig client is registered with a scheduling
* server.
*
* @return true if registered
*/
public static boolean isRegistered()
{
return StatusUpdater.isRegistered;
}
/**
* Returns a more descriptive error than is provided from the scheduling
* server, provided the error is a known type.
*
* @param msg message from server
* @return detailed error or provided message
*/
private String getNiceErrorMessage(String msg)
{
if ("Exists".equals(msg))
{
return "a rig with the same name already exists";
}
else if ("Not registered".equals(msg))
{
return "the rig is not registered";
}
return msg;
}
}
| true | true |
public void run()
{
while (!Thread.interrupted())
{
try
{
if (this.schedServerStub == null)
{
this.schedServerStub = new SchedulingServerProviderStub(this.endPoint);
}
ProviderResponse provResp;
if (StatusUpdater.isRegistered)
{
/* --------------------------------------------------------
* -- Registered - providing status update. --
* ------------------------------------------------------*/
/* 1) Set up message. */
UpdateRigStatus request = new UpdateRigStatus();
UpdateRigType updateType = new UpdateRigType();
request.setUpdateRigStatus(updateType);
updateType.setName(this.rig.getName());
StatusType status = new StatusType();
updateType.setStatus(status);
status.setIsOnline(this.rig.isMonitorStatusGood());
if (!this.rig.isMonitorStatusGood()) status.setOfflineReason(this.rig.getMonitorReason());
/* 2) Send message. */
UpdateRigStatusResponse response = this.schedServerStub.updateRigStatus(request);
provResp = response.getUpdateRigStatusResponse();
}
else
{
/* --------------------------------------------------------
* -- Not registered - attempt to register. --
* ------------------------------------------------------*/
/* 1) Set up message. */
RegisterRig request = new RegisterRig();
RegisterRigType registerType = new RegisterRigType();
request.setRegisterRig(registerType);
registerType.setName(this.rig.getName());
registerType.setType(this.rig.getType());
String caps[] = this.rig.getCapabilities();
StringBuilder capBuilder = new StringBuilder();
for (int i = 0; i < caps.length; i++)
{
capBuilder.append(caps[0]);
if ((i + 1) != caps.length) capBuilder.append(',');
}
registerType.setCapabilities(capBuilder.toString());
registerType.setContactUrl(this.rigClientAddress);
StatusType status = new StatusType();
registerType.setStatus(status);
status.setIsOnline(this.rig.isMonitorStatusGood());
status.setOfflineReason(this.rig.getMonitorReason());
/* 2) Send message. */
RegisterRigResponse response = this.schedServerStub.registerRig(request);
provResp = response.getRegisterRigResponse();
}
/* 3) Check response. */
if (provResp.getSuccessful())
{
this.logger.debug("Successfully communicated with the scheduling server to " +
(StatusUpdater.isRegistered ? "update the rig status." : "register the rig."));
StatusUpdater.isRegistered = true;
String identTok = provResp.getIdentityToken();
if (identTok != null && !identTok.equals(identToks[0]))
{
synchronized (StatusUpdater.class)
{
StatusUpdater.identToks[1] = StatusUpdater.identToks[0];
StatusUpdater.identToks[0] = identTok;
}
this.logger.info("Obtained new identity token with value '" + StatusUpdater.identToks[0] + "'.");
StatusUpdater.isRegistered = true;
}
}
else
{
/* Assuming the Scheduling Server does not have the rig client registered. */
synchronized (StatusUpdater.class)
{
StatusUpdater.identToks[1] = null;
StatusUpdater.identToks[0] = null;
}
this.logger.error("Failed to " + (StatusUpdater.isRegistered ? "update" : "register") + " the " +
"Scheduling Server. The provided reason for failing is '" +
this.getNiceErrorMessage(provResp.getErrorReason()) + "'.");
StatusUpdater.isRegistered = false;
}
}
catch (AxisFault ex)
{
synchronized (StatusUpdater.class)
{
StatusUpdater.identToks[1] = null;
StatusUpdater.identToks[0] = null;
}
StatusUpdater.isRegistered = false;
this.schedServerStub = null;
if (ex.getCause() instanceof ConnectException)
{
this.logger.error("SOAP fault trying to" + (StatusUpdater.isRegistered ? " update the rigs status" :
" register the rig") + ". Fault reason is connection error with reason: " + ex.getMessage() +
". Ensure the Scheduling Server is running and listening on the configured port number.");
}
else if (ex.getCause() instanceof UnknownHostException)
{
this.logger.error("SOAP fault trying to" + (StatusUpdater.isRegistered ? " update the rigs status" :
" register the rig") + ". Fault reason is unknown host " + ex.getMessage() + ". " +
"Configure the scheduling server host as a valid host name.");
}
else
{
this.logger.error("SOAP fault trying to" + (StatusUpdater.isRegistered ? " update the rigs status" :
" register the rig") + ". Fault reason is '" + ex.getReason() + "'.");
}
}
catch (RemoteException ex)
{
synchronized (StatusUpdater.class)
{
StatusUpdater.identToks[1] = null;
StatusUpdater.identToks[0] = null;
}
StatusUpdater.isRegistered = false;
this.schedServerStub = null;
this.logger.error("Remote exception when trying to" + (StatusUpdater.isRegistered ? " update the rigs status" :
" register the rig") + ". Exception message is '" + ex.getMessage() + "'.");
}
try
{
Thread.sleep(this.updatePeriod * 1000);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
/* --------------------------------------------------------------------
* -- 3) Unregister the rig. --
* ------------------------------------------------------------------*/
this.logger.debug("Received interrupt for the status updater, removing the rig client's registration.");
/* 1) Set up message. */
RemoveRig request = new RemoveRig();
RemoveRigType removeType = new RemoveRigType();
request.setRemoveRig(removeType);
removeType.setName(this.rig.getName());
Calendar cal = Calendar.getInstance();
removeType.setRemovalReason("Shutting down at time " + cal.get(Calendar.HOUR_OF_DAY) + ':' +
cal.get(Calendar.MINUTE) + ':' + cal.get(Calendar.SECOND) + " on " + cal.get(Calendar.DAY_OF_MONTH) +
'/' + (cal.get(Calendar.MONTH) + 1) + '/' + cal.get(Calendar.YEAR) + '.');
/* 2) Send message. */
try
{
RemoveRigResponse response = this.schedServerStub.removeRig(request);
if (response.getRemoveRigResponse().getSuccessful())
{
this.logger.info("Successfully removed the rig client's scheduling server registration.");
}
else
{
this.logger.error("Failed to remove the rig client's scheduling server registration with provided " +
"error '" + this.getNiceErrorMessage(response.getRemoveRigResponse().getErrorReason()) + "'.");
}
}
catch (RemoteException e)
{
this.logger.error("Failed to remove the scheduling servers registration because of remote exception " +
" with error message '" + e.getMessage() + "'.");
}
}
|
public void run()
{
while (!Thread.interrupted())
{
try
{
if (this.schedServerStub == null)
{
this.schedServerStub = new SchedulingServerProviderStub(this.endPoint);
}
ProviderResponse provResp;
if (StatusUpdater.isRegistered)
{
/* --------------------------------------------------------
* -- Registered - providing status update. --
* ------------------------------------------------------*/
/* 1) Set up message. */
UpdateRigStatus request = new UpdateRigStatus();
UpdateRigType updateType = new UpdateRigType();
request.setUpdateRigStatus(updateType);
updateType.setName(this.rig.getName());
StatusType status = new StatusType();
updateType.setStatus(status);
status.setIsOnline(this.rig.isMonitorStatusGood());
if (!this.rig.isMonitorStatusGood()) status.setOfflineReason(this.rig.getMonitorReason());
/* 2) Send message. */
UpdateRigStatusResponse response = this.schedServerStub.updateRigStatus(request);
provResp = response.getUpdateRigStatusResponse();
}
else
{
/* --------------------------------------------------------
* -- Not registered - attempt to register. --
* ------------------------------------------------------*/
/* 1) Set up message. */
RegisterRig request = new RegisterRig();
RegisterRigType registerType = new RegisterRigType();
request.setRegisterRig(registerType);
registerType.setName(this.rig.getName());
registerType.setType(this.rig.getType());
String caps[] = this.rig.getCapabilities();
StringBuilder capBuilder = new StringBuilder();
for (int i = 0; i < caps.length; i++)
{
capBuilder.append(caps[0]);
if ((i + 1) != caps.length) capBuilder.append(',');
}
registerType.setCapabilities(capBuilder.toString());
registerType.setContactUrl(this.rigClientAddress);
StatusType status = new StatusType();
registerType.setStatus(status);
status.setIsOnline(this.rig.isMonitorStatusGood());
status.setOfflineReason(this.rig.getMonitorReason());
/* 2) Send message. */
RegisterRigResponse response = this.schedServerStub.registerRig(request);
provResp = response.getRegisterRigResponse();
}
/* 3) Check response. */
if (provResp.getSuccessful())
{
this.logger.debug("Successfully communicated with the scheduling server to " +
(StatusUpdater.isRegistered ? "update the rig status." : "register the rig."));
StatusUpdater.isRegistered = true;
String identTok = provResp.getIdentityToken();
if (identTok != null && !identTok.equals(identToks[0]))
{
synchronized (StatusUpdater.class)
{
StatusUpdater.identToks[1] = StatusUpdater.identToks[0];
StatusUpdater.identToks[0] = identTok;
}
this.logger.info("Obtained new identity token with value '" + StatusUpdater.identToks[0] + "'.");
StatusUpdater.isRegistered = true;
}
}
else
{
/* Assuming the Scheduling Server does not have the rig client registered. */
synchronized (StatusUpdater.class)
{
StatusUpdater.identToks[1] = null;
StatusUpdater.identToks[0] = null;
}
this.logger.error("Failed to " + (StatusUpdater.isRegistered ? "update" : "register") + " the " +
"Scheduling Server. The provided reason for failing is '" +
this.getNiceErrorMessage(provResp.getErrorReason()) + "'.");
StatusUpdater.isRegistered = false;
}
}
catch (AxisFault ex)
{
synchronized (StatusUpdater.class)
{
StatusUpdater.identToks[1] = null;
StatusUpdater.identToks[0] = null;
}
StatusUpdater.isRegistered = false;
this.schedServerStub = null;
if (ex.getCause() instanceof ConnectException)
{
this.logger.error("SOAP fault trying to" + (StatusUpdater.isRegistered ? " update the rigs status" :
" register the rig") + ". Fault reason is connection error with reason: " + ex.getMessage() +
". Ensure the Scheduling Server is running and listening on the configured port number.");
}
else if (ex.getCause() instanceof UnknownHostException)
{
this.logger.error("SOAP fault trying to" + (StatusUpdater.isRegistered ? " update the rigs status" :
" register the rig") + ". Fault reason is unknown host " + ex.getMessage() + ". " +
"Configure the scheduling server host as a valid host name.");
}
else
{
this.logger.error("SOAP fault trying to" + (StatusUpdater.isRegistered ? " update the rigs status" :
" register the rig") + ". Fault reason is '" + ex.getReason() + "'.");
}
}
catch (RemoteException ex)
{
synchronized (StatusUpdater.class)
{
StatusUpdater.identToks[1] = null;
StatusUpdater.identToks[0] = null;
}
StatusUpdater.isRegistered = false;
this.schedServerStub = null;
this.logger.error("Remote exception when trying to" + (StatusUpdater.isRegistered ? " update the rigs status" :
" register the rig") + ". Exception message is '" + ex.getMessage() + "'.");
}
try
{
Thread.sleep(this.updatePeriod * 1000);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
/* --------------------------------------------------------------------
* -- 3) Unregister the rig. --
* ------------------------------------------------------------------*/
if (!StatusUpdater.isRegistered) return;
this.logger.debug("Received interrupt for the status updater, removing the rig client's registration.");
/* 1) Set up message. */
RemoveRig request = new RemoveRig();
RemoveRigType removeType = new RemoveRigType();
request.setRemoveRig(removeType);
removeType.setName(this.rig.getName());
Calendar cal = Calendar.getInstance();
removeType.setRemovalReason("Shutting down at time " + cal.get(Calendar.HOUR_OF_DAY) + ':' +
cal.get(Calendar.MINUTE) + ':' + cal.get(Calendar.SECOND) + " on " + cal.get(Calendar.DAY_OF_MONTH) +
'/' + (cal.get(Calendar.MONTH) + 1) + '/' + cal.get(Calendar.YEAR) + '.');
/* 2) Send message. */
try
{
RemoveRigResponse response = this.schedServerStub.removeRig(request);
if (response.getRemoveRigResponse().getSuccessful())
{
this.logger.info("Successfully removed the rig client's scheduling server registration.");
}
else
{
this.logger.error("Failed to remove the rig client's scheduling server registration with provided " +
"error '" + this.getNiceErrorMessage(response.getRemoveRigResponse().getErrorReason()) + "'.");
}
}
catch (RemoteException e)
{
this.logger.error("Failed to remove the scheduling servers registration because of remote exception " +
" with error message '" + e.getMessage() + "'.");
}
}
|
diff --git a/motech-server-core/src/main/java/org/motechproject/server/ws/RegistrarWebService.java b/motech-server-core/src/main/java/org/motechproject/server/ws/RegistrarWebService.java
index ddbf75fd..339fe180 100644
--- a/motech-server-core/src/main/java/org/motechproject/server/ws/RegistrarWebService.java
+++ b/motech-server-core/src/main/java/org/motechproject/server/ws/RegistrarWebService.java
@@ -1,1401 +1,1403 @@
/**
* MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT
*
* Copyright (c) 2010-11 The Trustees of Columbia University in the City of
* New York and Grameen Foundation USA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Grameen Foundation USA, Columbia University, or
* their respective contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY
* AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION
* USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.motechproject.server.ws;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.motechproject.server.model.Community;
import org.motechproject.server.model.ExpectedEncounter;
import org.motechproject.server.model.ExpectedObs;
import org.motechproject.server.model.Facility;
import org.motechproject.server.model.rct.RCTFacility;
import org.motechproject.server.svc.*;
import org.motechproject.ws.*;
import org.motechproject.ws.rct.RCTRegistrationConfirmation;
import org.motechproject.ws.server.RegistrarService;
import org.motechproject.ws.server.ValidationErrors;
import org.motechproject.ws.server.ValidationException;
import org.openmrs.Encounter;
import org.openmrs.Obs;
import org.openmrs.PersonName;
import org.openmrs.User;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import java.util.*;
/**
* This is the service enpoint implementation for the major motech server web
* service.
* <p/>
* This can be accessed via /openmrs/ws/RegistrarService since we mapped it to
* /ws/RegistrarService in the moduleApplicationContext.xml file.
*/
@WebService(targetNamespace = "http://server.ws.motechproject.org/")
public class RegistrarWebService implements RegistrarService {
Log log = LogFactory.getLog(RegistrarWebService.class);
RegistrarBean registrarBean;
OpenmrsBean openmrsBean;
WebServiceModelConverter modelConverter;
MessageSourceBean messageBean;
RCTService rctService;
@WebMethod
public void recordPatientHistory(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "lastIPT") Integer lastIPT,
@WebParam(name = "lastIPTDate") Date lastIPTDate,
@WebParam(name = "lastTT") Integer lastTT,
@WebParam(name = "lastTTDate") Date lastTTDate,
@WebParam(name = "bcgDate") Date bcgDate,
@WebParam(name = "lastOPV") Integer lastOPV,
@WebParam(name = "lastOPVDate") Date lastOPVDate,
@WebParam(name = "lastPenta") Integer lastPenta,
@WebParam(name = "lastPentaDate") Date lastPentaDate,
@WebParam(name = "measlesDate") Date measlesDate,
@WebParam(name = "yellowFeverDate") Date yellowFeverDate,
@WebParam(name = "lastIPTI") Integer lastIPTI,
@WebParam(name = "lastIPTIDate") Date lastIPTIDate,
@WebParam(name = "lastVitaminADate") Date lastVitaminADate)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Record Patient History request", errors);
}
registrarBean.recordPatientHistory(staff, facility.getLocation(), date,
patient, lastIPT, lastIPTDate, lastTT, lastTTDate, bcgDate,
lastOPV, lastOPVDate, lastPenta, lastPentaDate, measlesDate,
yellowFeverDate, lastIPTI, lastIPTIDate, lastVitaminADate, null);
}
@WebMethod
public void recordMotherANCVisit(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "visitNumber") Integer visitNumber,
@WebParam(name = "location") Integer location,
@WebParam(name = "house") String house,
@WebParam(name = "community") String community,
@WebParam(name = "estDeliveryDate") Date estDeliveryDate,
@WebParam(name = "bpSystolic") Integer bpSystolic,
@WebParam(name = "bpDiastolic") Integer bpDiastolic,
@WebParam(name = "weight") Double weight,
@WebParam(name = "ttDose") Integer ttDose,
@WebParam(name = "iptDose") Integer iptDose,
@WebParam(name = "iptReactive") Boolean iptReactive,
@WebParam(name = "itnUse") Boolean itnUse,
@WebParam(name = "fht") Double fht,
@WebParam(name = "fhr") Integer fhr,
@WebParam(name = "urineTestProtein") Integer urineTestProtein,
@WebParam(name = "urineTestGlucose") Integer urineTestGlucose,
@WebParam(name = "hemoglobin") Double hemoglobin,
@WebParam(name = "vdrlReactive") Boolean vdrlReactive,
@WebParam(name = "vdrlTreatment") Boolean vdrlTreatment,
@WebParam(name = "dewormer") Boolean dewormer,
@WebParam(name = "maleInvolved") Boolean maleInvolved,
@WebParam(name = "pmtct") Boolean pmtct,
@WebParam(name = "preTestCounseled") Boolean preTestCounseled,
@WebParam(name = "hivTestResult") HIVResult hivTestResult,
@WebParam(name = "postTestCounseled") Boolean postTestCounseled,
@WebParam(name = "pmtctTreatment") Boolean pmtctTreatment,
@WebParam(name = "referred") Boolean referred,
@WebParam(name = "nextANCDate") Date nextANCDate,
@WebParam(name = "comments") String comments)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Record Mother ANC Visit request", errors);
}
registrarBean.recordMotherANCVisit(staff, facility.getLocation(), date,
patient, visitNumber, location, house, community,
estDeliveryDate, bpSystolic, bpDiastolic, weight, ttDose,
iptDose, iptReactive, itnUse, fht, fhr, urineTestProtein,
urineTestGlucose, hemoglobin, vdrlReactive, vdrlTreatment,
dewormer, maleInvolved, pmtct, preTestCounseled, hivTestResult,
postTestCounseled, pmtctTreatment, referred, nextANCDate,
comments);
}
@WebMethod
public void recordPregnancyTermination(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "terminationType") Integer terminationType,
@WebParam(name = "procedure") Integer procedure,
@WebParam(name = "complications") Integer[] complications,
@WebParam(name = "maternalDeath") Boolean maternalDeath,
@WebParam(name = "referred") Boolean referred,
@WebParam(name = "postAbortionFPCounseled") Boolean postAbortionFPCounseled,
@WebParam(name = "postAbortionFPAccepted") Boolean postAbortionFPAccepted,
@WebParam(name = "comments") String comments)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Record Pregnancy Termination request", errors);
}
registrarBean.recordPregnancyTermination(staff, facility.getLocation(),
date, patient, terminationType, procedure, complications,
maternalDeath, referred, postAbortionFPCounseled,
postAbortionFPAccepted, comments);
}
@WebMethod
public Patient[] recordPregnancyDelivery(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "datetime") Date datetime,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "mode") Integer mode,
@WebParam(name = "outcome") Integer outcome,
@WebParam(name = "deliveryLocation") Integer deliveryLocation,
@WebParam(name = "deliveredBy") Integer deliveredBy,
@WebParam(name = "maleInvolved") Boolean maleInvolved,
@WebParam(name = "complications") Integer[] complications,
@WebParam(name = "vvf") Integer vvf,
@WebParam(name = "maternalDeath") Boolean maternalDeath,
@WebParam(name = "comments") String comments,
@WebParam(name = "child1Outcome") BirthOutcome child1Outcome,
@WebParam(name = "child1RegistrationType") RegistrationMode child1RegistrationType,
@WebParam(name = "child1MotechId") Integer child1MotechId,
@WebParam(name = "child1Sex") Gender child1Sex,
@WebParam(name = "child1FirstName") String child1FirstName,
@WebParam(name = "child1Weight") Double child1Weight,
@WebParam(name = "child2Outcome") BirthOutcome child2Outcome,
@WebParam(name = "child2RegistrationType") RegistrationMode child2RegistrationType,
@WebParam(name = "child2MotechId") Integer child2MotechId,
@WebParam(name = "child2Sex") Gender child2Sex,
@WebParam(name = "child2FirstName") String child2FirstName,
@WebParam(name = "child2Weight") Double child2Weight,
@WebParam(name = "child3Outcome") BirthOutcome child3Outcome,
@WebParam(name = "child3RegistrationType") RegistrationMode child3RegistrationType,
@WebParam(name = "child3MotechId") Integer child3MotechId,
@WebParam(name = "child3Sex") Gender child3Sex,
@WebParam(name = "child3FirstName") String child3FirstName,
@WebParam(name = "child3Weight") Double child3Weight)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
// Verify that patient ids are internally distinct
Integer[] motechIdArray = {child1MotechId, child2MotechId,
child3MotechId};
Set<Integer> motechIds = new HashSet<Integer>();
for (int i = 0; i < motechIdArray.length; i++) {
Integer childId = motechIdArray[i];
String fieldName = "Child" + (i + 1) + "MotechID";
if (childId != null) {
validateMotechId(childId, errors, fieldName, false);
if (motechIds.contains(childId))
errors.add(messageBean.getMessage("motechmodule.ws.inuse",
fieldName));
else
motechIds.add(childId);
}
}
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Record Pregnancy Delivery request", errors);
}
List<BirthOutcomeChild> outcomes = new ArrayList<BirthOutcomeChild>();
if (child1Outcome != null) {
outcomes.add(new BirthOutcomeChild(child1Outcome,
child1RegistrationType, child1MotechId, child1Sex,
child1FirstName, child1Weight));
}
if (child2Outcome != null) {
outcomes.add(new BirthOutcomeChild(child2Outcome,
child2RegistrationType, child2MotechId, child2Sex,
child2FirstName, child2Weight));
}
if (child3Outcome != null) {
outcomes.add(new BirthOutcomeChild(child3Outcome,
child3RegistrationType, child3MotechId, child3Sex,
child3FirstName, child3Weight));
}
List<org.openmrs.Patient> childPatients = registrarBean
.recordPregnancyDelivery(staff, facility,
datetime, patient, mode, outcome, deliveryLocation,
deliveredBy, maleInvolved, complications, vvf,
maternalDeath, comments, outcomes);
return modelConverter.patientToWebService(childPatients, true);
}
@WebMethod
public void recordDeliveryNotification(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "datetime") Date datetime,
@WebParam(name = "motechId") Integer motechId)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Record Delivery Notification request", errors);
}
registrarBean.recordPregnancyDeliveryNotification(staff, facility
.getLocation(), datetime, patient);
}
@WebMethod
public void recordMotherPNCVisit(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "datetime") Date datetime,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "visitNumber") Integer visitNumber,
@WebParam(name = "location") Integer location,
@WebParam(name = "house") String house,
@WebParam(name = "community") String community,
@WebParam(name = "referred") Boolean referred,
@WebParam(name = "maleInvolved") Boolean maleInvolved,
@WebParam(name = "vitaminA") Boolean vitaminA,
@WebParam(name = "ttDose") Integer ttDose,
@WebParam(name = "lochiaColour") Integer lochiaColour,
@WebParam(name = "lochiaAmountExcess") Boolean lochiaAmountExcess,
@WebParam(name = "lochiaOdourFoul") Boolean lochiaOdourFoul,
@WebParam(name = "temperature") Double temperature,
@WebParam(name = "fht") Double fht,
@WebParam(name = "comments") String comments)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Record Mother PNC Visit request", errors);
}
registrarBean
.recordMotherPNCVisit(staff, facility.getLocation(), datetime,
patient, visitNumber, location, house, community,
referred, maleInvolved, vitaminA, ttDose, lochiaColour,
lochiaAmountExcess, lochiaOdourFoul, temperature, fht,
comments);
}
@WebMethod
public void recordDeath(@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "motechId") Integer motechId)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException("Errors in Record Death request",
errors);
}
registrarBean.recordDeath(staff, facility.getLocation(), date, patient);
}
@WebMethod
public void recordTTVisit(@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "ttDose") Integer ttDose)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException("Errors in Record TT Visit request",
errors);
}
registrarBean.recordTTVisit(staff, facility.getLocation(), date,
patient, ttDose);
}
@WebMethod
public void recordChildPNCVisit(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "datetime") Date datetime,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "visitNumber") Integer visitNumber,
@WebParam(name = "location") Integer location,
@WebParam(name = "house") String house,
@WebParam(name = "community") String community,
@WebParam(name = "referred") Boolean referred,
@WebParam(name = "maleInvolved") Boolean maleInvolved,
@WebParam(name = "weight") Double weight,
@WebParam(name = "temperature") Double temperature,
@WebParam(name = "bcg") Boolean bcg,
@WebParam(name = "opv0") Boolean opv0,
@WebParam(name = "respiration") Integer respiration,
@WebParam(name = "cordConditionNormal") Boolean cordConditionNormal,
@WebParam(name = "babyConditionGood") Boolean babyConditionGood,
@WebParam(name = "comments") String comments)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Record Child PNC Visit request", errors);
}
registrarBean.recordChildPNCVisit(staff, facility.getLocation(),
datetime, patient, visitNumber, location, house, community,
referred, maleInvolved, weight, temperature, bcg, opv0,
respiration, cordConditionNormal, babyConditionGood, comments);
}
@WebMethod
public void recordChildCWCVisit(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "cwcLocation") Integer cwcLocation,
@WebParam(name = "house") String house,
@WebParam(name = "community") String community,
@WebParam(name = "bcg") Boolean bcg,
@WebParam(name = "opvDose") Integer opvDose,
@WebParam(name = "pentaDose") Integer pentaDose,
@WebParam(name = "measles") Boolean measles,
@WebParam(name = "yellowFever") Boolean yellowFever,
@WebParam(name = "csm") Boolean csm,
@WebParam(name = "iptiDose") Integer iptiDose,
@WebParam(name = "vitaminA") Boolean vitaminA,
@WebParam(name = "dewormer") Boolean dewormer,
@WebParam(name = "weight") Double weight,
@WebParam(name = "muac") Double muac,
@WebParam(name = "height") Double height,
@WebParam(name = "maleInvolved") Boolean maleInvolved,
@WebParam(name = "comments") String comments)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Record Child CWC Visit request", errors);
}
registrarBean.recordChildCWCVisit(staff, facility.getLocation(), date,
patient, cwcLocation, house, community, bcg, opvDose,
pentaDose, measles, yellowFever, csm, iptiDose, vitaminA,
dewormer, weight, muac, height, maleInvolved, comments);
}
@WebMethod
public Patient registerPatient(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "registrationMode") RegistrationMode registrationMode,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "registrantType") RegistrantType registrantType,
@WebParam(name = "firstName") String firstName,
@WebParam(name = "middleName") String middleName,
@WebParam(name = "lastName") String lastName,
@WebParam(name = "preferredName") String preferredName,
@WebParam(name = "dateOfBirth") Date dateOfBirth,
@WebParam(name = "estimatedBirthDate") Boolean estimatedBirthDate,
@WebParam(name = "sex") Gender sex,
@WebParam(name = "insured") Boolean insured,
@WebParam(name = "nhis") String nhis,
@WebParam(name = "nhisExpires") Date nhisExpires,
@WebParam(name = "motherMotechId") Integer motherMotechId,
@WebParam(name = "community") Integer community,
@WebParam(name = "address") String address,
@WebParam(name = "phoneNumber") String phoneNumber,
@WebParam(name = "expDeliveryDate") Date expDeliveryDate,
@WebParam(name = "deliveryDateConfirmed") Boolean deliveryDateConfirmed,
@WebParam(name = "enroll") Boolean enroll,
@WebParam(name = "consent") Boolean consent,
@WebParam(name = "ownership") ContactNumberType ownership,
@WebParam(name = "format") MediaType format,
@WebParam(name = "language") String language,
@WebParam(name = "dayOfWeek") DayOfWeek dayOfWeek,
@WebParam(name = "timeOfDay") Date timeOfDay,
@WebParam(name = "reason") InterestReason reason,
@WebParam(name = "howLearned") HowLearned howLearned,
@WebParam(name = "messagesStartWeek") Integer messagesStartWeek,
@WebParam(name = "cwcRegNumber") String cwcRegNumber,
@WebParam(name = "cwcRegDateToday") Boolean cwcRegToday,
@WebParam(name = "cwcRegDate") Date cwcRegDate,
@WebParam(name = "ancRegNumber") String ancRegNumber,
@WebParam(name = "ancRegDateToday") String ancRegToday,
@WebParam(name = "ancRegDate") Date ancRegDate,
@WebParam(name = "height") Double height,
@WebParam(name = "gravida") Integer gravida,
@WebParam(name = "parity") Integer parity,
@WebParam(name = "lastIPT") Integer lastIPT,
@WebParam(name = "lastIPTDate") Date lastIPTDate,
@WebParam(name = "lastTT") Integer lastTT,
@WebParam(name = "lastTTDate") Date lastTTDate,
@WebParam(name = "bcgDate") Date bcgDate,
@WebParam(name = "lastOPV") Integer lastOPV,
@WebParam(name = "lastOPVDate") Date lastOPVDate,
@WebParam(name = "lastPenta") Integer lastPenta,
@WebParam(name = "lastPentaDate") Date lastPentaDate,
@WebParam(name = "measlesDate") Date measlesDate,
@WebParam(name = "yellowFeverDate") Date yellowFeverDate,
@WebParam(name = "lastIPTI") Integer lastIPTI,
@WebParam(name = "lastIPTIDate") Date lastIPTIDate,
@WebParam(name = "lastVitaminADate") Date lastVitaminADate,
@WebParam(name = "whyNoHistory") Integer whyNoHistory)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
Community communityObj = validateCommunity(community, errors, "Community");
if (registrationMode == RegistrationMode.USE_PREPRINTED_ID) {
validateMotechId(motechId, errors, "MotechID", false);
} else {
// Ignore value if provided
motechId = null;
}
org.openmrs.Patient mother = validateMothersMotechId(motherMotechId, errors, registrantType);
if (registrantType == RegistrantType.CHILD_UNDER_FIVE) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -5);
if (dateOfBirth.before(calendar.getTime())) {
errors.add(messageBean.getMessage("motechmodule.ws.invalid",
"DOB"));
}
} else if (registrantType == RegistrantType.PREGNANT_MOTHER) {
if (sex != Gender.FEMALE)
errors.add(messageBean.getMessage("motechmodule.ws.invalid",
"Sex"));
if (expDeliveryDate == null)
errors.add(messageBean.getMessage("motechmodule.ws.missing",
"DeliveryDate"));
if (deliveryDateConfirmed == null)
errors.add(messageBean.getMessage("motechmodule.ws.missing",
"DeliveryDateConfirmed"));
}
validatePhoneNumber(phoneNumber, "phoneNumber", errors);
if (errors.getErrors().size() > 0) {
throw new ValidationException("Errors in Register Patient request",
errors);
}
org.openmrs.Patient patient = registrarBean.registerPatient(staff,
facility, date, registrationMode, motechId,
registrantType, firstName, middleName, lastName, preferredName,
dateOfBirth, estimatedBirthDate, sex, insured, nhis,
nhisExpires, mother, communityObj, address, phoneNumber,
expDeliveryDate, deliveryDateConfirmed, enroll, consent,
ownership, format, language, dayOfWeek, timeOfDay, reason,
howLearned, messagesStartWeek);
- if (cwcRegNumber != null) {
+ if (registrantType == RegistrantType.CHILD_UNDER_FIVE) {
cwcRegDate = (cwcRegToday) ? new Date() : cwcRegDate;
registrarBean.registerCWCChild(staff, facility.getLocation(), cwcRegDate,
patient, cwcRegNumber, enroll, consent, ownership, phoneNumber,
format, language, dayOfWeek, timeOfDay, howLearned);
}
- ancRegDate = decideANCRegistrationDate(ancRegToday, ancRegDate);
- Facility ancFacility = decideFacility(facilityId, errors, ancRegToday);
- registrarBean.registerANCMother(staff, ancFacility.getLocation(), ancRegDate,
- patient, ancRegNumber, expDeliveryDate, height, gravida,
- parity, enroll, consent, ownership, phoneNumber, format,
- language, dayOfWeek, timeOfDay, howLearned);
+ if (registrantType == RegistrantType.PREGNANT_MOTHER) {
+ ancRegDate = decideANCRegistrationDate(ancRegToday, ancRegDate);
+ Facility ancFacility = decideFacility(facilityId, errors, ancRegToday);
+ registrarBean.registerANCMother(staff, ancFacility.getLocation(), ancRegDate,
+ patient, ancRegNumber, expDeliveryDate, height, gravida,
+ parity, enroll, consent, ownership, phoneNumber, format,
+ language, dayOfWeek, timeOfDay, howLearned);
+ }
registrarBean.recordPatientHistory(staff, facility.getLocation(), date,
patient, lastIPT, lastIPTDate, lastTT, lastTTDate, bcgDate,
lastOPV, lastOPVDate, lastPenta, lastPentaDate, measlesDate,
yellowFeverDate, lastIPTI, lastIPTIDate, lastVitaminADate, whyNoHistory);
return modelConverter.patientToWebService(patient, true);
}
private Facility decideFacility(Integer facilityId, ValidationErrors errors, String ancRegToday) {
if (ANCRegisterOption.IN_THE_PAST_IN_OTHER_FACILITY.isSameAs(ancRegToday)) {
return registrarBean.getUnknownFacility();
}
return validateFacility(facilityId, errors, "FacilityID");
}
private Date decideANCRegistrationDate(String ancRegToday, Date ancRegDate) {
return ANCRegisterOption.TODAY.isSameAs(ancRegToday) ? new Date() : ancRegDate;
}
private void validatePhoneNumber(String phoneNumber, String fieldName, ValidationErrors errors) {
if (phoneNumber != null) {
if (!phoneNumber.trim().startsWith("0")) {
errors.add(messageBean.getMessage("motechmodule.ws.numberShouldStartsWithZero", fieldName));
}
if (phoneNumber.trim().length() != 10) {
errors.add(messageBean.getMessage("motechmodule.ws.numberShouldBeTenDigits", fieldName));
}
}
}
private org.openmrs.Patient validateMothersMotechId(Integer motherMotechId, ValidationErrors errors, RegistrantType registrantType) {
org.openmrs.Patient mother = null;
if (motherMotechId != null && RegistrantType.CHILD_UNDER_FIVE.equals(registrantType)) {
mother = validateMotechId(motherMotechId, errors, "MotherMotechID", true);
}
return mother;
}
@WebMethod
public void registerPregnancy(@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "estDeliveryDate") Date estDeliveryDate,
@WebParam(name = "enroll") Boolean enroll,
@WebParam(name = "consent") Boolean consent,
@WebParam(name = "ownership") ContactNumberType ownership,
@WebParam(name = "phoneNumber") String phoneNumber,
@WebParam(name = "format") MediaType format,
@WebParam(name = "language") String language,
@WebParam(name = "dayOfWeek") DayOfWeek dayOfWeek,
@WebParam(name = "timeOfDay") Date timeOfDay,
@WebParam(name = "howLearned") HowLearned howLearned)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Register Pregnancy request", errors);
}
registrarBean
.registerPregnancy(staff, facility.getLocation(), date,
patient, estDeliveryDate, enroll, consent, ownership,
phoneNumber, format, language, dayOfWeek, timeOfDay,
howLearned);
}
@WebMethod
public void registerANCMother(@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "ancRegNumber") String ancRegNumber,
@WebParam(name = "estDeliveryDate") Date estDeliveryDate,
@WebParam(name = "height") Double height,
@WebParam(name = "gravida") Integer gravida,
@WebParam(name = "parity") Integer parity,
@WebParam(name = "enroll") Boolean enroll,
@WebParam(name = "consent") Boolean consent,
@WebParam(name = "ownership") ContactNumberType ownership,
@WebParam(name = "phoneNumber") String phoneNumber,
@WebParam(name = "format") MediaType format,
@WebParam(name = "language") String language,
@WebParam(name = "dayOfWeek") DayOfWeek dayOfWeek,
@WebParam(name = "timeOfDay") Date timeOfDay,
@WebParam(name = "howLearned") HowLearned howLearned)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Register ANC Mother request", errors);
}
registrarBean.registerANCMother(staff, facility.getLocation(), date,
patient, ancRegNumber, estDeliveryDate, height, gravida,
parity, enroll, consent, ownership, phoneNumber, format,
language, dayOfWeek, timeOfDay, howLearned);
}
@WebMethod
public void registerCWCChild(@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "cwcRegNumber") String cwcRegNumber,
@WebParam(name = "enroll") Boolean enroll,
@WebParam(name = "consent") Boolean consent,
@WebParam(name = "ownership") ContactNumberType ownership,
@WebParam(name = "phoneNumber") String phoneNumber,
@WebParam(name = "format") MediaType format,
@WebParam(name = "language") String language,
@WebParam(name = "dayOfWeek") DayOfWeek dayOfWeek,
@WebParam(name = "timeOfDay") Date timeOfDay,
@WebParam(name = "howLearned") HowLearned howLearned)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Register CWC Child request", errors);
}
registrarBean.registerCWCChild(staff, facility.getLocation(), date,
patient, cwcRegNumber, enroll, consent, ownership, phoneNumber,
format, language, dayOfWeek, timeOfDay, howLearned);
}
@WebMethod
public void editPatient(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "mothersMotechId") Integer mothersMotechId,
@WebParam(name = "firstName") String firstName,
@WebParam(name = "middleName") String middleName,
@WebParam(name = "lastName") String lastName,
@WebParam(name = "preferredName") String preferredName,
@WebParam(name = "phoneNumber") String phoneNumber,
@WebParam(name = "phoneOwnership") ContactNumberType phoneOwnership,
@WebParam(name = "nhis") String nhis,
@WebParam(name = "nhisExpires") Date nhisExpires,
@WebParam(name = "edd") Date expectedDeliveryDate,
@WebParam(name = "stopEnrollment") Boolean stopEnrollment)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors, "MotechID", true);
org.openmrs.Patient mother = null;
if (patient != null) {
Date today = new Date();
RegistrantType registrantType = patient.getAge(today) <= 5 ? RegistrantType.CHILD_UNDER_FIVE : RegistrantType.OTHER;
mother = validateMothersMotechId(mothersMotechId, errors, registrantType);
}
if (errors.getErrors().size() > 0) {
throw new ValidationException("Errors in Edit Patient request",
errors);
}
Set<PersonName> patientNames = patient.getNames();
if (patientNames != null) {
for (PersonName personName : patientNames) {
if (firstName != null) {
if (!firstName.trim().equals(""))
personName.setGivenName(firstName);
}
if (middleName != null) {
if (!middleName.trim().equals(""))
personName.setMiddleName(middleName);
}
if (lastName != null) {
if (!lastName.trim().equals(""))
personName.setFamilyName(lastName);
}
if (personName.isPreferred()) {
if (preferredName != null) {
if (!preferredName.trim().equals(""))
personName.setGivenName(preferredName);
}
}
}
}
registrarBean.editPatient(staff, date, patient, mother, phoneNumber,
phoneOwnership, nhis, nhisExpires, expectedDeliveryDate, stopEnrollment);
}
@WebMethod
public void recordGeneralVisit(@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "serialNumber") String serialNumber,
@WebParam(name = "sex") Gender sex,
@WebParam(name = "dateOfBirth") Date dateOfBirth,
@WebParam(name = "insured") Boolean insured,
@WebParam(name = "diagnosis") Integer diagnosis,
@WebParam(name = "secondDiagnosis") Integer secondDiagnosis,
@WebParam(name = "rdtGiven") Boolean rdtGiven,
@WebParam(name = "rdtPositive") Boolean rdtPositive,
@WebParam(name = "actTreated") Boolean actTreated,
@WebParam(name = "newCase") Boolean newCase,
@WebParam(name = "newPatient") Boolean newPatient,
@WebParam(name = "referred") Boolean referred,
@WebParam(name = "comments") String comments)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
validateStaffId(staffId, errors, "StaffID");
validateFacility(facilityId, errors, "FacilityID");
if (errors.getErrors().size() > 0) {
throw new ValidationException("Errors in General Visit request",
errors);
}
registrarBean.recordGeneralOutpatientVisit(staffId, facilityId, date,
serialNumber, sex, dateOfBirth, insured, diagnosis,
secondDiagnosis, rdtGiven, rdtPositive, actTreated, newCase,
newPatient, referred, comments);
}
@WebMethod
public void recordChildVisit(@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "serialNumber") String serialNumber,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "insured") Boolean insured,
@WebParam(name = "diagnosis") Integer diagnosis,
@WebParam(name = "secondDiagnosis") Integer secondDiagnosis,
@WebParam(name = "rdtGiven") Boolean rdtGiven,
@WebParam(name = "rdtPositive") Boolean rdtPositive,
@WebParam(name = "actTreated") Boolean actTreated,
@WebParam(name = "newCase") Boolean newCase,
@WebParam(name = "newPatient") Boolean newPatient,
@WebParam(name = "referred") Boolean referred,
@WebParam(name = "comments") String comments)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Record Child Visit request", errors);
}
registrarBean.recordOutpatientVisit(staff, facility.getLocation(),
date, patient, serialNumber, insured, diagnosis,
secondDiagnosis, rdtGiven, rdtPositive, actTreated, newCase,
newPatient, referred, comments);
}
@WebMethod
public void recordMotherVisit(@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "serialNumber") String serialNumber,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "insured") Boolean insured,
@WebParam(name = "diagnosis") Integer diagnosis,
@WebParam(name = "secondDiagnosis") Integer secondDiagnosis,
@WebParam(name = "rdtGiven") Boolean rdtGiven,
@WebParam(name = "rdtPositive") Boolean rdtPositive,
@WebParam(name = "actTreated") Boolean actTreated,
@WebParam(name = "newCase") Boolean newCase,
@WebParam(name = "newPatient") Boolean newPatient,
@WebParam(name = "referred") Boolean referred,
@WebParam(name = "comments") String comments)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Record Mother Visit request", errors);
}
registrarBean.recordOutpatientVisit(staff, facility.getLocation(),
date, patient, serialNumber, insured, diagnosis,
secondDiagnosis, rdtGiven, rdtPositive, actTreated, newCase,
newPatient, referred, comments);
}
@WebMethod
public Care[] queryANCDefaulters(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in ANC Defaulters Query request", errors);
}
List<ExpectedEncounter> defaultedEncounters = registrarBean
.getDefaultedExpectedEncounters(facility,
new String[]{"ANC"});
List<ExpectedObs> defaultedObs = registrarBean.getDefaultedExpectedObs(
facility, new String[]{"TT", "IPT"});
Care[] upcomingCares = modelConverter.defaultedToWebServiceCares(
defaultedEncounters, defaultedObs);
return upcomingCares;
}
@WebMethod
public Care[] queryTTDefaulters(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in TT Defaulters Query request", errors);
}
List<ExpectedObs> defaultedObs = registrarBean.getDefaultedExpectedObs(
facility, new String[]{"TT"});
return modelConverter.defaultedObsToWebServiceCares(defaultedObs);
}
@WebMethod
public Care[] queryMotherPNCDefaulters(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Mother PNC Defaulters Query request", errors);
}
List<ExpectedEncounter> defaultedEncounters = registrarBean
.getDefaultedExpectedEncounters(facility,
new String[]{"PNC(mother)"});
return modelConverter
.defaultedEncountersToWebServiceCares(defaultedEncounters);
}
@WebMethod
public Care[] queryChildPNCDefaulters(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Child PNC Defaulters Query request", errors);
}
List<ExpectedEncounter> defaultedEncounters = registrarBean
.getDefaultedExpectedEncounters(facility,
new String[]{"PNC(baby)"});
return modelConverter
.defaultedEncountersToWebServiceCares(defaultedEncounters);
}
@WebMethod
public Care[] queryCWCDefaulters(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in CWC Defaulters Query request", errors);
}
List<ExpectedObs> defaultedObs = registrarBean.getDefaultedExpectedObs(
facility, new String[]{"OPV", "BCG", "Penta", "YellowFever",
"Measles", "VitaA", "IPTI"});
return modelConverter.defaultedObsToWebServiceCares(defaultedObs);
}
@WebMethod
public Patient[] queryUpcomingDeliveries(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Upcoming Deliveries Query request", errors);
}
List<Obs> dueDates = registrarBean
.getUpcomingPregnanciesDueDate(facility);
return modelConverter.dueDatesToWebServicePatients(dueDates);
}
@WebMethod
public Patient[] queryRecentDeliveries(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Recent Deliveries Query request", errors);
}
List<Encounter> deliveries = registrarBean
.getRecentDeliveries(facility);
return modelConverter.deliveriesToWebServicePatients(deliveries);
}
@WebMethod
public Patient[] queryOverdueDeliveries(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Overdue Deliveries Query request", errors);
}
List<Obs> dueDates = registrarBean
.getOverduePregnanciesDueDate(facility);
return modelConverter.dueDatesToWebServicePatients(dueDates);
}
@WebMethod
public Patient queryUpcomingCare(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "motechId") Integer motechId)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
validateStaffId(staffId, errors, "StaffID");
validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Upcoming Care Query request", errors);
}
Patient wsPatient = modelConverter.patientToWebService(patient, true);
List<ExpectedEncounter> upcomingEncounters = registrarBean
.getUpcomingExpectedEncounters(patient);
List<ExpectedObs> upcomingObs = registrarBean
.getUpcomingExpectedObs(patient);
Care[] upcomingCares = modelConverter.upcomingToWebServiceCares(
upcomingEncounters, upcomingObs, false);
wsPatient.setCares(upcomingCares);
return wsPatient;
}
@WebMethod
public Patient[] queryMotechId(@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "firstName") String firstName,
@WebParam(name = "lastName") String lastName,
@WebParam(name = "preferredName") String preferredName,
@WebParam(name = "birthDate") Date birthDate,
@WebParam(name = "nhis") String nhis,
@WebParam(name = "phoneNumber") String phoneNumber)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
validateStaffId(staffId, errors, "StaffID");
validateFacility(facilityId, errors, "FacilityID");
if (errors.getErrors().size() > 0) {
throw new ValidationException("Errors in MotechID Query request",
errors);
}
List<org.openmrs.Patient> patients = registrarBean.getPatients(
firstName, lastName, preferredName, birthDate, facilityId,
phoneNumber, nhis, null);
return modelConverter.patientToWebService(patients, true);
}
@WebMethod
public Patient queryPatient(@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "motechId") Integer motechId)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
validateStaffId(staffId, errors, "StaffID");
validateFacility(facilityId, errors, "FacilityID");
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException("Errors in Patient Query request",
errors);
}
return modelConverter.patientToWebService(patient, false);
}
@WebMethod
public String[] getPatientEnrollments(
@WebParam(name = "motechId") Integer motechId)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
org.openmrs.Patient patient = validateMotechId(motechId, errors,
"MotechID", true);
if (errors.getErrors().size() > 0) {
throw new ValidationException(
"Errors in Get Patient Enrollments request", errors);
}
return registrarBean.getActiveMessageProgramEnrollmentNames(patient);
}
@WebMethod
public void log(@WebParam(name = "type") LogType type,
@WebParam(name = "message") String message) {
log.info("Logtype: " + type + ", Message: " + message);
}
@WebMethod
public void setMessageStatus(
@WebParam(name = "messageId") String messageId,
@WebParam(name = "success") Boolean success) {
registrarBean.setMessageStatus(messageId, success);
}
@WebMethod(exclude = true)
public void setRegistrarBean(RegistrarBean registrarBean) {
this.registrarBean = registrarBean;
}
@WebMethod(exclude = true)
public void setOpenmrsBean(OpenmrsBean openmrsBean) {
this.openmrsBean = openmrsBean;
}
@WebMethod(exclude = true)
public void setModelConverter(WebServiceModelConverter modelConverter) {
this.modelConverter = modelConverter;
}
@WebMethod(exclude = true)
public void setMessageBean(MessageSourceBean messageBean) {
this.messageBean = messageBean;
}
@WebMethod(exclude = true)
public void setRctService(RCTService rctService) {
this.rctService = rctService;
}
@WebMethod
public RCTRegistrationConfirmation registerForRCT(@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "ownership") ContactNumberType ownership,
@WebParam(name = "regPhone") String regPhone) throws ValidationException {
ValidationErrors errors = new ValidationErrors();
validatePhoneNumber(regPhone, "regPhone", errors);
User staff = validateStaffId(staffId, errors, "StaffID");
validateFacility(facilityId, errors, "facilityId");
org.openmrs.Patient patient = validateMotechId(motechId, errors, "MotechID", true);
RCTFacility rctFacility = validateIfFacilityCoveredInRCT(facilityId, errors, "facilityId");
if (patient != null) {
validateIfPatientAlredayRegisterdForRCT(motechId, errors, "motechId");
}
throwExceptionIfValidationFailed(errors);
updatePatientPhoneDetails(ownership, regPhone, staff, patient);
Patient motechPatient = modelConverter.patientToWebService(patient, false);
RCTRegistrationConfirmation confirmation = rctService.register(motechPatient, staff, rctFacility);
if (confirmation.getErrors()) {
returnRegistrationError(confirmation.getText());
}
return confirmation;
}
private void returnRegistrationError(String error) throws ValidationException {
ValidationErrors registrationErrors = new ValidationErrors();
registrationErrors.add(messageBean.getMessage(error, "error"));
throw new ValidationException("Errors in Patient Query request", registrationErrors);
}
private void throwExceptionIfValidationFailed(ValidationErrors errors) throws ValidationException {
if (errors.getErrors().size() > 0) {
throw new ValidationException("Errors in Patient Query request",
errors);
}
}
private void updatePatientPhoneDetails(ContactNumberType ownership, String regPhone, User staff, org.openmrs.Patient patient) {
registrarBean.editPatient(staff, null, patient, null, regPhone, ownership, null, null, null, null);
}
private void validateIfPatientAlredayRegisterdForRCT(Integer motechId, ValidationErrors errors, String fieldName) {
if (rctService.isPatientRegisteredIntoRCT(motechId)) {
errors.add(messageBean.getMessage("motechmodule.rct.exists", fieldName));
}
}
private User validateStaffId(Integer staffId, ValidationErrors errors,
String fieldName) {
if (staffId == null) {
errors.add(messageBean.getMessage("motechmodule.ws.missing",
fieldName));
return null;
}
if (!registrarBean.isValidIdCheckDigit(staffId)) {
errors.add(messageBean.getMessage("motechmodule.ws.invalid",
fieldName));
return null;
}
User staff = openmrsBean.getStaffBySystemId(staffId.toString());
if (staff == null) {
errors.add(messageBean.getMessage("motechmodule.ws.notfound",
fieldName));
}
return staff;
}
private org.openmrs.Patient validateMotechId(Integer motechId,
ValidationErrors errors, String fieldName, boolean mustExist) {
if (motechId == null) {
errors.add(messageBean.getMessage("motechmodule.ws.missing",
fieldName));
return null;
}
if (!registrarBean.isValidMotechIdCheckDigit(motechId)) {
errors.add(messageBean.getMessage("motechmodule.ws.invalid",
fieldName));
return null;
}
org.openmrs.Patient patient = openmrsBean.getPatientByMotechId(motechId
.toString());
if (mustExist && patient == null) {
errors.add(messageBean.getMessage("motechmodule.ws.notfound",
fieldName));
} else if (!mustExist && patient != null) {
errors.add(messageBean.getMessage("motechmodule.ws.inuse",
fieldName));
}
return patient;
}
private Facility validateFacility(Integer facilityId,
ValidationErrors errors, String fieldName) {
if (facilityId == null) {
errors.add(messageBean.getMessage("motechmodule.ws.missing",
fieldName));
return null;
}
if (!registrarBean.isValidIdCheckDigit(facilityId)) {
errors.add(messageBean.getMessage("motechmodule.ws.invalid",
fieldName));
return null;
}
Facility facility = registrarBean.getFacilityById(facilityId);
if (facility == null) {
errors.add(messageBean.getMessage("motechmodule.ws.notfound",
fieldName));
}
return facility;
}
private RCTFacility validateIfFacilityCoveredInRCT(Integer facilityId,
ValidationErrors errors, String fieldName) {
RCTFacility facility = rctService.getRCTFacilityById(facilityId);
if (facility == null) {
errors.add(messageBean.getMessage("motechmodule.rct.not.covered",
fieldName));
}
return facility;
}
private Community validateCommunity(Integer communityId,
ValidationErrors errors, String fieldName) {
if (communityId == null) {
// errors.add(messageBean.getMessage("motechmodule.ws.missing",fieldName));
return null;
}
Community community = registrarBean.getCommunityById(communityId);
if (community == null) {
errors.add(messageBean.getMessage("motechmodule.ws.notfound", fieldName));
} else if (Boolean.TRUE.equals(community.getRetired())) {
errors.add(messageBean.getMessage("motechmodule.ws.invalid", fieldName));
}
return community;
}
}
| false | true |
public Patient registerPatient(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "registrationMode") RegistrationMode registrationMode,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "registrantType") RegistrantType registrantType,
@WebParam(name = "firstName") String firstName,
@WebParam(name = "middleName") String middleName,
@WebParam(name = "lastName") String lastName,
@WebParam(name = "preferredName") String preferredName,
@WebParam(name = "dateOfBirth") Date dateOfBirth,
@WebParam(name = "estimatedBirthDate") Boolean estimatedBirthDate,
@WebParam(name = "sex") Gender sex,
@WebParam(name = "insured") Boolean insured,
@WebParam(name = "nhis") String nhis,
@WebParam(name = "nhisExpires") Date nhisExpires,
@WebParam(name = "motherMotechId") Integer motherMotechId,
@WebParam(name = "community") Integer community,
@WebParam(name = "address") String address,
@WebParam(name = "phoneNumber") String phoneNumber,
@WebParam(name = "expDeliveryDate") Date expDeliveryDate,
@WebParam(name = "deliveryDateConfirmed") Boolean deliveryDateConfirmed,
@WebParam(name = "enroll") Boolean enroll,
@WebParam(name = "consent") Boolean consent,
@WebParam(name = "ownership") ContactNumberType ownership,
@WebParam(name = "format") MediaType format,
@WebParam(name = "language") String language,
@WebParam(name = "dayOfWeek") DayOfWeek dayOfWeek,
@WebParam(name = "timeOfDay") Date timeOfDay,
@WebParam(name = "reason") InterestReason reason,
@WebParam(name = "howLearned") HowLearned howLearned,
@WebParam(name = "messagesStartWeek") Integer messagesStartWeek,
@WebParam(name = "cwcRegNumber") String cwcRegNumber,
@WebParam(name = "cwcRegDateToday") Boolean cwcRegToday,
@WebParam(name = "cwcRegDate") Date cwcRegDate,
@WebParam(name = "ancRegNumber") String ancRegNumber,
@WebParam(name = "ancRegDateToday") String ancRegToday,
@WebParam(name = "ancRegDate") Date ancRegDate,
@WebParam(name = "height") Double height,
@WebParam(name = "gravida") Integer gravida,
@WebParam(name = "parity") Integer parity,
@WebParam(name = "lastIPT") Integer lastIPT,
@WebParam(name = "lastIPTDate") Date lastIPTDate,
@WebParam(name = "lastTT") Integer lastTT,
@WebParam(name = "lastTTDate") Date lastTTDate,
@WebParam(name = "bcgDate") Date bcgDate,
@WebParam(name = "lastOPV") Integer lastOPV,
@WebParam(name = "lastOPVDate") Date lastOPVDate,
@WebParam(name = "lastPenta") Integer lastPenta,
@WebParam(name = "lastPentaDate") Date lastPentaDate,
@WebParam(name = "measlesDate") Date measlesDate,
@WebParam(name = "yellowFeverDate") Date yellowFeverDate,
@WebParam(name = "lastIPTI") Integer lastIPTI,
@WebParam(name = "lastIPTIDate") Date lastIPTIDate,
@WebParam(name = "lastVitaminADate") Date lastVitaminADate,
@WebParam(name = "whyNoHistory") Integer whyNoHistory)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
Community communityObj = validateCommunity(community, errors, "Community");
if (registrationMode == RegistrationMode.USE_PREPRINTED_ID) {
validateMotechId(motechId, errors, "MotechID", false);
} else {
// Ignore value if provided
motechId = null;
}
org.openmrs.Patient mother = validateMothersMotechId(motherMotechId, errors, registrantType);
if (registrantType == RegistrantType.CHILD_UNDER_FIVE) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -5);
if (dateOfBirth.before(calendar.getTime())) {
errors.add(messageBean.getMessage("motechmodule.ws.invalid",
"DOB"));
}
} else if (registrantType == RegistrantType.PREGNANT_MOTHER) {
if (sex != Gender.FEMALE)
errors.add(messageBean.getMessage("motechmodule.ws.invalid",
"Sex"));
if (expDeliveryDate == null)
errors.add(messageBean.getMessage("motechmodule.ws.missing",
"DeliveryDate"));
if (deliveryDateConfirmed == null)
errors.add(messageBean.getMessage("motechmodule.ws.missing",
"DeliveryDateConfirmed"));
}
validatePhoneNumber(phoneNumber, "phoneNumber", errors);
if (errors.getErrors().size() > 0) {
throw new ValidationException("Errors in Register Patient request",
errors);
}
org.openmrs.Patient patient = registrarBean.registerPatient(staff,
facility, date, registrationMode, motechId,
registrantType, firstName, middleName, lastName, preferredName,
dateOfBirth, estimatedBirthDate, sex, insured, nhis,
nhisExpires, mother, communityObj, address, phoneNumber,
expDeliveryDate, deliveryDateConfirmed, enroll, consent,
ownership, format, language, dayOfWeek, timeOfDay, reason,
howLearned, messagesStartWeek);
if (cwcRegNumber != null) {
cwcRegDate = (cwcRegToday) ? new Date() : cwcRegDate;
registrarBean.registerCWCChild(staff, facility.getLocation(), cwcRegDate,
patient, cwcRegNumber, enroll, consent, ownership, phoneNumber,
format, language, dayOfWeek, timeOfDay, howLearned);
}
ancRegDate = decideANCRegistrationDate(ancRegToday, ancRegDate);
Facility ancFacility = decideFacility(facilityId, errors, ancRegToday);
registrarBean.registerANCMother(staff, ancFacility.getLocation(), ancRegDate,
patient, ancRegNumber, expDeliveryDate, height, gravida,
parity, enroll, consent, ownership, phoneNumber, format,
language, dayOfWeek, timeOfDay, howLearned);
registrarBean.recordPatientHistory(staff, facility.getLocation(), date,
patient, lastIPT, lastIPTDate, lastTT, lastTTDate, bcgDate,
lastOPV, lastOPVDate, lastPenta, lastPentaDate, measlesDate,
yellowFeverDate, lastIPTI, lastIPTIDate, lastVitaminADate, whyNoHistory);
return modelConverter.patientToWebService(patient, true);
}
|
public Patient registerPatient(
@WebParam(name = "staffId") Integer staffId,
@WebParam(name = "facilityId") Integer facilityId,
@WebParam(name = "date") Date date,
@WebParam(name = "registrationMode") RegistrationMode registrationMode,
@WebParam(name = "motechId") Integer motechId,
@WebParam(name = "registrantType") RegistrantType registrantType,
@WebParam(name = "firstName") String firstName,
@WebParam(name = "middleName") String middleName,
@WebParam(name = "lastName") String lastName,
@WebParam(name = "preferredName") String preferredName,
@WebParam(name = "dateOfBirth") Date dateOfBirth,
@WebParam(name = "estimatedBirthDate") Boolean estimatedBirthDate,
@WebParam(name = "sex") Gender sex,
@WebParam(name = "insured") Boolean insured,
@WebParam(name = "nhis") String nhis,
@WebParam(name = "nhisExpires") Date nhisExpires,
@WebParam(name = "motherMotechId") Integer motherMotechId,
@WebParam(name = "community") Integer community,
@WebParam(name = "address") String address,
@WebParam(name = "phoneNumber") String phoneNumber,
@WebParam(name = "expDeliveryDate") Date expDeliveryDate,
@WebParam(name = "deliveryDateConfirmed") Boolean deliveryDateConfirmed,
@WebParam(name = "enroll") Boolean enroll,
@WebParam(name = "consent") Boolean consent,
@WebParam(name = "ownership") ContactNumberType ownership,
@WebParam(name = "format") MediaType format,
@WebParam(name = "language") String language,
@WebParam(name = "dayOfWeek") DayOfWeek dayOfWeek,
@WebParam(name = "timeOfDay") Date timeOfDay,
@WebParam(name = "reason") InterestReason reason,
@WebParam(name = "howLearned") HowLearned howLearned,
@WebParam(name = "messagesStartWeek") Integer messagesStartWeek,
@WebParam(name = "cwcRegNumber") String cwcRegNumber,
@WebParam(name = "cwcRegDateToday") Boolean cwcRegToday,
@WebParam(name = "cwcRegDate") Date cwcRegDate,
@WebParam(name = "ancRegNumber") String ancRegNumber,
@WebParam(name = "ancRegDateToday") String ancRegToday,
@WebParam(name = "ancRegDate") Date ancRegDate,
@WebParam(name = "height") Double height,
@WebParam(name = "gravida") Integer gravida,
@WebParam(name = "parity") Integer parity,
@WebParam(name = "lastIPT") Integer lastIPT,
@WebParam(name = "lastIPTDate") Date lastIPTDate,
@WebParam(name = "lastTT") Integer lastTT,
@WebParam(name = "lastTTDate") Date lastTTDate,
@WebParam(name = "bcgDate") Date bcgDate,
@WebParam(name = "lastOPV") Integer lastOPV,
@WebParam(name = "lastOPVDate") Date lastOPVDate,
@WebParam(name = "lastPenta") Integer lastPenta,
@WebParam(name = "lastPentaDate") Date lastPentaDate,
@WebParam(name = "measlesDate") Date measlesDate,
@WebParam(name = "yellowFeverDate") Date yellowFeverDate,
@WebParam(name = "lastIPTI") Integer lastIPTI,
@WebParam(name = "lastIPTIDate") Date lastIPTIDate,
@WebParam(name = "lastVitaminADate") Date lastVitaminADate,
@WebParam(name = "whyNoHistory") Integer whyNoHistory)
throws ValidationException {
ValidationErrors errors = new ValidationErrors();
User staff = validateStaffId(staffId, errors, "StaffID");
Facility facility = validateFacility(facilityId, errors, "FacilityID");
Community communityObj = validateCommunity(community, errors, "Community");
if (registrationMode == RegistrationMode.USE_PREPRINTED_ID) {
validateMotechId(motechId, errors, "MotechID", false);
} else {
// Ignore value if provided
motechId = null;
}
org.openmrs.Patient mother = validateMothersMotechId(motherMotechId, errors, registrantType);
if (registrantType == RegistrantType.CHILD_UNDER_FIVE) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -5);
if (dateOfBirth.before(calendar.getTime())) {
errors.add(messageBean.getMessage("motechmodule.ws.invalid",
"DOB"));
}
} else if (registrantType == RegistrantType.PREGNANT_MOTHER) {
if (sex != Gender.FEMALE)
errors.add(messageBean.getMessage("motechmodule.ws.invalid",
"Sex"));
if (expDeliveryDate == null)
errors.add(messageBean.getMessage("motechmodule.ws.missing",
"DeliveryDate"));
if (deliveryDateConfirmed == null)
errors.add(messageBean.getMessage("motechmodule.ws.missing",
"DeliveryDateConfirmed"));
}
validatePhoneNumber(phoneNumber, "phoneNumber", errors);
if (errors.getErrors().size() > 0) {
throw new ValidationException("Errors in Register Patient request",
errors);
}
org.openmrs.Patient patient = registrarBean.registerPatient(staff,
facility, date, registrationMode, motechId,
registrantType, firstName, middleName, lastName, preferredName,
dateOfBirth, estimatedBirthDate, sex, insured, nhis,
nhisExpires, mother, communityObj, address, phoneNumber,
expDeliveryDate, deliveryDateConfirmed, enroll, consent,
ownership, format, language, dayOfWeek, timeOfDay, reason,
howLearned, messagesStartWeek);
if (registrantType == RegistrantType.CHILD_UNDER_FIVE) {
cwcRegDate = (cwcRegToday) ? new Date() : cwcRegDate;
registrarBean.registerCWCChild(staff, facility.getLocation(), cwcRegDate,
patient, cwcRegNumber, enroll, consent, ownership, phoneNumber,
format, language, dayOfWeek, timeOfDay, howLearned);
}
if (registrantType == RegistrantType.PREGNANT_MOTHER) {
ancRegDate = decideANCRegistrationDate(ancRegToday, ancRegDate);
Facility ancFacility = decideFacility(facilityId, errors, ancRegToday);
registrarBean.registerANCMother(staff, ancFacility.getLocation(), ancRegDate,
patient, ancRegNumber, expDeliveryDate, height, gravida,
parity, enroll, consent, ownership, phoneNumber, format,
language, dayOfWeek, timeOfDay, howLearned);
}
registrarBean.recordPatientHistory(staff, facility.getLocation(), date,
patient, lastIPT, lastIPTDate, lastTT, lastTTDate, bcgDate,
lastOPV, lastOPVDate, lastPenta, lastPentaDate, measlesDate,
yellowFeverDate, lastIPTI, lastIPTIDate, lastVitaminADate, whyNoHistory);
return modelConverter.patientToWebService(patient, true);
}
|
diff --git a/src/me/chaseoes/tf2/TF2.java b/src/me/chaseoes/tf2/TF2.java
index b9e8b46..bda2336 100644
--- a/src/me/chaseoes/tf2/TF2.java
+++ b/src/me/chaseoes/tf2/TF2.java
@@ -1,244 +1,245 @@
package me.chaseoes.tf2;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.logging.Level;
import me.chaseoes.tf2.capturepoints.CapturePointUtilities;
import me.chaseoes.tf2.classes.ClassUtilities;
import me.chaseoes.tf2.commands.CommandManager;
import me.chaseoes.tf2.commands.CreateCommand;
import me.chaseoes.tf2.commands.DebugCommand;
import me.chaseoes.tf2.commands.DeleteCommand;
import me.chaseoes.tf2.commands.DisableCommand;
import me.chaseoes.tf2.commands.EnableCommand;
import me.chaseoes.tf2.commands.JoinCommand;
import me.chaseoes.tf2.commands.LeaveCommand;
import me.chaseoes.tf2.commands.ListCommand;
import me.chaseoes.tf2.commands.RedefineCommand;
import me.chaseoes.tf2.commands.ReloadCommand;
import me.chaseoes.tf2.commands.SetCommand;
import me.chaseoes.tf2.commands.StartCommand;
import me.chaseoes.tf2.commands.StopCommand;
import me.chaseoes.tf2.listeners.BlockBreakListener;
import me.chaseoes.tf2.listeners.BlockPlaceListener;
import me.chaseoes.tf2.listeners.EntityDamageListener;
import me.chaseoes.tf2.listeners.EntityShootBowListener;
import me.chaseoes.tf2.listeners.FoodLevelChangeListener;
import me.chaseoes.tf2.listeners.PlayerCommandPreprocessListener;
import me.chaseoes.tf2.listeners.PlayerDamageByEntityListener;
import me.chaseoes.tf2.listeners.PlayerDeathListener;
import me.chaseoes.tf2.listeners.PlayerDropItemListener;
import me.chaseoes.tf2.listeners.PlayerInteractListener;
import me.chaseoes.tf2.listeners.PlayerJoinListener;
import me.chaseoes.tf2.listeners.PlayerMoveListener;
import me.chaseoes.tf2.listeners.PlayerQuitListener;
import me.chaseoes.tf2.listeners.PlayerReceiveNameTagListener;
import me.chaseoes.tf2.listeners.PotionSplashListener;
import me.chaseoes.tf2.listeners.ProjectileLaunchListener;
import me.chaseoes.tf2.listeners.SignChangeListener;
import me.chaseoes.tf2.listeners.TF2DeathListener;
import me.chaseoes.tf2.lobbywall.LobbyWall;
import me.chaseoes.tf2.lobbywall.LobbyWallUtilities;
import me.chaseoes.tf2.utilities.IconMenu;
import me.chaseoes.tf2.utilities.MetricsLite;
import me.chaseoes.tf2.utilities.SQLUtilities;
import me.chaseoes.tf2.utilities.SerializableLocation;
import me.chaseoes.tf2.utilities.UpdateChecker;
import me.chaseoes.tf2.utilities.WorldEditUtilities;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class TF2 extends JavaPlugin {
public HashMap<String, Map> maps = new HashMap<String, Map>();
public HashMap<String, String> usingSetSpawnMenu = new HashMap<String, String>();
public HashMap<String, StatCollector> stats = new HashMap<String, StatCollector>();
public UpdateChecker uc;
public IconMenu setSpawnMenu;
private static TF2 instance;
public static TF2 getInstance() {
return instance;
}
@Override
public void onEnable() {
instance = this;
getServer().getScheduler().cancelTasks(this);
setupClasses();
if (getServer().getPluginManager().getPlugin("TagAPI") == null) {
getLogger().log(Level.SEVERE, "The TagAPI plugin is required to run TF2. Disabling...");
getServer().getPluginManager().disablePlugin(this);
return;
}
if (getServer().getPluginManager().getPlugin("WorldEdit") == null) {
getLogger().log(Level.SEVERE, "The WorldEdit plugin is required to run TF2. Disabling...");
getServer().getPluginManager().disablePlugin(this);
return;
}
getCommand("tf2").setExecutor(new CommandManager());
getConfig().options().copyDefaults(true);
saveConfig();
+ DataConfiguration.getData().reloadData();
Schedulers.getSchedulers().startAFKChecker();
for (String map : MapUtilities.getUtilities().getEnabledMaps()) {
addMap(map, GameStatus.WAITING);
}
for (String map : MapUtilities.getUtilities().getDisabledMaps()) {
addMap(map, GameStatus.DISABLED);
}
LobbyWall.getWall().startTask();
uc = new UpdateChecker(this);
uc.startTask();
setSpawnMenu = new IconMenu("Set Spawns", 9, new IconMenu.OptionClickEventHandler() {
@Override
public void onOptionClick(IconMenu.OptionClickEvent event) {
String map = usingSetSpawnMenu.get(event.getPlayer().getName());
String name = ChatColor.stripColor(event.getName());
if (name.equalsIgnoreCase("Blue Lobby")) {
MapUtilities.getUtilities().setTeamLobby(map, Team.BLUE, event.getPlayer().getLocation());
event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] Successfully set the blue team's lobby.");
usingSetSpawnMenu.remove(event.getPlayer().getName());
} else if (name.equalsIgnoreCase("Red Lobby")) {
MapUtilities.getUtilities().setTeamLobby(map, Team.RED, event.getPlayer().getLocation());
event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] Successfully set the red team's lobby.");
usingSetSpawnMenu.remove(event.getPlayer().getName());
} else if (name.equalsIgnoreCase("Blue Spawn")) {
MapUtilities.getUtilities().setTeamSpawn(map, Team.BLUE, event.getPlayer().getLocation());
event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] Successfully set the blue team's spawn.");
usingSetSpawnMenu.remove(event.getPlayer().getName());
} else if (name.equalsIgnoreCase("Red Spawn")) {
MapUtilities.getUtilities().setTeamSpawn(map, Team.RED, event.getPlayer().getLocation());
event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] Successfully set the red team's spawn.");
usingSetSpawnMenu.remove(event.getPlayer().getName());
}
event.setWillClose(true);
}
}, this).setOption(2, new ItemStack(Material.getMaterial(331), 1), ChatColor.DARK_RED + "" + ChatColor.BOLD + "Red Lobby" + ChatColor.RESET, ChatColor.WHITE + "Set the red team lobby.").setOption(3, new ItemStack(Material.getMaterial(351), 1, (short) 4), ChatColor.AQUA + "" + ChatColor.BOLD + "Blue Lobby" + ChatColor.RESET, ChatColor.WHITE + "Set the blue team lobby.").setOption(4, new ItemStack(Material.WOOL, 1, (short) 14), ChatColor.DARK_RED + "" + ChatColor.BOLD + "Red Spawn" + ChatColor.RESET, ChatColor.WHITE + "Set the red team's spawn.").setOption(5, new ItemStack(Material.WOOL, 1, (short) 11), ChatColor.AQUA + "" + ChatColor.BOLD + "Blue Spawn" + ChatColor.RESET, ChatColor.WHITE + "Set the blue team's spawn.").setOption(6, new ItemStack(Material.BEDROCK, 1), ChatColor.RED + "" + ChatColor.BOLD + "Exit" + ChatColor.RESET, ChatColor.RED + "Exit this menu.");
try {
MetricsLite metrics = new MetricsLite(this);
metrics.start();
} catch (IOException e) {
// Failed to submit! :(
}
// Connect to database after everything else has loaded.
if (getConfig().getBoolean("stats-database.enabled")) {
SQLUtilities.getUtilities().setup(this);
}
}
@Override
public void onDisable() {
reloadConfig();
saveConfig();
for (Map map : MapUtilities.getUtilities().getMaps()) {
if (GameUtilities.getUtilities().getGame(map).getStatus() != GameStatus.WAITING && GameUtilities.getUtilities().getGame(map).getStatus() != GameStatus.DISABLED) {
GameUtilities.getUtilities().getGame(map).stopMatch(false);
}
}
getServer().getScheduler().cancelTasks(this);
instance = null;
}
public void setupClasses() {
MapUtilities.getUtilities().setup(this);
WorldEditUtilities.getWEUtilities().setup(this);
CreateCommand.getCommand().setup(this);
RedefineCommand.getCommand().setup(this);
LobbyWall.getWall().setup(this);
DataConfiguration.getData().setup(this);
LobbyWallUtilities.getUtilities().setup(this);
WorldEditUtilities.getWEUtilities().setupWorldEdit(getServer().getPluginManager());
ClassUtilities.getUtilities().setup(this);
GameUtilities.getUtilities().setup(this);
CapturePointUtilities.getUtilities().setup(this);
Schedulers.getSchedulers().setup(this);
CreateCommand.getCommand().setup(this);
DeleteCommand.getCommand().setup(this);
DisableCommand.getCommand().setup(this);
EnableCommand.getCommand().setup(this);
JoinCommand.getCommand().setup(this);
LeaveCommand.getCommand().setup(this);
ListCommand.getCommand().setup(this);
ReloadCommand.getCommand().setup(this);
SetCommand.getCommand().setup(this);
DebugCommand.getCommand().setup(this);
StartCommand.getCommand().setup(this);
StopCommand.getCommand().setup(this);
SerializableLocation.getUtilities().setup(this);
// Register Events
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(new BlockPlaceListener(), this);
pm.registerEvents(new FoodLevelChangeListener(), this);
pm.registerEvents(new PlayerInteractListener(), this);
pm.registerEvents(new PlayerCommandPreprocessListener(), this);
pm.registerEvents(new PlayerDamageByEntityListener(), this);
pm.registerEvents(new PlayerDeathListener(), this);
pm.registerEvents(new PlayerDropItemListener(), this);
pm.registerEvents(new PlayerJoinListener(), this);
pm.registerEvents(new PlayerMoveListener(), this);
pm.registerEvents(new PlayerQuitListener(), this);
pm.registerEvents(new PlayerReceiveNameTagListener(), this);
pm.registerEvents(new PotionSplashListener(), this);
pm.registerEvents(new ProjectileLaunchListener(), this);
pm.registerEvents(new SignChangeListener(), this);
pm.registerEvents(new TF2DeathListener(), this);
pm.registerEvents(new BlockBreakListener(), this);
pm.registerEvents(new EntityDamageListener(), this);
pm.registerEvents(new EntityShootBowListener(), this);
}
public Map getMap(String map) {
return maps.get(map);
}
public void addMap(String map, GameStatus status) {
Map m = new Map(this, map);
Game g = new Game(m, this);
maps.put(map, m);
GameUtilities.getUtilities().addGame(m, g);
m.load();
GameUtilities.getUtilities().getGame(m).redHasBeenTeleported = false;
GameUtilities.getUtilities().getGame(m).setStatus(status);
if (status == GameStatus.DISABLED) {
String[] creditlines = new String[4];
creditlines[0] = " ";
creditlines[1] = "--------------------------";
creditlines[2] = "--------------------------";
creditlines[3] = " ";
LobbyWall.getWall().setAllLines(map, null, creditlines, false, false);
}
}
public Collection<Map> getMaps() {
return maps.values();
}
public void removeMap(String map) {
Map m = maps.remove(map);
Game game = GameUtilities.getUtilities().removeGame(m);
game.stopMatch(false);
LobbyWall.getWall().unloadCacheInfo(map);
MapUtilities.getUtilities().destroyMap(m);
}
public boolean mapExists(String map) {
return maps.containsKey(map);
}
}
| true | true |
public void onEnable() {
instance = this;
getServer().getScheduler().cancelTasks(this);
setupClasses();
if (getServer().getPluginManager().getPlugin("TagAPI") == null) {
getLogger().log(Level.SEVERE, "The TagAPI plugin is required to run TF2. Disabling...");
getServer().getPluginManager().disablePlugin(this);
return;
}
if (getServer().getPluginManager().getPlugin("WorldEdit") == null) {
getLogger().log(Level.SEVERE, "The WorldEdit plugin is required to run TF2. Disabling...");
getServer().getPluginManager().disablePlugin(this);
return;
}
getCommand("tf2").setExecutor(new CommandManager());
getConfig().options().copyDefaults(true);
saveConfig();
Schedulers.getSchedulers().startAFKChecker();
for (String map : MapUtilities.getUtilities().getEnabledMaps()) {
addMap(map, GameStatus.WAITING);
}
for (String map : MapUtilities.getUtilities().getDisabledMaps()) {
addMap(map, GameStatus.DISABLED);
}
LobbyWall.getWall().startTask();
uc = new UpdateChecker(this);
uc.startTask();
setSpawnMenu = new IconMenu("Set Spawns", 9, new IconMenu.OptionClickEventHandler() {
@Override
public void onOptionClick(IconMenu.OptionClickEvent event) {
String map = usingSetSpawnMenu.get(event.getPlayer().getName());
String name = ChatColor.stripColor(event.getName());
if (name.equalsIgnoreCase("Blue Lobby")) {
MapUtilities.getUtilities().setTeamLobby(map, Team.BLUE, event.getPlayer().getLocation());
event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] Successfully set the blue team's lobby.");
usingSetSpawnMenu.remove(event.getPlayer().getName());
} else if (name.equalsIgnoreCase("Red Lobby")) {
MapUtilities.getUtilities().setTeamLobby(map, Team.RED, event.getPlayer().getLocation());
event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] Successfully set the red team's lobby.");
usingSetSpawnMenu.remove(event.getPlayer().getName());
} else if (name.equalsIgnoreCase("Blue Spawn")) {
MapUtilities.getUtilities().setTeamSpawn(map, Team.BLUE, event.getPlayer().getLocation());
event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] Successfully set the blue team's spawn.");
usingSetSpawnMenu.remove(event.getPlayer().getName());
} else if (name.equalsIgnoreCase("Red Spawn")) {
MapUtilities.getUtilities().setTeamSpawn(map, Team.RED, event.getPlayer().getLocation());
event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] Successfully set the red team's spawn.");
usingSetSpawnMenu.remove(event.getPlayer().getName());
}
event.setWillClose(true);
}
}, this).setOption(2, new ItemStack(Material.getMaterial(331), 1), ChatColor.DARK_RED + "" + ChatColor.BOLD + "Red Lobby" + ChatColor.RESET, ChatColor.WHITE + "Set the red team lobby.").setOption(3, new ItemStack(Material.getMaterial(351), 1, (short) 4), ChatColor.AQUA + "" + ChatColor.BOLD + "Blue Lobby" + ChatColor.RESET, ChatColor.WHITE + "Set the blue team lobby.").setOption(4, new ItemStack(Material.WOOL, 1, (short) 14), ChatColor.DARK_RED + "" + ChatColor.BOLD + "Red Spawn" + ChatColor.RESET, ChatColor.WHITE + "Set the red team's spawn.").setOption(5, new ItemStack(Material.WOOL, 1, (short) 11), ChatColor.AQUA + "" + ChatColor.BOLD + "Blue Spawn" + ChatColor.RESET, ChatColor.WHITE + "Set the blue team's spawn.").setOption(6, new ItemStack(Material.BEDROCK, 1), ChatColor.RED + "" + ChatColor.BOLD + "Exit" + ChatColor.RESET, ChatColor.RED + "Exit this menu.");
try {
MetricsLite metrics = new MetricsLite(this);
metrics.start();
} catch (IOException e) {
// Failed to submit! :(
}
// Connect to database after everything else has loaded.
if (getConfig().getBoolean("stats-database.enabled")) {
SQLUtilities.getUtilities().setup(this);
}
}
|
public void onEnable() {
instance = this;
getServer().getScheduler().cancelTasks(this);
setupClasses();
if (getServer().getPluginManager().getPlugin("TagAPI") == null) {
getLogger().log(Level.SEVERE, "The TagAPI plugin is required to run TF2. Disabling...");
getServer().getPluginManager().disablePlugin(this);
return;
}
if (getServer().getPluginManager().getPlugin("WorldEdit") == null) {
getLogger().log(Level.SEVERE, "The WorldEdit plugin is required to run TF2. Disabling...");
getServer().getPluginManager().disablePlugin(this);
return;
}
getCommand("tf2").setExecutor(new CommandManager());
getConfig().options().copyDefaults(true);
saveConfig();
DataConfiguration.getData().reloadData();
Schedulers.getSchedulers().startAFKChecker();
for (String map : MapUtilities.getUtilities().getEnabledMaps()) {
addMap(map, GameStatus.WAITING);
}
for (String map : MapUtilities.getUtilities().getDisabledMaps()) {
addMap(map, GameStatus.DISABLED);
}
LobbyWall.getWall().startTask();
uc = new UpdateChecker(this);
uc.startTask();
setSpawnMenu = new IconMenu("Set Spawns", 9, new IconMenu.OptionClickEventHandler() {
@Override
public void onOptionClick(IconMenu.OptionClickEvent event) {
String map = usingSetSpawnMenu.get(event.getPlayer().getName());
String name = ChatColor.stripColor(event.getName());
if (name.equalsIgnoreCase("Blue Lobby")) {
MapUtilities.getUtilities().setTeamLobby(map, Team.BLUE, event.getPlayer().getLocation());
event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] Successfully set the blue team's lobby.");
usingSetSpawnMenu.remove(event.getPlayer().getName());
} else if (name.equalsIgnoreCase("Red Lobby")) {
MapUtilities.getUtilities().setTeamLobby(map, Team.RED, event.getPlayer().getLocation());
event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] Successfully set the red team's lobby.");
usingSetSpawnMenu.remove(event.getPlayer().getName());
} else if (name.equalsIgnoreCase("Blue Spawn")) {
MapUtilities.getUtilities().setTeamSpawn(map, Team.BLUE, event.getPlayer().getLocation());
event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] Successfully set the blue team's spawn.");
usingSetSpawnMenu.remove(event.getPlayer().getName());
} else if (name.equalsIgnoreCase("Red Spawn")) {
MapUtilities.getUtilities().setTeamSpawn(map, Team.RED, event.getPlayer().getLocation());
event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] Successfully set the red team's spawn.");
usingSetSpawnMenu.remove(event.getPlayer().getName());
}
event.setWillClose(true);
}
}, this).setOption(2, new ItemStack(Material.getMaterial(331), 1), ChatColor.DARK_RED + "" + ChatColor.BOLD + "Red Lobby" + ChatColor.RESET, ChatColor.WHITE + "Set the red team lobby.").setOption(3, new ItemStack(Material.getMaterial(351), 1, (short) 4), ChatColor.AQUA + "" + ChatColor.BOLD + "Blue Lobby" + ChatColor.RESET, ChatColor.WHITE + "Set the blue team lobby.").setOption(4, new ItemStack(Material.WOOL, 1, (short) 14), ChatColor.DARK_RED + "" + ChatColor.BOLD + "Red Spawn" + ChatColor.RESET, ChatColor.WHITE + "Set the red team's spawn.").setOption(5, new ItemStack(Material.WOOL, 1, (short) 11), ChatColor.AQUA + "" + ChatColor.BOLD + "Blue Spawn" + ChatColor.RESET, ChatColor.WHITE + "Set the blue team's spawn.").setOption(6, new ItemStack(Material.BEDROCK, 1), ChatColor.RED + "" + ChatColor.BOLD + "Exit" + ChatColor.RESET, ChatColor.RED + "Exit this menu.");
try {
MetricsLite metrics = new MetricsLite(this);
metrics.start();
} catch (IOException e) {
// Failed to submit! :(
}
// Connect to database after everything else has loaded.
if (getConfig().getBoolean("stats-database.enabled")) {
SQLUtilities.getUtilities().setup(this);
}
}
|
diff --git a/engine/src/info/svitkine/alexei/wage/WBGameFinder.java b/engine/src/info/svitkine/alexei/wage/WBGameFinder.java
index 6a8c336..bbb9161 100644
--- a/engine/src/info/svitkine/alexei/wage/WBGameFinder.java
+++ b/engine/src/info/svitkine/alexei/wage/WBGameFinder.java
@@ -1,56 +1,60 @@
package info.svitkine.alexei.wage;
import java.awt.FileDialog;
import java.awt.Frame;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.RandomAccessFile;
import org.freeshell.gbsmith.rescafe.resourcemanager.ResourceModel;
public class WBGameFinder {
private static final FileFilter filter = new FileFilter() {
public boolean accept(File file) {
if (file.isDirectory())
return true;
ResourceModel model = new ResourceModel(file.getName());
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file.getPath() + "/rsrc", "r");
model.read(raf);
if (model.getResourceType("ASCN") != null) {
return true;
}
- } catch (IOException e) {
+ } catch (IOException ioe) {
+ } catch (Throwable t) {
+ System.gc();
+ //System.err.println("Failed on: " + file.getAbsolutePath());
+ //t.printStackTrace();
}
return false;
}
};
public static void main(String[] args) {
System.setProperty("apple.awt.fileDialogForDirectories", "true");
FileDialog dialog = new FileDialog(new Frame(), "Choose Folder", FileDialog.LOAD);
dialog.setVisible(true);
if (dialog.getFile() == null)
return;
File file = new File(dialog.getDirectory() + "/" + dialog.getFile());
if (filter.accept(file))
processFile(file);
System.out.println("Done");
System.exit(0);
}
private static void processFile(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles(filter);
if (files != null) {
for (File f : files) {
processFile(f);
}
}
} else {
System.out.println("Found WB Game: " + file.getAbsolutePath());
}
}
}
| true | true |
public boolean accept(File file) {
if (file.isDirectory())
return true;
ResourceModel model = new ResourceModel(file.getName());
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file.getPath() + "/rsrc", "r");
model.read(raf);
if (model.getResourceType("ASCN") != null) {
return true;
}
} catch (IOException e) {
}
return false;
}
|
public boolean accept(File file) {
if (file.isDirectory())
return true;
ResourceModel model = new ResourceModel(file.getName());
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file.getPath() + "/rsrc", "r");
model.read(raf);
if (model.getResourceType("ASCN") != null) {
return true;
}
} catch (IOException ioe) {
} catch (Throwable t) {
System.gc();
//System.err.println("Failed on: " + file.getAbsolutePath());
//t.printStackTrace();
}
return false;
}
|
diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java b/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java
index a46d76f4f..262ba6d39 100755
--- a/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java
+++ b/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java
@@ -1,220 +1,221 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.transport.discovery;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.jmx.AnnotatedMBean;
import org.apache.activemq.broker.jmx.ManagementContext;
import org.apache.activemq.transport.discovery.multicast.MulticastDiscoveryAgentFactory;
import org.apache.activemq.util.SocketProxy;
import org.apache.activemq.util.Wait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.action.CustomAction;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(JMock.class)
public class DiscoveryNetworkReconnectTest {
private static final Logger LOG = LoggerFactory.getLogger(DiscoveryNetworkReconnectTest.class);
final int maxReconnects = 2;
final String groupName = "GroupID-" + "DiscoveryNetworkReconnectTest";
final String discoveryAddress = "multicast://default?group=" + groupName + "&initialReconnectDelay=1000";
final Semaphore mbeanRegistered = new Semaphore(0);
final Semaphore mbeanUnregistered = new Semaphore(0);
BrokerService brokerA, brokerB;
Mockery context;
ManagementContext managementContext;
DiscoveryAgent agent;
SocketProxy proxy;
// ignore the hostname resolution component as this is machine dependent
class NetworkBridgeObjectNameMatcher<T> extends BaseMatcher<T> {
T name;
NetworkBridgeObjectNameMatcher(T o) {
name = o;
}
public boolean matches(Object arg0) {
ObjectName other = (ObjectName) arg0;
ObjectName mine = (ObjectName) name;
LOG.info("Match: " + mine + " vs: " + other);
return other.getKeyProperty("Type").equals(mine.getKeyProperty("Type")) &&
other.getKeyProperty("NetworkConnectorName").equals(mine.getKeyProperty("NetworkConnectorName"));
}
public void describeTo(Description arg0) {
arg0.appendText(this.getClass().getName());
}
}
@Before
public void setUp() throws Exception {
context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
brokerA = new BrokerService();
brokerA.setBrokerName("BrokerA");
configure(brokerA);
brokerA.addConnector("tcp://localhost:0");
brokerA.start();
brokerA.waitUntilStarted();
proxy = new SocketProxy(brokerA.getTransportConnectors().get(0).getConnectUri());
managementContext = context.mock(ManagementContext.class);
context.checking(new Expectations(){{
allowing (managementContext).getJmxDomainName(); will (returnValue("Test"));
+ allowing (managementContext).setBrokerName("BrokerNC");
allowing (managementContext).start();
allowing (managementContext).isCreateConnector();
allowing (managementContext).stop();
allowing (managementContext).isConnectorStarted();
// expected MBeans
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Broker"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=NC"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.NetworkBridge"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=jobScheduler,jobSchedulerName=JMS"))));
atLeast(maxReconnects - 1).of (managementContext).registerMBean(with(any(Object.class)), with(new NetworkBridgeObjectNameMatcher<ObjectName>(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=NC,Name=localhost/127.0.0.1_"
+ proxy.getUrl().getPort())))); will(new CustomAction("signal register network mbean") {
public Object invoke(Invocation invocation) throws Throwable {
LOG.info("Mbean Registered: " + invocation.getParameter(0));
mbeanRegistered.release();
return new ObjectInstance((ObjectName)invocation.getParameter(1), "dscription");
}
});
atLeast(maxReconnects - 1).of (managementContext).unregisterMBean(with(new NetworkBridgeObjectNameMatcher<ObjectName>(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=NC,Name=localhost/127.0.0.1_"
+ proxy.getUrl().getPort())))); will(new CustomAction("signal unregister network mbean") {
public Object invoke(Invocation invocation) throws Throwable {
LOG.info("Mbean Unregistered: " + invocation.getParameter(0));
mbeanUnregistered.release();
return null;
}
});
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Broker"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=NC"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.NetworkBridge"))));
}});
brokerB = new BrokerService();
brokerB.setManagementContext(managementContext);
brokerB.setBrokerName("BrokerNC");
configure(brokerB);
}
@After
public void tearDown() throws Exception {
brokerA.stop();
brokerA.waitUntilStopped();
brokerB.stop();
brokerB.waitUntilStopped();
proxy.close();
}
private void configure(BrokerService broker) {
broker.setPersistent(false);
broker.setUseJmx(true);
}
@Test
public void testMulicastReconnect() throws Exception {
// control multicast advertise agent to inject proxy
agent = MulticastDiscoveryAgentFactory.createDiscoveryAgent(new URI(discoveryAddress));
agent.registerService(proxy.getUrl().toString());
agent.start();
brokerB.addNetworkConnector(discoveryAddress + "&wireFormat.maxInactivityDuration=1000&wireFormat.maxInactivityDurationInitalDelay=1000");
brokerB.start();
brokerB.waitUntilStarted();
doReconnect();
}
@Test
public void testSimpleReconnect() throws Exception {
brokerB.addNetworkConnector("simple://(" + proxy.getUrl()
+ ")?useExponentialBackOff=false&initialReconnectDelay=500&wireFormat.maxInactivityDuration=1000&wireFormat.maxInactivityDurationInitalDelay=1000");
brokerB.start();
brokerB.waitUntilStarted();
doReconnect();
}
private void doReconnect() throws Exception {
for (int i=0; i<maxReconnects; i++) {
// Wait for connection
assertTrue("we got a network connection in a timely manner", Wait.waitFor(new Wait.Condition() {
public boolean isSatisified() throws Exception {
return proxy.connections.size() >= 1;
}
}));
// wait for network connector
assertTrue("network connector mbean registered within 3 minute", mbeanRegistered.tryAcquire(180, TimeUnit.SECONDS));
// force an inactivity timeout via the proxy
proxy.pause();
// wait for the inactivity timeout and network shutdown
assertTrue("network connector mbean unregistered within 3 minute", mbeanUnregistered.tryAcquire(180, TimeUnit.SECONDS));
// whack all connections
proxy.close();
// let a reconnect succeed
proxy.reopen();
}
}
}
| true | true |
public void setUp() throws Exception {
context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
brokerA = new BrokerService();
brokerA.setBrokerName("BrokerA");
configure(brokerA);
brokerA.addConnector("tcp://localhost:0");
brokerA.start();
brokerA.waitUntilStarted();
proxy = new SocketProxy(brokerA.getTransportConnectors().get(0).getConnectUri());
managementContext = context.mock(ManagementContext.class);
context.checking(new Expectations(){{
allowing (managementContext).getJmxDomainName(); will (returnValue("Test"));
allowing (managementContext).start();
allowing (managementContext).isCreateConnector();
allowing (managementContext).stop();
allowing (managementContext).isConnectorStarted();
// expected MBeans
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Broker"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=NC"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.NetworkBridge"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=jobScheduler,jobSchedulerName=JMS"))));
atLeast(maxReconnects - 1).of (managementContext).registerMBean(with(any(Object.class)), with(new NetworkBridgeObjectNameMatcher<ObjectName>(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=NC,Name=localhost/127.0.0.1_"
+ proxy.getUrl().getPort())))); will(new CustomAction("signal register network mbean") {
public Object invoke(Invocation invocation) throws Throwable {
LOG.info("Mbean Registered: " + invocation.getParameter(0));
mbeanRegistered.release();
return new ObjectInstance((ObjectName)invocation.getParameter(1), "dscription");
}
});
atLeast(maxReconnects - 1).of (managementContext).unregisterMBean(with(new NetworkBridgeObjectNameMatcher<ObjectName>(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=NC,Name=localhost/127.0.0.1_"
+ proxy.getUrl().getPort())))); will(new CustomAction("signal unregister network mbean") {
public Object invoke(Invocation invocation) throws Throwable {
LOG.info("Mbean Unregistered: " + invocation.getParameter(0));
mbeanUnregistered.release();
return null;
}
});
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Broker"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=NC"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.NetworkBridge"))));
}});
brokerB = new BrokerService();
brokerB.setManagementContext(managementContext);
brokerB.setBrokerName("BrokerNC");
configure(brokerB);
}
|
public void setUp() throws Exception {
context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
brokerA = new BrokerService();
brokerA.setBrokerName("BrokerA");
configure(brokerA);
brokerA.addConnector("tcp://localhost:0");
brokerA.start();
brokerA.waitUntilStarted();
proxy = new SocketProxy(brokerA.getTransportConnectors().get(0).getConnectUri());
managementContext = context.mock(ManagementContext.class);
context.checking(new Expectations(){{
allowing (managementContext).getJmxDomainName(); will (returnValue("Test"));
allowing (managementContext).setBrokerName("BrokerNC");
allowing (managementContext).start();
allowing (managementContext).isCreateConnector();
allowing (managementContext).stop();
allowing (managementContext).isConnectorStarted();
// expected MBeans
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Broker"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=NC"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.NetworkBridge"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=jobScheduler,jobSchedulerName=JMS"))));
atLeast(maxReconnects - 1).of (managementContext).registerMBean(with(any(Object.class)), with(new NetworkBridgeObjectNameMatcher<ObjectName>(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=NC,Name=localhost/127.0.0.1_"
+ proxy.getUrl().getPort())))); will(new CustomAction("signal register network mbean") {
public Object invoke(Invocation invocation) throws Throwable {
LOG.info("Mbean Registered: " + invocation.getParameter(0));
mbeanRegistered.release();
return new ObjectInstance((ObjectName)invocation.getParameter(1), "dscription");
}
});
atLeast(maxReconnects - 1).of (managementContext).unregisterMBean(with(new NetworkBridgeObjectNameMatcher<ObjectName>(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=NC,Name=localhost/127.0.0.1_"
+ proxy.getUrl().getPort())))); will(new CustomAction("signal unregister network mbean") {
public Object invoke(Invocation invocation) throws Throwable {
LOG.info("Mbean Unregistered: " + invocation.getParameter(0));
mbeanUnregistered.release();
return null;
}
});
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Broker"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=NC"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.NetworkBridge"))));
}});
brokerB = new BrokerService();
brokerB.setManagementContext(managementContext);
brokerB.setBrokerName("BrokerNC");
configure(brokerB);
}
|
diff --git a/src/ee/playtech/wallet/socket/server/Statistics.java b/src/ee/playtech/wallet/socket/server/Statistics.java
index c4c133d..74c50f7 100644
--- a/src/ee/playtech/wallet/socket/server/Statistics.java
+++ b/src/ee/playtech/wallet/socket/server/Statistics.java
@@ -1,83 +1,84 @@
package ee.playtech.wallet.socket.server;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ee.playtech.wallet.program.PropertiesLoaderUtil;
public class Statistics {
private static final Logger log = LoggerFactory.getLogger("statistics");
private int delay;
private int requestsCount;
private int requestsCountPerTick;
private int maxDuration;
private int minDuration;
private int averageDuration;
private List<Integer> durationsList = Collections.synchronizedList(new LinkedList<Integer>());
public Statistics() {
delay = PropertiesLoaderUtil.getStatisticInterval();
if (isEnabled()) {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
calculateAndLogStatics();
}
}, 0, delay, TimeUnit.SECONDS);
}
}
public boolean isEnabled() {
return delay > 0;
}
public synchronized void incrementRequestsCount() {
requestsCount++;
requestsCountPerTick++;
}
public void storeStatistic(long transactionID, int duration) {
durationsList.add(duration);
log.debug("Transaction {} has duration: {}ms", transactionID, duration);
}
private synchronized void calculateAndLogStatics() {
int count = durationsList.size();
if (count == 0) {
log.info("No requests was during last interval");
return;
}
int totalDuration = 0;
for (int i = 0; i < count; i++) {
int duration = durationsList.get(i);
if (maxDuration < duration) {
maxDuration = duration;
}
if (minDuration > duration) {
minDuration = duration;
}
totalDuration += duration;
}
averageDuration = totalDuration / count;
logStatiscs();
requestsCountPerTick = 0;
maxDuration = Integer.MIN_VALUE;
minDuration = Integer.MAX_VALUE;
averageDuration = 0;
+ durationsList.clear();
}
private void logStatiscs() {
if (log.isInfoEnabled()) {
log.info("Requests: total count={}, per collected interval={}. Durations: max={}ms, min={}ms, average={}ms.", new Object[] { requestsCount, requestsCountPerTick,
maxDuration, minDuration, averageDuration });
}
}
}
| true | true |
private synchronized void calculateAndLogStatics() {
int count = durationsList.size();
if (count == 0) {
log.info("No requests was during last interval");
return;
}
int totalDuration = 0;
for (int i = 0; i < count; i++) {
int duration = durationsList.get(i);
if (maxDuration < duration) {
maxDuration = duration;
}
if (minDuration > duration) {
minDuration = duration;
}
totalDuration += duration;
}
averageDuration = totalDuration / count;
logStatiscs();
requestsCountPerTick = 0;
maxDuration = Integer.MIN_VALUE;
minDuration = Integer.MAX_VALUE;
averageDuration = 0;
}
|
private synchronized void calculateAndLogStatics() {
int count = durationsList.size();
if (count == 0) {
log.info("No requests was during last interval");
return;
}
int totalDuration = 0;
for (int i = 0; i < count; i++) {
int duration = durationsList.get(i);
if (maxDuration < duration) {
maxDuration = duration;
}
if (minDuration > duration) {
minDuration = duration;
}
totalDuration += duration;
}
averageDuration = totalDuration / count;
logStatiscs();
requestsCountPerTick = 0;
maxDuration = Integer.MIN_VALUE;
minDuration = Integer.MAX_VALUE;
averageDuration = 0;
durationsList.clear();
}
|
diff --git a/src/com/gitblit/wicket/pages/EditTeamPage.java b/src/com/gitblit/wicket/pages/EditTeamPage.java
index 0af3cb4..d78f889 100644
--- a/src/com/gitblit/wicket/pages/EditTeamPage.java
+++ b/src/com/gitblit/wicket/pages/EditTeamPage.java
@@ -1,247 +1,251 @@
/*
* Copyright 2011 gitblit.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitblit.wicket.pages;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.wicket.PageParameters;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.extensions.markup.html.form.palette.Palette;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.util.CollectionModel;
import org.apache.wicket.model.util.ListModel;
import com.gitblit.Constants.AccessRestrictionType;
import com.gitblit.GitBlit;
import com.gitblit.GitBlitException;
import com.gitblit.models.RepositoryModel;
import com.gitblit.models.TeamModel;
import com.gitblit.utils.StringUtils;
import com.gitblit.wicket.RequiresAdminRole;
import com.gitblit.wicket.WicketUtils;
import com.gitblit.wicket.panels.BulletListPanel;
@RequiresAdminRole
public class EditTeamPage extends RootSubPage {
private final boolean isCreate;
private IModel<String> mailingLists;
public EditTeamPage() {
// create constructor
super();
isCreate = true;
setupPage(new TeamModel(""));
}
public EditTeamPage(PageParameters params) {
// edit constructor
super(params);
isCreate = false;
String name = WicketUtils.getTeamname(params);
TeamModel model = GitBlit.self().getTeamModel(name);
setupPage(model);
}
protected void setupPage(final TeamModel teamModel) {
if (isCreate) {
super.setupPage(getString("gb.newTeam"), "");
} else {
super.setupPage(getString("gb.edit"), teamModel.name);
}
CompoundPropertyModel<TeamModel> model = new CompoundPropertyModel<TeamModel>(teamModel);
List<String> repos = new ArrayList<String>();
for (String repo : GitBlit.self().getRepositoryList()) {
RepositoryModel repositoryModel = GitBlit.self().getRepositoryModel(repo);
if (repositoryModel.accessRestriction.exceeds(AccessRestrictionType.NONE)) {
repos.add(repo);
}
}
StringUtils.sortRepositorynames(repos);
List<String> teamUsers = new ArrayList<String>(teamModel.users);
Collections.sort(teamUsers);
List<String> preReceiveScripts = new ArrayList<String>();
List<String> postReceiveScripts = new ArrayList<String>();
final String oldName = teamModel.name;
// repositories palette
final Palette<String> repositories = new Palette<String>("repositories",
new ListModel<String>(new ArrayList<String>(teamModel.repositories)),
new CollectionModel<String>(repos), new ChoiceRenderer<String>("", ""), 10, false);
// users palette
final Palette<String> users = new Palette<String>("users", new ListModel<String>(
new ArrayList<String>(teamUsers)), new CollectionModel<String>(GitBlit.self()
.getAllUsernames()), new ChoiceRenderer<String>("", ""), 10, false);
// pre-receive palette
if (teamModel.preReceiveScripts != null) {
preReceiveScripts.addAll(teamModel.preReceiveScripts);
}
final Palette<String> preReceivePalette = new Palette<String>("preReceiveScripts",
new ListModel<String>(preReceiveScripts), new CollectionModel<String>(GitBlit
.self().getPreReceiveScriptsUnused(null)), new ChoiceRenderer<String>("",
""), 12, true);
// post-receive palette
if (teamModel.postReceiveScripts != null) {
postReceiveScripts.addAll(teamModel.postReceiveScripts);
}
final Palette<String> postReceivePalette = new Palette<String>("postReceiveScripts",
new ListModel<String>(postReceiveScripts), new CollectionModel<String>(GitBlit
.self().getPostReceiveScriptsUnused(null)), new ChoiceRenderer<String>("",
""), 12, true);
Form<TeamModel> form = new Form<TeamModel>("editForm", model) {
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see org.apache.wicket.markup.html.form.Form#onSubmit()
*/
@Override
protected void onSubmit() {
String teamname = teamModel.name;
if (StringUtils.isEmpty(teamname)) {
error("Please enter a teamname!");
return;
}
if (isCreate) {
TeamModel model = GitBlit.self().getTeamModel(teamname);
if (model != null) {
error(MessageFormat.format("Team name ''{0}'' is unavailable.", teamname));
return;
}
}
Iterator<String> selectedRepositories = repositories.getSelectedChoices();
List<String> repos = new ArrayList<String>();
while (selectedRepositories.hasNext()) {
repos.add(selectedRepositories.next().toLowerCase());
}
+ if (repos.size() == 0) {
+ error("A team must specify at least one repository.");
+ return;
+ }
teamModel.repositories.clear();
teamModel.repositories.addAll(repos);
Iterator<String> selectedUsers = users.getSelectedChoices();
List<String> members = new ArrayList<String>();
while (selectedUsers.hasNext()) {
members.add(selectedUsers.next().toLowerCase());
}
teamModel.users.clear();
teamModel.users.addAll(members);
// set mailing lists
String ml = mailingLists.getObject();
if (!StringUtils.isEmpty(ml)) {
Set<String> list = new HashSet<String>();
for (String address : ml.split("(,|\\s)")) {
if (StringUtils.isEmpty(address)) {
continue;
}
list.add(address.toLowerCase());
}
teamModel.mailingLists.clear();
teamModel.mailingLists.addAll(list);
}
// pre-receive scripts
List<String> preReceiveScripts = new ArrayList<String>();
Iterator<String> pres = preReceivePalette.getSelectedChoices();
while (pres.hasNext()) {
preReceiveScripts.add(pres.next());
}
teamModel.preReceiveScripts.clear();
teamModel.preReceiveScripts.addAll(preReceiveScripts);
// post-receive scripts
List<String> postReceiveScripts = new ArrayList<String>();
Iterator<String> post = postReceivePalette.getSelectedChoices();
while (post.hasNext()) {
postReceiveScripts.add(post.next());
}
teamModel.postReceiveScripts.clear();
teamModel.postReceiveScripts.addAll(postReceiveScripts);
try {
GitBlit.self().updateTeamModel(oldName, teamModel, isCreate);
} catch (GitBlitException e) {
error(e.getMessage());
return;
}
setRedirect(false);
if (isCreate) {
// create another team
info(MessageFormat.format("New team ''{0}'' successfully created.",
teamModel.name));
setResponsePage(EditTeamPage.class);
} else {
// back to users page
setResponsePage(UsersPage.class);
}
}
};
// do not let the browser pre-populate these fields
form.add(new SimpleAttributeModifier("autocomplete", "off"));
// field names reflective match TeamModel fields
form.add(new TextField<String>("name"));
form.add(users);
mailingLists = new Model<String>(teamModel.mailingLists == null ? ""
: StringUtils.flattenStrings(teamModel.mailingLists, " "));
form.add(new TextField<String>("mailingLists", mailingLists));
form.add(repositories);
form.add(preReceivePalette);
form.add(new BulletListPanel("inheritedPreReceive", "inherited", GitBlit.self()
.getPreReceiveScriptsInherited(null)));
form.add(postReceivePalette);
form.add(new BulletListPanel("inheritedPostReceive", "inherited", GitBlit.self()
.getPostReceiveScriptsInherited(null)));
form.add(new Button("save"));
Button cancel = new Button("cancel") {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
setResponsePage(UsersPage.class);
}
};
cancel.setDefaultFormProcessing(false);
form.add(cancel);
add(form);
}
}
| true | true |
protected void setupPage(final TeamModel teamModel) {
if (isCreate) {
super.setupPage(getString("gb.newTeam"), "");
} else {
super.setupPage(getString("gb.edit"), teamModel.name);
}
CompoundPropertyModel<TeamModel> model = new CompoundPropertyModel<TeamModel>(teamModel);
List<String> repos = new ArrayList<String>();
for (String repo : GitBlit.self().getRepositoryList()) {
RepositoryModel repositoryModel = GitBlit.self().getRepositoryModel(repo);
if (repositoryModel.accessRestriction.exceeds(AccessRestrictionType.NONE)) {
repos.add(repo);
}
}
StringUtils.sortRepositorynames(repos);
List<String> teamUsers = new ArrayList<String>(teamModel.users);
Collections.sort(teamUsers);
List<String> preReceiveScripts = new ArrayList<String>();
List<String> postReceiveScripts = new ArrayList<String>();
final String oldName = teamModel.name;
// repositories palette
final Palette<String> repositories = new Palette<String>("repositories",
new ListModel<String>(new ArrayList<String>(teamModel.repositories)),
new CollectionModel<String>(repos), new ChoiceRenderer<String>("", ""), 10, false);
// users palette
final Palette<String> users = new Palette<String>("users", new ListModel<String>(
new ArrayList<String>(teamUsers)), new CollectionModel<String>(GitBlit.self()
.getAllUsernames()), new ChoiceRenderer<String>("", ""), 10, false);
// pre-receive palette
if (teamModel.preReceiveScripts != null) {
preReceiveScripts.addAll(teamModel.preReceiveScripts);
}
final Palette<String> preReceivePalette = new Palette<String>("preReceiveScripts",
new ListModel<String>(preReceiveScripts), new CollectionModel<String>(GitBlit
.self().getPreReceiveScriptsUnused(null)), new ChoiceRenderer<String>("",
""), 12, true);
// post-receive palette
if (teamModel.postReceiveScripts != null) {
postReceiveScripts.addAll(teamModel.postReceiveScripts);
}
final Palette<String> postReceivePalette = new Palette<String>("postReceiveScripts",
new ListModel<String>(postReceiveScripts), new CollectionModel<String>(GitBlit
.self().getPostReceiveScriptsUnused(null)), new ChoiceRenderer<String>("",
""), 12, true);
Form<TeamModel> form = new Form<TeamModel>("editForm", model) {
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see org.apache.wicket.markup.html.form.Form#onSubmit()
*/
@Override
protected void onSubmit() {
String teamname = teamModel.name;
if (StringUtils.isEmpty(teamname)) {
error("Please enter a teamname!");
return;
}
if (isCreate) {
TeamModel model = GitBlit.self().getTeamModel(teamname);
if (model != null) {
error(MessageFormat.format("Team name ''{0}'' is unavailable.", teamname));
return;
}
}
Iterator<String> selectedRepositories = repositories.getSelectedChoices();
List<String> repos = new ArrayList<String>();
while (selectedRepositories.hasNext()) {
repos.add(selectedRepositories.next().toLowerCase());
}
teamModel.repositories.clear();
teamModel.repositories.addAll(repos);
Iterator<String> selectedUsers = users.getSelectedChoices();
List<String> members = new ArrayList<String>();
while (selectedUsers.hasNext()) {
members.add(selectedUsers.next().toLowerCase());
}
teamModel.users.clear();
teamModel.users.addAll(members);
// set mailing lists
String ml = mailingLists.getObject();
if (!StringUtils.isEmpty(ml)) {
Set<String> list = new HashSet<String>();
for (String address : ml.split("(,|\\s)")) {
if (StringUtils.isEmpty(address)) {
continue;
}
list.add(address.toLowerCase());
}
teamModel.mailingLists.clear();
teamModel.mailingLists.addAll(list);
}
// pre-receive scripts
List<String> preReceiveScripts = new ArrayList<String>();
Iterator<String> pres = preReceivePalette.getSelectedChoices();
while (pres.hasNext()) {
preReceiveScripts.add(pres.next());
}
teamModel.preReceiveScripts.clear();
teamModel.preReceiveScripts.addAll(preReceiveScripts);
// post-receive scripts
List<String> postReceiveScripts = new ArrayList<String>();
Iterator<String> post = postReceivePalette.getSelectedChoices();
while (post.hasNext()) {
postReceiveScripts.add(post.next());
}
teamModel.postReceiveScripts.clear();
teamModel.postReceiveScripts.addAll(postReceiveScripts);
try {
GitBlit.self().updateTeamModel(oldName, teamModel, isCreate);
} catch (GitBlitException e) {
error(e.getMessage());
return;
}
setRedirect(false);
if (isCreate) {
// create another team
info(MessageFormat.format("New team ''{0}'' successfully created.",
teamModel.name));
setResponsePage(EditTeamPage.class);
} else {
// back to users page
setResponsePage(UsersPage.class);
}
}
};
// do not let the browser pre-populate these fields
form.add(new SimpleAttributeModifier("autocomplete", "off"));
// field names reflective match TeamModel fields
form.add(new TextField<String>("name"));
form.add(users);
mailingLists = new Model<String>(teamModel.mailingLists == null ? ""
: StringUtils.flattenStrings(teamModel.mailingLists, " "));
form.add(new TextField<String>("mailingLists", mailingLists));
form.add(repositories);
form.add(preReceivePalette);
form.add(new BulletListPanel("inheritedPreReceive", "inherited", GitBlit.self()
.getPreReceiveScriptsInherited(null)));
form.add(postReceivePalette);
form.add(new BulletListPanel("inheritedPostReceive", "inherited", GitBlit.self()
.getPostReceiveScriptsInherited(null)));
form.add(new Button("save"));
Button cancel = new Button("cancel") {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
setResponsePage(UsersPage.class);
}
};
cancel.setDefaultFormProcessing(false);
form.add(cancel);
add(form);
}
|
protected void setupPage(final TeamModel teamModel) {
if (isCreate) {
super.setupPage(getString("gb.newTeam"), "");
} else {
super.setupPage(getString("gb.edit"), teamModel.name);
}
CompoundPropertyModel<TeamModel> model = new CompoundPropertyModel<TeamModel>(teamModel);
List<String> repos = new ArrayList<String>();
for (String repo : GitBlit.self().getRepositoryList()) {
RepositoryModel repositoryModel = GitBlit.self().getRepositoryModel(repo);
if (repositoryModel.accessRestriction.exceeds(AccessRestrictionType.NONE)) {
repos.add(repo);
}
}
StringUtils.sortRepositorynames(repos);
List<String> teamUsers = new ArrayList<String>(teamModel.users);
Collections.sort(teamUsers);
List<String> preReceiveScripts = new ArrayList<String>();
List<String> postReceiveScripts = new ArrayList<String>();
final String oldName = teamModel.name;
// repositories palette
final Palette<String> repositories = new Palette<String>("repositories",
new ListModel<String>(new ArrayList<String>(teamModel.repositories)),
new CollectionModel<String>(repos), new ChoiceRenderer<String>("", ""), 10, false);
// users palette
final Palette<String> users = new Palette<String>("users", new ListModel<String>(
new ArrayList<String>(teamUsers)), new CollectionModel<String>(GitBlit.self()
.getAllUsernames()), new ChoiceRenderer<String>("", ""), 10, false);
// pre-receive palette
if (teamModel.preReceiveScripts != null) {
preReceiveScripts.addAll(teamModel.preReceiveScripts);
}
final Palette<String> preReceivePalette = new Palette<String>("preReceiveScripts",
new ListModel<String>(preReceiveScripts), new CollectionModel<String>(GitBlit
.self().getPreReceiveScriptsUnused(null)), new ChoiceRenderer<String>("",
""), 12, true);
// post-receive palette
if (teamModel.postReceiveScripts != null) {
postReceiveScripts.addAll(teamModel.postReceiveScripts);
}
final Palette<String> postReceivePalette = new Palette<String>("postReceiveScripts",
new ListModel<String>(postReceiveScripts), new CollectionModel<String>(GitBlit
.self().getPostReceiveScriptsUnused(null)), new ChoiceRenderer<String>("",
""), 12, true);
Form<TeamModel> form = new Form<TeamModel>("editForm", model) {
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see org.apache.wicket.markup.html.form.Form#onSubmit()
*/
@Override
protected void onSubmit() {
String teamname = teamModel.name;
if (StringUtils.isEmpty(teamname)) {
error("Please enter a teamname!");
return;
}
if (isCreate) {
TeamModel model = GitBlit.self().getTeamModel(teamname);
if (model != null) {
error(MessageFormat.format("Team name ''{0}'' is unavailable.", teamname));
return;
}
}
Iterator<String> selectedRepositories = repositories.getSelectedChoices();
List<String> repos = new ArrayList<String>();
while (selectedRepositories.hasNext()) {
repos.add(selectedRepositories.next().toLowerCase());
}
if (repos.size() == 0) {
error("A team must specify at least one repository.");
return;
}
teamModel.repositories.clear();
teamModel.repositories.addAll(repos);
Iterator<String> selectedUsers = users.getSelectedChoices();
List<String> members = new ArrayList<String>();
while (selectedUsers.hasNext()) {
members.add(selectedUsers.next().toLowerCase());
}
teamModel.users.clear();
teamModel.users.addAll(members);
// set mailing lists
String ml = mailingLists.getObject();
if (!StringUtils.isEmpty(ml)) {
Set<String> list = new HashSet<String>();
for (String address : ml.split("(,|\\s)")) {
if (StringUtils.isEmpty(address)) {
continue;
}
list.add(address.toLowerCase());
}
teamModel.mailingLists.clear();
teamModel.mailingLists.addAll(list);
}
// pre-receive scripts
List<String> preReceiveScripts = new ArrayList<String>();
Iterator<String> pres = preReceivePalette.getSelectedChoices();
while (pres.hasNext()) {
preReceiveScripts.add(pres.next());
}
teamModel.preReceiveScripts.clear();
teamModel.preReceiveScripts.addAll(preReceiveScripts);
// post-receive scripts
List<String> postReceiveScripts = new ArrayList<String>();
Iterator<String> post = postReceivePalette.getSelectedChoices();
while (post.hasNext()) {
postReceiveScripts.add(post.next());
}
teamModel.postReceiveScripts.clear();
teamModel.postReceiveScripts.addAll(postReceiveScripts);
try {
GitBlit.self().updateTeamModel(oldName, teamModel, isCreate);
} catch (GitBlitException e) {
error(e.getMessage());
return;
}
setRedirect(false);
if (isCreate) {
// create another team
info(MessageFormat.format("New team ''{0}'' successfully created.",
teamModel.name));
setResponsePage(EditTeamPage.class);
} else {
// back to users page
setResponsePage(UsersPage.class);
}
}
};
// do not let the browser pre-populate these fields
form.add(new SimpleAttributeModifier("autocomplete", "off"));
// field names reflective match TeamModel fields
form.add(new TextField<String>("name"));
form.add(users);
mailingLists = new Model<String>(teamModel.mailingLists == null ? ""
: StringUtils.flattenStrings(teamModel.mailingLists, " "));
form.add(new TextField<String>("mailingLists", mailingLists));
form.add(repositories);
form.add(preReceivePalette);
form.add(new BulletListPanel("inheritedPreReceive", "inherited", GitBlit.self()
.getPreReceiveScriptsInherited(null)));
form.add(postReceivePalette);
form.add(new BulletListPanel("inheritedPostReceive", "inherited", GitBlit.self()
.getPostReceiveScriptsInherited(null)));
form.add(new Button("save"));
Button cancel = new Button("cancel") {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
setResponsePage(UsersPage.class);
}
};
cancel.setDefaultFormProcessing(false);
form.add(cancel);
add(form);
}
|
diff --git a/src/com/redhat/ceylon/compiler/java/codegen/AbstractTransformer.java b/src/com/redhat/ceylon/compiler/java/codegen/AbstractTransformer.java
index bf953701a..0e2ec7027 100755
--- a/src/com/redhat/ceylon/compiler/java/codegen/AbstractTransformer.java
+++ b/src/com/redhat/ceylon/compiler/java/codegen/AbstractTransformer.java
@@ -1,2781 +1,2782 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.codegen;
import static com.sun.tools.javac.code.Flags.FINAL;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.antlr.runtime.Token;
import com.redhat.ceylon.ceylondoc.Util;
import com.redhat.ceylon.common.Versions;
import com.redhat.ceylon.compiler.java.codegen.CallBuilder.ArgumentHandling;
import com.redhat.ceylon.compiler.java.codegen.Naming.DeclNameFlag;
import com.redhat.ceylon.compiler.java.loader.CeylonModelLoader;
import com.redhat.ceylon.compiler.java.loader.TypeFactory;
import com.redhat.ceylon.compiler.java.tools.CeylonLog;
import com.redhat.ceylon.compiler.loader.AbstractModelLoader;
import com.redhat.ceylon.compiler.loader.ModelLoader.DeclarationType;
import com.redhat.ceylon.compiler.typechecker.model.Annotation;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.FunctionalParameter;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.ModuleImport;
import com.redhat.ceylon.compiler.typechecker.model.NothingType;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ProducedReference;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.ProducedTypedReference;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.model.UnknownType;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Comprehension;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.PositionalArgument;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTags;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.Factory;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCLiteral;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.JCTree.LetExpr;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Names;
import com.sun.tools.javac.util.Position;
import com.sun.tools.javac.util.Position.LineMap;
/**
* Base class for all delegating transformers
*/
public abstract class AbstractTransformer implements Transformation {
private Context context;
private TreeMaker make;
private Names names;
private Symtab syms;
private AbstractModelLoader loader;
private TypeFactory typeFact;
protected Log log;
final Naming naming;
public AbstractTransformer(Context context) {
this.context = context;
make = TreeMaker.instance(context);
names = Names.instance(context);
syms = Symtab.instance(context);
loader = CeylonModelLoader.instance(context);
typeFact = TypeFactory.instance(context);
log = CeylonLog.instance(context);
naming = Naming.instance(context);
}
Context getContext() {
return context;
}
@Override
public TreeMaker make() {
return make;
}
private static JavaPositionsRetriever javaPositionsRetriever = null;
public static void trackNodePositions(JavaPositionsRetriever positionsRetriever) {
javaPositionsRetriever = positionsRetriever;
}
@Override
public Factory at(Node node) {
if (node == null) {
make.at(Position.NOPOS);
}
else {
Token token = node.getToken();
if (token != null) {
int tokenStartPosition = getMap().getStartPosition(token.getLine()) + token.getCharPositionInLine();
make().at(tokenStartPosition);
if (javaPositionsRetriever != null) {
javaPositionsRetriever.addCeylonNode(tokenStartPosition, node);
}
}
}
return make();
}
@Override
public Symtab syms() {
return syms;
}
@Override
public Names names() {
return names;
}
@Override
public AbstractModelLoader loader() {
return loader;
}
@Override
public TypeFactory typeFact() {
return typeFact;
}
void setMap(LineMap map) {
gen().setMap(map);
}
LineMap getMap() {
return gen().getMap();
}
@Override
public CeylonTransformer gen() {
return CeylonTransformer.getInstance(context);
}
@Override
public ExpressionTransformer expressionGen() {
return ExpressionTransformer.getInstance(context);
}
@Override
public StatementTransformer statementGen() {
return StatementTransformer.getInstance(context);
}
@Override
public ClassTransformer classGen() {
return ClassTransformer.getInstance(context);
}
/**
* Makes an <strong>unquoted</strong> simple identifier
* @param ident The identifier
* @return The ident
*/
JCExpression makeUnquotedIdent(String ident) {
return naming.makeUnquotedIdent(ident);
}
/**
* Makes an <strong>quoted</strong> simple identifier
* @param ident The identifier
* @return The ident
*/
JCIdent makeQuotedIdent(String ident) {
// TODO Only 3 callers
return naming.makeQuotedIdent(ident);
}
/**
* Makes a <strong>quoted</strong> qualified (compound) identifier from
* the given qualified name. Each part of the name will be
* quoted if it is a Java keyword.
* @param qualifiedName The qualified name
*/
JCExpression makeQuotedQualIdentFromString(String qualifiedName) {
return naming.makeQuotedQualIdentFromString(qualifiedName);
}
/**
* Makes an <strong>unquoted</strong> qualified (compound) identifier
* from the given qualified name components
* @param expr A starting expression (may be null)
* @param names The components of the name (may be null)
* @see #makeQuotedQualIdentFromString(String)
*/
JCExpression makeQualIdent(JCExpression expr, String name) {
return naming.makeQualIdent(expr, name);
}
JCExpression makeQuotedQualIdent(JCExpression expr, String... names) {
// TODO Remove this method: Only 1 caller
return naming.makeQuotedQualIdent(expr, names);
}
JCExpression makeQuotedFQIdent(String qualifiedName) {
// TODO Remove this method??: Only 2 callers
return naming.makeQuotedFQIdent(qualifiedName);
}
JCExpression makeIdent(Type type) {
return naming.makeIdent(type);
}
/**
* Makes a <strong>unquoted</strong> field access
* @param s1 The base expression
* @param s2 The field to access
* @return The field access
*/
JCFieldAccess makeSelect(JCExpression s1, String s2) {
return naming.makeSelect(s1, s2);
}
/**
* Makes a <strong>unquoted</strong> field access
* @param s1 The base expression
* @param s2 The field to access
* @return The field access
*/
JCFieldAccess makeSelect(String s1, String s2) {
return naming.makeSelect(s1, s2);
}
JCLiteral makeNull() {
return make().Literal(TypeTags.BOT, null);
}
JCExpression makeInteger(int i) {
return make().Literal(Integer.valueOf(i));
}
JCExpression makeLong(long i) {
return make().Literal(Long.valueOf(i));
}
JCExpression makeBoolean(boolean b) {
JCExpression expr;
if (b) {
expr = make().Literal(TypeTags.BOOLEAN, Integer.valueOf(1));
} else {
expr = make().Literal(TypeTags.BOOLEAN, Integer.valueOf(0));
}
return expr;
}
// Creates a "foo foo = new foo();"
JCTree.JCVariableDecl makeLocalIdentityInstance(String varName, String className, boolean isShared) {
return makeLocalIdentityInstance(varName, className, isShared, null);
}
// Creates a "foo foo = new foo(parameter);"
JCTree.JCVariableDecl makeLocalIdentityInstance(String varName, String className, boolean isShared, JCTree.JCExpression parameter) {
JCExpression name = makeQuotedIdent(className);
JCExpression initValue = makeNewClass(className, false, parameter);
int modifiers = isShared ? 0 : FINAL;
JCTree.JCVariableDecl var = make().VarDef(
make().Modifiers(modifiers),
names().fromString(varName),
name,
initValue);
return var;
}
// Creates a "new foo();"
JCTree.JCNewClass makeNewClass(String className, boolean fullyQualified, JCTree.JCExpression parameter) {
JCExpression name = fullyQualified ? naming.makeQuotedFQIdent(className) : makeQuotedQualIdentFromString(className);
List<JCTree.JCExpression> params = parameter != null ? List.of(parameter) : List.<JCTree.JCExpression>nil();
return makeNewClass(name, params);
}
/** Creates a "new foo();" */
JCTree.JCNewClass makeSyntheticInstance(Declaration decl) {
JCExpression clazz = naming.makeSyntheticClassname(decl);
return makeNewClass(clazz, List.<JCTree.JCExpression>nil());
}
JCTree.JCNewClass makeNewClass(JCExpression clazz) {
return makeNewClass(clazz, null);
}
// Creates a "new foo(arg1, arg2, ...);"
JCTree.JCNewClass makeNewClass(JCExpression clazz, List<JCTree.JCExpression> args) {
if (args == null) {
args = List.<JCTree.JCExpression>nil();
}
return make().NewClass(null, null, clazz, args, null);
}
JCVariableDecl makeVar(String varName, JCExpression typeExpr, JCExpression valueExpr) {
return make().VarDef(make().Modifiers(0), names().fromString(varName), typeExpr, valueExpr);
}
JCVariableDecl makeVar(Naming.SyntheticName varName, JCExpression typeExpr, JCExpression valueExpr) {
return make().VarDef(make().Modifiers(0), varName.asName(), typeExpr, valueExpr);
}
/**
* Creates a {@code ( let var1=expr1,var2=expr2,...,varN=exprN in varN; )}
* or a {@code ( let var1=expr1,var2=expr2,...,varN=exprN,exprO in exprO; )}
* @param args
* @return
*/
JCExpression makeLetExpr(JCExpression... args) {
return makeLetExpr(naming.temp(), null, args);
}
/** Creates a
* {@code ( let var1=expr1,var2=expr2,...,varN=exprN in statements; varN; )}
* or a {@code ( let var1=expr1,var2=expr2,...,varN=exprN in statements; exprO; )}
*
*/
JCExpression makeLetExpr(Naming.SyntheticName varBaseName, List<JCStatement> statements, JCExpression... args) {
return makeLetExpr(varBaseName.getName(), statements, args);
}
private JCExpression makeLetExpr(String varBaseName, List<JCStatement> statements, JCExpression... args) {
String varName = null;
ListBuffer<JCStatement> decls = ListBuffer.lb();
int i;
for (i = 0; (i + 1) < args.length; i += 2) {
JCExpression typeExpr = args[i];
JCExpression valueExpr = args[i+1];
varName = varBaseName + ((args.length > 3) ? "$" + i : "");
JCVariableDecl varDecl = makeVar(varName, typeExpr, valueExpr);
decls.append(varDecl);
}
JCExpression result;
if (i == args.length) {
result = makeUnquotedIdent(varName);
} else {
result = args[i];
}
if (statements != null) {
decls.appendList(statements);
}
return make().LetExpr(decls.toList(), result);
}
/*
* Type handling
*/
boolean isBooleanTrue(Declaration decl) {
return decl == loader().getDeclaration("ceylon.language.true", DeclarationType.VALUE);
}
boolean isBooleanFalse(Declaration decl) {
return decl == loader().getDeclaration("ceylon.language.false", DeclarationType.VALUE);
}
/**
* Determines whether the given type is optional.
*/
boolean isOptional(ProducedType type) {
// Note we don't use typeFact().isOptionalType(type) because
// that implements a stricter test used in the type checker.
return typeFact().getNullValueDeclaration().getType().isSubtypeOf(type);
}
boolean isNull(ProducedType type) {
return type.getSupertype(typeFact.getNullDeclaration()) != null;
}
boolean isNullValue(ProducedType type) {
return type.getSupertype(typeFact.getNullValueDeclaration().getTypeDeclaration()) != null;
}
public boolean isVoid(ProducedType type) {
return CodegenUtil.isVoid(type);
}
private boolean isObject(ProducedType type) {
return typeFact.getObjectDeclaration().getType().isExactly(type);
}
public boolean isAlias(ProducedType type) {
return type.getDeclaration().isAlias() || typeFact.getDefiniteType(type).getDeclaration().isAlias();
}
ProducedType simplifyType(ProducedType orgType) {
if(orgType == null)
return null;
ProducedType type = orgType.resolveAliases();
if (isOptional(type)) {
// For an optional type T?:
// - The Ceylon type T? results in the Java type T
type = typeFact().getDefiniteType(type);
if (type.getUnderlyingType() != null) {
// A definite type should not have its underlyingType set so we make a copy
type = type.withoutUnderlyingType();
}
}
TypeDeclaration tdecl = type.getDeclaration();
if (tdecl instanceof UnionType && tdecl.getCaseTypes().size() == 1) {
// Special case when the Union contains only a single CaseType
// FIXME This is not correct! We might lose information about type arguments!
type = tdecl.getCaseTypes().get(0);
} else if (tdecl instanceof IntersectionType) {
java.util.List<ProducedType> satisfiedTypes = tdecl.getSatisfiedTypes();
if (satisfiedTypes.size() == 1) {
// Special case when the Intersection contains only a single SatisfiedType
// FIXME This is not correct! We might lose information about type arguments!
type = satisfiedTypes.get(0);
} else if (satisfiedTypes.size() == 2) {
// special case for T? simplified as T&Object
if (isTypeParameter(satisfiedTypes.get(0)) && isObject(satisfiedTypes.get(1))) {
type = satisfiedTypes.get(0);
}
}
}
return type;
}
ProducedTypedReference getTypedReference(TypedDeclaration decl){
if(decl.getContainer() instanceof TypeDeclaration){
TypeDeclaration containerDecl = (TypeDeclaration) decl.getContainer();
return containerDecl.getType().getTypedMember(decl, Collections.<ProducedType>emptyList());
}
return decl.getProducedTypedReference(null, Collections.<ProducedType>emptyList());
}
ProducedTypedReference nonWideningTypeDecl(ProducedTypedReference typedReference) {
ProducedTypedReference refinedTypedReference = getRefinedDeclaration(typedReference);
if(refinedTypedReference != null){
/*
* We are widening if the type:
* - is not object
* - is erased to object
* - refines a declaration that is not erased to object
*/
ProducedType declType = typedReference.getType();
ProducedType refinedDeclType = refinedTypedReference.getType();
if(declType == null || refinedDeclType == null)
return typedReference;
boolean isWidening = isWidening(declType, refinedDeclType);
if(!isWidening){
// make sure we get the instantiated refined decl
if(refinedDeclType.getDeclaration() instanceof TypeParameter
&& !(declType.getDeclaration() instanceof TypeParameter))
refinedDeclType = nonWideningType(typedReference, refinedTypedReference);
isWidening = isWideningTypeArguments(declType, refinedDeclType, true);
}
if(isWidening)
return refinedTypedReference;
}
return typedReference;
}
/*
* We have several special cases here to find the best non-widening refinement in case of multiple inheritace:
*
* - The first special case is for some decls like None.first, which inherits from ContainerWithFirstElement
* twice: once with Nothing (erased to j.l.Object) and once with Element (a type param). Now, in order to not widen the
* return type it can't be Nothing (j.l.Object), it must be Element (a type param that is not instantiated), because in Java
* a type param refines j.l.Object but not the other way around.
* - The second special case is when implementing an interface first with a non-erased type, then with an erased type. In this
* case we want the refined decl to be the one with the non-erased type.
* - The third special case is when we implement a declaration via multiple super types, without having any refining
* declarations in those supertypes, simply by instantiating a common super type with different type parameters
*/
private ProducedTypedReference getRefinedDeclaration(ProducedTypedReference typedReference) {
TypedDeclaration decl = typedReference.getDeclaration();
TypedDeclaration modelRefinedDecl = (TypedDeclaration)decl.getRefinedDeclaration();
// quick exit
if(decl == modelRefinedDecl)
return null;
if(decl.getContainer() instanceof ClassOrInterface){
// only try to find better if we're erasing to Object and we're not returning a type param
if(willEraseToObject(typedReference.getType())
|| isWideningTypeArguments(decl.getType(), modelRefinedDecl.getType(), true)
&& !isTypeParameter(typedReference.getType())){
ClassOrInterface declaringType = (ClassOrInterface) decl.getContainer();
Set<TypedDeclaration> refinedMembers = getRefinedMembers(declaringType, decl.getName(),
com.redhat.ceylon.compiler.typechecker.model.Util.getSignature(decl), false);
// now we must select a different refined declaration if we refine it more than once
if(refinedMembers.size() > 1){
// first case
for(TypedDeclaration refinedDecl : refinedMembers){
// get the type reference to see if any eventual type param is instantiated in our inheritance of this type/method
ProducedTypedReference refinedTypedReference = getRefinedTypedReference(typedReference, refinedDecl);
// if it is not instantiated, that's the one we're looking for
if(isTypeParameter(refinedTypedReference.getType()))
return refinedTypedReference;
}
// second case
for(TypedDeclaration refinedDecl : refinedMembers){
// get the type reference to see if any eventual type param is instantiated in our inheritance of this type/method
ProducedTypedReference refinedTypedReference = getRefinedTypedReference(typedReference, refinedDecl);
// if we're not erasing this one to Object let's select it
if(!willEraseToObject(refinedTypedReference.getType()) && !isWideningTypeArguments(refinedDecl.getType(), modelRefinedDecl.getType(), true))
return refinedTypedReference;
}
// third case
if(isTypeParameter(modelRefinedDecl.getType())){
// it can happen that we have inherited a method twice from a single refined declaration
// via different supertype instantiations, without having ever refined them in supertypes
// so we try each super type to see if we already have a matching typed reference
// first super type
ProducedType extendedType = declaringType.getExtendedType();
if(extendedType != null){
ProducedTypedReference refinedTypedReference = getRefinedTypedReference(extendedType, modelRefinedDecl);
ProducedType refinedType = refinedTypedReference.getType();
if(!isTypeParameter(refinedType)
&& !willEraseToObject(refinedType))
return refinedTypedReference;
}
// then satisfied interfaces
for(ProducedType satisfiedType : declaringType.getSatisfiedTypes()){
ProducedTypedReference refinedTypedReference = getRefinedTypedReference(satisfiedType, modelRefinedDecl);
ProducedType refinedType = refinedTypedReference.getType();
if(!isTypeParameter(refinedType)
&& !willEraseToObject(refinedType))
return refinedTypedReference;
}
}
}
}
}
return getRefinedTypedReference(typedReference, modelRefinedDecl);
}
// Finds all member declarations (original and refinements) with the
// given name and signature within the given type and it's super
// classes and interfaces
public Set<TypedDeclaration> getRefinedMembers(TypeDeclaration decl,
String name,
java.util.List<ProducedType> signature, boolean ellipsis) {
Set<TypedDeclaration> ret = new HashSet<TypedDeclaration>();
collectRefinedMembers(decl, name, signature, ellipsis,
new HashSet<TypeDeclaration>(), ret);
return ret;
}
private void collectRefinedMembers(TypeDeclaration decl, String name,
java.util.List<ProducedType> signature, boolean ellipsis,
java.util.Set<TypeDeclaration> visited, Set<TypedDeclaration> ret) {
if (visited.contains(decl)) {
return;
}
else {
visited.add(decl);
TypeDeclaration et = decl.getExtendedTypeDeclaration();
if (et!=null) {
collectRefinedMembers(et, name, signature, ellipsis, visited, ret);
}
for (TypeDeclaration st: decl.getSatisfiedTypeDeclarations()) {
collectRefinedMembers(st, name, signature, ellipsis, visited, ret);
}
Declaration found = decl.getDirectMember(name, signature, ellipsis);
if(found != null)
ret.add((TypedDeclaration) found);
}
}
private ProducedTypedReference getRefinedTypedReference(ProducedTypedReference typedReference,
TypedDeclaration refinedDeclaration) {
return getRefinedTypedReference(typedReference.getQualifyingType(), refinedDeclaration);
}
private ProducedTypedReference getRefinedTypedReference(ProducedType qualifyingType,
TypedDeclaration refinedDeclaration) {
TypeDeclaration refinedContainer = (TypeDeclaration)refinedDeclaration.getContainer();
ProducedType refinedContainerType = qualifyingType.getSupertype(refinedContainer);
return refinedDeclaration.getProducedTypedReference(refinedContainerType, Collections.<ProducedType>emptyList());
}
public boolean isWidening(ProducedType declType, ProducedType refinedDeclType) {
return !sameType(syms().ceylonObjectType, declType)
&& willEraseToObject(declType)
&& !willEraseToObject(refinedDeclType);
}
private boolean isWideningTypeArguments(ProducedType declType, ProducedType refinedDeclType, boolean allowSubtypes) {
// make sure we work on simplified types, to avoid stuff like optional or size-1 unions
declType = simplifyType(declType);
refinedDeclType = simplifyType(refinedDeclType);
// special case for type parameters
if(declType.getDeclaration() instanceof TypeParameter
&& refinedDeclType.getDeclaration() instanceof TypeParameter){
// consider them equivalent if they have the same bounds
TypeParameter tp = (TypeParameter) declType.getDeclaration();
TypeParameter refinedTP = (TypeParameter) refinedDeclType.getDeclaration();
if(haveSameBounds(tp, refinedTP))
return false;
// if they don't have the same bounds and we don't allow subtypes then we're widening
if(!allowSubtypes)
return false;
// if we allow subtypes, we're widening if tp is not a subtype of refinedTP
return !tp.getType().isSubtypeOf(refinedTP.getType());
}
if(allowSubtypes){
// if we don't erase to object and we refine something that does, we can't possibly be widening
if((willEraseToObject(refinedDeclType) || willEraseToSequential(refinedDeclType))
&& !willEraseToObject(declType) && !willEraseToSequential(declType))
return false;
// if we have exactly the same type don't bother finding a common ancestor
if(!declType.isExactly(refinedDeclType)){
// check if we can form an informed decision
if(refinedDeclType.getDeclaration() == null)
return true;
// find the instantiation of the refined decl type in the decl type
// special case for optional types: let's find the definite type since
// in java they are equivalent
ProducedType definiteType = typeFact().getDefiniteType(refinedDeclType);
if(definiteType != null)
refinedDeclType = definiteType;
declType = declType.getSupertype(refinedDeclType.getDeclaration());
// could not find common type, we must be widening somehow
if(declType == null)
return true;
}
}
Map<TypeParameter, ProducedType> typeArguments = declType.getTypeArguments();
Map<TypeParameter, ProducedType> refinedTypeArguments = refinedDeclType.getTypeArguments();
for(Entry<TypeParameter, ProducedType> typeArgument : typeArguments.entrySet()){
ProducedType refinedTypeArgument = refinedTypeArguments.get(typeArgument.getKey());
if(refinedTypeArgument == null)
return true; // something fishy here
// check if the type arg is widening due to erasure
if(isWidening(typeArgument.getValue(), refinedTypeArgument))
return true;
// check if the type arg is a subtype, or if its type args are widening
if(isWideningTypeArguments(typeArgument.getValue(), refinedTypeArgument, false))
return true;
}
// so far so good
return false;
}
public boolean haveSameBounds(TypeParameter tp, TypeParameter refinedTP) {
java.util.List<ProducedType> satTP = tp.getSatisfiedTypes();
java.util.List<ProducedType> satRefinedTP = new LinkedList<ProducedType>();
satRefinedTP.addAll(refinedTP.getSatisfiedTypes());
// same number of bounds
if(satTP.size() != satRefinedTP.size())
return false;
// make sure all the bounds are the same
OUT:
for(ProducedType satisfiedType : satTP){
for(ProducedType refinedSatisfiedType : satRefinedTP){
// if we found it, remove it from the second list to not match it again
if(satisfiedType.isExactly(refinedSatisfiedType)){
satRefinedTP.remove(satRefinedTP);
continue OUT;
}
}
// not found
return false;
}
// all bounds are equal
return true;
}
ProducedType nonWideningType(ProducedTypedReference declaration, ProducedTypedReference refinedDeclaration){
final ProducedReference pr;
if (declaration == refinedDeclaration) {
pr = declaration;
} else {
ProducedType refinedType = refinedDeclaration.getType();
// if the refined type is a method TypeParam, use the original decl that will be more correct
if(refinedType.getDeclaration() instanceof TypeParameter
&& refinedType.getDeclaration().getContainer() instanceof Method){
pr = declaration;
} else {
pr = refinedType;
}
}
if (pr.getDeclaration() instanceof Functional
&& Decl.isMpl((Functional)pr.getDeclaration())) {
// Methods with MPL have a Callable return type, not the type of
// the innermost Callable.
return getReturnTypeOfCallable(pr.getFullType());
}
return pr.getType();
}
private ProducedType toPType(com.sun.tools.javac.code.Type t) {
return loader().getType(t.tsym.packge().getQualifiedName().toString(), t.tsym.getQualifiedName().toString(), null);
}
private boolean sameType(Type t1, ProducedType t2) {
return t2 != null && toPType(t1).isExactly(t2);
}
/**
* Determines if a type will be erased to java.lang.Object once converted to Java
* @param type
* @return
*/
boolean willEraseToObject(ProducedType type) {
if(type == null)
return false;
type = simplifyType(type);
TypeDeclaration decl = type.getDeclaration();
// All the following types either are Object or erase to Object
if (decl == typeFact.getObjectDeclaration()
|| decl == typeFact.getIdentifiableDeclaration()
|| decl == typeFact.getBasicDeclaration()
|| decl == typeFact.getNullDeclaration()
|| decl == typeFact.getNullValueDeclaration().getTypeDeclaration()
|| decl == typeFact.getAnythingDeclaration()
|| decl instanceof NothingType) {
return true;
}
// Any Unions and Intersections erase to Object as well
// except for the ones that erase to Sequential
return ((decl instanceof UnionType || decl instanceof IntersectionType)
&& !typeFact().isSequentialType(type));
}
boolean willEraseToPrimitive(ProducedType type) {
return (isCeylonBoolean(type) || isCeylonInteger(type) || isCeylonFloat(type) || isCeylonCharacter(type));
}
boolean willEraseToException(ProducedType type) {
type = simplifyType(type);
return (sameType(syms().ceylonExceptionType, type));
}
boolean willEraseToSequential(ProducedType type) {
type = simplifyType(type);
TypeDeclaration decl = type.getDeclaration();
return (decl instanceof UnionType || decl instanceof IntersectionType)
&& typeFact().isSequentialType(type);
}
// keep in sync with MethodDefinitionBuilder.paramType()
public boolean willEraseToBestBounds(Parameter param) {
ProducedType type = param.getType();
if (typeFact().isUnion(type)
|| typeFact().isIntersection(type)) {
final TypeDeclaration refinedTypeDecl = ((TypedDeclaration)CodegenUtil.getTopmostRefinedDeclaration(param)).getType().getDeclaration();
if (refinedTypeDecl instanceof TypeParameter
&& !refinedTypeDecl.getSatisfiedTypes().isEmpty()) {
return true;
}
}
return false;
}
boolean hasErasure(ProducedType type) {
return hasErasureResolved(type.resolveAliases());
}
private boolean hasErasureResolved(ProducedType type) {
TypeDeclaration declaration = type.getDeclaration();
if(declaration == null)
return false;
if(declaration instanceof UnionType){
UnionType ut = (UnionType) declaration;
java.util.List<ProducedType> caseTypes = ut.getCaseTypes();
// special case for optional types
if(caseTypes.size() == 2){
if(isOptional(caseTypes.get(0)))
return hasErasureResolved(caseTypes.get(1));
if(isOptional(caseTypes.get(1)))
return hasErasureResolved(caseTypes.get(0));
}
// must be erased
return true;
}
if(declaration instanceof IntersectionType){
IntersectionType ut = (IntersectionType) declaration;
java.util.List<ProducedType> satisfiedTypes = ut.getSatisfiedTypes();
// special case for non-optional types
if(satisfiedTypes.size() == 2){
if(isObject(satisfiedTypes.get(0)))
return hasErasureResolved(satisfiedTypes.get(1));
if(isObject(satisfiedTypes.get(1)))
return hasErasureResolved(satisfiedTypes.get(0));
}
// must be erased
return true;
}
// Note: we don't consider types like Anything, Null, Basic, Identifiable as erased because
// they can never be better than Object as far as Java is concerned
// FIXME: what about Nothing then?
// special case for Callable where we stop after the first type param
boolean isCallable = isCeylonCallable(type);
// now check its type parameters
for(ProducedType pt : type.getTypeArgumentList()){
if(hasErasureResolved(pt))
return true;
if(isCallable)
break;
}
// no erasure here
return false;
}
/**
* This method should do the same sort of logic as AbstractTransformer.makeTypeArgs to determine
* that the given type will be turned raw as a return type
*/
boolean isTurnedToRaw(ProducedType type){
return isTurnedToRawResolved(type.resolveAliases());
}
private boolean isTurnedToRawResolved(ProducedType type) {
// if we don't have type arguments we can't be raw
if(type.getTypeArguments().isEmpty())
return false;
// we only go raw if every type param is an erased union/intersection
// special case for Callable where we stop after the first type param
boolean isCallable = isCeylonCallable(type);
boolean everyTypeParameterIsErasedUnionIntersection = true;
for(ProducedType typeArg : type.getTypeArgumentList()){
// skip invalid input
if(typeArg == null)
return false;
everyTypeParameterIsErasedUnionIntersection &= isErasedUnionOrIntersection(typeArg);
// Callable really has a single type arg in Java
if(isCallable)
break;
// don't recurse
}
// we're only raw if every type param is an erased union/intersection
return everyTypeParameterIsErasedUnionIntersection;
}
private boolean isErasedUnionOrIntersection(ProducedType producedType) {
TypeDeclaration typeDeclaration = producedType.getDeclaration();
if(typeDeclaration instanceof UnionType){
UnionType ut = (UnionType) typeDeclaration;
java.util.List<ProducedType> caseTypes = ut.getCaseTypes();
// special case for optional types
if(caseTypes.size() == 2){
if(isNull(caseTypes.get(0))){
return isErasedUnionOrIntersection(caseTypes.get(1));
}else if(isNull(caseTypes.get(1))){
return isErasedUnionOrIntersection(caseTypes.get(0));
}
}
// it is erased unless we turn it into Sequential something
return !willEraseToSequential(producedType);
}
if(typeDeclaration instanceof IntersectionType){
IntersectionType ut = (IntersectionType) typeDeclaration;
java.util.List<ProducedType> satisfiedTypes = ut.getSatisfiedTypes();
// special case for non-optional types
if(satisfiedTypes.size() == 2){
if(isObject(satisfiedTypes.get(0))){
return isErasedUnionOrIntersection(satisfiedTypes.get(1));
}else if(isObject(satisfiedTypes.get(1))){
return isErasedUnionOrIntersection(satisfiedTypes.get(0));
}
}
// it is erased unless we turn it into Sequential something
return !willEraseToSequential(producedType);
}
// we found something which is not erased entirely
return false;
}
boolean isCeylonString(ProducedType type) {
return (sameType(syms().ceylonStringType, type));
}
boolean isCeylonBoolean(ProducedType type) {
return type.isSubtypeOf(typeFact.getBooleanDeclaration().getType())
&& !(type.getDeclaration() instanceof NothingType);
}
boolean isCeylonInteger(ProducedType type) {
return (sameType(syms().ceylonIntegerType, type));
}
boolean isCeylonFloat(ProducedType type) {
return (sameType(syms().ceylonFloatType, type));
}
boolean isCeylonCharacter(ProducedType type) {
return (sameType(syms().ceylonCharacterType, type));
}
boolean isCeylonArray(ProducedType type) {
return type.getSupertype(typeFact.getArrayDeclaration()) != null;
}
boolean isCeylonObject(ProducedType type) {
return sameType(syms().ceylonObjectType, type);
}
boolean isCeylonBasicType(ProducedType type) {
return (isCeylonString(type) || isCeylonBoolean(type) || isCeylonInteger(type) || isCeylonFloat(type) || isCeylonCharacter(type));
}
boolean isCeylonCallable(ProducedType type) {
return type.getDeclaration().getUnit().isCallableType(type);
}
boolean isExactlySequential(ProducedType type) {
return typeFact().getDefiniteType(type).getDeclaration() == typeFact.getSequentialDeclaration();
}
/*
* Java Type creation
*/
/** For use in {@code implements} clauses. */
static final int JT_SATISFIES = 1 << 0;
/** For use in {@code extends} clauses. */
static final int JT_EXTENDS = 1 << 1;
/** For use when a primitive type won't do. */
static final int JT_NO_PRIMITIVES = 1 << 2;
/** For generating a type without type arguments. */
static final int JT_RAW = 1 << 3;
/** For use in {@code catch} statements. */
static final int JT_CATCH = 1 << 4;
/**
* Generate a 'small' primitive type (if the type is primitive and has a
* small variant).
*/
static final int JT_SMALL = 1 << 5;
/** For use in {@code new} expressions. */
static final int JT_CLASS_NEW = 1 << 6;
/** Generates the Java type of the companion class of the given type */
static final int JT_COMPANION = 1 << 7;
static final int JT_NON_QUALIFIED = 1 << 8;
private static final int __JT_RAW_TP_BOUND = 1 << 9;
/**
* If the type is a type parameter, return the Java type for its upper bound.
* Implies {@link #JT_RAW}
*/
static final int JT_RAW_TP_BOUND = JT_RAW | __JT_RAW_TP_BOUND;
private static final int __JT_TYPE_ARGUMENT = 1 << 10;
/** For use when generating a type argument. Implies {@code JT_NO_PRIMITIVES} */
static final int JT_TYPE_ARGUMENT = JT_NO_PRIMITIVES | __JT_TYPE_ARGUMENT;
/**
* This function is used solely for method return types and parameters
*/
JCExpression makeJavaType(TypedDeclaration typeDecl, ProducedType type, int flags) {
if (typeDecl instanceof FunctionalParameter) {
FunctionalParameter p = (FunctionalParameter)typeDecl;
ProducedType pt = type;
for (int ii = 1; ii < p.getParameterLists().size(); ii++) {
pt = typeFact().getCallableType(pt);
}
return makeJavaType(typeFact().getCallableType(pt), flags);
} else {
boolean usePrimitives = CodegenUtil.isUnBoxed(typeDecl);
return makeJavaType(type, flags | (usePrimitives ? 0 : AbstractTransformer.JT_NO_PRIMITIVES));
}
}
JCExpression makeJavaType(ProducedType producedType) {
return makeJavaType(producedType, 0);
}
JCExpression makeJavaType(ProducedType type, final int flags) {
if(type == null
|| type.getDeclaration() instanceof UnknownType)
return make().Erroneous();
// resolve aliases
type = type.resolveAliases();
if ((flags & __JT_RAW_TP_BOUND) != 0
&& type.getDeclaration() instanceof TypeParameter) {
type = ((TypeParameter)type.getDeclaration()).getExtendedType();
}
// ERASURE
if (willEraseToObject(type)) {
// For an erased type:
// - Any of the Ceylon types Anything, Object, Null,
// Basic, and Nothing result in the Java type Object
// For any other union type U|V (U nor V is Optional):
// - The Ceylon type U|V results in the Java type Object
if ((flags & JT_SATISFIES) != 0) {
return null;
} else {
return make().Type(syms().objectType);
}
} else if (willEraseToSequential(type)) {
type = typeFact().getDefiniteType(type).getSupertype(typeFact().getSequentialDeclaration());
} else if (willEraseToException(type)) {
if ((flags & JT_CLASS_NEW) != 0
|| (flags & JT_EXTENDS) != 0) {
return makeIdent(syms().ceylonExceptionType);
} else if ((flags & JT_CATCH) != 0) {
return make().Type(syms().exceptionType);
} else {
return make().Type(syms().throwableType);
}
} else if ((flags & (JT_SATISFIES | JT_EXTENDS | JT_NO_PRIMITIVES | JT_CLASS_NEW)) == 0
&& (!isOptional(type) || isJavaString(type))) {
if (isCeylonString(type) || isJavaString(type)) {
return make().Type(syms().stringType);
} else if (isCeylonBoolean(type)) {
return make().TypeIdent(TypeTags.BOOLEAN);
} else if (isCeylonInteger(type)) {
if ("byte".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.BYTE);
} else if ("short".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.SHORT);
} else if ((flags & JT_SMALL) != 0 || "int".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.INT);
} else {
return make().TypeIdent(TypeTags.LONG);
}
} else if (isCeylonFloat(type)) {
if ((flags & JT_SMALL) != 0 || "float".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.FLOAT);
} else {
return make().TypeIdent(TypeTags.DOUBLE);
}
} else if (isCeylonCharacter(type)) {
if ("char".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.CHAR);
} else {
return make().TypeIdent(TypeTags.INT);
}
}
} else if (isCeylonBoolean(type)
&& !isTypeParameter(type)) {
//&& (flags & TYPE_ARGUMENT) == 0){
// special case to get rid of $true and $false types
type = typeFact.getBooleanDeclaration().getType();
}
JCExpression jt = null;
ProducedType simpleType = simplifyType(type);
java.util.List<ProducedType> qualifyingTypes = new java.util.ArrayList<ProducedType>();
ProducedType qType = simpleType;
boolean hasTypeParameters = false;
while (qType != null) {
hasTypeParameters |= !qType.getTypeArguments().isEmpty();
qualifyingTypes.add(qType);
qType = qType.getQualifyingType();
}
int firstQualifyingTypeWithTypeParameters = qualifyingTypes.size() - 1;
// find the first static one, from the right to the left
for(ProducedType pt : qualifyingTypes){
TypeDeclaration declaration = pt.getDeclaration();
if(Decl.isStatic(declaration)){
break;
}
firstQualifyingTypeWithTypeParameters--;
}
if(firstQualifyingTypeWithTypeParameters < 0)
firstQualifyingTypeWithTypeParameters = 0;
// put them in outer->inner order
Collections.reverse(qualifyingTypes);
if (((flags & JT_RAW) == 0) && hasTypeParameters) {
// special case for interfaces because we pull them into toplevel types
if(Decl.isCeylon(simpleType.getDeclaration())
&& qualifyingTypes.size() > 1
&& simpleType.getDeclaration() instanceof Interface){
JCExpression baseType;
TypeDeclaration tdecl = simpleType.getDeclaration();
// collect all the qualifying type args we'd normally have
java.util.List<TypeParameter> qualifyingTypeParameters = new java.util.ArrayList<TypeParameter>();
java.util.Map<TypeParameter, ProducedType> qualifyingTypeArguments = new java.util.HashMap<TypeParameter, ProducedType>();
for (ProducedType qualifiedType : qualifyingTypes) {
Map<TypeParameter, ProducedType> tas = qualifiedType.getTypeArguments();
java.util.List<TypeParameter> tps = qualifiedType.getDeclaration().getTypeParameters();
if (tps != null) {
qualifyingTypeParameters.addAll(tps);
qualifyingTypeArguments.putAll(tas);
}
}
ListBuffer<JCExpression> typeArgs = makeTypeArgs(isCeylonCallable(simpleType),
flags,
qualifyingTypeArguments, qualifyingTypeParameters);
if (isCeylonCallable(type) &&
(flags & JT_CLASS_NEW) != 0) {
baseType = makeIdent(syms().ceylonAbstractCallableType);
} else {
baseType = naming.makeDeclarationName(tdecl, DeclNameFlag.QUALIFIED);
}
if (typeArgs != null && typeArgs.size() > 0) {
jt = make().TypeApply(baseType, typeArgs.toList());
} else {
jt = baseType;
}
}else if((flags & JT_NON_QUALIFIED) == 0){
int index = 0;
for (ProducedType qualifyingType : qualifyingTypes) {
jt = makeParameterisedType(qualifyingType, type, flags, jt, qualifyingTypes, firstQualifyingTypeWithTypeParameters, index);
index++;
}
}else{
jt = makeParameterisedType(type, type, flags, jt, qualifyingTypes, 0, 0);
}
} else {
TypeDeclaration tdecl = simpleType.getDeclaration();
// For an ordinary class or interface type T:
// - The Ceylon type T results in the Java type T
if(tdecl instanceof TypeParameter)
jt = makeQuotedIdent(tdecl.getName());
// don't use underlying type if we want no primitives
else if((flags & (JT_SATISFIES | JT_NO_PRIMITIVES)) != 0 || simpleType.getUnderlyingType() == null){
jt = naming.makeDeclarationName(tdecl, jtFlagsToDeclNameOpts(flags));
}else
jt = makeQuotedFQIdent(simpleType.getUnderlyingType());
}
return (jt != null) ? jt : makeErroneous();
}
public JCExpression makeParameterisedType(ProducedType type, ProducedType generalType, final int flags,
JCExpression qualifyingExpression, java.util.List<ProducedType> qualifyingTypes,
int firstQualifyingTypeWithTypeParameters, int index) {
JCExpression baseType;
TypeDeclaration tdecl = type.getDeclaration();
ListBuffer<JCExpression> typeArgs = null;
if(index >= firstQualifyingTypeWithTypeParameters)
typeArgs = makeTypeArgs(
type,
//tdecl,
flags);
if (isCeylonCallable(generalType) &&
(flags & JT_CLASS_NEW) != 0) {
baseType = makeIdent(syms().ceylonAbstractCallableType);
} else if (index == 0) {
// in Ceylon we'd move the nested decl to a companion class
// but in Java we just don't have type params to the qualifying type if the
// qualified type is static
if (tdecl instanceof Interface
&& qualifyingTypes.size() > 1
&& firstQualifyingTypeWithTypeParameters == 0) {
baseType = naming.makeCompanionClassName(tdecl);
} else {
baseType = naming.makeDeclarationName(tdecl, jtFlagsToDeclNameOpts(flags));
}
} else {
baseType = naming.makeDeclName(qualifyingExpression, tdecl,
jtFlagsToDeclNameOpts(flags
| JT_NON_QUALIFIED
| (type.getDeclaration() instanceof Interface ? JT_COMPANION : 0)));
}
if (typeArgs != null && typeArgs.size() > 0) {
qualifyingExpression = make().TypeApply(baseType, typeArgs.toList());
} else {
qualifyingExpression = baseType;
}
return qualifyingExpression;
}
private ListBuffer<JCExpression> makeTypeArgs(
ProducedType simpleType,
int flags) {
Map<TypeParameter, ProducedType> tas = simpleType.getTypeArguments();
java.util.List<TypeParameter> tps = simpleType.getDeclaration().getTypeParameters();
return makeTypeArgs(isCeylonCallable(simpleType), flags, tas, tps);
}
private ListBuffer<JCExpression> makeTypeArgs(boolean isCeylonCallable,
int flags, Map<TypeParameter, ProducedType> tas,
java.util.List<TypeParameter> tps) {
boolean onlyErasedUnions = true;
ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>();
for (TypeParameter tp : tps) {
ProducedType ta = tas.get(tp);
boolean isDependedOn = false;
// Partial hack for https://github.com/ceylon/ceylon-compiler/issues/920
// We need to find if a covariant param has other type parameters with bounds to this one
// For example if we have "Foo<out A, out B>() given B satisfies A" then we can't generate
// the following signature: "Foo<? extends Object, ? extends String" because the subtype of
// String that can satisfy B is not necessarily the subtype of Object that we used for A.
if(tp.isCovariant()){
for(TypeParameter otherTypeParameter : tps){
// skip this very type parameter
if(otherTypeParameter == tp)
continue;
if(dependsOnTypeParameter(otherTypeParameter, tp)){
isDependedOn = true;
break;
}
}
}
// Null will claim to be optional, but if we get its non-null type we will land with Nothing, which is not what
// we want, so we make sure it's not Null
if (isOptional(ta) && !isNull(ta)) {
// For an optional type T?:
// - The Ceylon type Foo<T?> results in the Java type Foo<T>.
ta = getNonNullType(ta);
}
if (typeFact().isUnion(ta) || typeFact().isIntersection(ta)) {
// For any other union type U|V (U nor V is Optional):
// - The Ceylon type Foo<U|V> results in the raw Java type Foo.
// For any other intersection type U&V:
// - The Ceylon type Foo<U&V> results in the raw Java type Foo.
ProducedType listType = typeFact().getDefiniteType(ta).getSupertype(typeFact().getSequentialDeclaration());
// don't break if the union type is erased to something better than Object
if(listType == null){
// use raw types if:
// - we're calling a constructor
// - we're not in a type argument (when used as type arguments raw types have more constraint than at the toplevel)
// or we're in an extends or satisfies and the type parameter is a self type
if((flags & JT_CLASS_NEW) != 0
|| ((flags & (JT_EXTENDS | JT_SATISFIES)) != 0 && tp.getSelfTypedDeclaration() != null)){
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
typeArgs = null;
break;
} else if((flags & (__JT_TYPE_ARGUMENT | JT_EXTENDS | JT_SATISFIES)) != 0) {
onlyErasedUnions = false;
}
// otherwise just go on
}else{
ta = listType;
onlyErasedUnions = false;
}
} else {
onlyErasedUnions = false;
}
if (isCeylonBoolean(ta)
&& !isTypeParameter(ta)) {
ta = typeFact.getBooleanDeclaration().getType();
}
JCExpression jta;
if (sameType(syms().ceylonAnythingType, ta)) {
// For the root type Void:
if ((flags & (JT_SATISFIES | JT_EXTENDS)) != 0) {
// - The Ceylon type Foo<Void> appearing in an extends or satisfies
// clause results in the Java raw type Foo<Object>
jta = make().Type(syms().objectType);
} else {
// - The Ceylon type Foo<Void> appearing anywhere else results in the Java type
// - Foo<Object> if Foo<T> is invariant in T
// - Foo<?> if Foo<T> is covariant in T, or
// - Foo<Object> if Foo<T> is contravariant in T
if (tp.isContravariant()) {
jta = make().Type(syms().objectType);
} else if (tp.isCovariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta, flags | JT_TYPE_ARGUMENT));
} else {
jta = make().Type(syms().objectType);
}
}
} else if (ta.getDeclaration() instanceof NothingType
// if we're in a type argument, extends or satisfies already, union and intersection types should
// use the same erasure rules as bottom: prefer wildcards
|| ((flags & (__JT_TYPE_ARGUMENT | JT_EXTENDS | JT_SATISFIES)) != 0
&& (typeFact().isUnion(ta) || typeFact().isIntersection(ta)))) {
// For the bottom type Bottom:
if ((flags & (JT_CLASS_NEW)) != 0) {
// - The Ceylon type Foo<Bottom> or Foo<erased_type> appearing in an instantiation
// clause results in the Java raw type Foo
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
typeArgs = null;
break;
} else {
// - The Ceylon type Foo<Bottom> appearing in an extends or satisfies location results in the Java type
// Foo<Object> (see https://github.com/ceylon/ceylon-compiler/issues/633 for why)
if((flags & (JT_SATISFIES | JT_EXTENDS)) != 0){
if (ta.getDeclaration() instanceof NothingType) {
jta = make().Type(syms().objectType);
} else {
if (!tp.getSatisfiedTypes().isEmpty()) {
// union or intersection: Use the common upper bound of the types
jta = makeJavaType(tp.getSatisfiedTypes().get(0), JT_TYPE_ARGUMENT);
} else {
jta = make().Type(syms().objectType);
}
}
}else if (ta.getDeclaration() instanceof NothingType){
// - The Ceylon type Foo<Bottom> appearing anywhere else results in the Java type
// - Foo<? super Object> if Foo is contravariant in T, or
// - Foo<? extends Object> if Foo is covariant in T and not depended on by other type params
// - Foo<Object> otherwise
// this is more correct than Foo<?> because a method returning Foo<?> could never override a method returning Foo<Object>
// see https://github.com/ceylon/ceylon-compiler/issues/1003
if (tp.isContravariant()) {
- jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), make().Type(syms().objectType));
+ typeArgs = null;
+ break;
} else if (tp.isCovariant() && !isDependedOn) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), make().Type(syms().objectType));
} else {
jta = make().Type(syms().objectType);
}
}else{
// - The Ceylon type Foo<T> appearing anywhere else results in the Java type
// - Foo<T> if Foo is invariant in T,
// - Foo<? extends T> if Foo is covariant in T, or
// - Foo<? super T> if Foo is contravariant in T
if (((flags & JT_CLASS_NEW) == 0) && tp.isContravariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), makeJavaType(ta, JT_TYPE_ARGUMENT));
} else if (((flags & JT_CLASS_NEW) == 0) && tp.isCovariant() && !isDependedOn) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), makeJavaType(ta, JT_TYPE_ARGUMENT));
} else {
jta = makeJavaType(ta, JT_TYPE_ARGUMENT);
}
}
}
} else {
// For an ordinary class or interface type T:
if ((flags & (JT_SATISFIES | JT_EXTENDS)) != 0) {
// - The Ceylon type Foo<T> appearing in an extends or satisfies clause
// results in the Java type Foo<T>
jta = makeJavaType(ta, JT_TYPE_ARGUMENT);
} else {
// - The Ceylon type Foo<T> appearing anywhere else results in the Java type
// - Foo<T> if Foo is invariant in T,
// - Foo<? extends T> if Foo is covariant in T, or
// - Foo<? super T> if Foo is contravariant in T
if (((flags & JT_CLASS_NEW) == 0) && tp.isContravariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), makeJavaType(ta, JT_TYPE_ARGUMENT));
} else if (((flags & JT_CLASS_NEW) == 0) && tp.isCovariant() && !isDependedOn) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), makeJavaType(ta, JT_TYPE_ARGUMENT));
} else {
jta = makeJavaType(ta, JT_TYPE_ARGUMENT);
}
}
}
typeArgs.add(jta);
if (isCeylonCallable) {
// In the runtime Callable only has a single type param
break;
}
}
if (onlyErasedUnions) {
typeArgs = null;
}
return typeArgs;
}
private ProducedType getNonNullType(ProducedType pt) {
// typeFact().getDefiniteType() intersects with Object, which isn't
// always right for working with the java type system.
if (typeFact().getAnythingDeclaration().equals(pt.getDeclaration())) {
pt = typeFact().getObjectDeclaration().getType();
}
else {
pt = pt.eliminateNull();
}
return pt;
}
private boolean isJavaString(ProducedType type) {
return "java.lang.String".equals(type.getUnderlyingType());
}
private ClassDefinitionBuilder ccdb;
ClassDefinitionBuilder current() {
return ((AbstractTransformer)gen()).ccdb;
}
ClassDefinitionBuilder replace(ClassDefinitionBuilder ccdb) {
ClassDefinitionBuilder result = ((AbstractTransformer)gen()).ccdb;
((AbstractTransformer)gen()).ccdb = ccdb;
return result;
}
private DeclNameFlag[] jtFlagsToDeclNameOpts(int flags) {
java.util.List<DeclNameFlag> args = new LinkedList<DeclNameFlag>();
if ((flags & JT_COMPANION) != 0) {
args.add(DeclNameFlag.COMPANION);
}
if ((flags & JT_NON_QUALIFIED) == 0) {
args.add(DeclNameFlag.QUALIFIED);
}
DeclNameFlag[] opts = args.toArray(new DeclNameFlag[args.size()]);
return opts;
}
/**
* Gets the first type parameter from the type model representing a
* {@code ceylon.language.Callable<Result, ParameterTypes...>}.
* @param typeModel A {@code ceylon.language.Callable<Result, ParameterTypes...>}.
* @return The result type of the {@code Callable}.
*/
ProducedType getReturnTypeOfCallable(ProducedType typeModel) {
Assert.that(isCeylonCallable(typeModel), "Expected Callable<...>, but was " + typeModel);
return typeModel.getTypeArgumentList().get(0);
}
ProducedType getParameterTypeOfCallable(ProducedType callableType, int parameter) {
Assert.that(isCeylonCallable(callableType));
ProducedType sequentialType = removeDefaultedCallableParameter(callableType.getTypeArgumentList().get(1));
for (int ii = 0; ii < parameter; ii++) {
sequentialType = removeDefaultedCallableParameter(sequentialType.getTypeArgumentList().get(2));
}
TypeDeclaration decl = sequentialType.getDeclaration();
if (decl.equals(typeFact().getTupleDeclaration())) {
return sequentialType.getTypeArgumentList().get(1);
} else if (decl.equals(typeFact().getEmptyDeclaration())) {
// FIXME: this one is just weird
return decl.getType();
} else if (decl.equals(typeFact().getSequentialDeclaration())) {
return sequentialType;//Sequence|Empty (i.e. a ...)
}
throw Assert.fail(""+decl);
}
private ProducedType removeDefaultedCallableParameter(ProducedType type) {
TypeDeclaration decl = type.getDeclaration();
if(decl instanceof UnionType == false)
return type;
java.util.List<ProducedType> cts = decl.getCaseTypes();
if (cts.size()==2) {
TypeDeclaration lc = cts.get(0).getDeclaration();
if (lc instanceof Interface &&
lc.equals(typeFact().getEmptyDeclaration())) {
return cts.get(1);
}
TypeDeclaration rc = cts.get(1).getDeclaration();
if (lc instanceof Interface &&
rc.equals(typeFact().getEmptyDeclaration())) {
return cts.get(0);
}
}
return type;
}
private boolean isDefaultedCallableParameter(ProducedType type) {
TypeDeclaration decl = type.getDeclaration();
if(decl instanceof UnionType == false)
return false;
java.util.List<ProducedType> cts = decl.getCaseTypes();
if (cts.size()==2) {
TypeDeclaration lc = cts.get(0).getDeclaration();
if (lc instanceof Interface &&
lc.equals(typeFact().getEmptyDeclaration())) {
return true;
}
TypeDeclaration rc = cts.get(1).getDeclaration();
if (lc instanceof Interface &&
rc.equals(typeFact().getEmptyDeclaration())) {
return true;
}
}
return false;
}
int getNumParametersOfCallable(ProducedType callableType) {
Assert.that(isCeylonCallable(callableType));
ProducedType sequentialType = removeDefaultedCallableParameter(callableType.getTypeArgumentList().get(1));
int num = 0;
while (sequentialType.getSupertype(typeFact().getTupleDeclaration()) != null
&& sequentialType.getTypeArgumentList().size() == 3) {
num++;
sequentialType = removeDefaultedCallableParameter(sequentialType.getTypeArgumentList().get(2));
}
// is is sequential?
if(sequentialType.getSupertype(typeFact().getTupleDeclaration()) == null
&& sequentialType.getSupertype(typeFact().getEmptyDeclaration()) == null)
num++;
return num;
}
boolean isVariadicCallable(ProducedType callableType) {
Assert.that(isCeylonCallable(callableType));
ProducedType sequentialType = removeDefaultedCallableParameter(callableType.getTypeArgumentList().get(1));
while (sequentialType.getSupertype(typeFact().getTupleDeclaration()) != null
&& sequentialType.getTypeArgumentList().size() == 3) {
sequentialType = removeDefaultedCallableParameter(sequentialType.getTypeArgumentList().get(2));
}
// it's variadic if it's not a Tuple and not empty
return sequentialType.getSupertype(typeFact().getTupleDeclaration()) == null
&& sequentialType.getSupertype(typeFact().getEmptyDeclaration()) == null;
}
public int getMinimumParameterCountForCallable(ProducedType callableType) {
Assert.that(isCeylonCallable(callableType));
ProducedType sequentialType = callableType.getTypeArgumentList().get(1);
int count = 0;
if(isDefaultedCallableParameter(sequentialType))
return count;
while (sequentialType.getSupertype(typeFact().getTupleDeclaration()) != null
&& sequentialType.getTypeArgumentList().size() == 3) {
count++;
sequentialType = sequentialType.getTypeArgumentList().get(2);
if(isDefaultedCallableParameter(sequentialType))
return count;
}
return count;
}
/**
* <p>Gets the type of the given functional
* (ignoring parameter types) according to
* the functionals parameter lists. The result is always a
* {@code Callable} of some kind (because Functionals always have
* at least one parameter list).</p>
*
* <p>For example:</p>
* <table>
* <tbody>
* <tr><th>functional</th><th>functionalType(functional)</th></tr>
* <tr><td><code>String m()</code></td><td><code>Callable<String></code></td></tr>
* <tr><td><code>String m()()</code></td><td><code>Callable<Callable<String>></code></td></tr>
* </tbody>
* </table>
*/
ProducedType functionalType(Functional model) {
return typeFact().getCallableType(functionalReturnType(model));
}
/**
* <p>Gets the return type of the given functional (ignoring parameter
* types) according to the functionals parameter lists. If the functional
* has multiple parameter lists the return type will be a
* {@code Callable}.</p>
*
* <p>For example:</p>
* <table>
* <tbody>
* <tr><th>functional</th><th>functionalReturnType(functional)</th></tr>
* <tr><td><code>String m()</code></td><td><code>String</code></td></tr>
* <tr><td><code>String m()()</code></td><td><code>Callable<String></code></td></tr>
* </tbody>
* </table>
*/
ProducedType functionalReturnType(Functional model) {
ProducedType callableType = model.getType();
for (int ii = 1; ii < model.getParameterLists().size(); ii++) {
callableType = typeFact().getCallableType(callableType);
}
return callableType;
}
/**
* Return the upper bound of any type parameter, instead of the type
* parameter itself
*/
static final int TP_TO_BOUND = 1<<0;
/**
* Return the type of the sequenced parameter (T[]) rather than its element type (T)
*/
static final int TP_SEQUENCED_TYPE = 1<<1;
ProducedType getTypeForParameter(Parameter parameter, ProducedReference producedReference, int flags) {
boolean functional = parameter instanceof FunctionalParameter;
if (producedReference == null) {
return parameter.getType();
}
final ProducedTypedReference producedTypedReference = producedReference.getTypedParameter(parameter);
final ProducedType type = functional ? producedTypedReference.getFullType() : producedTypedReference.getType();
final TypedDeclaration producedParameterDecl = producedTypedReference.getDeclaration();
final ProducedType declType = producedParameterDecl.getType();
// be more resilient to upstream errors
if(declType == null)
return typeFact.getUnknownType();
final TypeDeclaration declTypeDecl = declType.getDeclaration();
if(isJavaVariadic(parameter) && (flags & TP_SEQUENCED_TYPE) == 0){
// type of param must be Iterable<T>
ProducedType elementType = typeFact.getIteratedType(type);
if(elementType == null){
log.error("ceylon", "Invalid type for Java variadic parameter: "+type.getProducedTypeQualifiedName());
return type;
}
return elementType;
}
if (type.getDeclaration() instanceof ClassOrInterface) {
// Explicit type parameter
return type;
} else if (declTypeDecl instanceof ClassOrInterface) {
return declType;
} else if ((declTypeDecl instanceof TypeParameter)
&& (flags & TP_TO_BOUND) != 0) {
if (!declTypeDecl.getSatisfiedTypes().isEmpty()) {
// use upper bound
ProducedType upperBound = declTypeDecl.getSatisfiedTypes().get(0);
// make sure we apply the type arguments
return upperBound.substitute(producedReference.getTypeArguments());
}
} else if (willEraseToSequential(declType)) {
// Erasure: If the declType would be Sequential<Element>
// treat the parameter type as Sequential<Element>, because that's all
// Java will see.
ProducedType erasedType = typeFact().getDefiniteType(declType).getSupertype(typeFact().getSequentialDeclaration());
return erasedType.substitute(producedReference.getTypeArguments());
}
return type;
}
private boolean isJavaVariadic(Parameter parameter) {
return parameter.isSequenced()
&& parameter.getContainer() instanceof Method
&& isJavaMethod((Method) parameter.getContainer());
}
boolean isJavaMethod(Method method) {
ClassOrInterface container = Decl.getClassOrInterfaceContainer(method);
return container != null && !Decl.isCeylon(container);
}
boolean isJavaCtor(Class cls) {
return !Decl.isCeylon(cls);
}
ProducedType getTypeForFunctionalParameter(FunctionalParameter fp) {
return fp.getProducedTypedReference(null, java.util.Collections.<ProducedType>emptyList()).getFullType();
}
/*
* Annotation generation
*/
List<JCAnnotation> makeAtOverride() {
return List.<JCAnnotation> of(make().Annotation(makeIdent(syms().overrideType), List.<JCExpression> nil()));
}
boolean checkCompilerAnnotations(Tree.Declaration decl){
boolean old = gen().disableModelAnnotations;
if(CodegenUtil.hasCompilerAnnotation(decl, "nomodel"))
gen().disableModelAnnotations = true;
return old;
}
void resetCompilerAnnotations(boolean value){
gen().disableModelAnnotations = value;
}
private List<JCAnnotation> makeModelAnnotation(Type annotationType, List<JCExpression> annotationArgs) {
if (gen().disableModelAnnotations)
return List.nil();
return List.of(make().Annotation(makeIdent(annotationType), annotationArgs));
}
private List<JCAnnotation> makeModelAnnotation(Type annotationType) {
return makeModelAnnotation(annotationType, List.<JCExpression>nil());
}
List<JCAnnotation> makeAtCeylon() {
JCExpression majorAttribute = make().Assign(naming.makeUnquotedIdent("major"), make().Literal(Versions.JVM_BINARY_MAJOR_VERSION));
List<JCExpression> annotationArgs;
if(Versions.JVM_BINARY_MINOR_VERSION != 0){
JCExpression minorAttribute = make().Assign(naming.makeUnquotedIdent("minor"), make().Literal(Versions.JVM_BINARY_MINOR_VERSION));
annotationArgs = List.<JCExpression>of(majorAttribute, minorAttribute);
}else{
// keep the minor implicit value of 0 to reduce bytecode size
annotationArgs = List.<JCExpression>of(majorAttribute);
}
return makeModelAnnotation(syms().ceylonAtCeylonType, annotationArgs);
}
/** Returns a ListBuffer with assignment expressions for the doc, license and by arguments, as well as name,
* to be used in an annotation which requires them (such as Module and Package) */
ListBuffer<JCExpression> getLicenseAuthorsDocAnnotationArguments(String name, java.util.List<Annotation> anns) {
ListBuffer<JCExpression> authors = new ListBuffer<JCTree.JCExpression>();
ListBuffer<JCExpression> res = new ListBuffer<JCExpression>();
res.add(make().Assign(naming.makeUnquotedIdent("name"), make().Literal(name)));
for (Annotation a : anns) {
if (a.getPositionalArguments() != null && !a.getPositionalArguments().isEmpty()) {
if (a.getName().equals("doc")) {
res.add(make().Assign(naming.makeUnquotedIdent("doc"),
make().Literal(a.getPositionalArguments().get(0))));
} else if (a.getName().equals("license")) {
res.add(make().Assign(naming.makeUnquotedIdent("license"),
make().Literal(a.getPositionalArguments().get(0))));
} else if (a.getName().equals("by")) {
for (String author : a.getPositionalArguments()) {
authors.add(make().Literal(author));
}
}
}
}
if (!authors.isEmpty()) {
res.add(make().Assign(naming.makeUnquotedIdent("by"), make().NewArray(null, null, authors.toList())));
}
return res;
}
List<JCAnnotation> makeAtModule(Module module) {
ListBuffer<JCExpression> imports = new ListBuffer<JCTree.JCExpression>();
for(ModuleImport dependency : module.getImports()){
Module dependencyModule = dependency.getModule();
// do not include the implicit language module as a dependency
if(dependencyModule.getNameAsString().equals("ceylon.language"))
continue;
JCExpression dependencyName = make().Assign(naming.makeUnquotedIdent("name"),
make().Literal(dependencyModule.getNameAsString()));
JCExpression dependencyVersion = null;
if(dependencyModule.getVersion() != null)
dependencyVersion = make().Assign(naming.makeUnquotedIdent("version"),
make().Literal(dependencyModule.getVersion()));
List<JCExpression> spec;
if(dependencyVersion != null)
spec = List.<JCExpression>of(dependencyName, dependencyVersion);
else
spec = List.<JCExpression>of(dependencyName);
if (Util.getAnnotation(dependency, "export") != null) {
JCExpression exported = make().Assign(naming.makeUnquotedIdent("export"), make().Literal(true));
spec = spec.append(exported);
}
if (Util.getAnnotation(dependency, "optional") != null) {
JCExpression exported = make().Assign(naming.makeUnquotedIdent("optional"), make().Literal(true));
spec = spec.append(exported);
}
JCAnnotation atImport = make().Annotation(makeIdent(syms().ceylonAtImportType), spec);
imports.add(atImport);
}
ListBuffer<JCExpression> annotationArgs = getLicenseAuthorsDocAnnotationArguments(
module.getNameAsString(), module.getAnnotations());
annotationArgs.add(make().Assign(naming.makeUnquotedIdent("version"), make().Literal(module.getVersion())));
annotationArgs.add(make().Assign(naming.makeUnquotedIdent("dependencies"),
make().NewArray(null, null, imports.toList())));
return makeModelAnnotation(syms().ceylonAtModuleType, annotationArgs.toList());
}
List<JCAnnotation> makeAtPackage(Package pkg) {
ListBuffer<JCExpression> annotationArgs = getLicenseAuthorsDocAnnotationArguments(
pkg.getNameAsString(), pkg.getAnnotations());
annotationArgs.add(make().Assign(naming.makeUnquotedIdent("shared"), makeBoolean(pkg.isShared())));
return makeModelAnnotation(syms().ceylonAtPackageType, annotationArgs.toList());
}
List<JCAnnotation> makeAtName(String name) {
return makeModelAnnotation(syms().ceylonAtNameType, List.<JCExpression>of(make().Literal(name)));
}
List<JCAnnotation> makeAtAlias(ProducedType type) {
String name = serialiseTypeSignature(type);
return makeModelAnnotation(syms().ceylonAtAliasType, List.<JCExpression>of(make().Literal(name)));
}
List<JCAnnotation> makeAtTypeAlias(ProducedType type) {
String name = serialiseTypeSignature(type);
return makeModelAnnotation(syms().ceylonAtTypeAliasType, List.<JCExpression>of(make().Literal(name)));
}
final JCAnnotation makeAtTypeParameter(String name, java.util.List<ProducedType> satisfiedTypes, java.util.List<ProducedType> caseTypes,
boolean covariant, boolean contravariant, ProducedType defaultValue) {
ListBuffer<JCExpression> attributes = new ListBuffer<JCExpression>();
// name
attributes.add(make().Assign(naming.makeUnquotedIdent("value"), make().Literal(name)));
// variance
String variance = "NONE";
if(covariant)
variance = "OUT";
else if(contravariant)
variance = "IN";
JCExpression varianceAttribute = make().Assign(naming.makeUnquotedIdent("variance"),
make().Select(makeIdent(syms().ceylonVarianceType), names().fromString(variance)));
attributes.add(varianceAttribute);
// upper bounds
ListBuffer<JCExpression> upperBounds = new ListBuffer<JCTree.JCExpression>();
for(ProducedType satisfiedType : satisfiedTypes){
String type = serialiseTypeSignature(satisfiedType);
upperBounds.append(make().Literal(type));
}
JCExpression satisfiesAttribute = make().Assign(naming.makeUnquotedIdent("satisfies"),
make().NewArray(null, null, upperBounds.toList()));
attributes.add(satisfiesAttribute);
// case types
ListBuffer<JCExpression> caseTypesExpressions = new ListBuffer<JCTree.JCExpression>();
if(caseTypes != null){
for(ProducedType caseType : caseTypes){
String type = serialiseTypeSignature(caseType);
caseTypesExpressions.append(make().Literal(type));
}
}
JCExpression caseTypeAttribute = make().Assign(naming.makeUnquotedIdent("caseTypes"),
make().NewArray(null, null, caseTypesExpressions.toList()));
attributes.add(caseTypeAttribute);
if(defaultValue != null){
attributes.add(make().Assign(naming.makeUnquotedIdent("defaultValue"), make().Literal(serialiseTypeSignature(defaultValue))));
}
// all done
return make().Annotation(makeIdent(syms().ceylonAtTypeParameter), attributes.toList());
}
List<JCAnnotation> makeAtTypeParameters(List<JCExpression> typeParameters) {
JCExpression value = make().NewArray(null, null, typeParameters);
return makeModelAnnotation(syms().ceylonAtTypeParameters, List.of(value));
}
List<JCAnnotation> makeAtSequenced() {
return makeModelAnnotation(syms().ceylonAtSequencedType);
}
List<JCAnnotation> makeAtDefaulted() {
return makeModelAnnotation(syms().ceylonAtDefaultedType);
}
List<JCAnnotation> makeAtAttribute() {
return makeModelAnnotation(syms().ceylonAtAttributeType);
}
List<JCAnnotation> makeAtMethod() {
return makeModelAnnotation(syms().ceylonAtMethodType);
}
List<JCAnnotation> makeAtObject() {
return makeModelAnnotation(syms().ceylonAtObjectType);
}
List<JCAnnotation> makeAtClass(ProducedType extendedType) {
List<JCExpression> attributes = List.nil();
JCExpression extendsValue = null;
if (extendedType == null) {
extendsValue = make().Literal("");
} else if (!extendedType.isExactly(typeFact.getBasicDeclaration().getType())){
extendsValue = make().Literal(serialiseTypeSignature(extendedType));
}
if (extendsValue != null) {
JCExpression extendsAttribute = make().Assign(naming.makeUnquotedIdent("extendsType"), extendsValue);
attributes = attributes.prepend(extendsAttribute);
}
return makeModelAnnotation(syms().ceylonAtClassType, attributes);
}
List<JCAnnotation> makeAtSatisfiedTypes(java.util.List<ProducedType> satisfiedTypes) {
JCExpression attrib = makeTypesListAttr(satisfiedTypes);
if (attrib != null) {
return makeModelAnnotation(syms().ceylonAtSatisfiedTypes, List.of(attrib));
} else {
return List.nil();
}
}
List<JCAnnotation> makeAtCaseTypes(java.util.List<ProducedType> caseTypes, ProducedType ofType) {
List<JCExpression> attribs = List.nil();
if (ofType != null) {
JCExpression ofAttr = makeOfTypeAttr(ofType);
attribs = attribs.append(ofAttr);
} else {
if (caseTypes != null && !caseTypes.isEmpty()) {
JCExpression casesAttr = makeTypesListAttr(caseTypes);
attribs = attribs.append(casesAttr);
}
}
if (!attribs.isEmpty()) {
return makeModelAnnotation(syms().ceylonAtCaseTypes, attribs);
} else {
return List.nil();
}
}
private JCExpression makeTypesListAttr(java.util.List<ProducedType> types) {
if(types.isEmpty())
return null;
ListBuffer<JCExpression> upperBounds = new ListBuffer<JCTree.JCExpression>();
for(ProducedType type : types){
String typeSig = serialiseTypeSignature(type);
upperBounds.append(make().Literal(typeSig));
}
JCExpression caseAttribute = make().Assign(naming.makeUnquotedIdent("value"),
make().NewArray(null, null, upperBounds.toList()));
return caseAttribute;
}
private JCExpression makeOfTypeAttr(ProducedType ofType) {
if(ofType == null)
return null;
String typeSig = serialiseTypeSignature(ofType);
JCExpression ofAttribute = make().Assign(naming.makeUnquotedIdent("of"),
make().Literal(typeSig));
return ofAttribute;
}
List<JCAnnotation> makeAtIgnore() {
return makeModelAnnotation(syms().ceylonAtIgnore);
}
List<JCAnnotation> makeAtAnnotations(java.util.List<Annotation> annotations) {
if(annotations == null || annotations.isEmpty())
return List.nil();
ListBuffer<JCExpression> array = new ListBuffer<JCTree.JCExpression>();
for(Annotation annotation : annotations){
array.append(makeAtAnnotation(annotation));
}
JCExpression annotationsAttribute = make().Assign(naming.makeUnquotedIdent("value"),
make().NewArray(null, null, array.toList()));
return makeModelAnnotation(syms().ceylonAtAnnotationsType, List.of(annotationsAttribute));
}
private JCExpression makeAtAnnotation(Annotation annotation) {
JCExpression valueAttribute = make().Assign(naming.makeUnquotedIdent("value"),
make().Literal(annotation.getName()));
List<JCExpression> attributes;
if(!annotation.getPositionalArguments().isEmpty()){
java.util.List<String> positionalArguments = annotation.getPositionalArguments();
ListBuffer<JCExpression> array = new ListBuffer<JCTree.JCExpression>();
for(String val : positionalArguments)
array.add(make().Literal(val));
JCExpression argumentsAttribute = make().Assign(naming.makeUnquotedIdent("arguments"),
make().NewArray(null, null, array.toList()));
attributes = List.of(valueAttribute, argumentsAttribute);
}else if(!annotation.getNamedArguments().isEmpty()){
Map<String, String> namedArguments = annotation.getNamedArguments();
ListBuffer<JCExpression> array = new ListBuffer<JCTree.JCExpression>();
for(Entry<String, String> entry : namedArguments.entrySet()){
JCExpression argNameAttribute = make().Assign(naming.makeUnquotedIdent("name"),
make().Literal(entry.getKey()));
JCExpression argValueAttribute = make().Assign(naming.makeUnquotedIdent("value"),
make().Literal(entry.getValue()));
JCAnnotation namedArg = make().Annotation(makeIdent(syms().ceylonAtNamedArgumentType),
List.of(argNameAttribute, argValueAttribute));
array.add(namedArg);
}
JCExpression argumentsAttribute = make().Assign(naming.makeUnquotedIdent("namedArguments"),
make().NewArray(null, null, array.toList()));
attributes = List.of(valueAttribute, argumentsAttribute);
}else
attributes = List.of(valueAttribute);
return make().Annotation(makeIdent(syms().ceylonAtAnnotationType), attributes);
}
List<JCAnnotation> makeAtContainer(String ceylonName, String javaClass, String pkg) {
JCExpression nameAttribute = make().Assign(naming.makeUnquotedIdent("name"),
make().Literal(ceylonName));
JCExpression javaClassAttribute = make().Assign(naming.makeUnquotedIdent("javaClass"),
make().Literal(javaClass));
JCExpression packageAttribute = make().Assign(naming.makeUnquotedIdent("packageName"),
make().Literal(pkg));
List<JCExpression> attributes = List.of(nameAttribute, javaClassAttribute, packageAttribute);
return makeModelAnnotation(syms().ceylonAtContainerType, attributes);
}
JCAnnotation makeAtMember(String ceylonName, String javaClass, String pkg) {
JCExpression nameAttribute = make().Assign(naming.makeUnquotedIdent("name"),
make().Literal(ceylonName));
JCExpression javaClassAttribute = make().Assign(naming.makeUnquotedIdent("javaClass"),
make().Literal(javaClass));
JCExpression packageAttribute = make().Assign(naming.makeUnquotedIdent("packageName"),
make().Literal(pkg));
List<JCExpression> attributes = List.of(nameAttribute, javaClassAttribute, packageAttribute);
return make().Annotation(makeIdent(syms().ceylonAtMemberType), attributes);
}
List<JCAnnotation> makeAtMembers(List<JCExpression> members) {
if(members.isEmpty())
return List.nil();
JCExpression attr = make().Assign(naming.makeUnquotedIdent("value"),
make().NewArray(null, null, members));
return makeModelAnnotation(syms().ceylonAtMembersType, List.of(attr));
}
/** Determine whether the given declaration requires a
* {@code @TypeInfo} annotation
*/
private boolean needsJavaTypeAnnotations(Declaration decl) {
Declaration reqdecl = decl;
if (reqdecl instanceof Parameter) {
Parameter p = (Parameter)reqdecl;
reqdecl = p.getDeclaration();
}
if (reqdecl instanceof TypeDeclaration) {
return true;
} else { // TypedDeclaration
return !Decl.isLocal(reqdecl);
}
}
List<JCTree.JCAnnotation> makeJavaTypeAnnotations(TypedDeclaration decl) {
if(decl == null || decl.getType() == null)
return List.nil();
ProducedType type;
if (decl instanceof FunctionalParameter) {
type = getTypeForFunctionalParameter((FunctionalParameter)decl);
} else if (decl instanceof Functional && Decl.isMpl((Functional)decl)) {
type = getReturnTypeOfCallable(decl.getProducedTypedReference(null, Collections.<ProducedType>emptyList()).getFullType());
} else {
type = decl.getType();
}
return makeJavaTypeAnnotations(type, needsJavaTypeAnnotations(decl));
}
private List<JCTree.JCAnnotation> makeJavaTypeAnnotations(ProducedType type, boolean required) {
if (!required)
return List.nil();
String name = serialiseTypeSignature(type);
boolean erased = hasErasure(type);
// Add the original type to the annotations
if (!erased) {
return makeModelAnnotation(syms().ceylonAtTypeInfoType, List.<JCExpression>of(make().Literal(name)));
}
return makeModelAnnotation(syms().ceylonAtTypeInfoType, List.<JCExpression>of(
make().Assign(naming.makeUnquotedIdent("value"), make().Literal(name)),
make().Assign(naming.makeUnquotedIdent("erased"), make().Literal(erased))));
}
private String serialiseTypeSignature(ProducedType type){
// resolve aliases
type = type.resolveAliases();
return type.getProducedTypeQualifiedName();
}
/*
* Boxing
*/
public enum BoxingStrategy {
UNBOXED, BOXED, INDIFFERENT;
}
public boolean canUnbox(ProducedType type){
// all the rest is boxed
return isCeylonBasicType(type) || isJavaString(type);
}
JCExpression boxUnboxIfNecessary(JCExpression javaExpr, Tree.Term expr,
ProducedType exprType,
BoxingStrategy boxingStrategy) {
boolean exprBoxed = !CodegenUtil.isUnBoxed(expr);
return boxUnboxIfNecessary(javaExpr, exprBoxed, exprType, boxingStrategy);
}
JCExpression boxUnboxIfNecessary(JCExpression javaExpr, boolean exprBoxed,
ProducedType exprType,
BoxingStrategy boxingStrategy) {
if(boxingStrategy == BoxingStrategy.INDIFFERENT)
return javaExpr;
boolean targetBoxed = boxingStrategy == BoxingStrategy.BOXED;
// only box if the two differ
if(targetBoxed == exprBoxed)
return javaExpr;
if (targetBoxed) {
// box
javaExpr = boxType(javaExpr, exprType);
} else {
// unbox
javaExpr = unboxType(javaExpr, exprType);
}
return javaExpr;
}
boolean isTypeParameter(ProducedType type) {
if (typeFact().isOptionalType(type)) {
type = type.eliminateNull();
}
return type.getDeclaration() instanceof TypeParameter;
}
JCExpression unboxType(JCExpression expr, ProducedType exprType) {
if (isCeylonInteger(exprType)) {
expr = unboxInteger(expr);
} else if (isCeylonFloat(exprType)) {
expr = unboxFloat(expr);
} else if (isCeylonString(exprType)) {
expr = unboxString(expr);
} else if (isCeylonCharacter(exprType)) {
boolean isJavaCharacter = exprType.getUnderlyingType() != null;
expr = unboxCharacter(expr, isJavaCharacter);
} else if (isCeylonBoolean(exprType)) {
expr = unboxBoolean(expr);
} else if (isCeylonArray(exprType)) {
expr = unboxArray(expr);
} else if (isOptional(exprType)) {
exprType = typeFact().getDefiniteType(exprType);
if (isCeylonString(exprType)){
expr = unboxOptionalString(expr);
}
}
return expr;
}
JCExpression boxType(JCExpression expr, ProducedType exprType) {
if (isCeylonInteger(exprType)) {
expr = boxInteger(expr);
} else if (isCeylonFloat(exprType)) {
expr = boxFloat(expr);
} else if (isCeylonString(exprType)) {
expr = boxString(expr);
} else if (isCeylonCharacter(exprType)) {
expr = boxCharacter(expr);
} else if (isCeylonBoolean(exprType)) {
expr = boxBoolean(expr);
} else if (isCeylonArray(exprType)) {
expr = boxArray(expr, typeFact.getArrayElementType(exprType));
} else if (isVoid(exprType)) {
expr = make().LetExpr(List.<JCStatement>of(make().Exec(expr)), makeNull());
} else if (isOptional(exprType)) {
// sometimes, due to interop we will get an unboxed java.lang.String whose Ceylon type
// is String? or passes for a boxed thing, and if we need to box it well we do
exprType = typeFact().getDefiniteType(exprType);
if (isCeylonString(exprType)){
expr = boxOptionalJavaString(expr);
}
}
return expr;
}
private JCTree.JCMethodInvocation boxInteger(JCExpression value) {
return makeBoxType(value, syms().ceylonIntegerType);
}
private JCTree.JCMethodInvocation boxFloat(JCExpression value) {
return makeBoxType(value, syms().ceylonFloatType);
}
private JCTree.JCMethodInvocation boxString(JCExpression value) {
return makeBoxType(value, syms().ceylonStringType);
}
private JCTree.JCMethodInvocation boxCharacter(JCExpression value) {
return makeBoxType(value, syms().ceylonCharacterType);
}
private JCTree.JCMethodInvocation boxBoolean(JCExpression value) {
return makeBoxType(value, syms().ceylonBooleanType);
}
private JCTree.JCMethodInvocation boxArray(JCExpression value, ProducedType type) {
JCExpression typeExpr = makeJavaType(type, JT_TYPE_ARGUMENT);
return make().Apply(List.<JCExpression>of(typeExpr), makeSelect(makeIdent(syms().ceylonArrayType), "instance"), List.<JCExpression>of(value));
}
private JCTree.JCMethodInvocation makeBoxType(JCExpression value, Type type) {
return make().Apply(null, makeSelect(makeIdent(type), "instance"), List.<JCExpression>of(value));
}
private JCTree.JCMethodInvocation unboxInteger(JCExpression value) {
return makeUnboxType(value, "longValue");
}
private JCTree.JCMethodInvocation unboxFloat(JCExpression value) {
return makeUnboxType(value, "doubleValue");
}
private JCExpression unboxString(JCExpression value) {
if (isStringLiteral(value)) {
// If it's already a String literal, why call .toString on it?
return value;
}
return makeUnboxType(value, "toString");
}
private boolean isStringLiteral(JCExpression value) {
return value instanceof JCLiteral
&& ((JCLiteral)value).value instanceof String;
}
private JCExpression unboxOptionalString(JCExpression value){
if (isStringLiteral(value)) {
// If it's already a String literal, why call .toString on it?
return value;
}
Naming.SyntheticName name = naming.temp();
JCExpression type = makeJavaType(typeFact().getStringDeclaration().getType(), JT_NO_PRIMITIVES);
JCExpression expr = make().Conditional(make().Binary(JCTree.NE, name.makeIdent(), makeNull()),
unboxString(name.makeIdent()),
makeNull());
return makeLetExpr(name, null, type, value, expr);
}
private JCExpression boxOptionalJavaString(JCExpression value){
Naming.SyntheticName name = naming.temp();
JCExpression type = makeJavaType(typeFact().getStringDeclaration().getType());
JCExpression expr = make().Conditional(make().Binary(JCTree.NE, name.makeIdent(), makeNull()),
boxString(name.makeIdent()),
makeNull());
return makeLetExpr(name, null, type, value, expr);
}
private JCTree.JCMethodInvocation unboxCharacter(JCExpression value, boolean isJava) {
return makeUnboxType(value, isJava ? "charValue" : "intValue");
}
private JCTree.JCMethodInvocation unboxBoolean(JCExpression value) {
return makeUnboxType(value, "booleanValue");
}
private JCTree.JCMethodInvocation unboxArray(JCExpression value) {
return makeUnboxType(value, "toArray");
}
private JCTree.JCMethodInvocation makeUnboxType(JCExpression value, String unboxMethodName) {
return make().Apply(null, makeSelect(value, unboxMethodName), List.<JCExpression>nil());
}
/*
* Sequences
*/
/**
* Invokes getSequence() on an Iterable to get a Sequential
*/
JCExpression iterableToSequence(JCExpression iterable){
return make().Apply(null, makeSelect(iterable, "getSequence"), List.<JCExpression>nil());
}
/**
* Returns a JCExpression along the lines of
* {@code new ArraySequence<seqElemType>(list...)}
* @param elems The elements in the sequence
* @param seqElemType The sequence type parameter
* @param makeJavaTypeOpts The option flags to pass to makeJavaType().
* @return a JCExpression
* @see #makeSequenceRaw(java.util.List)
*/
JCExpression makeSequence(List<JCExpression> elems, ProducedType seqElemType, int makeJavaTypeOpts) {
ProducedType arraySequenceType = toPType(syms().ceylonArraySequenceType);
ProducedType sequenceType = arraySequenceType.getDeclaration().getProducedType(null, Arrays.asList(seqElemType));
JCExpression typeExpr = makeJavaType(sequenceType, makeJavaTypeOpts);
List<ExpressionAndType> argsAndTypes = List.<ExpressionAndType>nil();
for (JCExpression arg : elems) {
argsAndTypes = argsAndTypes.append(new ExpressionAndType(arg, makeJavaType(seqElemType, makeJavaTypeOpts)));
}
CallBuilder cb = CallBuilder.instance(this)
.instantiate(typeExpr)
.argumentsAndTypes(argsAndTypes);
if (expressionGen().hasBackwardBranches()) {
cb.argumentHandling(ArgumentHandling.ARGUMENTS_EVAL_FIRST, naming.alias("uninit"));
}
return cb.build();
}
/**
* Returns a JCExpression along the lines of
* {@code new ArraySequence<seqElemType>(list...)}
* @param list The elements in the sequence
* @param seqElemType The sequence type parameter
* @return a JCExpression
* @see #makeSequenceRaw(java.util.List)
*/
JCExpression makeSequence(java.util.List<Expression> list, ProducedType seqElemType) {
ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
if (list.size() != 1 || !isNull(list.get(0).getTypeModel())) {
for (Expression expr : list) {
elems.append(expressionGen().transformExpression(expr, BoxingStrategy.BOXED, seqElemType));
}
} else {
// Resolve the ambiguous situation of being passed a single "null" argument
elems.append(make().TypeCast(syms().objectType, expressionGen().transformExpression(list.get(0))));
}
return makeSequence(elems.toList(), seqElemType, CeylonTransformer.JT_CLASS_NEW);
}
/**
* Makes an iterable literal, for a sequenced argument
*/
JCExpression makeIterable(Tree.SequencedArgument sequencedArgument, ProducedType seqElemType, int flags) {
ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
java.util.List<PositionalArgument> list = sequencedArgument.getPositionalArguments();
int i = list.size();
boolean spread = false;
for (Tree.PositionalArgument arg : list) {
at(arg);
i--;
JCExpression jcExpression;
// last expression can be an Iterable<seqElemType>
if(arg instanceof Tree.SpreadArgument || arg instanceof Tree.Comprehension){
// make sure we only have spread/comprehension as last
if(i != 0){
jcExpression = makeErroneous(arg, "Spread or comprehension argument is not last in sequence literal");
}else{
ProducedType type = typeFact().getIterableType(seqElemType);
spread = true;
if(arg instanceof Tree.SpreadArgument){
Tree.Expression expr = ((Tree.SpreadArgument) arg).getExpression();
// always boxed since it is a sequence
jcExpression = expressionGen().transformExpression(expr, BoxingStrategy.BOXED, type);
}else{
jcExpression = expressionGen().transformComprehension((Comprehension) arg, type);
}
}
}else if(arg instanceof Tree.ListedArgument){
Tree.Expression expr = ((Tree.ListedArgument) arg).getExpression();
// always boxed since we stuff them into a sequence
jcExpression = expressionGen().transformExpression(expr, BoxingStrategy.BOXED, seqElemType);
}else{
jcExpression = makeErroneous(arg, "Unknown argument type: " + arg);
}
// the last iterable goes first if spread
if(i == 0 && spread)
elems.prepend(jcExpression);
else
elems.append(jcExpression);
}
// small optimisation if we have only a single element
if(elems.size() == 1 && spread)
return elems.first();
at(sequencedArgument);
if(spread)
return makeIterable(elems.toList(), seqElemType, flags | JT_NO_PRIMITIVES);
else
return makeSequence(elems.toList(), seqElemType, flags | JT_NO_PRIMITIVES);
}
/**
* Makes an iterable literal, where the first element of elems is an Iterable, and the rest are the start of the
* iterable.
*/
JCExpression makeIterable(List<JCExpression> elems, ProducedType seqElemType, int makeJavaTypeOpts) {
JCExpression elemTypeExpr = makeJavaType(seqElemType, makeJavaTypeOpts);
// we delegate to ArrayIterable.instance() so that we can filter out empty Iterables
return make().Apply(List.<JCExpression>of(elemTypeExpr), makeSelect(makeIdent(syms().ceylonArrayIterableType), "instance"), elems);
}
/**
* Returns a JCExpression along the lines of
* {@code new ArraySequence(list...)}
* @param list The elements in the sequence
* @return a JCExpression
* @see #makeSequence(java.util.List, ProducedType)
*/
JCExpression makeSequenceRaw(java.util.List<Expression> list) {
ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
for (Expression expr : list) {
// no need for erasure casts here
elems.append(expressionGen().transformExpression(expr));
}
return makeSequenceRaw(elems.toList());
}
JCExpression makeSequenceRaw(List<JCExpression> elems) {
return makeSequence(elems, typeFact().getObjectDeclaration().getType(), CeylonTransformer.JT_RAW);
}
JCExpression makeEmptyAsSequential(boolean needsCast){
if(needsCast)
return make().TypeCast(makeJavaType(typeFact().getSequentialDeclaration().getType(), JT_RAW), makeEmpty());
return makeEmpty();
}
JCExpression makeEmpty() {
return make().Apply(
List.<JCTree.JCExpression>nil(),
naming.makeLanguageValue("empty"),
List.<JCTree.JCExpression>nil());
}
JCExpression makeFinished() {
return make().Apply(
List.<JCTree.JCExpression>nil(),
naming.makeLanguageValue("finished"),
List.<JCTree.JCExpression>nil());
}
/**
* Turns a sequence into a Java array
* @param expr the sequence
* @param sequenceType the (destination) sequence type
* @param boxingStrategy the boxing strategy for expr
* @param exprType the (source) expression type
* @param initialElements the elements to place at the beginning of the Java array
*/
JCExpression sequenceToJavaArray(JCExpression expr, ProducedType sequenceType,
BoxingStrategy boxingStrategy, ProducedType exprType,
List<JCTree.JCExpression> initialElements) {
String methodName = null;
// find the sequence element type
ProducedType type = typeFact().getIteratedType(sequenceType);
if(boxingStrategy == BoxingStrategy.UNBOXED){
if(isCeylonInteger(type)){
if("byte".equals(type.getUnderlyingType()))
methodName = "toByteArray";
else if("short".equals(type.getUnderlyingType()))
methodName = "toShortArray";
else if("int".equals(type.getUnderlyingType()))
methodName = "toIntArray";
else
methodName = "toLongArray";
}else if(isCeylonFloat(type)){
if("float".equals(type.getUnderlyingType()))
methodName = "toFloatArray";
else
methodName = "toDoubleArray";
} else if (isCeylonCharacter(type)) {
if ("char".equals(type.getUnderlyingType()))
methodName = "toCharArray";
// else it must be boxed, right?
} else if (isCeylonBoolean(type)) {
methodName = "toBooleanArray";
} else if (isJavaString(type)) {
methodName = "toJavaStringArray";
} else if (isCeylonString(type)) {
return objectVariadicToJavaArray(type, sequenceType, expr, exprType, initialElements);
}
if(methodName == null){
log.error("ceylon", "Don't know how to convert sequences of type "+type+" to Java array (This is a compiler bug)");
return expr;
}
return makeUtilInvocation(methodName, initialElements.prepend(expr), null);
}else{
return objectVariadicToJavaArray(type, sequenceType, expr, exprType, initialElements);
}
}
private JCExpression objectVariadicToJavaArray(ProducedType type,
ProducedType sequenceType, JCExpression expr, ProducedType exprType, List<JCExpression> initialElements) {
if(typeFact().getSequentialType(exprType) != null){
return objectSequentialToJavaArray(type, expr, initialElements);
}
return objectIterableToJavaArray(type, typeFact().getIterableType(sequenceType), expr, initialElements);
}
// This can't be reached anymore since we can't spread iterables anymore ATM
private JCExpression objectIterableToJavaArray(ProducedType type,
ProducedType iterableType, JCExpression expr, List<JCExpression> initialElements) {
JCExpression klass = makeJavaType(type, JT_CLASS_NEW | JT_NO_PRIMITIVES);
JCExpression klassLiteral = make().Select(klass, names().fromString("class"));
return makeUtilInvocation("toArray", initialElements.prependList(List.of(expr, klassLiteral)), null);
}
private JCExpression objectSequentialToJavaArray(ProducedType type, JCExpression expr, List<JCExpression> initialElements) {
JCExpression klass1 = makeJavaType(type, JT_RAW | JT_NO_PRIMITIVES);
JCExpression klass2 = makeJavaType(type, JT_CLASS_NEW | JT_NO_PRIMITIVES);
Naming.SyntheticName seqName = naming.temp().suffixedBy("$0");
ProducedType fixedSizedType = typeFact().getSequentialDeclaration().getProducedType(null, Arrays.asList(type));
JCExpression seqTypeExpr1 = makeJavaType(fixedSizedType);
//JCExpression seqTypeExpr2 = makeJavaType(fixedSizedType);
JCExpression sizeExpr = make().Apply(List.<JCExpression>nil(),
make().Select(seqName.makeIdent(), names().fromString("getSize")),
List.<JCExpression>nil());
sizeExpr = make().TypeCast(syms().intType, sizeExpr);
// add initial elements if required
if(!initialElements.isEmpty())
sizeExpr = make().Binary(JCTree.PLUS,
sizeExpr,
makeInteger(initialElements.size()));
JCExpression newArrayExpr = make().NewArray(klass1, List.of(sizeExpr), null);
JCExpression sequenceToArrayExpr = makeUtilInvocation("toArray",
initialElements.prependList(List.of(seqName.makeIdent(), newArrayExpr)),
List.of(klass2));
// since T[] is erased to Sequential<T> we probably need a cast to FixedSized<T>
//JCExpression castedExpr = make().TypeCast(seqTypeExpr2, expr);
return makeLetExpr(seqName, List.<JCStatement>nil(), seqTypeExpr1, expr, sequenceToArrayExpr);
}
// Creates comparisons of expressions against types
JCExpression makeTypeTest(JCExpression firstTimeExpr, Naming.CName varName, ProducedType type) {
JCExpression result = null;
// make sure aliases are resolved
type = type.resolveAliases();
if (typeFact().isUnion(type)) {
UnionType union = (UnionType)type.getDeclaration();
for (ProducedType pt : union.getCaseTypes()) {
JCExpression partExpr = makeTypeTest(firstTimeExpr, varName, pt);
firstTimeExpr = null;
if (result == null) {
result = partExpr;
} else {
result = make().Binary(JCTree.OR, result, partExpr);
}
}
} else if (typeFact().isIntersection(type)) {
IntersectionType union = (IntersectionType)type.getDeclaration();
for (ProducedType pt : union.getSatisfiedTypes()) {
JCExpression partExpr = makeTypeTest(firstTimeExpr, varName, pt);
firstTimeExpr = null;
if (result == null) {
result = partExpr;
} else {
result = make().Binary(JCTree.AND, result, partExpr);
}
}
} else {
JCExpression varExpr = firstTimeExpr != null ? firstTimeExpr : varName.makeIdent();
if (isVoid(type)){
// everything is Void, it's the root of the hierarchy
return makeIgnoredEvalAndReturn(varExpr, makeBoolean(true));
} else if (type.isExactly(typeFact().getNullDeclaration().getType())){
// is Null => is null
return make().Binary(JCTree.EQ, varExpr, makeNull());
} else if (type.isExactly(typeFact().getObjectDeclaration().getType())){
// is Object => is not null
return make().Binary(JCTree.NE, varExpr, makeNull());
} else if (type.isExactly(typeFact().getIdentifiableDeclaration().getType())){
// it's erased
return makeUtilInvocation("isIdentifiable", List.of(varExpr), null);
} else if (type.isExactly(typeFact().getBasicDeclaration().getType())){
// it's erased
return makeUtilInvocation("isBasic", List.of(varExpr), null);
} else if (type.getDeclaration() instanceof NothingType){
// nothing is Bottom
return makeIgnoredEvalAndReturn(varExpr, makeBoolean(false));
} else {
JCExpression rawTypeExpr = makeJavaType(type, JT_NO_PRIMITIVES | JT_RAW);
result = make().TypeTest(varExpr, rawTypeExpr);
}
}
return result;
}
JCExpression makeNonEmptyTest(JCExpression firstTimeExpr) {
Interface sequence = typeFact().getSequenceDeclaration();
JCExpression sequenceType = makeJavaType(sequence.getType(), JT_NO_PRIMITIVES | JT_RAW);
return make().TypeTest(firstTimeExpr, sequenceType);
}
/**
* Invokes a static method of the Util helper class
* @param methodName name of the method
* @param params parameters
* @return the invocation AST
*/
public JCExpression makeUtilInvocation(String methodName, List<JCExpression> params, List<JCExpression> typeParams) {
return make().Apply(typeParams,
make().Select(make().QualIdent(syms().ceylonUtilType.tsym),
names().fromString(methodName)),
params);
}
private LetExpr makeIgnoredEvalAndReturn(JCExpression toEval, JCExpression toReturn){
// define a variable of type j.l.Object to hold the result of the evaluation
JCVariableDecl def = makeVar(naming.temp(), make().Type(syms().objectType), toEval);
// then ignore this result and return something else
return make().LetExpr(def, toReturn);
}
JCExpression makeErroneous() {
return makeErroneous(null);
}
/**
* Makes an 'erroneous' AST node with no message
*/
JCExpression makeErroneous(Node node) {
return makeErroneous(node, null, List.<JCTree>nil());
}
/**
* Makes an 'erroneous' AST node with a message to be logged as an error
*/
JCExpression makeErroneous(Node node, String message) {
return makeErroneous(node, message, List.<JCTree>nil());
}
/**
* Makes an 'erroneous' AST node with a message to be logged as an error
*/
JCExpression makeErroneous(Node node, String message, List<? extends JCTree> errs) {
if (node != null) {
at(node);
}
if (message != null) {
if (node != null) {
log.error(getPosition(node), "ceylon", message);
} else {
log.error("ceylon", message);
}
}
return make().Erroneous(errs);
}
List<JCExpression> makeTypeParameterBounds(java.util.List<ProducedType> satisfiedTypes){
ListBuffer<JCExpression> bounds = new ListBuffer<JCExpression>();
for (ProducedType t : satisfiedTypes) {
if (!willEraseToObject(t)) {
JCExpression bound = makeJavaType(t, AbstractTransformer.JT_NO_PRIMITIVES);
// if it's a class, we need to move it first as per JLS http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.4
if(t.getDeclaration() instanceof Class)
bounds.prepend(bound);
else
bounds.append(bound);
}
}
return bounds.toList();
}
private boolean dependsOnTypeParameter(TypeParameter tpToCheck, TypeParameter tpToDependOn) {
for(ProducedType pt : tpToCheck.getSatisfiedTypes()){
if(dependsOnTypeParameter(pt, tpToDependOn))
return true;
}
return false;
}
private boolean dependsOnTypeParameter(ProducedType t, TypeParameter tp) {
TypeDeclaration decl = t.getDeclaration();
if(decl instanceof UnionType){
for(ProducedType pt : decl.getCaseTypes()){
if(dependsOnTypeParameter(pt, tp)){
return true;
}
}
}else if(decl instanceof IntersectionType){
for(ProducedType pt : decl.getSatisfiedTypes()){
if(dependsOnTypeParameter(pt, tp)){
return true;
}
}
}else if(decl instanceof TypeParameter){
if(tp == null || tp == decl)
return true;
}else if(decl instanceof ClassOrInterface){
for(ProducedType ta : t.getTypeArgumentList()){
if(dependsOnTypeParameter(ta, tp)){
return true;
}
}
}
return false;
}
private JCTypeParameter makeTypeParameter(String name, java.util.List<ProducedType> satisfiedTypes, boolean covariant, boolean contravariant) {
return make().TypeParameter(names().fromString(name), makeTypeParameterBounds(satisfiedTypes));
}
JCTypeParameter makeTypeParameter(TypeParameter declarationModel) {
TypeParameter typeParameterForBounds = declarationModel;
// special case for method refinenement where Java doesn't let us refine the parameter bounds
if(declarationModel.getContainer() instanceof Method){
Method method = (Method) declarationModel.getContainer();
Method refinedMethod = (Method) method.getRefinedDeclaration();
if(method != refinedMethod){
// find the param index
int index = method.getTypeParameters().indexOf(declarationModel);
if(index == -1){
log.error("Failed to find type parameter index: "+declarationModel.getName());
}else if(refinedMethod.getTypeParameters().size() > index){
// ignore smaller index than size since the typechecker would have found the error
TypeParameter refinedTP = refinedMethod.getTypeParameters().get(index);
if(!haveSameBounds(declarationModel, refinedTP)){
typeParameterForBounds = refinedTP;
}
}
}
}
return makeTypeParameter(declarationModel.getName(),
typeParameterForBounds.getSatisfiedTypes(),
typeParameterForBounds.isCovariant(),
typeParameterForBounds.isContravariant());
}
JCTypeParameter makeTypeParameter(Tree.TypeParameterDeclaration param) {
at(param);
return makeTypeParameter(param.getDeclarationModel());
}
JCAnnotation makeAtTypeParameter(TypeParameter declarationModel) {
return makeAtTypeParameter(declarationModel.getName(),
declarationModel.getSatisfiedTypes(),
declarationModel.getCaseTypes(),
declarationModel.isCovariant(),
declarationModel.isContravariant(),
declarationModel.getDefaultTypeArgument());
}
JCAnnotation makeAtTypeParameter(Tree.TypeParameterDeclaration param) {
at(param);
return makeAtTypeParameter(param.getDeclarationModel());
}
final List<JCExpression> typeArguments(Tree.AnyMethod method) {
return typeArguments(method.getDeclarationModel());
}
final List<JCExpression> typeArguments(Tree.AnyClass type) {
return typeArguments(type);
}
final List<JCExpression> typeArguments(Functional method) {
return typeArguments(method.getTypeParameters(), method.getType().getTypeArguments());
}
final List<JCExpression> typeArguments(Tree.ClassOrInterface type) {
return typeArguments(type.getDeclarationModel().getTypeParameters(), type.getDeclarationModel().getType().getTypeArguments());
}
final List<JCExpression> typeArguments(java.util.List<TypeParameter> typeParameters, Map<TypeParameter, ProducedType> typeArguments) {
ListBuffer<JCExpression> typeArgs = ListBuffer.<JCExpression>lb();
for (TypeParameter tp : typeParameters) {
ProducedType type = typeArguments.get(tp);
if (type != null) {
typeArgs.append(makeJavaType(type, JT_TYPE_ARGUMENT));
} else {
typeArgs.append(makeJavaType(tp.getType(), JT_TYPE_ARGUMENT));
}
}
return typeArgs.toList();
}
/**
* Returns the name of the field in classes which holds the companion
* instance.
*/
final String getCompanionFieldName(Interface def) {
return naming.getCompanionFieldName(def);
}
/**
* Returns the name of the method in interfaces and classes used to get
* the companion instance.
*/
final String getCompanionAccessorName(Interface def) {
return naming.getCompanionAccessorName(def);
}
protected int getPosition(Node node) {
int pos = getMap().getStartPosition(node.getToken().getLine())
+ node.getToken().getCharPositionInLine();
log.useSource(gen().getFileObject());
return pos;
}
}
| true | true |
private ListBuffer<JCExpression> makeTypeArgs(boolean isCeylonCallable,
int flags, Map<TypeParameter, ProducedType> tas,
java.util.List<TypeParameter> tps) {
boolean onlyErasedUnions = true;
ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>();
for (TypeParameter tp : tps) {
ProducedType ta = tas.get(tp);
boolean isDependedOn = false;
// Partial hack for https://github.com/ceylon/ceylon-compiler/issues/920
// We need to find if a covariant param has other type parameters with bounds to this one
// For example if we have "Foo<out A, out B>() given B satisfies A" then we can't generate
// the following signature: "Foo<? extends Object, ? extends String" because the subtype of
// String that can satisfy B is not necessarily the subtype of Object that we used for A.
if(tp.isCovariant()){
for(TypeParameter otherTypeParameter : tps){
// skip this very type parameter
if(otherTypeParameter == tp)
continue;
if(dependsOnTypeParameter(otherTypeParameter, tp)){
isDependedOn = true;
break;
}
}
}
// Null will claim to be optional, but if we get its non-null type we will land with Nothing, which is not what
// we want, so we make sure it's not Null
if (isOptional(ta) && !isNull(ta)) {
// For an optional type T?:
// - The Ceylon type Foo<T?> results in the Java type Foo<T>.
ta = getNonNullType(ta);
}
if (typeFact().isUnion(ta) || typeFact().isIntersection(ta)) {
// For any other union type U|V (U nor V is Optional):
// - The Ceylon type Foo<U|V> results in the raw Java type Foo.
// For any other intersection type U&V:
// - The Ceylon type Foo<U&V> results in the raw Java type Foo.
ProducedType listType = typeFact().getDefiniteType(ta).getSupertype(typeFact().getSequentialDeclaration());
// don't break if the union type is erased to something better than Object
if(listType == null){
// use raw types if:
// - we're calling a constructor
// - we're not in a type argument (when used as type arguments raw types have more constraint than at the toplevel)
// or we're in an extends or satisfies and the type parameter is a self type
if((flags & JT_CLASS_NEW) != 0
|| ((flags & (JT_EXTENDS | JT_SATISFIES)) != 0 && tp.getSelfTypedDeclaration() != null)){
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
typeArgs = null;
break;
} else if((flags & (__JT_TYPE_ARGUMENT | JT_EXTENDS | JT_SATISFIES)) != 0) {
onlyErasedUnions = false;
}
// otherwise just go on
}else{
ta = listType;
onlyErasedUnions = false;
}
} else {
onlyErasedUnions = false;
}
if (isCeylonBoolean(ta)
&& !isTypeParameter(ta)) {
ta = typeFact.getBooleanDeclaration().getType();
}
JCExpression jta;
if (sameType(syms().ceylonAnythingType, ta)) {
// For the root type Void:
if ((flags & (JT_SATISFIES | JT_EXTENDS)) != 0) {
// - The Ceylon type Foo<Void> appearing in an extends or satisfies
// clause results in the Java raw type Foo<Object>
jta = make().Type(syms().objectType);
} else {
// - The Ceylon type Foo<Void> appearing anywhere else results in the Java type
// - Foo<Object> if Foo<T> is invariant in T
// - Foo<?> if Foo<T> is covariant in T, or
// - Foo<Object> if Foo<T> is contravariant in T
if (tp.isContravariant()) {
jta = make().Type(syms().objectType);
} else if (tp.isCovariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta, flags | JT_TYPE_ARGUMENT));
} else {
jta = make().Type(syms().objectType);
}
}
} else if (ta.getDeclaration() instanceof NothingType
// if we're in a type argument, extends or satisfies already, union and intersection types should
// use the same erasure rules as bottom: prefer wildcards
|| ((flags & (__JT_TYPE_ARGUMENT | JT_EXTENDS | JT_SATISFIES)) != 0
&& (typeFact().isUnion(ta) || typeFact().isIntersection(ta)))) {
// For the bottom type Bottom:
if ((flags & (JT_CLASS_NEW)) != 0) {
// - The Ceylon type Foo<Bottom> or Foo<erased_type> appearing in an instantiation
// clause results in the Java raw type Foo
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
typeArgs = null;
break;
} else {
// - The Ceylon type Foo<Bottom> appearing in an extends or satisfies location results in the Java type
// Foo<Object> (see https://github.com/ceylon/ceylon-compiler/issues/633 for why)
if((flags & (JT_SATISFIES | JT_EXTENDS)) != 0){
if (ta.getDeclaration() instanceof NothingType) {
jta = make().Type(syms().objectType);
} else {
if (!tp.getSatisfiedTypes().isEmpty()) {
// union or intersection: Use the common upper bound of the types
jta = makeJavaType(tp.getSatisfiedTypes().get(0), JT_TYPE_ARGUMENT);
} else {
jta = make().Type(syms().objectType);
}
}
}else if (ta.getDeclaration() instanceof NothingType){
// - The Ceylon type Foo<Bottom> appearing anywhere else results in the Java type
// - Foo<? super Object> if Foo is contravariant in T, or
// - Foo<? extends Object> if Foo is covariant in T and not depended on by other type params
// - Foo<Object> otherwise
// this is more correct than Foo<?> because a method returning Foo<?> could never override a method returning Foo<Object>
// see https://github.com/ceylon/ceylon-compiler/issues/1003
if (tp.isContravariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), make().Type(syms().objectType));
} else if (tp.isCovariant() && !isDependedOn) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), make().Type(syms().objectType));
} else {
jta = make().Type(syms().objectType);
}
}else{
// - The Ceylon type Foo<T> appearing anywhere else results in the Java type
// - Foo<T> if Foo is invariant in T,
// - Foo<? extends T> if Foo is covariant in T, or
// - Foo<? super T> if Foo is contravariant in T
if (((flags & JT_CLASS_NEW) == 0) && tp.isContravariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), makeJavaType(ta, JT_TYPE_ARGUMENT));
} else if (((flags & JT_CLASS_NEW) == 0) && tp.isCovariant() && !isDependedOn) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), makeJavaType(ta, JT_TYPE_ARGUMENT));
} else {
jta = makeJavaType(ta, JT_TYPE_ARGUMENT);
}
}
}
} else {
// For an ordinary class or interface type T:
if ((flags & (JT_SATISFIES | JT_EXTENDS)) != 0) {
// - The Ceylon type Foo<T> appearing in an extends or satisfies clause
// results in the Java type Foo<T>
jta = makeJavaType(ta, JT_TYPE_ARGUMENT);
} else {
// - The Ceylon type Foo<T> appearing anywhere else results in the Java type
// - Foo<T> if Foo is invariant in T,
// - Foo<? extends T> if Foo is covariant in T, or
// - Foo<? super T> if Foo is contravariant in T
if (((flags & JT_CLASS_NEW) == 0) && tp.isContravariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), makeJavaType(ta, JT_TYPE_ARGUMENT));
} else if (((flags & JT_CLASS_NEW) == 0) && tp.isCovariant() && !isDependedOn) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), makeJavaType(ta, JT_TYPE_ARGUMENT));
} else {
jta = makeJavaType(ta, JT_TYPE_ARGUMENT);
}
}
}
typeArgs.add(jta);
if (isCeylonCallable) {
// In the runtime Callable only has a single type param
break;
}
}
if (onlyErasedUnions) {
typeArgs = null;
}
return typeArgs;
}
|
private ListBuffer<JCExpression> makeTypeArgs(boolean isCeylonCallable,
int flags, Map<TypeParameter, ProducedType> tas,
java.util.List<TypeParameter> tps) {
boolean onlyErasedUnions = true;
ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>();
for (TypeParameter tp : tps) {
ProducedType ta = tas.get(tp);
boolean isDependedOn = false;
// Partial hack for https://github.com/ceylon/ceylon-compiler/issues/920
// We need to find if a covariant param has other type parameters with bounds to this one
// For example if we have "Foo<out A, out B>() given B satisfies A" then we can't generate
// the following signature: "Foo<? extends Object, ? extends String" because the subtype of
// String that can satisfy B is not necessarily the subtype of Object that we used for A.
if(tp.isCovariant()){
for(TypeParameter otherTypeParameter : tps){
// skip this very type parameter
if(otherTypeParameter == tp)
continue;
if(dependsOnTypeParameter(otherTypeParameter, tp)){
isDependedOn = true;
break;
}
}
}
// Null will claim to be optional, but if we get its non-null type we will land with Nothing, which is not what
// we want, so we make sure it's not Null
if (isOptional(ta) && !isNull(ta)) {
// For an optional type T?:
// - The Ceylon type Foo<T?> results in the Java type Foo<T>.
ta = getNonNullType(ta);
}
if (typeFact().isUnion(ta) || typeFact().isIntersection(ta)) {
// For any other union type U|V (U nor V is Optional):
// - The Ceylon type Foo<U|V> results in the raw Java type Foo.
// For any other intersection type U&V:
// - The Ceylon type Foo<U&V> results in the raw Java type Foo.
ProducedType listType = typeFact().getDefiniteType(ta).getSupertype(typeFact().getSequentialDeclaration());
// don't break if the union type is erased to something better than Object
if(listType == null){
// use raw types if:
// - we're calling a constructor
// - we're not in a type argument (when used as type arguments raw types have more constraint than at the toplevel)
// or we're in an extends or satisfies and the type parameter is a self type
if((flags & JT_CLASS_NEW) != 0
|| ((flags & (JT_EXTENDS | JT_SATISFIES)) != 0 && tp.getSelfTypedDeclaration() != null)){
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
typeArgs = null;
break;
} else if((flags & (__JT_TYPE_ARGUMENT | JT_EXTENDS | JT_SATISFIES)) != 0) {
onlyErasedUnions = false;
}
// otherwise just go on
}else{
ta = listType;
onlyErasedUnions = false;
}
} else {
onlyErasedUnions = false;
}
if (isCeylonBoolean(ta)
&& !isTypeParameter(ta)) {
ta = typeFact.getBooleanDeclaration().getType();
}
JCExpression jta;
if (sameType(syms().ceylonAnythingType, ta)) {
// For the root type Void:
if ((flags & (JT_SATISFIES | JT_EXTENDS)) != 0) {
// - The Ceylon type Foo<Void> appearing in an extends or satisfies
// clause results in the Java raw type Foo<Object>
jta = make().Type(syms().objectType);
} else {
// - The Ceylon type Foo<Void> appearing anywhere else results in the Java type
// - Foo<Object> if Foo<T> is invariant in T
// - Foo<?> if Foo<T> is covariant in T, or
// - Foo<Object> if Foo<T> is contravariant in T
if (tp.isContravariant()) {
jta = make().Type(syms().objectType);
} else if (tp.isCovariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta, flags | JT_TYPE_ARGUMENT));
} else {
jta = make().Type(syms().objectType);
}
}
} else if (ta.getDeclaration() instanceof NothingType
// if we're in a type argument, extends or satisfies already, union and intersection types should
// use the same erasure rules as bottom: prefer wildcards
|| ((flags & (__JT_TYPE_ARGUMENT | JT_EXTENDS | JT_SATISFIES)) != 0
&& (typeFact().isUnion(ta) || typeFact().isIntersection(ta)))) {
// For the bottom type Bottom:
if ((flags & (JT_CLASS_NEW)) != 0) {
// - The Ceylon type Foo<Bottom> or Foo<erased_type> appearing in an instantiation
// clause results in the Java raw type Foo
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
typeArgs = null;
break;
} else {
// - The Ceylon type Foo<Bottom> appearing in an extends or satisfies location results in the Java type
// Foo<Object> (see https://github.com/ceylon/ceylon-compiler/issues/633 for why)
if((flags & (JT_SATISFIES | JT_EXTENDS)) != 0){
if (ta.getDeclaration() instanceof NothingType) {
jta = make().Type(syms().objectType);
} else {
if (!tp.getSatisfiedTypes().isEmpty()) {
// union or intersection: Use the common upper bound of the types
jta = makeJavaType(tp.getSatisfiedTypes().get(0), JT_TYPE_ARGUMENT);
} else {
jta = make().Type(syms().objectType);
}
}
}else if (ta.getDeclaration() instanceof NothingType){
// - The Ceylon type Foo<Bottom> appearing anywhere else results in the Java type
// - Foo<? super Object> if Foo is contravariant in T, or
// - Foo<? extends Object> if Foo is covariant in T and not depended on by other type params
// - Foo<Object> otherwise
// this is more correct than Foo<?> because a method returning Foo<?> could never override a method returning Foo<Object>
// see https://github.com/ceylon/ceylon-compiler/issues/1003
if (tp.isContravariant()) {
typeArgs = null;
break;
} else if (tp.isCovariant() && !isDependedOn) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), make().Type(syms().objectType));
} else {
jta = make().Type(syms().objectType);
}
}else{
// - The Ceylon type Foo<T> appearing anywhere else results in the Java type
// - Foo<T> if Foo is invariant in T,
// - Foo<? extends T> if Foo is covariant in T, or
// - Foo<? super T> if Foo is contravariant in T
if (((flags & JT_CLASS_NEW) == 0) && tp.isContravariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), makeJavaType(ta, JT_TYPE_ARGUMENT));
} else if (((flags & JT_CLASS_NEW) == 0) && tp.isCovariant() && !isDependedOn) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), makeJavaType(ta, JT_TYPE_ARGUMENT));
} else {
jta = makeJavaType(ta, JT_TYPE_ARGUMENT);
}
}
}
} else {
// For an ordinary class or interface type T:
if ((flags & (JT_SATISFIES | JT_EXTENDS)) != 0) {
// - The Ceylon type Foo<T> appearing in an extends or satisfies clause
// results in the Java type Foo<T>
jta = makeJavaType(ta, JT_TYPE_ARGUMENT);
} else {
// - The Ceylon type Foo<T> appearing anywhere else results in the Java type
// - Foo<T> if Foo is invariant in T,
// - Foo<? extends T> if Foo is covariant in T, or
// - Foo<? super T> if Foo is contravariant in T
if (((flags & JT_CLASS_NEW) == 0) && tp.isContravariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), makeJavaType(ta, JT_TYPE_ARGUMENT));
} else if (((flags & JT_CLASS_NEW) == 0) && tp.isCovariant() && !isDependedOn) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), makeJavaType(ta, JT_TYPE_ARGUMENT));
} else {
jta = makeJavaType(ta, JT_TYPE_ARGUMENT);
}
}
}
typeArgs.add(jta);
if (isCeylonCallable) {
// In the runtime Callable only has a single type param
break;
}
}
if (onlyErasedUnions) {
typeArgs = null;
}
return typeArgs;
}
|
diff --git a/RutubeApp/src/ru/rutube/RutubeApp/ui/AuthorFeedActivity.java b/RutubeApp/src/ru/rutube/RutubeApp/ui/AuthorFeedActivity.java
index 87443a9..19e1ab1 100644
--- a/RutubeApp/src/ru/rutube/RutubeApp/ui/AuthorFeedActivity.java
+++ b/RutubeApp/src/ru/rutube/RutubeApp/ui/AuthorFeedActivity.java
@@ -1,29 +1,35 @@
package ru.rutube.RutubeApp.ui;
import ru.rutube.RutubeApp.MainApplication;
import ru.rutube.RutubeApp.R;
import ru.rutube.RutubeFeed.ui.FeedActivity;
/**
* Created by tumbler on 18.08.13.
*/
public class AuthorFeedActivity extends FeedActivity {
@Override
public void setContentView(int layoutResID) {
super.setContentView(R.layout.feed_activity);
}
@Override
protected void onStart() {
- super.onStart();
- MainApplication.feedActivityStart(this, String.valueOf(getIntent().getData()));
+ try {
+ super.onStart();
+ MainApplication.feedActivityStart(this, String.valueOf(getIntent().getData()));
+ } catch (NullPointerException e) {
+ ((MainApplication)MainApplication.getInstance()).reportError(this,
+ String.format("NullPointerException: %s", String.valueOf(e),
+ String.valueOf(getIntent())));
+ }
}
@Override
protected void onStop() {
super.onStop();
MainApplication.activityStop(this);
}
}
| true | true |
protected void onStart() {
super.onStart();
MainApplication.feedActivityStart(this, String.valueOf(getIntent().getData()));
}
|
protected void onStart() {
try {
super.onStart();
MainApplication.feedActivityStart(this, String.valueOf(getIntent().getData()));
} catch (NullPointerException e) {
((MainApplication)MainApplication.getInstance()).reportError(this,
String.format("NullPointerException: %s", String.valueOf(e),
String.valueOf(getIntent())));
}
}
|
diff --git a/src/main/java/io/github/benas/jpopulator/impl/PopulatorImpl.java b/src/main/java/io/github/benas/jpopulator/impl/PopulatorImpl.java
index 6379f44e..ad8d9e49 100644
--- a/src/main/java/io/github/benas/jpopulator/impl/PopulatorImpl.java
+++ b/src/main/java/io/github/benas/jpopulator/impl/PopulatorImpl.java
@@ -1,238 +1,243 @@
/*
* The MIT License
*
* Copyright (c) 2013, benas ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.benas.jpopulator.impl;
import io.github.benas.jpopulator.api.Randomizer;
import io.github.benas.jpopulator.api.Populator;
import org.apache.commons.beanutils.PropertyUtils;
import java.lang.reflect.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The core implementation of the {@link Populator} interface.
*
* @author benas ([email protected])
*/
public class PopulatorImpl implements Populator {
private final Logger logger = Logger.getLogger(this.getClass().getName());
/**
* Custom randomizers map to use to generate random values.
*/
private Map<RandomizerDefinition, Randomizer> randomizers;
/**
* The supported java types list.
*/
private final List<Class> javaTypesList;
public PopulatorImpl() {
randomizers = new HashMap<RandomizerDefinition, Randomizer>();
javaTypesList = new ArrayList<Class>();
//initialize supported java types
Class[] javaTypes = {String.class, Character.TYPE, Character.class,
Boolean.TYPE, Boolean.class,
Byte.TYPE, Byte.class, Short.TYPE, Short.class, Integer.TYPE, Integer.class, Long.TYPE, Long.class,
Double.TYPE, Double.class, Float.TYPE, Float.class, BigInteger.class, BigDecimal.class,
AtomicLong.class, AtomicInteger.class,
java.util.Date.class, java.sql.Date.class, java.sql.Time.class, java.sql.Timestamp.class, Calendar.class};
javaTypesList.addAll(Arrays.asList(javaTypes));
}
@Override
public Object populateBean(Class type) {
Object result;
try {
/*
* For enum types, no instantiation needed (else java.lang.InstantiationException)
*/
if (type.isEnum()) {
return DefaultRandomizer.getRandomValue(type);
}
/*
* Create an instance of the type
*/
result = type.newInstance();
/*
* Retrieve declared fields
*/
List<Field> declaredFields = new ArrayList<Field>(Arrays.asList(result.getClass().getDeclaredFields()));
/*
* Retrieve inherited fields for all type hierarchy
*/
Class clazz = type;
while (clazz.getSuperclass() != null) {
Class superclass = clazz.getSuperclass();
declaredFields.addAll(Arrays.asList(superclass.getDeclaredFields()));
clazz = superclass;
}
/*
* Generate random data for each field
*/
for (Field field : declaredFields) {
+ //do not populate static nor final fields
+ int fieldModifiers = field.getModifiers();
+ if ( Modifier.isStatic(fieldModifiers) || Modifier.isFinal(fieldModifiers) ) {
+ continue;
+ }
if (isCollectionType(field.getType())) {
populateCollectionType(result, field);
} else {
populateSimpleType(result, field);
}
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Unable to populate an instance of type " + type, e);
return null;
}
return result;
}
@Override
public List<Object> populateBeans(Class type) {
byte size = (byte) Math.abs((Byte) DefaultRandomizer.getRandomValue(Byte.TYPE));
return populateBeans(type, size);
}
@Override
public List<Object> populateBeans(Class type, int size) {
Object[] beans = new Object[size];
for (int i = 0; i < size; i++) {
Object bean = populateBeans(type);
beans[i] = bean;
}
return Arrays.asList(beans);
}
/**
* Method to populate a simple (ie non collection) type which can be a java built-in type or a user's custom type.
*
* @param result The result object on which the generated value will be set
* @param field The field in which the generated value will be set
* @throws Exception Thrown when the generated value cannot be set to the given field
*/
private void populateSimpleType(Object result, Field field) throws Exception {
Class<?> fieldType = field.getType();
String fieldName = field.getName();
Class<?> resultClass = result.getClass();
Object object;
if (customRandomizer(resultClass, fieldType, fieldName)) { // use custom randomizer if any
object = randomizers.get(new RandomizerDefinition(resultClass, fieldType, fieldName)).getRandomValue();
} else if (isJavaType(fieldType)) { //Java type (no need for recursion)
object = DefaultRandomizer.getRandomValue(fieldType);
} else { // Custom type (recursion needed to populate nested custom types if any)
object = populateBean(fieldType);
}
PropertyUtils.setProperty(result, fieldName, object);
}
/**
* This methods checks if the user has registered a custom randomizer for the given type and field.
*
* @param type The class type for which the method should check if a custom randomizer is registered
* @param fieldType the field type within the class for which the method should check if a custom randomizer is registered
* @param fieldName the field name within the class for which the method should check if a custom randomizer is registered
* @return True if a custom randomizer is registered for the given type and field, false else
*/
private boolean customRandomizer(Class<?> type, Class<?> fieldType, String fieldName) {
return randomizers.get(new RandomizerDefinition(type, fieldType, fieldName)) != null;
}
/**
* Method to populate a collection type which can be a array or a {@link Collection}.
*
* @param result The result object on which the generated value will be set
* @param field The field in which the generated value will be set
* @throws Exception Thrown when the generated value cannot be set to the given field
*/
private void populateCollectionType(Object result, Field field) throws Exception {
Class<?> fieldType = field.getType();
String fieldName = field.getName();
//Array type
if (fieldType.isArray()) {
PropertyUtils.setProperty(result, fieldName, Array.newInstance(fieldType.getComponentType(), 0));
return;
}
//Collection type
Object collection = null;
if (List.class.isAssignableFrom(fieldType)) { // List, ArrayList, LinkedList, etc
collection = Collections.emptyList();
} else if (Set.class.isAssignableFrom(fieldType)) { // Set, HashSet, TreeSet, LinkedHashSet, etc
collection = Collections.emptySet();
} else if (Map.class.isAssignableFrom(fieldType)) { // Map, HashMap, Dictionary, Properties, etc
collection = Collections.emptyMap();
}
PropertyUtils.setProperty(result, fieldName, collection);
}
/**
* This method checks if the given type is a java built-in (primitive/boxed) type (ie, int, long, etc)
*
* @param type the type that the method should check
* @return true if the given type is a java built-in type
*/
private boolean isJavaType(Class<?> type) {
return javaTypesList.contains(type);
}
/**
* This method checks if the given type is a java built-in collection type (ie, array, List, Set, Map, etc)
*
* @param type the type that the method should check
* @return true if the given type is a java built-in collection type
*/
private boolean isCollectionType(Class<?> type) {
return type.isArray() || Map.class.isAssignableFrom(type) || Collection.class.isAssignableFrom(type);
}
/**
* Setter for the custom randomizers to use. Used to register custom randomizers by the {@link PopulatorBuilder}
*
* @param randomizers the custom randomizers to use.
*/
public void setRandomizers(Map<RandomizerDefinition, Randomizer> randomizers) {
this.randomizers = randomizers;
}
}
| true | true |
public Object populateBean(Class type) {
Object result;
try {
/*
* For enum types, no instantiation needed (else java.lang.InstantiationException)
*/
if (type.isEnum()) {
return DefaultRandomizer.getRandomValue(type);
}
/*
* Create an instance of the type
*/
result = type.newInstance();
/*
* Retrieve declared fields
*/
List<Field> declaredFields = new ArrayList<Field>(Arrays.asList(result.getClass().getDeclaredFields()));
/*
* Retrieve inherited fields for all type hierarchy
*/
Class clazz = type;
while (clazz.getSuperclass() != null) {
Class superclass = clazz.getSuperclass();
declaredFields.addAll(Arrays.asList(superclass.getDeclaredFields()));
clazz = superclass;
}
/*
* Generate random data for each field
*/
for (Field field : declaredFields) {
if (isCollectionType(field.getType())) {
populateCollectionType(result, field);
} else {
populateSimpleType(result, field);
}
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Unable to populate an instance of type " + type, e);
return null;
}
return result;
}
|
public Object populateBean(Class type) {
Object result;
try {
/*
* For enum types, no instantiation needed (else java.lang.InstantiationException)
*/
if (type.isEnum()) {
return DefaultRandomizer.getRandomValue(type);
}
/*
* Create an instance of the type
*/
result = type.newInstance();
/*
* Retrieve declared fields
*/
List<Field> declaredFields = new ArrayList<Field>(Arrays.asList(result.getClass().getDeclaredFields()));
/*
* Retrieve inherited fields for all type hierarchy
*/
Class clazz = type;
while (clazz.getSuperclass() != null) {
Class superclass = clazz.getSuperclass();
declaredFields.addAll(Arrays.asList(superclass.getDeclaredFields()));
clazz = superclass;
}
/*
* Generate random data for each field
*/
for (Field field : declaredFields) {
//do not populate static nor final fields
int fieldModifiers = field.getModifiers();
if ( Modifier.isStatic(fieldModifiers) || Modifier.isFinal(fieldModifiers) ) {
continue;
}
if (isCollectionType(field.getType())) {
populateCollectionType(result, field);
} else {
populateSimpleType(result, field);
}
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Unable to populate an instance of type " + type, e);
return null;
}
return result;
}
|
diff --git a/src/edu/jhu/nlp/wikipedia/WikiTextParser.java b/src/edu/jhu/nlp/wikipedia/WikiTextParser.java
index f65338b..f3de5bd 100644
--- a/src/edu/jhu/nlp/wikipedia/WikiTextParser.java
+++ b/src/edu/jhu/nlp/wikipedia/WikiTextParser.java
@@ -1,94 +1,95 @@
package edu.jhu.nlp.wikipedia;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* For internal use only -- Used by the {@link WikiPage} class.
* Can also be used as a stand alone class to parse wiki formatted text.
* @author Delip Rao
*
*/
public class WikiTextParser {
private String wikiText = null;
private Vector<String> pageCats = null;
private Vector<String> pageLinks = null;
private boolean redirect = false;
private String redirectString = null;
public WikiTextParser(String wtext) {
wikiText = wtext;
Pattern redirectPattern = Pattern.compile("#REDIRECT\\s+\\[\\[(.*?)\\]\\]");
Matcher matcher = redirectPattern.matcher(wikiText);
if(matcher.find()) {
redirect = true;
if(matcher.groupCount() == 1)
redirectString = matcher.group(1);
}
}
public boolean isRedirect() {
return redirect;
}
public String getRedirectText() {
return redirectString;
}
public String getText() {
return wikiText;
}
public Vector<String> getCategories() {
if(pageCats == null) parseCategories();
return pageCats;
}
public Vector<String> getLinks() {
if(pageLinks == null) parseLinks();
return pageLinks;
}
private void parseCategories() {
pageCats = new Vector<String>();
Pattern catPattern = Pattern.compile("\\[\\[Category:(.*?)\\]\\]", Pattern.MULTILINE);
Matcher matcher = catPattern.matcher(wikiText);
while(matcher.find()) {
String [] temp = matcher.group(1).split("\\|");
pageCats.add(temp[0]);
}
}
private void parseLinks() {
pageLinks = new Vector<String>();
Pattern catPattern = Pattern.compile("\\[\\[(.*?)\\]\\]", Pattern.MULTILINE);
Matcher matcher = catPattern.matcher(wikiText);
while(matcher.find()) {
String [] temp = matcher.group(1).split("\\|");
+ if(temp == null || temp.length == 0) continue;
String link = temp[0];
if(link.contains(":") == false) {
pageLinks.add(link);
}
}
}
public String getPlainText() {
String text = wikiText.replaceAll("<ref>.*?</ref>", " ");
text = text.replaceAll("</?.*?>", " ");
text = text.replaceAll("\\{\\{.*?\\}\\}", " ");
text = text.replaceAll("\\[\\[.*?:.*?\\]\\]", " ");
text = text.replaceAll("\\[\\[(.*?)\\]\\]", "$1");
text = text.replaceAll("\\s(.*?)\\|(\\w+\\s)", " $2");
text = text.replaceAll("\\[.*?\\]", " ");
text = text.replaceAll("\\'+", "");
return text;
}
public InfoBox getInfoBox() {
throw new UnsupportedOperationException();
}
}
| true | true |
private void parseLinks() {
pageLinks = new Vector<String>();
Pattern catPattern = Pattern.compile("\\[\\[(.*?)\\]\\]", Pattern.MULTILINE);
Matcher matcher = catPattern.matcher(wikiText);
while(matcher.find()) {
String [] temp = matcher.group(1).split("\\|");
String link = temp[0];
if(link.contains(":") == false) {
pageLinks.add(link);
}
}
}
|
private void parseLinks() {
pageLinks = new Vector<String>();
Pattern catPattern = Pattern.compile("\\[\\[(.*?)\\]\\]", Pattern.MULTILINE);
Matcher matcher = catPattern.matcher(wikiText);
while(matcher.find()) {
String [] temp = matcher.group(1).split("\\|");
if(temp == null || temp.length == 0) continue;
String link = temp[0];
if(link.contains(":") == false) {
pageLinks.add(link);
}
}
}
|
diff --git a/qualitas-engines-ode-validation/src/test/java/com/google/code/qualitas/engines/ode/validation/OdeValidatorTest.java b/qualitas-engines-ode-validation/src/test/java/com/google/code/qualitas/engines/ode/validation/OdeValidatorTest.java
index c1f0c26..3fd3926 100644
--- a/qualitas-engines-ode-validation/src/test/java/com/google/code/qualitas/engines/ode/validation/OdeValidatorTest.java
+++ b/qualitas-engines-ode-validation/src/test/java/com/google/code/qualitas/engines/ode/validation/OdeValidatorTest.java
@@ -1,84 +1,84 @@
package com.google.code.qualitas.engines.ode.validation;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.xml.namespace.QName;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.code.qualitas.engines.api.validation.ValidationException;
import com.google.code.qualitas.engines.ode.core.OdeBundle;
public class OdeValidatorTest {
private static String odePlatform;
private static String odeHome;
private static OdeBundle odeProcessBundle;
private static OdeBundle odeProcessBundleError;
private static OdeValidator odeProcessBundleValidator;
@BeforeClass
public static void setUpClass() throws IOException {
odeProcessBundle = new OdeBundle();
byte[] zippedArchive = FileUtils.readFileToByteArray(new File(
"src/test/resources/XhGPWWhile.zip"));
odeProcessBundle.setBundle(zippedArchive);
odeProcessBundle.setMainProcessQName(new QName("XhGPWWhile"));
odeProcessBundleError = new OdeBundle();
byte[] zippedArchiveError = FileUtils.readFileToByteArray(new File(
"src/test/resources/XhGPWWhileError.zip"));
odeProcessBundleError.setBundle(zippedArchiveError);
odeProcessBundleError.setMainProcessQName(new QName("XhGPWWhile"));
Properties properties = new Properties();
- InputStream is = OdeValidatorTest.class.getResourceAsStream("/environment.properties");
+ InputStream is = OdeValidatorTest.class.getResourceAsStream("/qualitas-engines-ode-validation.properties");
properties.load(is);
odePlatform = properties.getProperty("ode.platform");
odeHome = properties.getProperty("ode.home");
odeProcessBundleValidator = new OdeValidator();
odeProcessBundleValidator.setExternalToolHome(odeHome);
odeProcessBundleValidator.setExternalToolPlatform(odePlatform);
}
@AfterClass
public static void tearDownClass() throws IOException {
odeProcessBundle.cleanUp();
odeProcessBundleError.cleanUp();
}
@Test
public void testSetExternalToolHome() {
odeProcessBundleValidator.setExternalToolHome(odeHome);
}
@Test
public void testSetExternalToolPlatform() {
odeProcessBundleValidator.setExternalToolPlatform(odePlatform);
}
@Test
public void testValidateODEArchive() throws ValidationException {
odeProcessBundleValidator.validate(odeProcessBundle);
}
@Test
public void testValidateODEArchiveString() throws ValidationException {
odeProcessBundleValidator.validate(odeProcessBundle,
"XhGPWWhile");
}
@Test(expected = ValidationException.class)
public void testValidateODEArchiveError() throws ValidationException {
odeProcessBundleValidator.validate(odeProcessBundleError);
}
}
| true | true |
public static void setUpClass() throws IOException {
odeProcessBundle = new OdeBundle();
byte[] zippedArchive = FileUtils.readFileToByteArray(new File(
"src/test/resources/XhGPWWhile.zip"));
odeProcessBundle.setBundle(zippedArchive);
odeProcessBundle.setMainProcessQName(new QName("XhGPWWhile"));
odeProcessBundleError = new OdeBundle();
byte[] zippedArchiveError = FileUtils.readFileToByteArray(new File(
"src/test/resources/XhGPWWhileError.zip"));
odeProcessBundleError.setBundle(zippedArchiveError);
odeProcessBundleError.setMainProcessQName(new QName("XhGPWWhile"));
Properties properties = new Properties();
InputStream is = OdeValidatorTest.class.getResourceAsStream("/environment.properties");
properties.load(is);
odePlatform = properties.getProperty("ode.platform");
odeHome = properties.getProperty("ode.home");
odeProcessBundleValidator = new OdeValidator();
odeProcessBundleValidator.setExternalToolHome(odeHome);
odeProcessBundleValidator.setExternalToolPlatform(odePlatform);
}
|
public static void setUpClass() throws IOException {
odeProcessBundle = new OdeBundle();
byte[] zippedArchive = FileUtils.readFileToByteArray(new File(
"src/test/resources/XhGPWWhile.zip"));
odeProcessBundle.setBundle(zippedArchive);
odeProcessBundle.setMainProcessQName(new QName("XhGPWWhile"));
odeProcessBundleError = new OdeBundle();
byte[] zippedArchiveError = FileUtils.readFileToByteArray(new File(
"src/test/resources/XhGPWWhileError.zip"));
odeProcessBundleError.setBundle(zippedArchiveError);
odeProcessBundleError.setMainProcessQName(new QName("XhGPWWhile"));
Properties properties = new Properties();
InputStream is = OdeValidatorTest.class.getResourceAsStream("/qualitas-engines-ode-validation.properties");
properties.load(is);
odePlatform = properties.getProperty("ode.platform");
odeHome = properties.getProperty("ode.home");
odeProcessBundleValidator = new OdeValidator();
odeProcessBundleValidator.setExternalToolHome(odeHome);
odeProcessBundleValidator.setExternalToolPlatform(odePlatform);
}
|
diff --git a/cadejo/src/com/devcamp/cadejo/world/World.java b/cadejo/src/com/devcamp/cadejo/world/World.java
index c5eb3a5..b47bfe0 100644
--- a/cadejo/src/com/devcamp/cadejo/world/World.java
+++ b/cadejo/src/com/devcamp/cadejo/world/World.java
@@ -1,218 +1,218 @@
package com.devcamp.cadejo.world;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.devcamp.cadejo.actors.Background;
import com.devcamp.cadejo.actors.Cadejo;
import com.devcamp.cadejo.actors.Character;
import com.devcamp.cadejo.actors.Character.State;
import com.devcamp.cadejo.actors.Obstacle;
import com.devcamp.cadejo.screens.MainGameScreen;
import com.devcamp.cadejo.screens.MainGameScreen.GameState;
public class World {
private Character mainCharacter;
private Cadejo cadejo;
private MainGameScreen screen;
private Array<Background> backgrounds = new Array<Background>();
private Array<Obstacle> obstacles = new Array<Obstacle>();
//Cache:
private Array<Background> cachedBackgrounds = new Array<Background>();
private Array<Obstacle> cachedObstacles = new Array<Obstacle>();
//stuff Exit screen
private Array<Background> goneBackgrounds = new Array<Background>();
private Array<Obstacle> goneObstacles = new Array<Obstacle>();
public World(MainGameScreen screen){
this.screen = screen;
createWorld();
}
private void createWorld(){
mainCharacter = new Character(new Vector2(7.5f, 1.5f));
cadejo = new Cadejo(new Vector2(0.5f, 3.1f));
backgrounds.add(new Background(new Vector2(0, 0), 1));
for(int i = 1; i < 4; i++){
backgrounds.add(new Background(new Vector2((float)i*Background.SIZE_W, 0), 1));
}
}
public void update(float delta, float dificulty){
checkCollisions();
updateBackground(delta);
updateObstacles(delta);
checkGone();
makeCache();
deleteGone();
checkBackgroundCreation();
checkObstacleCreation(delta);
}
public void checkCollisions(){
for(Obstacle i: obstacles){
if(mainCharacter.getPosition().x+mainCharacter.getBounds().width-(mainCharacter.getBounds().width*0.25) > i.getPosition().x &&
mainCharacter.getPosition().x < i.getPosition().x+i.getBounds().width-(i.getBounds().width*0.25) &&
mainCharacter.getPosition().y < i.getPosition().y+i.getBounds().height-(i.getBounds().height*0.25)){
mainCharacter.setState(State.COLLISION);
screen.state = GameState.STOPPED;
}
}
}
public void updateBackground(float delta){
for(Background i : backgrounds){
i.update(delta);
}
}
public void updateObstacles(float delta){
for(Obstacle i : obstacles){
i.update(delta);
}
}
public void checkGone(){
for(Background i : backgrounds){
if(i.getPosition().x < -Background.SIZE_W){
goneBackgrounds.add(i);
}
}
for(Obstacle i : obstacles){
if(i.getPosition().x < -i.size_w){
goneObstacles.add(i);
}
}
}
public void makeCache(){
for(Background i : goneBackgrounds){
if(i.getPosition().x < 0){
cachedBackgrounds.add(i);
}
}
for(Obstacle i : goneObstacles){
if(i.getPosition().x < 0){
cachedObstacles.add(i);
}
}
}
public void deleteGone(){
for(Background i : goneBackgrounds){
if(i.getPosition().x < 0){
backgrounds.removeValue(i, false);
}
}
for(Obstacle i : goneObstacles){
if(i.getPosition().x < 0){
obstacles.removeValue(i, false);
}
}
goneBackgrounds.clear();
goneObstacles.clear();
}
public void checkBackgroundCreation(){
Background newBackground = null;
int randomBackground = 1 + (int)(Math.random() * 1); //5);
if(backgrounds.get(backgrounds.size-1).getPosition().x <= (WorldRenderer.CAMERA_W - Background.SIZE_W)+(Background.SIZE_W*0.0075)){
for(int i = 0; i < cachedBackgrounds.size-1; i++){
if(cachedBackgrounds.get(i).getId() == randomBackground){
newBackground = cachedBackgrounds.get(i);
newBackground.getPosition().x = WorldRenderer.CAMERA_W;
break;
}
}
if(newBackground != null){
backgrounds.add(newBackground);
cachedBackgrounds.removeValue(newBackground, false);
}
else{
backgrounds.add(new Background(new Vector2(WorldRenderer.CAMERA_W, 0), randomBackground));
}
}
}
public void checkObstacleCreation(float dificulty){
Obstacle newObstacle = null;
boolean enable = false;
int randomObstacle = 1 + (int)(Math.random() * 4);
if(Math.random() < 1*dificulty){
if(obstacles.size > 0 && obstacles.size < 8){
if(obstacles.get(obstacles.size-1).getPosition().x <
WorldRenderer.CAMERA_W - (obstacles.get(obstacles.size-1).size_w+
- mainCharacter.getBounds().width*2)){
+ mainCharacter.getBounds().width*2.75)){
enable = true;
}
else{
enable = false;
}
}
else{
enable = true;
}
if(enable){
for(int i = 0; i < cachedObstacles.size-1; i++){
if(cachedObstacles.get(i).getId() == randomObstacle){
newObstacle = cachedObstacles.get(i);
newObstacle.getPosition().x = WorldRenderer.CAMERA_W;
break;
}
}
if(newObstacle != null){
obstacles.add(newObstacle);
cachedObstacles.removeValue(newObstacle, false);
}
else{
obstacles.add(new Obstacle(new Vector2(WorldRenderer.CAMERA_W, 0.75f), randomObstacle));
}
}
}
}
public Character getMainCharacter() {
return mainCharacter;
}
public void setMainCharacter(Character mainCharacter) {
this.mainCharacter = mainCharacter;
}
public Cadejo getCadejo() {
return cadejo;
}
public void setCadejo(Cadejo cadejo) {
this.cadejo = cadejo;
}
public Array<Background> getBackgrounds() {
return backgrounds;
}
public void setBackgrounds(Array<Background> backgrounds) {
this.backgrounds = backgrounds;
}
public Array<Obstacle> getObstacles() {
return obstacles;
}
public void setObstacles(Array<Obstacle> obstacles) {
this.obstacles = obstacles;
}
}
| true | true |
public void checkObstacleCreation(float dificulty){
Obstacle newObstacle = null;
boolean enable = false;
int randomObstacle = 1 + (int)(Math.random() * 4);
if(Math.random() < 1*dificulty){
if(obstacles.size > 0 && obstacles.size < 8){
if(obstacles.get(obstacles.size-1).getPosition().x <
WorldRenderer.CAMERA_W - (obstacles.get(obstacles.size-1).size_w+
mainCharacter.getBounds().width*2)){
enable = true;
}
else{
enable = false;
}
}
else{
enable = true;
}
if(enable){
for(int i = 0; i < cachedObstacles.size-1; i++){
if(cachedObstacles.get(i).getId() == randomObstacle){
newObstacle = cachedObstacles.get(i);
newObstacle.getPosition().x = WorldRenderer.CAMERA_W;
break;
}
}
if(newObstacle != null){
obstacles.add(newObstacle);
cachedObstacles.removeValue(newObstacle, false);
}
else{
obstacles.add(new Obstacle(new Vector2(WorldRenderer.CAMERA_W, 0.75f), randomObstacle));
}
}
}
}
|
public void checkObstacleCreation(float dificulty){
Obstacle newObstacle = null;
boolean enable = false;
int randomObstacle = 1 + (int)(Math.random() * 4);
if(Math.random() < 1*dificulty){
if(obstacles.size > 0 && obstacles.size < 8){
if(obstacles.get(obstacles.size-1).getPosition().x <
WorldRenderer.CAMERA_W - (obstacles.get(obstacles.size-1).size_w+
mainCharacter.getBounds().width*2.75)){
enable = true;
}
else{
enable = false;
}
}
else{
enable = true;
}
if(enable){
for(int i = 0; i < cachedObstacles.size-1; i++){
if(cachedObstacles.get(i).getId() == randomObstacle){
newObstacle = cachedObstacles.get(i);
newObstacle.getPosition().x = WorldRenderer.CAMERA_W;
break;
}
}
if(newObstacle != null){
obstacles.add(newObstacle);
cachedObstacles.removeValue(newObstacle, false);
}
else{
obstacles.add(new Obstacle(new Vector2(WorldRenderer.CAMERA_W, 0.75f), randomObstacle));
}
}
}
}
|
diff --git a/aop-mc-int/src/main/org/jboss/aop/microcontainer/integration/AspectDependencyBuilderListItem.java b/aop-mc-int/src/main/org/jboss/aop/microcontainer/integration/AspectDependencyBuilderListItem.java
index e7471a36..cb7d3aa8 100644
--- a/aop-mc-int/src/main/org/jboss/aop/microcontainer/integration/AspectDependencyBuilderListItem.java
+++ b/aop-mc-int/src/main/org/jboss/aop/microcontainer/integration/AspectDependencyBuilderListItem.java
@@ -1,99 +1,100 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.aop.microcontainer.integration;
import java.util.Set;
import org.jboss.beans.metadata.spi.BeanMetaData;
import org.jboss.dependency.plugins.AbstractDependencyItem;
import org.jboss.dependency.spi.ControllerState;
import org.jboss.dependency.spi.DependencyInfo;
import org.jboss.dependency.spi.DependencyItem;
import org.jboss.kernel.spi.dependency.DependencyBuilderListItem;
import org.jboss.kernel.spi.dependency.KernelControllerContext;
import org.jboss.logging.Logger;
/**
*
* @author <a href="[email protected]">Kabir Khan</a>
* @version $Revision: 1.1 $
*/
class AspectDependencyBuilderListItem implements DependencyBuilderListItem
{
protected static Logger log = Logger.getLogger(AspectDependencyBuilderListItem.class);
/**
* The name of our dependency
*/
protected String dependencyName;
AspectDependencyBuilderListItem(String name)
{
this.dependencyName = name;
}
public void addDependency(KernelControllerContext context)
{
BeanMetaData metaData = context.getBeanMetaData();
DependencyItem dependencyItem = new AbstractDependencyItem(metaData.getName(), dependencyName, ControllerState.INSTANTIATED, ControllerState.INSTALLED);
DependencyInfo depends = context.getDependencyInfo();
depends.addIDependOn(dependencyItem);
}
public void removeDependency(KernelControllerContext context)
{
DependencyInfo depends = context.getDependencyInfo();
Set<DependencyItem> items = depends.getIDependOn(null);
if (items.size() > 0)
{
for (DependencyItem item : items)
{
try
{
- if (item.getIDependOn().equals(dependencyName))
+ Object iDependOn = item.getIDependOn();
+ if (iDependOn != null && iDependOn.equals(dependencyName))
{
depends.removeIDependOn(item);
}
}
catch (RuntimeException e)
{
log.warn("Problem uninstalling dependency " + dependencyName + " for " + context, e);
}
}
}
}
public boolean equals(Object o)
{
if (o instanceof AspectDependencyBuilderListItem)
{
return dependencyName.equals(((AspectDependencyBuilderListItem)o).dependencyName);
}
return false;
}
public int hashCode()
{
return dependencyName.hashCode();
}
}
| true | true |
public void removeDependency(KernelControllerContext context)
{
DependencyInfo depends = context.getDependencyInfo();
Set<DependencyItem> items = depends.getIDependOn(null);
if (items.size() > 0)
{
for (DependencyItem item : items)
{
try
{
if (item.getIDependOn().equals(dependencyName))
{
depends.removeIDependOn(item);
}
}
catch (RuntimeException e)
{
log.warn("Problem uninstalling dependency " + dependencyName + " for " + context, e);
}
}
}
}
|
public void removeDependency(KernelControllerContext context)
{
DependencyInfo depends = context.getDependencyInfo();
Set<DependencyItem> items = depends.getIDependOn(null);
if (items.size() > 0)
{
for (DependencyItem item : items)
{
try
{
Object iDependOn = item.getIDependOn();
if (iDependOn != null && iDependOn.equals(dependencyName))
{
depends.removeIDependOn(item);
}
}
catch (RuntimeException e)
{
log.warn("Problem uninstalling dependency " + dependencyName + " for " + context, e);
}
}
}
}
|
diff --git a/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java b/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java
index 6f082b1b..322e263c 100644
--- a/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java
+++ b/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java
@@ -1,767 +1,767 @@
package com.jayway.maven.plugins.android.phase04processclasses;
import com.jayway.maven.plugins.android.AbstractAndroidMojo;
import com.jayway.maven.plugins.android.CommandExecutor;
import com.jayway.maven.plugins.android.ExecutionException;
import com.jayway.maven.plugins.android.config.ConfigHandler;
import com.jayway.maven.plugins.android.config.ConfigPojo;
import com.jayway.maven.plugins.android.config.PullParameter;
import com.jayway.maven.plugins.android.configuration.Proguard;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.RepositoryUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.util.artifact.JavaScopes;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Processes both application and dependency classes using the ProGuard byte code obfuscator,
* minimzer, and optimizer. For more information, see https://proguard.sourceforge.net.
*
* @author Jonson
* @author Matthias Kaeppler
* @author Manfred Moser
* @author Michal Harakal
* @goal proguard
* @phase process-classes
* @requiresDependencyResolution compile
*/
public class ProguardMojo extends AbstractAndroidMojo
{
/**
* <p>
* ProGuard configuration. ProGuard is disabled by default. Set the skip parameter to false to activate proguard.
* A complete configuartion can include any of the following:
* </p>
* <p/>
* <pre>
* <proguard>
* <skip>true|false</skip>
* <config>proguard.cfg</config>
* <configs>
* <config>${env.ANDROID_HOME}/tools/proguard/proguard-android.txt</config>
* </configs>
* <proguardJarPath>someAbsolutePathToProguardJar</proguardJarPath>
* <filterMavenDescriptor>true|false</filterMavenDescriptor>
* <filterManifest>true|false</filterManifest>
* <jvmArguments>
* <jvmArgument>-Xms256m</jvmArgument>
* <jvmArgument>-Xmx512m</jvmArgument>
* </jvmArguments>
* </proguard>
* </pre>
* <p>
* A good practice is to create a release profile in your POM, in which you enable ProGuard.
* ProGuard should be disabled for development builds, since it obfuscates class and field
* names, and it may interfere with test projects that rely on your application classes.
* All parameters can be overridden in profiles or the the proguard* properties. Default values apply and are
* documented with these properties.
* </p>
*
* @parameter
*/
@ConfigPojo
protected Proguard proguard;
/**
* Whether ProGuard is enabled or not. Defaults to true.
*
* @parameter expression="${android.proguard.skip}"
* @optional
*/
private Boolean proguardSkip;
@PullParameter( defaultValue = "true" )
private Boolean parsedSkip;
/**
* Path to the ProGuard configuration file (relative to project root). Defaults to "proguard.cfg"
*
* @parameter expression="${android.proguard.config}"
* @optional
*/
private File proguardConfig;
@PullParameter( defaultValue = "${project.basedir}/proguard.cfg" )
private File parsedConfig;
/**
* Additional ProGuard configuration files (relative to project root).
*
* @parameter expression="${android.proguard.configs}"
* @optional
*/
private String[] proguardConfigs;
@PullParameter( defaultValueGetterMethod = "getDefaultProguardConfigs" )
private String[] parsedConfigs;
/**
* Additional ProGuard options
*
* @parameter expression="${android.proguard.options}"
* @optional
*/
private String[] proguardOptions;
@PullParameter( defaultValueGetterMethod = "getDefaultProguardOptions" )
private String[] parsedOptions;
/**
* Path to the proguard jar and therefore version of proguard to be used. By default this will load the jar from
* the Android SDK install. Overriding it with an absolute path allows you to use a newer or custom proguard
* version..
* <p/>
* You can also reference an external Proguard version as a plugin dependency like this:
* <pre>
* <plugin>
* <groupId>com.jayway.maven.plugins.android.generation2</groupId>
* <artifactId>android-maven-plugin</artifactId>
* <dependencies>
* <dependency>
* <groupId>net.sf.proguard</groupId>
* <artifactId>proguard-base</artifactId>
* <version>4.7</version>
* </dependency>
* </dependencies>
* </pre>
* <p/>
* which will download and use Proguard 4.7 as deployed to the Central Repository.
*
* @parameter expression="${android.proguard.proguardJarPath}
* @optional
*/
private String proguardProguardJarPath;
@PullParameter( defaultValueGetterMethod = "getProguardJarPath" )
private String parsedProguardJarPath;
/**
* Path relative to the project's build directory (target) where proguard puts folowing files:
* <p/>
* <ul>
* <li>dump.txt</li>
* <li>seeds.txt</li>
* <li>usage.txt</li>
* <li>mapping.txt</li>
* </ul>
* <p/>
* You can define the directory like this:
* <pre>
* <proguard>
* <skip>false</skip>
* <config>proguard.cfg</config>
* <outputDirectory>my_proguard</outputDirectory>
* </proguard>
* </pre>
* <p/>
* Output directory is defined relatively so it could be also outside of the target directory.
* <p/>
*
* @parameter expression="${android.proguard.outputDirectory}"
* @optional
*/
private File outputDirectory;
@PullParameter( defaultValue = "${project.build.directory}/proguard" )
private File parsedOutputDirectory;
/**
* @parameter expression="${android.proguard.obfuscatedJar}"
* default-value="${project.build.directory}/${project.build.finalName}_obfuscated.jar"
*/
private String obfuscatedJar;
/**
* Extra JVM Arguments. Using these you can e.g. increase memory for the jvm running the build.
* Defaults to "-Xmx512M".
*
* @parameter expression="${android.proguard.jvmArguments}"
* @optional
*/
private String[] proguardJvmArguments;
@PullParameter( defaultValueGetterMethod = "getDefaultJvmArguments" )
private String[] parsedJvmArguments;
/**
* If set to true will add a filter to remove META-INF/maven/* files. Defaults to false.
*
* @parameter expression="${android.proguard.filterMavenDescriptor}"
* @optional
*/
private Boolean proguardFilterMavenDescriptor;
@PullParameter( defaultValue = "true" )
private Boolean parsedFilterMavenDescriptor;
/**
* If set to true will add a filter to remove META-INF/MANIFEST.MF files. Defaults to false.
*
* @parameter expression="${android.proguard.filterManifest}"
* @optional
*/
private Boolean proguardFilterManifest;
@PullParameter( defaultValue = "true" )
private Boolean parsedFilterManifest;
/**
* If set to true JDK jars will be included as library jars and corresponding filters
* will be applied to android.jar. Defaults to true.
* @parameter expression="${android.proguard.includeJdkLibs}"
*/
private Boolean includeJdkLibs;
@PullParameter( defaultValue = "true" )
private Boolean parsedIncludeJdkLibs;
/**
* If set to true the mapping.txt file will be attached as artifact of type <code>map</code>
* @parameter expression="${android.proguard.attachMap}"
*/
private Boolean attachMap;
@PullParameter( defaultValue = "false" )
private Boolean parsedAttachMap;
/**
* The plugin dependencies.
*
* @parameter expression="${plugin.artifacts}"
* @required
* @readonly
*/
protected List< Artifact > pluginDependencies;
private static final Collection< String > ANDROID_LIBRARY_EXCLUDED_FILTER = Arrays
.asList( "org/xml/**", "org/w3c/**", "java/**", "javax/**" );
private static final Collection< String > MAVEN_DESCRIPTOR = Arrays.asList( "META-INF/maven/**" );
private static final Collection< String > META_INF_MANIFEST = Arrays.asList( "META-INF/MANIFEST.MF" );
/**
* For Proguard is required only jar type dependencies, all other like .so or .apklib can be skipped.
*/
private static final String USED_DEPENDENCY_TYPE = "jar";
private Collection< String > globalInJarExcludes = new HashSet< String >();
private List< Artifact > artifactBlacklist = new LinkedList< Artifact >();
private List< Artifact > artifactsToShift = new LinkedList< Artifact >();
private List< ProGuardInput > inJars = new LinkedList< ProguardMojo.ProGuardInput >();
private List< ProGuardInput > libraryJars = new LinkedList< ProguardMojo.ProGuardInput >();
private File javaHomeDir;
private File javaLibDir;
private File altJavaLibDir;
private static class ProGuardInput
{
private String path;
private Collection< String > excludedFilter;
public ProGuardInput( String path, Collection< String > excludedFilter )
{
this.path = path;
this.excludedFilter = excludedFilter;
}
public String toCommandLine()
{
if ( excludedFilter != null && !excludedFilter.isEmpty() )
{
StringBuilder sb = new StringBuilder( "'\"" );
sb.append( path );
sb.append( "\"(" );
for ( Iterator< String > it = excludedFilter.iterator(); it.hasNext(); )
{
sb.append( '!' ).append( it.next() );
if ( it.hasNext() )
{
sb.append( ',' );
}
}
sb.append( ")'" );
return sb.toString();
}
else
{
return "\'\"" + path + "\"\'";
}
}
@Override
public String toString()
{
return "ProGuardInput{"
+ "path='" + path + '\''
+ ", excludedFilter=" + excludedFilter
+ '}';
}
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException
{
ConfigHandler configHandler = new ConfigHandler( this, this.session, this.execution );
configHandler.parseConfiguration();
if ( !parsedSkip )
{
if ( parsedConfig.exists() )
{
// TODO: make the property name a constant sometime after switching to @Mojo
project.getProperties().setProperty( "android.proguard.obfuscatedJar", obfuscatedJar );
executeProguard();
}
else
{
getLog().info( String
.format( "Proguard skipped because the configuration file doesn't exist: %s", parsedConfig ) );
}
}
}
private void executeProguard() throws MojoExecutionException
{
final File proguardDir = this.parsedOutputDirectory;
if ( !proguardDir.exists() && !proguardDir.mkdir() )
{
throw new MojoExecutionException( "Cannot create proguard output directory" );
}
else
{
if ( proguardDir.exists() && !proguardDir.isDirectory() )
{
throw new MojoExecutionException( "Non-directory exists at " + proguardDir.getAbsolutePath() );
}
}
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List< String > commands = new ArrayList< String >();
collectJvmArguments( commands );
commands.add( "-jar" );
commands.add( parsedProguardJarPath );
- commands.add( "@" + parsedConfig );
+ commands.add( "@\"" + parsedConfig + "\"" );
for ( String config : parsedConfigs )
{
- commands.add( "@" + config );
+ commands.add( "@\"" + config + "\"" );
}
if ( proguardFile != null )
{
- commands.add( "@" + proguardFile.getAbsolutePath() );
+ commands.add( "@\"" + proguardFile.getAbsolutePath() + "\"" );
}
collectInputFiles( commands );
commands.add( "-outjars" );
commands.add( "'\"" + obfuscatedJar + "\"'" );
commands.add( "-dump" );
commands.add( "'\"" + proguardDir + File.separator + "dump.txt\"'" );
commands.add( "-printseeds" );
commands.add( "'\"" + proguardDir + File.separator + "seeds.txt\"'" );
commands.add( "-printusage" );
commands.add( "'\"" + proguardDir + File.separator + "usage.txt\"'" );
File mapFile = new File( proguardDir, "mapping.txt" );
commands.add( "-printmapping" );
commands.add( "'\"" + mapFile + "\"'" );
commands.addAll( Arrays.asList( parsedOptions ) );
final String javaExecutable = getJavaExecutable().getAbsolutePath();
getLog().info( javaExecutable + " " + commands.toString() );
try
{
executor.executeCommand( javaExecutable, commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
if ( parsedAttachMap )
{
projectHelper.attachArtifact( project, "map", mapFile );
}
}
/**
* Convert the jvm arguments in parsedJvmArguments as populated by the config in format as needed by the java
* command. Also preserve backwards compatibility in terms of dashes required or not..
*
* @param commands
*/
private void collectJvmArguments( List< String > commands )
{
if ( parsedJvmArguments != null )
{
for ( String jvmArgument : parsedJvmArguments )
{
// preserve backward compatibility allowing argument with or without dash (e.g.
// Xmx512m as well as -Xmx512m should work) (see
// http://code.google.com/p/maven-android-plugin/issues/detail?id=153)
if ( !jvmArgument.startsWith( "-" ) )
{
jvmArgument = "-" + jvmArgument;
}
commands.add( jvmArgument );
}
}
}
private void collectInputFiles( List< String > commands )
{
// commons-logging breaks everything horribly, so we skip it from the program
// dependencies and declare it to be a library dependency instead
skipArtifact( "commons-logging", "commons-logging", true );
collectProgramInputFiles();
for ( ProGuardInput injar : inJars )
{
getLog().debug( "Added injar : " + injar );
commands.add( "-injars" );
commands.add( injar.toCommandLine() );
}
collectLibraryInputFiles();
for ( ProGuardInput libraryjar : libraryJars )
{
getLog().debug( "Added libraryJar : " + libraryjar );
commands.add( "-libraryjars" );
commands.add( libraryjar.toCommandLine() );
}
}
/**
* Figure out the full path to the current java executable.
*
* @return the full path to the current java executable.
*/
private static File getJavaExecutable()
{
final String javaHome = System.getProperty( "java.home" );
final String slash = File.separator;
return new File( javaHome + slash + "bin" + slash + "java" );
}
private void skipArtifact( String groupId, String artifactId, boolean shiftToLibraries )
{
artifactBlacklist.add( RepositoryUtils.toArtifact( new DefaultArtifact( groupId, artifactId, null, null ) ) );
if ( shiftToLibraries )
{
artifactsToShift
.add( RepositoryUtils.toArtifact( new DefaultArtifact( groupId, artifactId, null, null ) ) );
}
}
private boolean isBlacklistedArtifact( Artifact artifact )
{
for ( Artifact artifactToSkip : artifactBlacklist )
{
if ( artifactToSkip.getGroupId().equals( artifact.getGroupId() ) && artifactToSkip.getArtifactId()
.equals( artifact.getArtifactId() ) )
{
return true;
}
}
return false;
}
private boolean isShiftedArtifact( Artifact artifact )
{
for ( Artifact artifactToShift : artifactsToShift )
{
if ( artifactToShift.getGroupId().equals( artifact.getGroupId() ) && artifactToShift.getArtifactId()
.equals( artifact.getArtifactId() ) )
{
return true;
}
}
return false;
}
private void collectProgramInputFiles()
{
if ( parsedFilterManifest )
{
globalInJarExcludes.addAll( META_INF_MANIFEST );
}
if ( parsedFilterMavenDescriptor )
{
globalInJarExcludes.addAll( MAVEN_DESCRIPTOR );
}
// we first add the application's own class files
addInJar( project.getBuild().getOutputDirectory() );
// we then add all its dependencies (incl. transitive ones), unless they're blacklisted
for ( Artifact artifact : getTransitiveDependencyArtifacts() )
{
if ( isBlacklistedArtifact( artifact ) || !USED_DEPENDENCY_TYPE.equals( artifact.getType() ) )
{
continue;
}
addInJar( artifact.getFile().getAbsolutePath(), globalInJarExcludes );
}
}
private void addInJar( String path, Collection< String > filterExpression )
{
inJars.add( new ProGuardInput( path, filterExpression ) );
}
private void addInJar( String path )
{
addInJar( path, null );
}
private void addLibraryJar( String path, Collection< String > filterExpression )
{
libraryJars.add( new ProGuardInput( path, filterExpression ) );
}
private void addLibraryJar( String path )
{
addLibraryJar( path, null );
}
private void collectLibraryInputFiles()
{
if ( parsedIncludeJdkLibs )
{
// we have to add the Java framework classes to the library JARs, since they are not
// distributed with the JAR on Central, and since we'll strip them out of the android.jar
// that is shipped with the SDK (since that is not a complete Java distribution)
File rtJar = getJVMLibrary( "rt.jar" );
if ( rtJar == null )
{
rtJar = getJVMLibrary( "classes.jar" );
}
if ( rtJar != null )
{
addLibraryJar( rtJar.getPath() );
}
// we also need to add the JAR containing e.g. javax.servlet
File jsseJar = getJVMLibrary( "jsse.jar" );
if ( jsseJar != null )
{
addLibraryJar( jsseJar.getPath() );
}
// and the javax.crypto stuff
File jceJar = getJVMLibrary( "jce.jar" );
if ( jceJar != null )
{
addLibraryJar( jceJar.getPath() );
}
}
// we treat any dependencies with provided scope as library JARs
for ( Artifact artifact : project.getArtifacts() )
{
if ( artifact.getScope().equals( JavaScopes.PROVIDED ) )
{
if ( artifact.getArtifactId().equals( "android" ) && parsedIncludeJdkLibs )
{
addLibraryJar( artifact.getFile().getAbsolutePath(), ANDROID_LIBRARY_EXCLUDED_FILTER );
}
else
{
addLibraryJar( artifact.getFile().getAbsolutePath() );
}
}
else
{
if ( isShiftedArtifact( artifact ) )
{
// this is a blacklisted artifact that should be processed as a library instead
addLibraryJar( artifact.getFile().getAbsolutePath() );
}
}
}
}
/**
* Get the path to the proguard jar.
*
* @return
* @throws MojoExecutionException
*/
private String getProguardJarPath() throws MojoExecutionException
{
String proguardJarPath = getProguardJarPathFromDependencies();
if ( StringUtils.isEmpty( proguardJarPath ) )
{
File proguardJarPathFile = new File( getAndroidSdk().getToolsPath(), "proguard/lib/proguard.jar" );
return proguardJarPathFile.getAbsolutePath();
}
return proguardJarPath;
}
private String getProguardJarPathFromDependencies() throws MojoExecutionException
{
Artifact proguardArtifact = null;
int proguardArtifactDistance = -1;
for ( Artifact artifact : pluginDependencies )
{
getLog().debug( "pluginArtifact: " + artifact.getFile() );
if ( ( "proguard".equals( artifact.getArtifactId() ) ) || ( "proguard-base"
.equals( artifact.getArtifactId() ) ) )
{
int distance = artifact.getDependencyTrail().size();
getLog().debug( "proguard DependencyTrail: " + distance );
if ( proguardArtifactDistance == -1 )
{
proguardArtifact = artifact;
proguardArtifactDistance = distance;
}
else
{
if ( distance < proguardArtifactDistance )
{
proguardArtifact = artifact;
proguardArtifactDistance = distance;
}
}
}
}
if ( proguardArtifact != null )
{
getLog().debug( "proguardArtifact: " + proguardArtifact.getFile() );
return proguardArtifact.getFile().getAbsoluteFile().toString();
}
else
{
return null;
}
}
/**
* Get the default JVM arguments for the proguard invocation.
*
* @return
* @see #parsedJvmArguments
*/
private String[] getDefaultJvmArguments()
{
return new String[] { "-Xmx512M" };
}
/**
* Get the default ProGuard config files.
*
* @return
* @see #parsedConfigs
*/
private String[] getDefaultProguardConfigs()
{
return new String[0];
}
/**
* Get the default ProGuard options.
*
* @return
* @see #parsedOptions
*/
private String[] getDefaultProguardOptions()
{
return new String[0];
}
/**
* Finds a library file in either the primary or alternate lib directory.
* @param fileName The base name of the file.
* @return Either a canonical filename, or {@code null} if not found.
*/
private File getJVMLibrary( String fileName )
{
File libFile = new File( getJavaLibDir(), fileName );
if ( !libFile.exists() )
{
libFile = new File( getAltJavaLibDir(), fileName );
if ( !libFile.exists() )
{
libFile = null;
}
}
return libFile;
}
/**
* Determines the java.home directory.
* @return The java.home directory, as a File.
*/
private File getJavaHomeDir()
{
if ( javaHomeDir == null )
{
javaHomeDir = new File( System.getProperty( "java.home" ) );
}
return javaHomeDir;
}
/**
* Determines the primary JVM library location.
* @return The primary library directory, as a File.
*/
private File getJavaLibDir()
{
if ( javaLibDir == null )
{
javaLibDir = new File( getJavaHomeDir(), "lib" );
}
return javaLibDir;
}
/**
* Determines the alternate JVM library location (applies with older
* MacOSX JVMs).
* @return The alternate JVM library location, as a File.
*/
private File getAltJavaLibDir()
{
if ( altJavaLibDir == null )
{
altJavaLibDir = new File( getJavaHomeDir().getParent(), "Classes" );
}
return altJavaLibDir;
}
}
| false | true |
private void executeProguard() throws MojoExecutionException
{
final File proguardDir = this.parsedOutputDirectory;
if ( !proguardDir.exists() && !proguardDir.mkdir() )
{
throw new MojoExecutionException( "Cannot create proguard output directory" );
}
else
{
if ( proguardDir.exists() && !proguardDir.isDirectory() )
{
throw new MojoExecutionException( "Non-directory exists at " + proguardDir.getAbsolutePath() );
}
}
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List< String > commands = new ArrayList< String >();
collectJvmArguments( commands );
commands.add( "-jar" );
commands.add( parsedProguardJarPath );
commands.add( "@" + parsedConfig );
for ( String config : parsedConfigs )
{
commands.add( "@" + config );
}
if ( proguardFile != null )
{
commands.add( "@" + proguardFile.getAbsolutePath() );
}
collectInputFiles( commands );
commands.add( "-outjars" );
commands.add( "'\"" + obfuscatedJar + "\"'" );
commands.add( "-dump" );
commands.add( "'\"" + proguardDir + File.separator + "dump.txt\"'" );
commands.add( "-printseeds" );
commands.add( "'\"" + proguardDir + File.separator + "seeds.txt\"'" );
commands.add( "-printusage" );
commands.add( "'\"" + proguardDir + File.separator + "usage.txt\"'" );
File mapFile = new File( proguardDir, "mapping.txt" );
commands.add( "-printmapping" );
commands.add( "'\"" + mapFile + "\"'" );
commands.addAll( Arrays.asList( parsedOptions ) );
final String javaExecutable = getJavaExecutable().getAbsolutePath();
getLog().info( javaExecutable + " " + commands.toString() );
try
{
executor.executeCommand( javaExecutable, commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
if ( parsedAttachMap )
{
projectHelper.attachArtifact( project, "map", mapFile );
}
}
|
private void executeProguard() throws MojoExecutionException
{
final File proguardDir = this.parsedOutputDirectory;
if ( !proguardDir.exists() && !proguardDir.mkdir() )
{
throw new MojoExecutionException( "Cannot create proguard output directory" );
}
else
{
if ( proguardDir.exists() && !proguardDir.isDirectory() )
{
throw new MojoExecutionException( "Non-directory exists at " + proguardDir.getAbsolutePath() );
}
}
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List< String > commands = new ArrayList< String >();
collectJvmArguments( commands );
commands.add( "-jar" );
commands.add( parsedProguardJarPath );
commands.add( "@\"" + parsedConfig + "\"" );
for ( String config : parsedConfigs )
{
commands.add( "@\"" + config + "\"" );
}
if ( proguardFile != null )
{
commands.add( "@\"" + proguardFile.getAbsolutePath() + "\"" );
}
collectInputFiles( commands );
commands.add( "-outjars" );
commands.add( "'\"" + obfuscatedJar + "\"'" );
commands.add( "-dump" );
commands.add( "'\"" + proguardDir + File.separator + "dump.txt\"'" );
commands.add( "-printseeds" );
commands.add( "'\"" + proguardDir + File.separator + "seeds.txt\"'" );
commands.add( "-printusage" );
commands.add( "'\"" + proguardDir + File.separator + "usage.txt\"'" );
File mapFile = new File( proguardDir, "mapping.txt" );
commands.add( "-printmapping" );
commands.add( "'\"" + mapFile + "\"'" );
commands.addAll( Arrays.asList( parsedOptions ) );
final String javaExecutable = getJavaExecutable().getAbsolutePath();
getLog().info( javaExecutable + " " + commands.toString() );
try
{
executor.executeCommand( javaExecutable, commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
if ( parsedAttachMap )
{
projectHelper.attachArtifact( project, "map", mapFile );
}
}
|
diff --git a/java/src/org/tom/weather/comm/Main.java b/java/src/org/tom/weather/comm/Main.java
index f973918f..1bdcebbc 100644
--- a/java/src/org/tom/weather/comm/Main.java
+++ b/java/src/org/tom/weather/comm/Main.java
@@ -1,91 +1,95 @@
/*
* Created on 16-Oct-2004
*
*/
package org.tom.weather.comm;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Main {
private static final int MAX_ERRORS = 20;
public static final Logger LOGGER = Logger.getLogger(Main.class);
private Station station;
private boolean checkArchive;
/**
* Main method
*
* @param args
* @since 1.0
*/
public static void main(String[] args) {
int errorCount = 0;
while (true) {
try {
ApplicationContext factory = new FileSystemXmlApplicationContext(
"weather.xml");
Main main = (Main) factory.getBean("weatherMonitor");
main.monitorWeather();
} catch (Exception e) {
LOGGER.error(e);
try {
if (errorCount++ > MAX_ERRORS) {
System.exit(1);
}
Thread.sleep(5000);
} catch (InterruptedException ex) {
LOGGER.error(ex);
}
}
}
}
public void monitorWeather() throws Exception {
+ int errorCount = 0;
try {
getStation().test();
} catch (IOException ex) {
LOGGER.error(ex);
}
while (true) {
try {
for (int i = 0; i < 15; i++) {
getStation().readCurrentConditions();
}
if (isCheckArchive()) {
getStation().readArchiveMemory();
}
} catch (Exception e) {
LOGGER.error("exception - waiting 5s", e);
try {
Thread.sleep(5000);
boolean ok = getStation().test();
// show results of station test after the wait
LOGGER.warn("station test:" + (ok ? "ok" : "not ok"));
} catch (Exception e1) {
+ if (errorCount++ > MAX_ERRORS) {
+ System.exit(1);
+ }
LOGGER.error(e1);
throw e1;
}
}
}
}
public void setStation(Station station) {
this.station = station;
}
public Station getStation() {
return station;
}
public boolean isCheckArchive() {
return checkArchive;
}
public void setCheckArchive(boolean checkArchive) {
this.checkArchive = checkArchive;
}
}
| false | true |
public void monitorWeather() throws Exception {
try {
getStation().test();
} catch (IOException ex) {
LOGGER.error(ex);
}
while (true) {
try {
for (int i = 0; i < 15; i++) {
getStation().readCurrentConditions();
}
if (isCheckArchive()) {
getStation().readArchiveMemory();
}
} catch (Exception e) {
LOGGER.error("exception - waiting 5s", e);
try {
Thread.sleep(5000);
boolean ok = getStation().test();
// show results of station test after the wait
LOGGER.warn("station test:" + (ok ? "ok" : "not ok"));
} catch (Exception e1) {
LOGGER.error(e1);
throw e1;
}
}
}
}
|
public void monitorWeather() throws Exception {
int errorCount = 0;
try {
getStation().test();
} catch (IOException ex) {
LOGGER.error(ex);
}
while (true) {
try {
for (int i = 0; i < 15; i++) {
getStation().readCurrentConditions();
}
if (isCheckArchive()) {
getStation().readArchiveMemory();
}
} catch (Exception e) {
LOGGER.error("exception - waiting 5s", e);
try {
Thread.sleep(5000);
boolean ok = getStation().test();
// show results of station test after the wait
LOGGER.warn("station test:" + (ok ? "ok" : "not ok"));
} catch (Exception e1) {
if (errorCount++ > MAX_ERRORS) {
System.exit(1);
}
LOGGER.error(e1);
throw e1;
}
}
}
}
|
diff --git a/src/main/java/de/peterspan/csv2db/converter/Converter.java b/src/main/java/de/peterspan/csv2db/converter/Converter.java
index c777f7d..8036ac1 100644
--- a/src/main/java/de/peterspan/csv2db/converter/Converter.java
+++ b/src/main/java/de/peterspan/csv2db/converter/Converter.java
@@ -1,109 +1,109 @@
/**
* Copyright 2012-2013 Frederik Hahne, Christoph Stiehm
*
* This file is part of csv2db.
*
* csv2db is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* csv2db is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with csv2db. If not, see <http://www.gnu.org/licenses/>.
*/
package de.peterspan.csv2db.converter;
import java.io.File;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import de.peterspan.csv2db.domain.entities.DataSet;
import de.peterspan.csv2db.domain.entities.Location;
import de.peterspan.csv2db.domain.entities.MeasurementValues;
public class Converter extends AbstractConverter {
public Converter() {
super();
};
public Converter(File inputFile) {
super(inputFile);
}
public void readLine(String[] line, Session session) {
DatasetLine datasetLine = new DatasetLine(line);
DataSet dataset = datasetLine.getDataset();
session.saveOrUpdate(dataset);
Location loc = datasetLine.getLocation();
Location sessionLoc = locationDao.getByLocationNumber(session,
loc.getLocationNumber());
if (sessionLoc != null) {
dataset.setLocation(sessionLoc);
session.saveOrUpdate(dataset);
} else {
session.saveOrUpdate(loc);
dataset.setLocation(loc);
}
MeasurementValues values = datasetLine.getValues();
session.saveOrUpdate(values);
dataset.setMeasurementValues(values);
session.saveOrUpdate(dataset);
}
@Override
protected Void doInBackground() throws Exception {
Session session = null;
Transaction tx = null;
try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
List<String[]> allLines = readFile();
double increment = 100.0 / allLines.size();
double progress = 0.0;
for (String[] line : allLines) {
progress = progress + increment;
setProgress((int)Math.round(progress));
- if (line[0].equals("Standort-Nr.")) {
+ if (line[0].equals("locnumber")) {
continue;
}
if (line[0].equals("")) {
continue;
}
readLine(line, session);
}
session.flush();
tx.commit();
} catch (HibernateException he) {
if(tx != null){
tx.rollback();
}
}finally{
if(session != null){
session.close();
}
}
return null;
}
}
| true | true |
protected Void doInBackground() throws Exception {
Session session = null;
Transaction tx = null;
try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
List<String[]> allLines = readFile();
double increment = 100.0 / allLines.size();
double progress = 0.0;
for (String[] line : allLines) {
progress = progress + increment;
setProgress((int)Math.round(progress));
if (line[0].equals("Standort-Nr.")) {
continue;
}
if (line[0].equals("")) {
continue;
}
readLine(line, session);
}
session.flush();
tx.commit();
} catch (HibernateException he) {
if(tx != null){
tx.rollback();
}
}finally{
if(session != null){
session.close();
}
}
return null;
}
|
protected Void doInBackground() throws Exception {
Session session = null;
Transaction tx = null;
try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
List<String[]> allLines = readFile();
double increment = 100.0 / allLines.size();
double progress = 0.0;
for (String[] line : allLines) {
progress = progress + increment;
setProgress((int)Math.round(progress));
if (line[0].equals("locnumber")) {
continue;
}
if (line[0].equals("")) {
continue;
}
readLine(line, session);
}
session.flush();
tx.commit();
} catch (HibernateException he) {
if(tx != null){
tx.rollback();
}
}finally{
if(session != null){
session.close();
}
}
return null;
}
|
diff --git a/src/multitallented/redcastlemedia/bukkit/herostronghold/HeroStronghold.java b/src/multitallented/redcastlemedia/bukkit/herostronghold/HeroStronghold.java
index d8473b5..77680d7 100644
--- a/src/multitallented/redcastlemedia/bukkit/herostronghold/HeroStronghold.java
+++ b/src/multitallented/redcastlemedia/bukkit/herostronghold/HeroStronghold.java
@@ -1,2353 +1,2354 @@
package multitallented.redcastlemedia.bukkit.herostronghold;
/**
*
* @author Multitallented
*/
import com.herocraftonline.heroes.Heroes;
import com.herocraftonline.heroes.characters.Hero;
import com.herocraftonline.heroes.characters.classes.HeroClass.ExperienceType;
import com.massivecraft.factions.*;
import com.massivecraft.factions.struct.Role;
import com.palmergames.bukkit.towny.Towny;
import com.palmergames.bukkit.towny.object.Resident;
import com.palmergames.bukkit.towny.object.TownyUniverse;
import java.io.IOException;
import java.util.*;
import java.util.logging.Logger;
import multitallented.redcastlemedia.bukkit.herostronghold.checkregiontask.CheckRegionTask;
import multitallented.redcastlemedia.bukkit.herostronghold.effect.EffectManager;
import multitallented.redcastlemedia.bukkit.herostronghold.events.CommandEffectEvent;
import multitallented.redcastlemedia.bukkit.herostronghold.listeners.*;
import multitallented.redcastlemedia.bukkit.herostronghold.region.*;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.hidendra.bukkit.metrics.Metrics;
public class HeroStronghold extends JavaPlugin {
private PluginServerListener serverListener;
private Logger log;
protected FileConfiguration config;
private RegionManager regionManager;
private RegionBlockListener blockListener;
public static Economy econ;
public static Permission perms;
public static Towny towny;
public static Factions factions;
private RegionEntityListener regionEntityListener;
private RegionPlayerInteractListener dpeListener;
private Map<String, String> pendingInvites = new HashMap<String, String>();
private static ConfigManager configManager;
private Map<String, List<String>> pendingCharters = new HashMap<String, List<String>>();
public static Heroes heroes = null;
private HashSet<String> effectCommands = new HashSet<String>();
@Override
public void onDisable() {
log = Logger.getLogger("Minecraft");
log.info("[HeroStronghold] is now disabled!");
}
@Override
public void onEnable() {
try {
Metrics metrics = new Metrics(this);
metrics.start();
} catch (IOException e) {
// Failed to submit the stats :-(
}
//setup configs
config = getConfig();
config.options().copyDefaults(true);
saveConfig();
//Setup RegionManager
regionManager = new RegionManager(this, config);
setupPermissions();
setupEconomy();
setupTowny();
//Register Listeners Here
serverListener = new PluginServerListener(this);
blockListener = new RegionBlockListener(this);
dpeListener = new RegionPlayerInteractListener(this);
regionEntityListener = new RegionEntityListener(this);
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(blockListener, this);
pm.registerEvents(serverListener, this);
pm.registerEvents(regionEntityListener, this);
pm.registerEvents(dpeListener, this);
pm.registerEvents(new CustomListener(this), this);
log = Logger.getLogger("Minecraft");
//Check for Heroes
log.info("[HeroStronghold] is looking for Heroes...");
Plugin currentPlugin = pm.getPlugin("Heroes");
if (currentPlugin != null) {
log.info("[HeroStronghold] found Heroes!");
heroes = ((Heroes) currentPlugin);
} else {
log.info("[HeroStronghold] didnt find Heroes, waiting for Heroes to be enabled.");
}
new EffectManager(this);
//Setup repeating sync task for checking regions
CheckRegionTask theSender = new CheckRegionTask(getServer(), this);
getServer().getScheduler().scheduleSyncRepeatingTask(this, theSender, 10L, 10L);
System.currentTimeMillis();
Date date = new Date();
date.setSeconds(0);
date.setMinutes(0);
date.setHours(0);
long timeUntilDay = (86400000 + date.getTime() - System.currentTimeMillis()) / 50;
System.out.println("[HeroStronghold] " + timeUntilDay + " ticks until 00:00");
DailyTimerTask dtt = new DailyTimerTask(this);
getServer().getScheduler().scheduleSyncRepeatingTask(this, dtt, timeUntilDay, 1728000);
log.info("[HeroStronghold] is now enabled!");
}
public static ConfigManager getConfigManager() {
return configManager;
}
public Map<Player, String> getChannels() {
return dpeListener.getChannels();
}
@Override
public boolean onCommand(CommandSender sender, org.bukkit.command.Command command, String label, String[] args) {
String debug = label;
for (String s : args) {
debug += " " + s;
}
System.out.println("[HeroStronghold] " + debug);
Player player = null;
try {
player = (Player) sender;
} catch (Exception e) {
}
if (args[0].equalsIgnoreCase("reload")) {
if (player != null && !(HeroStronghold.perms == null || HeroStronghold.perms.has(player, "herostronghold.admin"))) {
return true;
}
config = getConfig();
regionManager.reload();
configManager = new ConfigManager(config, this);
sender.sendMessage("[HeroStronghold] reloaded");
return true;
}
if (player == null) {
sender.sendMessage("[HeroStronghold] doesn't recognize non-player commands.");
return true;
}
if (args.length > 2 && args[0].equalsIgnoreCase("war")) {
//hs war mySR urSR
//Check for valid super-regions
SuperRegion sr1 = regionManager.getSuperRegion(args[1]);
SuperRegion sr2 = regionManager.getSuperRegion(args[2]);
if (sr1 == null || sr2 == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That isn't a valid super-region.");
return true;
}
//Check if already at war
if (regionManager.hasWar(sr1, sr2)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr1.getName() + " is already at war!");
return true;
}
//Check owner
if (!sr1.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not an owner of " + sr1.getName());
return true;
}
//Calculate Cost
ConfigManager cm = getConfigManager();
if (!cm.getUseWar()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This command is disabled in config.yml");
return true;
}
double cost = cm.getDeclareWarBase() + cm.getDeclareWarPer() * (sr1.getOwners().size() + sr1.getMembers().size() +
sr2.getOwners().size() + sr2.getMembers().size());
//Check money
if (HeroStronghold.econ != null) {
if (sr1.getBalance() < cost) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr1.getName() + " doesn't have enough money to war with " + sr2.getName());
return true;
} else {
regionManager.addBalance(sr1, -1 * cost);
}
}
regionManager.setWar(sr1, sr2);
final SuperRegion sr1a = sr1;
final SuperRegion sr2a = sr2;
new Runnable() {
@Override
public void run()
{
getServer().broadcastMessage(ChatColor.RED + "[HeroStronghold] " + sr1a.getName() + " has declared war on " + sr2a.getName() + "!");
}
}.run();
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("peace")) {
//hs peace mySR urSR
//Check for valid super-regions
SuperRegion sr1 = regionManager.getSuperRegion(args[1]);
SuperRegion sr2 = regionManager.getSuperRegion(args[2]);
if (sr1 == null || sr2 == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That isn't a valid super-region.");
return true;
}
//Check if already at war
if (!regionManager.hasWar(sr1, sr2)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr1.getName() + " isn't at war.");
return true;
}
//Check owner
if (!sr1.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not an owner of " + sr1.getName());
return true;
}
//Calculate Cost
ConfigManager cm = getConfigManager();
if (!cm.getUseWar()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This command is disabled in config.yml");
return true;
}
double cost = cm.getMakePeaceBase() + cm.getMakePeacePer() * (sr1.getOwners().size() + sr1.getMembers().size() +
sr2.getOwners().size() + sr2.getMembers().size());
//Check money
if (HeroStronghold.econ != null) {
if (sr1.getBalance() < cost) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr1.getName() + " doesn't have enough money to make peace with " + sr2.getName());
return true;
} else {
regionManager.addBalance(sr1, -1 * cost);
}
}
regionManager.setWar(sr1, sr2);
final SuperRegion sr1a = sr1;
final SuperRegion sr2a = sr2;
new Runnable() {
@Override
public void run()
{
getServer().broadcastMessage(ChatColor.RED + "[HeroStronghold] " + sr1a.getName() + " has made peace with " + sr2a.getName() + "!");
}
}.run();
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("charter")) {
//Check if valid super region
SuperRegionType currentRegionType = regionManager.getSuperRegionType(args[1]);
if (currentRegionType == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " isnt a valid region type");
int j=0;
String message = ChatColor.GOLD + "";
for (String s : regionManager.getSuperRegionTypes()) {
if (perms == null || (perms.has(player, "herostronghold.create.all") ||
perms.has(player, "herostronghold.create." + s))) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message + ", ");
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += ", " + s;
}
}
}
if (!message.equals(ChatColor.GOLD + "")) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
String regionTypeName = args[1].toLowerCase();
//Permission Check
if (perms != null && !perms.has(player, "herostronghold.create.all") &&
!perms.has(player, "herostronghold.create." + regionTypeName)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] you dont have permission to create a " + regionTypeName);
return true;
}
//Make sure the super-region requires a Charter
if (currentRegionType.getCharter() <= 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " doesnt require a charter. /hs create " + args[1]);
return true;
}
//Make sure the name isn't too long
if (args[2].length() > 15) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Sorry but that name is too long. (16 max)");
return true;
}
//Check if valid filename
if (!Util.validateFileName(args[2])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Sorry but that is an invalid filename.");
return true;
}
//Check if valid name
if (pendingCharters.containsKey(args[2].toLowerCase())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is already a charter or region with that name.");
return true;
}
if (getServer().getPlayerExact(args[2]) != null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Dont name a super-region after a player");
return true;
}
//Check if allowed super-region
if (regionManager.getSuperRegion(args[2]) != null && (!regionManager.getSuperRegion(args[2]).hasOwner(player.getName())
|| regionManager.getSuperRegion(args[2]).getType().equalsIgnoreCase(args[1]))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That exact super-region already exists.");
return true;
}
//Add the charter
List<String> tempList = new ArrayList<String>();
tempList.add(args[1]);
tempList.add(player.getName());
pendingCharters.put(args[2].toLowerCase(), tempList);
configManager.writeToCharter(args[2].toLowerCase(), tempList);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] Youve successfully created a charter for " + args[2]);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] Get other people to type /hs signcharter " + args[2] + " to get started.");
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("charterstats")) {
//Check if valid charter
if (!pendingCharters.containsKey(args[1].toLowerCase())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " isn't a valid charter type.");
return true;
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " signatures: ");
int j=0;
String message = ChatColor.GOLD + "";
List<String> charter = pendingCharters.get(args[1]);
if (charter != null) {
for (String s : charter) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!charter.isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
} else {
player.sendMessage(ChatColor.RED + "[HeroStronghold] There was an error loading that charter");
warning("Failed to load charter " + args[1] + ".yml");
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("signcharter")) {
//Check if valid name
if (!pendingCharters.containsKey(args[1].toLowerCase())) {
player.sendMessage(ChatColor.GRAY + "[Herostronghold] There is no charter for " + args[1]);
return true;
}
//Check permission
if (perms != null && !perms.has(player, "herostronghold.join")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission to sign a charter.");
return true;
}
//Sign Charter
List<String> charter = pendingCharters.get(args[1].toLowerCase());
//Check if the player has already signed the charter once
if (charter.contains(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You've already signed this charter.");
return true;
}
charter.add(player.getName());
configManager.writeToCharter(args[1], charter);
pendingCharters.put(args[1], charter);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You just signed the charter for " + args[1]);
int remaining = 0;
SuperRegionType srt = regionManager.getSuperRegionType(charter.get(0));
if (srt != null) {
remaining = srt.getCharter() - charter.size() + 1;
}
if (remaining > 0) {
player.sendMessage(ChatColor.GOLD + "" + remaining + " signatures to go!");
}
Player owner = getServer().getPlayer(charter.get(1));
if (owner != null && owner.isOnline()) {
owner.sendMessage(ChatColor.GOLD + "[HeroStronghold] " + player.getDisplayName() + " just signed your charter for " + args[1]);
if (remaining > 0) {
owner.sendMessage(ChatColor.GOLD + "" + remaining + " signatures to go!");
}
}
return true;
} else if (args.length > 1 && args[0].equals("cancelcharter")) {
if (!pendingCharters.containsKey(args[1].toLowerCase())) {
player.sendMessage(ChatColor.GRAY + "[Herostronghold] There is no charter for " + args[1]);
return true;
}
if (pendingCharters.get(args[1]).size() < 2 || !pendingCharters.get(args[1]).get(1).equals(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are the not owner of this charter.");
return true;
}
configManager.removeCharter(args[1]);
pendingCharters.remove(args[1]);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You have canceled the charter for " + args[1]);
return true;
} else if (args.length == 2 && args[0].equalsIgnoreCase("create")) {
String regionName = args[1];
//Permission Check
boolean nullPerms = perms == null;
boolean createAll = nullPerms || perms.has(player, "herostronghold.create.all");
if (!(nullPerms || createAll || perms.has(player, "herostronghold.create." + regionName))) {
//TODO add limited quantity permissions here
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] you dont have permission to create a " + regionName);
return true;
}
Location currentLocation = player.getLocation();
//Check if player is standing someplace where a chest can be placed.
Block currentBlock = currentLocation.getBlock();
if (currentBlock.getTypeId() != 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] please stand someplace where a chest can be placed.");
return true;
}
RegionType currentRegionType = regionManager.getRegionType(regionName);
if (currentRegionType == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + regionName + " isnt a valid region type");
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Try /hs create " + regionName + " <insert_name_here>");
return true;
}
//Check if player can afford to create this herostronghold
double costCheck = 0;
if (econ != null) {
double cost = currentRegionType.getMoneyRequirement();
if (econ.getBalance(player.getName()) < cost) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need $" + cost + " to make this type of structure.");
return true;
} else {
costCheck = cost;
}
}
//Check if over max number of regions of that type
if (regionManager.isAtMaxRegions(player, currentRegionType)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission to build more " + currentRegionType.getName());
return true;
}
//Check if too close to other HeroStrongholds
if (!regionManager.getContainingBuildRegions(currentLocation).isEmpty()) {
player.sendMessage (ChatColor.GRAY + "[HeroStronghold] You are too close to another HeroStronghold");
return true;
}
//Check if in a super region and if has permission to make that region
String playername = player.getName();
List<String> reqSuperRegion = currentRegionType.getSuperRegions();
boolean meetsReqs = reqSuperRegion == null || reqSuperRegion.isEmpty();
for (SuperRegion sr : regionManager.getContainingSuperRegions(currentLocation)) {
if (!meetsReqs && reqSuperRegion != null && reqSuperRegion.contains(sr.getType())) {
meetsReqs = true;
}
if (!sr.hasOwner(playername)) {
if (!sr.hasMember(playername) || !sr.getMember(playername).contains(regionName)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission from an owner of " + sr.getName()
+ " to create a " + regionName + " here");
return true;
}
}
}
if (!meetsReqs) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are required to build this " + regionName + " in a:");
String message = ChatColor.GOLD + "";
int j=0;
for (String s : reqSuperRegion) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!reqSuperRegion.isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
//Prepare a requirements checklist
ArrayList<ItemStack> requirements = currentRegionType.getRequirements();
Map<Integer, Integer> reqMap = null;
if (!requirements.isEmpty()) {
reqMap = new HashMap<Integer, Integer>();
for (ItemStack currentIS : requirements) {
reqMap.put(new Integer(currentIS.getTypeId()), new Integer(currentIS.getAmount()));
}
//Check the area for required blocks
int radius = (int) Math.sqrt(currentRegionType.getBuildRadius());
int lowerLeftX = (int) currentLocation.getX() - radius;
int lowerLeftY = (int) currentLocation.getY() - radius;
lowerLeftY = lowerLeftY < 0 ? 0 : lowerLeftY;
int lowerLeftZ = (int) currentLocation.getZ() - radius;
int upperRightX = (int) currentLocation.getX() + radius;
int upperRightY = (int) currentLocation.getY() + radius;
upperRightY = upperRightY > 255 ? 255 : upperRightY;
int upperRightZ = (int) currentLocation.getZ() + radius;
World world = currentLocation.getWorld();
outer: for (int x=lowerLeftX; x<upperRightX; x++) {
for (int z=lowerLeftZ; z<upperRightZ; z++) {
for (int y=lowerLeftY; y<upperRightY; y++) {
int type = world.getBlockTypeIdAt(x, y, z);
if (type != 0 && reqMap.containsKey(type)) {
if (reqMap.get(type) < 2) {
reqMap.remove(type);
if (reqMap.isEmpty()) {
break outer;
}
} else {
reqMap.put(type, reqMap.get(type) - 1);
}
}
}
}
}
}
if (reqMap != null && !reqMap.isEmpty()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] you don't have all of the required blocks in this structure.");
String message = ChatColor.GOLD + "";
int j=0;
for (int type : reqMap.keySet()) {
int reqAmount = reqMap.get(type);
String reqType = Material.getMaterial(type).name();
if (message.length() + reqAmount + reqType.length() + 3 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += reqAmount + ":" + reqType + ", ";
}
}
if (!reqMap.isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
//Create chest at players feet for tracking reagents and removing upkeep items
currentBlock.setType(Material.CHEST);
ArrayList<String> owners = new ArrayList<String>();
owners.add(player.getName());
if (costCheck > 0) {
econ.withdrawPlayer(player.getName(), costCheck);
}
if (heroes != null) {
heroes.getCharacterManager().getHero(player).gainExp(currentRegionType.getExp(), ExperienceType.EXTERNAL, player.getLocation());
}
regionManager.addRegion(currentLocation, regionName, owners);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "You successfully create a " + ChatColor.RED + regionName);
//Tell the player what reagents are required for it to work
String message = ChatColor.GOLD + "Reagents: ";
if (currentRegionType.getReagents() != null) {
int j=0;
for (ItemStack is : currentRegionType.getReagents()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j < 14) {
message += addLine;
} else {
break;
}
}
}
if (currentRegionType.getReagents() == null || currentRegionType.getReagents().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("create")) {
//Check if valid name (further name checking later)
if (args[2].length() > 16 || !Util.validateFileName(args[2])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That name is invalid.");
return true;
}
if (getServer().getPlayerExact(args[2]) != null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Dont name a super-region after a player.");
return true;
}
String regionTypeName = args[1];
//Permission Check
if (perms != null && !perms.has(player, "herostronghold.create.all") &&
!perms.has(player, "herostronghold.create." + regionTypeName)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] you dont have permission to create a " + regionTypeName);
return true;
}
//Check if valid super region
Location currentLocation = player.getLocation();
SuperRegionType currentRegionType = regionManager.getSuperRegionType(regionTypeName);
if (currentRegionType == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + regionTypeName + " isnt a valid region type");
int j=0;
String message = ChatColor.GOLD + "";
for (String s : regionManager.getSuperRegionTypes()) {
if (perms == null || (perms.has(player, "herostronghold.create.all") ||
perms.has(player, "herostronghold.create." + s))) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
}
if (!regionManager.getSuperRegionTypes().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
//Check if player can afford to create this herostronghold
double costCheck = 0;
if (econ != null) {
double cost = currentRegionType.getMoneyRequirement();
if (econ.getBalance(player.getName()) < cost) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need $" + cost + " to make this type of region.");
return true;
} else {
costCheck = cost;
}
}
Map<String, List<String>> members = new HashMap<String, List<String>>();
int currentCharter = currentRegionType.getCharter();
//Make sure the super-region has a valid charter
if (!HeroStronghold.perms.has(player, "herostronghold.admin")) {
if (currentCharter > 0) {
try {
if (!pendingCharters.containsKey(args[2])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need to start a charter first. /hs charter " + args[1] + " " + args[2]);
return true;
} else if (pendingCharters.get(args[2]).size() <= currentCharter) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need " + currentCharter + " signature(s). /hs signcharter " + args[2]);
return true;
} else if (!pendingCharters.get(args[2]).get(0).equalsIgnoreCase(args[1]) ||
!pendingCharters.get(args[2]).get(1).equalsIgnoreCase(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] The charter for this name is for a different region type or owner.");
player.sendMessage(ChatColor.GRAY + "Owner: " + pendingCharters.get(args[2]).get(1) + ", Type: " + pendingCharters.get(args[2]).get(0));
return true;
} else {
int i =0;
for (String s : pendingCharters.get(args[2])) {
ArrayList<String> tempArray = new ArrayList<String>();
tempArray.add("member");
if (i > 2) {
members.put(s, tempArray);
} else {
i++;
}
}
}
} catch (Exception e) {
warning("Possible failure to find correct charter for " + args[2]);
}
}
} else if (pendingCharters.containsKey(args[2])) {
if (currentCharter > 0) {
try {
if (pendingCharters.get(args[2]).size() <= currentCharter) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need " + currentCharter + " signature(s). /hs signcharter " + args[2]);
return true;
} else if (!pendingCharters.get(args[2]).get(0).equalsIgnoreCase(args[1]) ||
!pendingCharters.get(args[2]).get(1).equalsIgnoreCase(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] The charter for this name is for a different region type or owner.");
player.sendMessage(ChatColor.GRAY + "Owner: " + pendingCharters.get(args[2]).get(1) + ", Type: " + pendingCharters.get(args[2]).get(0));
return true;
} else {
int i =0;
for (String s : pendingCharters.get(args[2])) {
ArrayList<String> tempArray = new ArrayList<String>();
tempArray.add("member");
if (i > 2) {
members.put(s, tempArray);
} else {
i++;
}
}
}
} catch (Exception e) {
warning("Possible failure to find correct charter for " + args[2]);
}
}
}
Map<String, Integer> requirements = currentRegionType.getRequirements();
HashMap<String, Integer> req = new HashMap<String, Integer>();
for (String s : currentRegionType.getRequirements().keySet()) {
req.put(new String(s), new Integer(requirements.get(s)));
}
//Check for required regions
List<String> children = currentRegionType.getChildren();
if (children != null) {
for (String s : children) {
if (!req.containsKey(s))
req.put(new String(s), 1);
}
}
//Check if there already is a super-region by that name, but not if it's one of the child regions
if (regionManager.getSuperRegion(args[2]) != null && (children == null || !children.contains(regionManager.getSuperRegion(args[2]).getType()))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is already a super-region by that name.");
return true;
}
List<String> quietDestroy = new ArrayList<String>();
int radius = (int) currentRegionType.getRawRadius();
//Check if there is an overlapping super-region of the same type
for (SuperRegion sr : regionManager.getSortedSuperRegions()) {
try {
if (sr.getLocation().distance(currentLocation) < radius + regionManager.getSuperRegionType(sr.getType()).getRawRadius() &&
(sr.getType().equalsIgnoreCase(regionTypeName) || !sr.hasOwner(player.getName()))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr.getName() + " is already here.");
return true;
}
} catch (IllegalArgumentException iae) {
}
}
if (!req.isEmpty()) {
for (SuperRegion sr : regionManager.getContainingSuperRegions(currentLocation)) {
if (children.contains(sr.getType()) && sr.hasOwner(player.getName())) {
quietDestroy.add(sr.getName());
}
String rType = sr.getType();
if (!sr.hasOwner(player.getName()) && (!sr.hasMember(player.getName()) || !sr.getMember(player.getName()).contains(regionTypeName))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not permitted to build a " + regionTypeName + " inside " + sr.getName());
return true;
}
if (req.containsKey(rType)) {
int amount = req.get(rType);
if (amount < 2) {
req.remove(rType);
if (req.isEmpty()) {
break;
}
} else {
req.put(rType, amount - 1);
}
}
}
Location loc = player.getLocation();
double x = loc.getX();
double y = loc.getY();
double z = loc.getZ();
int radius1 = currentRegionType.getRawRadius();
for (Region r : regionManager.getSortedRegions()) {
Location l = r.getLocation();
if (l.getX() + radius1 < x) {
break;
}
if (l.getX() - radius1 < x && l.getY() + radius1 > y && l.getY() - radius1 < y &&
l.getZ() + radius1 > z && l.getZ() - radius1 < z && l.getWorld().equals(loc.getWorld()) && req.containsKey(r.getType())) {
if (req.get(r.getType()) < 2) {
req.remove(r.getType());
} else {
req.put(r.getType(), req.get(r.getType()) - 1);
}
}
}
if (!req.isEmpty()) {
for (Region r : regionManager.getContainingRegions(currentLocation)) {
String rType = regionManager.getRegion(r.getLocation()).getType();
if (req.containsKey(rType)) {
int amount = req.get(rType);
if (amount <= 1) {
req.remove(rType);
} else {
req.put(rType, amount - 1);
}
}
}
}
}
if (!req.isEmpty()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This area doesnt have all of the required regions.");
int j=0;
String message = ChatColor.GOLD + "";
for (String s : req.keySet()) {
if (message.length() + s.length() + 3 + req.get(s).toString().length() > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j >14) {
break;
} else {
message += req.get(s) + " " + s + ", ";
}
}
if (!req.isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
//Assimulate any child super regions
List<String> owners = new ArrayList<String>();
double balance = 0.0;
for (String s : quietDestroy) {
SuperRegion sr = regionManager.getSuperRegion(s);
for (String so : sr.getOwners()) {
if (!owners.contains(so))
owners.add(so);
}
for (String sm : sr.getMembers().keySet()) {
if (!members.containsKey(sm) && sr.getMember(sm).contains("member"))
members.put(sm, sr.getMember(sm));
}
balance += sr.getBalance();
}
//Check if more members needed to create the super-region
if (owners.size() + members.size() < currentRegionType.getPopulation()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need " + (currentRegionType.getPopulation() - owners.size() - members.size()) + " more members.");
return true;
}
for (String s : quietDestroy) {
regionManager.destroySuperRegion(s, false);
}
if (currentCharter > 0 && pendingCharters.containsKey(args[2])) {
configManager.removeCharter(args[2]);
pendingCharters.remove(args[2]);
}
String playername = player.getName();
if (!owners.contains(playername)) {
owners.add(playername);
}
if (costCheck > 0) {
econ.withdrawPlayer(player.getName(), costCheck);
}
if (heroes != null) {
Hero hero = heroes.getCharacterManager().getHero(player);
if (hero.hasParty()) {
hero.getParty().gainExp(currentRegionType.getExp(), ExperienceType.EXTERNAL, player.getLocation());
} else {
heroes.getCharacterManager().getHero(player).gainExp(currentRegionType.getExp(), ExperienceType.EXTERNAL, player.getLocation());
}
}
regionManager.addSuperRegion(args[2], currentLocation, regionTypeName, owners, members, currentRegionType.getDailyPower(), balance);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You've created a new " + args[1] + " called " + args[2]);
return true;
} else if (args.length > 0 && args[0].equalsIgnoreCase("listall")) {
if (args.length > 1) {
SuperRegionType srt = regionManager.getSuperRegionType(args[1]);
if (srt == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region type named " + args[1]);
return true;
}
String message = ChatColor.GOLD + "";
int j =0;
for (SuperRegion sr : regionManager.getSortedSuperRegions()) {
if (message.length() + sr.getName().length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += sr.getName() + ", ";
}
}
if (!message.equals(ChatColor.GOLD + "")) {
player.sendMessage(message);
}
} else {
String message = ChatColor.GOLD + "";
int j =0;
for (SuperRegion sr : regionManager.getSortedSuperRegions()) {
if (message.length() + sr.getName().length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += sr.getName() + ", ";
}
}
if (!message.equals(ChatColor.GOLD + "")) {
player.sendMessage(message);
}
}
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("withdraw")) {
if (econ == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] No econ plugin recognized");
return true;
}
double amount = 0;
try {
amount = Double.parseDouble(args[1]);
if (amount < 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Withdraw a positive amount only.");
return true;
}
} catch (Exception e) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Invalid amount /hs withdraw <amount> <superregionname>");
return true;
}
//Check if valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[2] + " is not a super-region");
return true;
}
//Check if owner or permitted member
if ((!sr.hasMember(player.getName()) || !sr.getMember(player.getName()).contains("withdraw")) && !sr.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not a member or dont have permission to withdraw");
return true;
}
//Check if bank has that money
double output = regionManager.getSuperRegionType(sr.getType()).getOutput();
if (output < 0 && sr.getBalance() - amount < -output) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You cant withdraw below the the minimum required.");
return true;
} else if (output >= 0 && sr.getBalance() - amount < 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr.getName() + " doesnt have that much money.");
return true;
}
//Withdraw the money
econ.depositPlayer(player.getName(), amount);
regionManager.addBalance(sr, -amount);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You withdrew " + amount + " in the bank of " + args[2]);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("deposit")) {
if (econ == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] No econ plugin recognized");
return true;
}
double amount = 0;
try {
amount = Double.parseDouble(args[1]);
if (amount < 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Nice try. Deposit a positive amount.");
return true;
}
} catch (Exception e) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Invalid amount /hs deposit <amount> <superregionname>");
return true;
}
//Check if player has that money
if (!econ.has(player.getName(), amount)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have that much money.");
return true;
}
//Check if valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[2] + " is not a super-region");
return true;
}
//Check if owner or member
if (!sr.hasMember(player.getName()) && !sr.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not a member of " + args[2]);
return true;
}
//Deposit the money
econ.withdrawPlayer(player.getName(), amount);
regionManager.addBalance(sr, amount);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You deposited " + amount + " in the bank of " + args[2]);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("settaxes")) {
String playername = player.getName();
//Check if the player is a owner or member of the super region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region called " + args[2]);
return true;
}
if (!sr.hasOwner(playername) && !sr.hasMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission to set taxes for " + args[2] + ".");
return true;
}
//Check if member has permission
if (sr.hasMember(playername) && !sr.getMember(playername).contains("settaxes")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission to set taxes for " + args[2] + ".");
return true;
}
//Check if valid amount
double taxes = 0;
try {
taxes = Double.parseDouble(args[1]);
double maxTax = configManager.getMaxTax();
- if (taxes < 0 && (maxTax == 0 || taxes <= maxTax)) {
- player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You cant set negative taxes.");
+ System.out.println(maxTax);
+ if (taxes < 0 || taxes > maxTax) {
+ player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You cant set taxes that high/low.");
return true;
}
} catch (Exception e) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Use /hs settaxes <amount> <superregionname>.");
return true;
}
//Set the taxes
regionManager.setTaxes(sr, taxes);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You've set " + args[2] + "'s taxes to " + args[1]);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("listperms")) {
//Get target player
String playername = "";
if (args.length > 3) {
Player currentPlayer = getServer().getPlayer(args[1]);
if (currentPlayer == null) {
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] Could not find " + args[1]);
return true;
} else {
playername = currentPlayer.getName();
}
} else {
playername = player.getName();
}
String message = ChatColor.GRAY + "[HeroStronghold] " + playername + " perms for " + args[2] + ":";
String message2 = ChatColor.GOLD + "";
//Check if the player is a owner or member of the super region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region called " + args[2]);
return true;
}
if (sr.hasOwner(playername)) {
player.sendMessage(message);
player.sendMessage(message2 + "All Permissions");
return true;
} else if (sr.hasMember(playername)) {
player.sendMessage(message);
int j=0;
for (String s : sr.getMember(label)) {
if (message2.length() + s.length() + 2 > 57) {
player.sendMessage(message2);
message2 = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message2 += s + ", ";
}
}
if (!sr.getMember(label).isEmpty()) {
player.sendMessage(message2.substring(0, message2.length() - 2));
}
return true;
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " doesn't belong to that region.");
return true;
} else if (args.length > 0 && args[0].equalsIgnoreCase("listallperms")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] List of all member permissions:");
player.sendMessage(ChatColor.GRAY + "member = is a member of the super-region.");
player.sendMessage(ChatColor.GRAY + "title:<title> = player's title in channel");
player.sendMessage(ChatColor.GRAY + "addmember = lets the player use /hs addmember");
player.sendMessage(ChatColor.GRAY + "<regiontype> = lets the player build that region type");
player.sendMessage(ChatColor.GRAY + "withdraw = lets the player withdraw from the bank");
return true;
} else if (args.length > 0 && args[0].equalsIgnoreCase("ch")) {
//Check if wanting to be set to any other channel
if (args.length == 1 || args[1].equalsIgnoreCase("o") || args[1].equalsIgnoreCase("all") || args[1].equalsIgnoreCase("none")) {
dpeListener.setPlayerChannel(player, "");
return true;
}
if (args.length < 2) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] /hs ch channelname. /hs ch (to go to all chat)");
return true;
}
//Check if valid super region
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region by that name (" + args[1] + ").");
player.sendMessage(ChatColor.GRAY + "Try /hs ch to go to all chat.");
return true;
}
//Check if player is a member or owner of that super-region
String playername = player.getName();
if (!sr.hasMember(playername) && !sr.hasOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You must be a member of " + args[1] + " before joining thier channel");
return true;
}
//Set the player as being in that channel
dpeListener.setPlayerChannel(player, args[1]);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("addmember")) {
//Check if valid super region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region by that name (" + args[2] + ").");
return true;
}
//Check if player is a member or owner of that super-region
String playername = player.getName();
boolean isOwner = sr.hasOwner(playername);
boolean isMember = sr.hasMember(playername);
boolean isAdmin = HeroStronghold.perms.has(player, "herostronghold.admin");
if (!isMember && !isOwner && !isAdmin) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You arent a member of " + args[2]);
return true;
}
//Check if player has permission to invite players
if (!isAdmin && isMember && !sr.getMember(playername).contains("addmember")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need permission addmember from an owner of " + args[2]);
return true;
}
//Check if valid player
Player invitee = getServer().getPlayer(args[1]);
if (invitee == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is not online.");
return true;
}
//Check permission herostronghold.join
if (!perms.has(invitee, "herostronghold.join")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " doesnt have permission to join a super-region.");
return true;
}
//Check if has housing effect and if has enough housing
if (regionManager.getSuperRegionType(sr.getType()).hasEffect("housing") && !regionManager.hasAvailableHousing(sr)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You cant addmember people to " + sr.getName() + " until you build more housing");
}
//Send an invite
pendingInvites.put(invitee.getName(), args[2]);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You have invited " + ChatColor.GOLD + invitee.getDisplayName() + ChatColor.GRAY + " to join " + ChatColor.GOLD + args[2]);
if (invitee != null)
invitee.sendMessage(ChatColor.GOLD + "[HeroStronghold] You have been invited to join " + args[2] + ". /hs accept " + args[2]);
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("accept")) {
//Check if player has a pending invite to that super-region
if (!pendingInvites.containsKey(player.getName()) || !pendingInvites.get(player.getName()).equals(args[1])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't have an invite to " + args[1]);
return true;
}
//Check if valid super region
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region by that name (" + args[1] + ").");
return true;
}
//Check if player is a member or owner of that super-region
String playername = player.getName();
if (sr.hasMember(playername) || sr.hasOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are already a member of " + args[1]);
return true;
}
//Add the player to the super region
ArrayList<String> perm = new ArrayList<String>();
perm.add("member");
regionManager.setMember(sr, player.getName(), perm);
pendingInvites.remove(player.getName());
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] Welcome to " + args[1]);
for (String s : sr.getMembers().keySet()) {
Player p = getServer().getPlayer(s);
if (p != null) {
p.sendMessage(ChatColor.GOLD + playername + " has joined " + args[1]);
}
}
for (String s : sr.getOwners()) {
Player p = getServer().getPlayer(s);
if (p != null) {
p.sendMessage(ChatColor.GOLD + playername + " has joined " + args[1]);
}
}
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("addowner")) {
Player p = getServer().getPlayer(args[1]);
String playername = args[1];
//Check valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region named " + args[2]);
return true;
}
//Check valid player
if (p == null && !sr.hasMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[Herostronghold] There is no player online named: " + args[1]);
return true;
} else {
playername = p.getName();
}
//Check if player is an owner of that region
if (!sr.hasOwner(player.getName()) && !HeroStronghold.perms.has(player, "herostronghold.admin")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You arent an owner of " + args[2]);
return true;
}
//Check if playername is already an owner
if (sr.hasOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is already an owner of " + args[2]);
return true;
}
//Check if player is member of super-region
if (!sr.hasMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is not a member of " + args[2]);
return true;
}
regionManager.removeMember(sr, playername);
if (p != null)
p.sendMessage(ChatColor.GOLD + "[HeroStronghold] You are now an owner of " + args[2]);
for (String s : sr.getMembers().keySet()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " is now an owner of " + args[2]);
}
}
for (String s : sr.getOwners()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " is now an owner of " + args[2]);
}
}
regionManager.setOwner(sr, playername);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("remove")) {
Player p = getServer().getPlayer(args[1]);
String playername = args[1];
//Check valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region named " + args[2]);
return true;
}
//Check valid player
if (p != null) {
playername = p.getName();
}
boolean isMember = sr.hasMember(playername);
boolean isOwner = sr.hasOwner(playername);
boolean isAdmin = HeroStronghold.perms.has(player, "herostronghold.admin");
//Check if player is member or owner of super-region
if (!isMember && !isOwner) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is not a member of " + args[2]);
return true;
}
//Check if player is removing self
if (playername.equalsIgnoreCase(player.getName())) {
if (isMember) {
regionManager.removeMember(sr, playername);
} else if (isOwner) {
regionManager.setOwner(sr, playername);
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You have left " + args[2]);
for (String s : sr.getMembers().keySet()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " left " + args[2]);
}
}
for (String s : sr.getOwners()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " left " + args[2]);
}
}
return true;
}
//Check if player has remove permission
if (!sr.hasOwner(player.getName()) && !(!sr.hasMember(player.getName()) || !sr.getMember(player.getName()).contains("remove"))
&& !isAdmin) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't have permission to remove that member.");
return true;
}
if (isMember) {
regionManager.removeMember(sr, playername);
} else if (isOwner) {
regionManager.setOwner(sr, playername);
} else {
return true;
}
if (p != null)
p.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are no longer a member of " + args[2]);
for (String s : sr.getMembers().keySet()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " was removed from " + args[2]);
}
}
for (String s : sr.getOwners()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " was removed from " + args[2]);
}
}
return true;
} else if (args.length > 3 && args[0].equalsIgnoreCase("toggleperm")) {
Player p = getServer().getPlayer(args[1]);
String playername = args[1];
//Check valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[3]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region named " + args[3]);
return true;
}
//Check if player is an owner of the super region
if (!sr.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You aren't an owner of " + args[3]);
return true;
}
//Check valid player
if (p == null && !sr.hasMember(args[1])) {
player.sendMessage(ChatColor.GRAY + "[Herostronghold] There is no player named: " + args[1]);
return true;
} else if (p != null) {
playername = p.getName();
}
//Check if player is member and not owner of super-region
if (!sr.hasMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " either owns, or is not a member of " + args[3]);
return true;
}
List<String> perm = sr.getMember(playername);
if (perm.contains(args[2])) {
perm.remove(args[2]);
regionManager.setMember(sr, playername, perm);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Removed perm " + args[2] + " for " + args[1] + " in " + args[3]);
if (p != null)
p.sendMessage(ChatColor.GRAY + "[HeroStronghold] Your perm " + args[2] + " was revoked in " + args[3]);
return true;
} else {
perm.add(args[2]);
regionManager.setMember(sr, playername, perm);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Added perm " + args[2] + " for " + args[1] + " in " + args[3]);
if (p != null)
p.sendMessage(ChatColor.GRAY + "[HeroStronghold] You were granted permission " + args[2] + " in " + args[3]);
return true;
}
} else if (args.length > 0 && args[0].equalsIgnoreCase("whatshere")) {
Location loc = player.getLocation();
boolean foundRegion = false;
for (Region r : regionManager.getContainingRegions(loc)) {
foundRegion = true;
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Found Region ID: " + ChatColor.GOLD + r.getID());
String message = ChatColor.GRAY + "Type: " + r.getType();
if (!r.getOwners().isEmpty()) {
message += ", Owned by: " + r.getOwners().get(0);
}
player.sendMessage(message);
}
for (SuperRegion sr : regionManager.getContainingSuperRegions(loc)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Found Super-Region named: " + ChatColor.GOLD + sr.getName());
String message = ChatColor.GRAY + "Type: " + sr.getType();
if (!sr.getOwners().isEmpty()) {
message += ", Owned by: " + sr.getOwners().get(0);
}
player.sendMessage(message);
}
if (!foundRegion) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There are no regions here.");
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("info")) {
//Check if valid regiontype or super-regiontype
RegionType rt = regionManager.getRegionType(args[1]);
SuperRegionType srt = regionManager.getSuperRegionType(args[1]);
if (rt == null && srt == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region type called " + args[1]);
return true;
}
if (rt != null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Info for region type " + ChatColor.GOLD + args[1] + ":");
player.sendMessage(ChatColor.GRAY + "Cost: " + ChatColor.GOLD + rt.getMoneyRequirement() + ChatColor.GRAY +
", Payout: " + ChatColor.GOLD + rt.getMoneyOutput() + ChatColor.GRAY + ", Radius: " + ChatColor.GOLD + (int) Math.sqrt(rt.getRadius()));
String message = ChatColor.GRAY + "Description: " + ChatColor.GOLD;
int j=0;
if (rt.getDescription() != null) {
String tempMess = rt.getDescription();
if (tempMess.length() + message.length() <= 55) {
player.sendMessage(message + tempMess);
tempMess = null;
}
while (tempMess != null && j<12) {
if (tempMess.length() > 53) {
message += tempMess.substring(0, 53);
player.sendMessage(message);
tempMess = tempMess.substring(53);
message = ChatColor.GOLD + "";
j++;
} else {
player.sendMessage(message + tempMess);
tempMess = null;
j++;
}
}
}
message = ChatColor.GRAY + "Effects: " + ChatColor.GOLD;
if (rt.getEffects() != null) {
for (String is : rt.getEffects()) {
String addLine = is.split("\\.")[0] + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getEffects() == null || rt.getEffects().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Requirements: " + ChatColor.GOLD;
if (rt.getRequirements() != null) {
for (ItemStack is : rt.getRequirements()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getRequirements() == null || rt.getRequirements().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Reagents: " + ChatColor.GOLD;
if (rt.getReagents() != null) {
for (ItemStack is : rt.getReagents()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getReagents() == null || rt.getReagents().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "UpkeepCost: " + ChatColor.GOLD;
if (rt.getUpkeep() != null) {
for (ItemStack is : rt.getUpkeep()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getUpkeep() == null || rt.getUpkeep().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Output: " + ChatColor.GOLD;
if (rt.getOutput() != null) {
for (ItemStack is : rt.getOutput()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getOutput() == null || rt.getOutput().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
} else if (srt != null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Info for super-region type " + ChatColor.GOLD + args[1] + ":");
player.sendMessage(ChatColor.GRAY + "Cost: " + ChatColor.GOLD + srt.getMoneyRequirement() + ChatColor.GRAY +
", Payout: " + ChatColor.GOLD + srt.getOutput());
player.sendMessage(ChatColor.GRAY + "Power: " + ChatColor.GOLD + srt.getMaxPower() + " (+" + srt.getDailyPower() + "), " +
ChatColor.GRAY + "Charter: " + ChatColor.GOLD + srt.getCharter() + ChatColor.GRAY + ", Radius: " + ChatColor.GOLD + (int) Math.sqrt(srt.getRadius()));
String message = ChatColor.GRAY + "Description: " + ChatColor.GOLD;
int j=0;
if (srt.getDescription() != null) {
String tempMess = srt.getDescription();
if (tempMess.length() + message.length() <= 55) {
player.sendMessage(message + tempMess);
tempMess = null;
}
while (tempMess != null && j<12) {
if (tempMess.length() > 53) {
message += tempMess.substring(0, 53);
player.sendMessage(message);
tempMess = tempMess.substring(53);
message = ChatColor.GOLD + "";
j++;
} else {
player.sendMessage(message + tempMess);
tempMess = null;
j++;
}
}
}
message = ChatColor.GRAY + "Effects: " + ChatColor.GOLD;
if (srt.getEffects() != null) {
for (String is : srt.getEffects()) {
String addLine = is + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 11) {
message += addLine;
} else {
break;
}
}
}
if (srt == null || srt.getEffects().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Requirements: " + ChatColor.GOLD;
if (srt.getRequirements() != null) {
for (String is : srt.getRequirements().keySet()) {
String addLine = is + ":" + srt.getRequirement(is) + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (srt.getRequirements() == null || srt.getRequirements().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Evolves from: " + ChatColor.GOLD;
if (srt.getChildren() != null) {
for (String is : srt.getChildren()) {
String addLine = is + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (srt.getChildren() == null || srt.getChildren().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("addowner")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer != null) {
playername = aPlayer.getName();
}
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
Resident res = null;
boolean townyOverride = false;
boolean factionsOverride = false;
if (HeroStronghold.towny != null) {
try {
res = TownyUniverse.getDataSource().getResident(player.getName());
if (TownyUniverse.getTownBlock(loc) != null &&
(TownyUniverse.getTownBlock(loc).getTown().getMayor().equals(res) ||
TownyUniverse.getTownBlock(loc).getTown().hasAssistant(res))) {
townyOverride = true;
}
} catch (Exception ex) {
}
}
if (HeroStronghold.factions != null) {
Faction f = Board.getFactionAt(new FLocation(loc));
if (f != null) {
if (f.getFPlayerAdmin().getPlayer().getName().equals(player.getName())) {
factionsOverride = true;
} else {
for (FPlayer fp : f.getFPlayersWhereRole(Role.MODERATOR)) {
if (fp.getPlayer().getName().equals(player.getName())) {
factionsOverride = true;
break;
}
}
}
}
}
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin")) ||
townyOverride || factionsOverride) {
if (r.isOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " is already an owner of this region.");
return true;
}
if (r.isMember(playername)) {
regionManager.setMember(r, playername);
}
regionManager.setOwner(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " as an owner.");
if (aPlayer != null) {
aPlayer.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "You're now a co-owner of " + player.getDisplayName() + "'s " + r.getType());
}
return true;
} else {
boolean takeover = false;
for (SuperRegion sr : regionManager.getContainingSuperRegions(loc)) {
if (!sr.hasOwner(player.getName())) {
takeover = false;
break;
}
if (regionManager.getSuperRegionType(sr.getType()).hasEffect("control")) {
takeover = true;
}
}
if (takeover) {
if (r.isOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " is already an owner of this region.");
return true;
}
if (r.isMember(playername)) {
regionManager.setMember(r, playername);
}
regionManager.setOwner(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " as an owner.");
if (aPlayer != null) {
aPlayer.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "You're now a co-owner of " + player.getDisplayName() + "'s " + r.getType());
}
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("addmember")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer == null) {
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
playername = args[1];
} else {
playername = "sr:" + sr.getName();
}
} else {
playername = aPlayer.getName();
}
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
if (r.isMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " is already a member of this region.");
return true;
}
if (r.isOwner(playername) && !(playername.equals(player.getName()) && r.getOwners().get(0).equals(player.getName()))) {
regionManager.setOwner(r, playername);
}
regionManager.setMember(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " to the region.");
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
return true;
} else if (args.length > 2 && args[0].equals("addmemberid")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer == null) {
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
playername = args[1];
} else {
playername = "sr:" + sr.getName();
}
} else {
playername = aPlayer.getName();
}
Region r = null;
try {
r = regionManager.getRegionByID(Integer.parseInt(args[2]));
r.getType();
} catch (Exception e) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is not a valid id");
return true;
}
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
if (r.isMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " is already a member of this region.");
return true;
}
if (r.isOwner(playername) && !(playername.equals(player.getName()) && r.getOwners().get(0).equals(player.getName()))) {
regionManager.setOwner(r, playername);
}
regionManager.setMember(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " to the region.");
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
} else if (args.length > 1 && args[0].equalsIgnoreCase("whereis")) {
RegionType rt = regionManager.getRegionType(args[1]);
if (rt == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region type " + args[1]);
return true;
}
boolean found = false;
for (Region r : regionManager.getSortedRegions()) {
if (r.isOwner(player.getName()) && r.getType().equals(args[1])) {
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] " + args[1] + " at " + ((int) r.getLocation().getX())
+ ", " + ((int) r.getLocation().getY()) + ", " + ((int) r.getLocation().getZ()));
found = true;
}
}
if (!found) {
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] " + args[1] + " not found.");
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("setowner")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer != null) {
playername = aPlayer.getName();
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " must be online to setowner");
return true;
}
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
//Check if too far away
try {
if (player.getLocation().distanceSquared(aPlayer.getLocation()) > regionManager.getRegionType(r.getType()).getRawRadius()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " must be close by also.");
return true;
}
} catch (IllegalArgumentException iae) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " must be close by also.");
return true;
}
if (r.isMember(playername)) {
regionManager.setMember(r, playername);
}
regionManager.setMember(r, player.getName());
regionManager.setOwner(r, player.getName());
regionManager.setPrimaryOwner(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " as an owner.");
if (aPlayer != null) {
aPlayer.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "You're now a co-owner of " + player.getDisplayName() + "'s " + r.getType());
}
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("remove")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer != null) {
playername = aPlayer.getName();
}
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
if (r.isPrimaryOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You must use /hs setowner to change the original owner.");
return true;
}
if (!r.isMember(playername) && !r.isOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " doesn't belong to this region");
return true;
}
if (r.isMember(playername)) {
regionManager.setMember(r, playername);
} else if (r.isOwner(playername)) {
regionManager.setOwner(r, playername);
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Removed " + playername + " from the region.");
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("destroy")) {
Location loc = player.getLocation();
Location locationToDestroy = null;
for (Region r : regionManager.getContainingRegions(loc)) {
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
regionManager.destroyRegion(r.getLocation());
locationToDestroy = r.getLocation();
break;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
if (locationToDestroy != null) {
regionManager.removeRegion(locationToDestroy);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Region destroyed.");
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("destroy")) {
//Check if valid region
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region named " + args[1]);
return true;
}
//Check if owner or admin of that region
if ((perms == null || !perms.has(player, "herostronghold.admin")) && (sr.getOwners().isEmpty() || !sr.getOwners().contains(player.getName()))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not the owner of that region.");
return true;
}
regionManager.destroySuperRegion(args[1], true);
return true;
} else if (args.length > 0 && args[0].equalsIgnoreCase("list")) {
int j=0;
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] list of Region Types");
String message = ChatColor.GOLD + "";
boolean permNull = perms == null;
boolean createAll = permNull || perms.has(player, "herostronghold.create.all");
for (String s : regionManager.getRegionTypes()) {
if (createAll || permNull || perms.has(player, "herostronghold.create." + s)) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
}
for (String s : regionManager.getSuperRegionTypes()) {
if (createAll || permNull || perms.has(player, "herostronghold.create." + s)) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
}
if (!message.equals(ChatColor.GOLD + "")) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("rename")) {
//Check if valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region by that name");
return true;
}
//Check if valid name
if (args[2].length() > 16 && Util.validateFileName(args[2])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That name is too long. Use 15 characters or less");
return true;
}
//Check if player can rename the super-region
if (!sr.hasOwner(player.getName()) && !HeroStronghold.perms.has(player, "herostronghold.admin")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't have permission to rename that super-region.");
return true;
}
double cost = configManager.getRenameCost();
if (HeroStronghold.econ != null && cost > 0) {
if (!HeroStronghold.econ.has(player.getName(), cost)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] It costs " + ChatColor.RED + cost + " to rename that.");
return true;
} else {
HeroStronghold.econ.withdrawPlayer(player.getName(), cost);
}
}
regionManager.destroySuperRegion(args[1], false);
regionManager.addSuperRegion(args[2], sr.getLocation(), sr.getType(), sr.getOwners(), sr.getMembers(), sr.getPower(), sr.getBalance());
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] " + args[1] + " is now " + args[2]);
return true;
} else if (args.length > 0 && (args[0].equalsIgnoreCase("show"))) {
return true;
} else if (args.length > 0 && (args[0].equalsIgnoreCase("stats") || args[0].equalsIgnoreCase("who"))) {
if (args.length == 1) {
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] ==:|" + ChatColor.GOLD + r.getID() + " (" + r.getType() + ") " + ChatColor.GRAY + "|:==");
String message = ChatColor.GRAY + "Owners: " + ChatColor.GOLD;
int j = 0;
for (String s : r.getOwners()) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!r.getOwners().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
message = ChatColor.GRAY + "Members: " + ChatColor.GOLD;
for (String s : r.getMembers()) {
if (message.length() + 2 + s.length() > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!r.getMembers().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
return true;
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There are no regions here.");
return true;
}
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr != null) {
//TODO make revenue include all owned regions within the super region
SuperRegionType srt = regionManager.getSuperRegionType(sr.getType());
int population = sr.getOwners().size() + sr.getMembers().size();
double revenue = sr.getTaxes() * population + srt.getOutput();
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] ==:|" + ChatColor.GOLD + sr.getName() + " (" + sr.getType() + ") " + ChatColor.GRAY + "|:==");
player.sendMessage(ChatColor.GRAY + "Population: " + ChatColor.GOLD + population + ChatColor.GRAY +
" Bank: " + (sr.getBalance() < srt.getOutput() ? ChatColor.RED : ChatColor.GOLD) + sr.getBalance() + ChatColor.GRAY +
" Power: " + (sr.getPower() < srt.getDailyPower() ? ChatColor.RED : ChatColor.GOLD) + sr.getPower() +
" (+" + srt.getDailyPower() + ") / " + srt.getMaxPower());
player.sendMessage(ChatColor.GRAY + "Taxes: " + ChatColor.GOLD + sr.getTaxes()
+ ChatColor.GRAY + " Total Revenue: " + (revenue < 0 ? ChatColor.RED : ChatColor.GOLD) + revenue +
ChatColor.GRAY + " Disabled: " + (regionManager.hasAllRequiredRegions(sr) ? (ChatColor.GOLD + "false") : (ChatColor.RED + "true")));
//TODO state why the sr is disabled
if (sr.hasMember(player.getName()) || sr.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "Location: " + ChatColor.GOLD + (int) sr.getLocation().getX() + ", " + (int) sr.getLocation().getY() + ", " + (int) sr.getLocation().getZ());
}
if (sr.getTaxes() != 0) {
String message = ChatColor.GRAY + "Tax Revenue History: " + ChatColor.GOLD;
for (double d : sr.getTaxRevenue()) {
message += d + ", ";
}
if (!sr.getTaxRevenue().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
}
String message = ChatColor.GRAY + "Owners: " + ChatColor.GOLD;
int j = 0;
for (String s : sr.getOwners()) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!sr.getOwners().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
message = ChatColor.GRAY + "Members: " + ChatColor.GOLD;
for (String s : sr.getMembers().keySet()) {
if (message.length() + 2 + s.length() > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!sr.getMembers().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
message = ChatColor.GRAY + "Wars: " + ChatColor.GOLD;
for (SuperRegion srr : regionManager.getWars(sr)) {
String s = srr.getName();
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!sr.getOwners().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
return true;
}
Player p = getServer().getPlayer(args[1]);
if (p != null) {
String playername = p.getName();
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + p.getDisplayName() + " is a member of:");
String message = ChatColor.GOLD + "";
int j = 0;
for (SuperRegion sr1 : regionManager.getSortedSuperRegions()) {
if (sr1.hasOwner(playername) || sr1.hasMember(playername)) {
if (message.length() + sr1.getName().length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += sr1.getName() + ", ";
}
}
}
if (!regionManager.getSortedRegions().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Could not find player or super-region by that name");
return true;
} else if (args.length > 0 && effectCommands.contains(args[0])) {
Bukkit.getServer().getPluginManager().callEvent(new CommandEffectEvent(args, player));
return true;
} else {
//TODO add a page 3 to help for more instruction?
if (args.length > 0 && args[args.length - 1].equals("2")) {
sender.sendMessage(ChatColor.GRAY + "[HeroStronghold] by " + ChatColor.GOLD + "Multitallented" + ChatColor.GRAY + ": <> = required, () = optional" +
ChatColor.GOLD + " Page 2");
sender.sendMessage(ChatColor.GRAY + "/hs accept <name>");
sender.sendMessage(ChatColor.GRAY + "/hs rename <name> <newname>");
sender.sendMessage(ChatColor.GRAY + "/hs settaxes <amount> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs withdraw|deposit <amount> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs listperms <playername> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs listallperms");
sender.sendMessage(ChatColor.GRAY + "/hs toggleperm <playername> <perm> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs destroy (name)");
sender.sendMessage(ChatColor.GRAY + "/hs ch (channel) -- Use /hs ch for all chat");
sender.sendMessage(ChatColor.GRAY + "Google 'HeroStronghold bukkit' for more info | " + ChatColor.GOLD + "Page 2/3");
} else if (args.length > 0 && args[args.length - 1].equals("3")) {
sender.sendMessage(ChatColor.GRAY + "[HeroStronghold] by " + ChatColor.GOLD + "Multitallented" + ChatColor.GRAY + ": <> = required, () = optional" +
ChatColor.GOLD + " Page 3");
sender.sendMessage(ChatColor.GRAY + "/hs war <mysuperregion> <enemysuperregion>");
sender.sendMessage(ChatColor.GRAY + "/hs peace <mysuperregion> <enemysuperregion>");
sender.sendMessage(ChatColor.GRAY + "Google 'HeroStronghold bukkit' for more info | " + ChatColor.GOLD + "Page 3/3");
} else {
sender.sendMessage(ChatColor.GRAY + "[HeroStronghold] by " + ChatColor.GOLD + "Multitallented" + ChatColor.GRAY + ": () = optional" +
ChatColor.GOLD + " Page 1");
sender.sendMessage(ChatColor.GRAY + "/hs list");
sender.sendMessage(ChatColor.GRAY + "/hs info <regiontype|superregiontype>");
sender.sendMessage(ChatColor.GRAY + "/hs charter <superregiontype> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs charterstats <name>");
sender.sendMessage(ChatColor.GRAY + "/hs signcharter <name>");
sender.sendMessage(ChatColor.GRAY + "/hs cancelcharter <name>");
sender.sendMessage(ChatColor.GRAY + "/hs create <regiontype> (name)");
sender.sendMessage(ChatColor.GRAY + "/hs addowner|addmember|remove <playername> (name)");
sender.sendMessage(ChatColor.GRAY + "/hs whatshere");
sender.sendMessage(ChatColor.GRAY + "Google 'HeroStronghold bukkit' for more info |" + ChatColor.GOLD + " Page 1/3");
}
return true;
}
}
public void addCommand(String command) {
effectCommands.add(command);
}
public boolean setupEconomy() {
RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
if (rsp != null) {
econ = rsp.getProvider();
if (econ != null)
System.out.println("[HeroStronghold] Hooked into " + econ.getName());
}
return econ != null;
}
private boolean setupPermissions()
{
RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
if (permissionProvider != null) {
perms = permissionProvider.getProvider();
if (perms != null)
System.out.println("[HeroStronghold] Hooked into " + perms.getName());
}
return (perms != null);
}
private void setupTowny() {
if (Bukkit.getPluginManager().isPluginEnabled("Towny")) {
try {
HeroStronghold.towny = (Towny) Bukkit.getPluginManager().getPlugin("Towny");
} catch (Exception e) {
return;
}
}
}
public RegionManager getRegionManager() {
return regionManager;
}
public void warning(String s) {
String warning = "[HeroStronghold] " + s;
Logger.getLogger("Minecraft").warning(warning);
}
public void setConfigManager(ConfigManager cm) {
configManager = cm;
}
public void setCharters(Map<String, List<String>> input) {
this.pendingCharters = input;
}
}
| true | true |
public boolean onCommand(CommandSender sender, org.bukkit.command.Command command, String label, String[] args) {
String debug = label;
for (String s : args) {
debug += " " + s;
}
System.out.println("[HeroStronghold] " + debug);
Player player = null;
try {
player = (Player) sender;
} catch (Exception e) {
}
if (args[0].equalsIgnoreCase("reload")) {
if (player != null && !(HeroStronghold.perms == null || HeroStronghold.perms.has(player, "herostronghold.admin"))) {
return true;
}
config = getConfig();
regionManager.reload();
configManager = new ConfigManager(config, this);
sender.sendMessage("[HeroStronghold] reloaded");
return true;
}
if (player == null) {
sender.sendMessage("[HeroStronghold] doesn't recognize non-player commands.");
return true;
}
if (args.length > 2 && args[0].equalsIgnoreCase("war")) {
//hs war mySR urSR
//Check for valid super-regions
SuperRegion sr1 = regionManager.getSuperRegion(args[1]);
SuperRegion sr2 = regionManager.getSuperRegion(args[2]);
if (sr1 == null || sr2 == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That isn't a valid super-region.");
return true;
}
//Check if already at war
if (regionManager.hasWar(sr1, sr2)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr1.getName() + " is already at war!");
return true;
}
//Check owner
if (!sr1.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not an owner of " + sr1.getName());
return true;
}
//Calculate Cost
ConfigManager cm = getConfigManager();
if (!cm.getUseWar()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This command is disabled in config.yml");
return true;
}
double cost = cm.getDeclareWarBase() + cm.getDeclareWarPer() * (sr1.getOwners().size() + sr1.getMembers().size() +
sr2.getOwners().size() + sr2.getMembers().size());
//Check money
if (HeroStronghold.econ != null) {
if (sr1.getBalance() < cost) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr1.getName() + " doesn't have enough money to war with " + sr2.getName());
return true;
} else {
regionManager.addBalance(sr1, -1 * cost);
}
}
regionManager.setWar(sr1, sr2);
final SuperRegion sr1a = sr1;
final SuperRegion sr2a = sr2;
new Runnable() {
@Override
public void run()
{
getServer().broadcastMessage(ChatColor.RED + "[HeroStronghold] " + sr1a.getName() + " has declared war on " + sr2a.getName() + "!");
}
}.run();
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("peace")) {
//hs peace mySR urSR
//Check for valid super-regions
SuperRegion sr1 = regionManager.getSuperRegion(args[1]);
SuperRegion sr2 = regionManager.getSuperRegion(args[2]);
if (sr1 == null || sr2 == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That isn't a valid super-region.");
return true;
}
//Check if already at war
if (!regionManager.hasWar(sr1, sr2)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr1.getName() + " isn't at war.");
return true;
}
//Check owner
if (!sr1.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not an owner of " + sr1.getName());
return true;
}
//Calculate Cost
ConfigManager cm = getConfigManager();
if (!cm.getUseWar()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This command is disabled in config.yml");
return true;
}
double cost = cm.getMakePeaceBase() + cm.getMakePeacePer() * (sr1.getOwners().size() + sr1.getMembers().size() +
sr2.getOwners().size() + sr2.getMembers().size());
//Check money
if (HeroStronghold.econ != null) {
if (sr1.getBalance() < cost) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr1.getName() + " doesn't have enough money to make peace with " + sr2.getName());
return true;
} else {
regionManager.addBalance(sr1, -1 * cost);
}
}
regionManager.setWar(sr1, sr2);
final SuperRegion sr1a = sr1;
final SuperRegion sr2a = sr2;
new Runnable() {
@Override
public void run()
{
getServer().broadcastMessage(ChatColor.RED + "[HeroStronghold] " + sr1a.getName() + " has made peace with " + sr2a.getName() + "!");
}
}.run();
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("charter")) {
//Check if valid super region
SuperRegionType currentRegionType = regionManager.getSuperRegionType(args[1]);
if (currentRegionType == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " isnt a valid region type");
int j=0;
String message = ChatColor.GOLD + "";
for (String s : regionManager.getSuperRegionTypes()) {
if (perms == null || (perms.has(player, "herostronghold.create.all") ||
perms.has(player, "herostronghold.create." + s))) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message + ", ");
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += ", " + s;
}
}
}
if (!message.equals(ChatColor.GOLD + "")) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
String regionTypeName = args[1].toLowerCase();
//Permission Check
if (perms != null && !perms.has(player, "herostronghold.create.all") &&
!perms.has(player, "herostronghold.create." + regionTypeName)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] you dont have permission to create a " + regionTypeName);
return true;
}
//Make sure the super-region requires a Charter
if (currentRegionType.getCharter() <= 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " doesnt require a charter. /hs create " + args[1]);
return true;
}
//Make sure the name isn't too long
if (args[2].length() > 15) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Sorry but that name is too long. (16 max)");
return true;
}
//Check if valid filename
if (!Util.validateFileName(args[2])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Sorry but that is an invalid filename.");
return true;
}
//Check if valid name
if (pendingCharters.containsKey(args[2].toLowerCase())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is already a charter or region with that name.");
return true;
}
if (getServer().getPlayerExact(args[2]) != null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Dont name a super-region after a player");
return true;
}
//Check if allowed super-region
if (regionManager.getSuperRegion(args[2]) != null && (!regionManager.getSuperRegion(args[2]).hasOwner(player.getName())
|| regionManager.getSuperRegion(args[2]).getType().equalsIgnoreCase(args[1]))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That exact super-region already exists.");
return true;
}
//Add the charter
List<String> tempList = new ArrayList<String>();
tempList.add(args[1]);
tempList.add(player.getName());
pendingCharters.put(args[2].toLowerCase(), tempList);
configManager.writeToCharter(args[2].toLowerCase(), tempList);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] Youve successfully created a charter for " + args[2]);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] Get other people to type /hs signcharter " + args[2] + " to get started.");
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("charterstats")) {
//Check if valid charter
if (!pendingCharters.containsKey(args[1].toLowerCase())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " isn't a valid charter type.");
return true;
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " signatures: ");
int j=0;
String message = ChatColor.GOLD + "";
List<String> charter = pendingCharters.get(args[1]);
if (charter != null) {
for (String s : charter) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!charter.isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
} else {
player.sendMessage(ChatColor.RED + "[HeroStronghold] There was an error loading that charter");
warning("Failed to load charter " + args[1] + ".yml");
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("signcharter")) {
//Check if valid name
if (!pendingCharters.containsKey(args[1].toLowerCase())) {
player.sendMessage(ChatColor.GRAY + "[Herostronghold] There is no charter for " + args[1]);
return true;
}
//Check permission
if (perms != null && !perms.has(player, "herostronghold.join")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission to sign a charter.");
return true;
}
//Sign Charter
List<String> charter = pendingCharters.get(args[1].toLowerCase());
//Check if the player has already signed the charter once
if (charter.contains(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You've already signed this charter.");
return true;
}
charter.add(player.getName());
configManager.writeToCharter(args[1], charter);
pendingCharters.put(args[1], charter);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You just signed the charter for " + args[1]);
int remaining = 0;
SuperRegionType srt = regionManager.getSuperRegionType(charter.get(0));
if (srt != null) {
remaining = srt.getCharter() - charter.size() + 1;
}
if (remaining > 0) {
player.sendMessage(ChatColor.GOLD + "" + remaining + " signatures to go!");
}
Player owner = getServer().getPlayer(charter.get(1));
if (owner != null && owner.isOnline()) {
owner.sendMessage(ChatColor.GOLD + "[HeroStronghold] " + player.getDisplayName() + " just signed your charter for " + args[1]);
if (remaining > 0) {
owner.sendMessage(ChatColor.GOLD + "" + remaining + " signatures to go!");
}
}
return true;
} else if (args.length > 1 && args[0].equals("cancelcharter")) {
if (!pendingCharters.containsKey(args[1].toLowerCase())) {
player.sendMessage(ChatColor.GRAY + "[Herostronghold] There is no charter for " + args[1]);
return true;
}
if (pendingCharters.get(args[1]).size() < 2 || !pendingCharters.get(args[1]).get(1).equals(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are the not owner of this charter.");
return true;
}
configManager.removeCharter(args[1]);
pendingCharters.remove(args[1]);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You have canceled the charter for " + args[1]);
return true;
} else if (args.length == 2 && args[0].equalsIgnoreCase("create")) {
String regionName = args[1];
//Permission Check
boolean nullPerms = perms == null;
boolean createAll = nullPerms || perms.has(player, "herostronghold.create.all");
if (!(nullPerms || createAll || perms.has(player, "herostronghold.create." + regionName))) {
//TODO add limited quantity permissions here
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] you dont have permission to create a " + regionName);
return true;
}
Location currentLocation = player.getLocation();
//Check if player is standing someplace where a chest can be placed.
Block currentBlock = currentLocation.getBlock();
if (currentBlock.getTypeId() != 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] please stand someplace where a chest can be placed.");
return true;
}
RegionType currentRegionType = regionManager.getRegionType(regionName);
if (currentRegionType == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + regionName + " isnt a valid region type");
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Try /hs create " + regionName + " <insert_name_here>");
return true;
}
//Check if player can afford to create this herostronghold
double costCheck = 0;
if (econ != null) {
double cost = currentRegionType.getMoneyRequirement();
if (econ.getBalance(player.getName()) < cost) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need $" + cost + " to make this type of structure.");
return true;
} else {
costCheck = cost;
}
}
//Check if over max number of regions of that type
if (regionManager.isAtMaxRegions(player, currentRegionType)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission to build more " + currentRegionType.getName());
return true;
}
//Check if too close to other HeroStrongholds
if (!regionManager.getContainingBuildRegions(currentLocation).isEmpty()) {
player.sendMessage (ChatColor.GRAY + "[HeroStronghold] You are too close to another HeroStronghold");
return true;
}
//Check if in a super region and if has permission to make that region
String playername = player.getName();
List<String> reqSuperRegion = currentRegionType.getSuperRegions();
boolean meetsReqs = reqSuperRegion == null || reqSuperRegion.isEmpty();
for (SuperRegion sr : regionManager.getContainingSuperRegions(currentLocation)) {
if (!meetsReqs && reqSuperRegion != null && reqSuperRegion.contains(sr.getType())) {
meetsReqs = true;
}
if (!sr.hasOwner(playername)) {
if (!sr.hasMember(playername) || !sr.getMember(playername).contains(regionName)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission from an owner of " + sr.getName()
+ " to create a " + regionName + " here");
return true;
}
}
}
if (!meetsReqs) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are required to build this " + regionName + " in a:");
String message = ChatColor.GOLD + "";
int j=0;
for (String s : reqSuperRegion) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!reqSuperRegion.isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
//Prepare a requirements checklist
ArrayList<ItemStack> requirements = currentRegionType.getRequirements();
Map<Integer, Integer> reqMap = null;
if (!requirements.isEmpty()) {
reqMap = new HashMap<Integer, Integer>();
for (ItemStack currentIS : requirements) {
reqMap.put(new Integer(currentIS.getTypeId()), new Integer(currentIS.getAmount()));
}
//Check the area for required blocks
int radius = (int) Math.sqrt(currentRegionType.getBuildRadius());
int lowerLeftX = (int) currentLocation.getX() - radius;
int lowerLeftY = (int) currentLocation.getY() - radius;
lowerLeftY = lowerLeftY < 0 ? 0 : lowerLeftY;
int lowerLeftZ = (int) currentLocation.getZ() - radius;
int upperRightX = (int) currentLocation.getX() + radius;
int upperRightY = (int) currentLocation.getY() + radius;
upperRightY = upperRightY > 255 ? 255 : upperRightY;
int upperRightZ = (int) currentLocation.getZ() + radius;
World world = currentLocation.getWorld();
outer: for (int x=lowerLeftX; x<upperRightX; x++) {
for (int z=lowerLeftZ; z<upperRightZ; z++) {
for (int y=lowerLeftY; y<upperRightY; y++) {
int type = world.getBlockTypeIdAt(x, y, z);
if (type != 0 && reqMap.containsKey(type)) {
if (reqMap.get(type) < 2) {
reqMap.remove(type);
if (reqMap.isEmpty()) {
break outer;
}
} else {
reqMap.put(type, reqMap.get(type) - 1);
}
}
}
}
}
}
if (reqMap != null && !reqMap.isEmpty()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] you don't have all of the required blocks in this structure.");
String message = ChatColor.GOLD + "";
int j=0;
for (int type : reqMap.keySet()) {
int reqAmount = reqMap.get(type);
String reqType = Material.getMaterial(type).name();
if (message.length() + reqAmount + reqType.length() + 3 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += reqAmount + ":" + reqType + ", ";
}
}
if (!reqMap.isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
//Create chest at players feet for tracking reagents and removing upkeep items
currentBlock.setType(Material.CHEST);
ArrayList<String> owners = new ArrayList<String>();
owners.add(player.getName());
if (costCheck > 0) {
econ.withdrawPlayer(player.getName(), costCheck);
}
if (heroes != null) {
heroes.getCharacterManager().getHero(player).gainExp(currentRegionType.getExp(), ExperienceType.EXTERNAL, player.getLocation());
}
regionManager.addRegion(currentLocation, regionName, owners);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "You successfully create a " + ChatColor.RED + regionName);
//Tell the player what reagents are required for it to work
String message = ChatColor.GOLD + "Reagents: ";
if (currentRegionType.getReagents() != null) {
int j=0;
for (ItemStack is : currentRegionType.getReagents()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j < 14) {
message += addLine;
} else {
break;
}
}
}
if (currentRegionType.getReagents() == null || currentRegionType.getReagents().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("create")) {
//Check if valid name (further name checking later)
if (args[2].length() > 16 || !Util.validateFileName(args[2])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That name is invalid.");
return true;
}
if (getServer().getPlayerExact(args[2]) != null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Dont name a super-region after a player.");
return true;
}
String regionTypeName = args[1];
//Permission Check
if (perms != null && !perms.has(player, "herostronghold.create.all") &&
!perms.has(player, "herostronghold.create." + regionTypeName)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] you dont have permission to create a " + regionTypeName);
return true;
}
//Check if valid super region
Location currentLocation = player.getLocation();
SuperRegionType currentRegionType = regionManager.getSuperRegionType(regionTypeName);
if (currentRegionType == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + regionTypeName + " isnt a valid region type");
int j=0;
String message = ChatColor.GOLD + "";
for (String s : regionManager.getSuperRegionTypes()) {
if (perms == null || (perms.has(player, "herostronghold.create.all") ||
perms.has(player, "herostronghold.create." + s))) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
}
if (!regionManager.getSuperRegionTypes().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
//Check if player can afford to create this herostronghold
double costCheck = 0;
if (econ != null) {
double cost = currentRegionType.getMoneyRequirement();
if (econ.getBalance(player.getName()) < cost) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need $" + cost + " to make this type of region.");
return true;
} else {
costCheck = cost;
}
}
Map<String, List<String>> members = new HashMap<String, List<String>>();
int currentCharter = currentRegionType.getCharter();
//Make sure the super-region has a valid charter
if (!HeroStronghold.perms.has(player, "herostronghold.admin")) {
if (currentCharter > 0) {
try {
if (!pendingCharters.containsKey(args[2])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need to start a charter first. /hs charter " + args[1] + " " + args[2]);
return true;
} else if (pendingCharters.get(args[2]).size() <= currentCharter) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need " + currentCharter + " signature(s). /hs signcharter " + args[2]);
return true;
} else if (!pendingCharters.get(args[2]).get(0).equalsIgnoreCase(args[1]) ||
!pendingCharters.get(args[2]).get(1).equalsIgnoreCase(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] The charter for this name is for a different region type or owner.");
player.sendMessage(ChatColor.GRAY + "Owner: " + pendingCharters.get(args[2]).get(1) + ", Type: " + pendingCharters.get(args[2]).get(0));
return true;
} else {
int i =0;
for (String s : pendingCharters.get(args[2])) {
ArrayList<String> tempArray = new ArrayList<String>();
tempArray.add("member");
if (i > 2) {
members.put(s, tempArray);
} else {
i++;
}
}
}
} catch (Exception e) {
warning("Possible failure to find correct charter for " + args[2]);
}
}
} else if (pendingCharters.containsKey(args[2])) {
if (currentCharter > 0) {
try {
if (pendingCharters.get(args[2]).size() <= currentCharter) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need " + currentCharter + " signature(s). /hs signcharter " + args[2]);
return true;
} else if (!pendingCharters.get(args[2]).get(0).equalsIgnoreCase(args[1]) ||
!pendingCharters.get(args[2]).get(1).equalsIgnoreCase(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] The charter for this name is for a different region type or owner.");
player.sendMessage(ChatColor.GRAY + "Owner: " + pendingCharters.get(args[2]).get(1) + ", Type: " + pendingCharters.get(args[2]).get(0));
return true;
} else {
int i =0;
for (String s : pendingCharters.get(args[2])) {
ArrayList<String> tempArray = new ArrayList<String>();
tempArray.add("member");
if (i > 2) {
members.put(s, tempArray);
} else {
i++;
}
}
}
} catch (Exception e) {
warning("Possible failure to find correct charter for " + args[2]);
}
}
}
Map<String, Integer> requirements = currentRegionType.getRequirements();
HashMap<String, Integer> req = new HashMap<String, Integer>();
for (String s : currentRegionType.getRequirements().keySet()) {
req.put(new String(s), new Integer(requirements.get(s)));
}
//Check for required regions
List<String> children = currentRegionType.getChildren();
if (children != null) {
for (String s : children) {
if (!req.containsKey(s))
req.put(new String(s), 1);
}
}
//Check if there already is a super-region by that name, but not if it's one of the child regions
if (regionManager.getSuperRegion(args[2]) != null && (children == null || !children.contains(regionManager.getSuperRegion(args[2]).getType()))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is already a super-region by that name.");
return true;
}
List<String> quietDestroy = new ArrayList<String>();
int radius = (int) currentRegionType.getRawRadius();
//Check if there is an overlapping super-region of the same type
for (SuperRegion sr : regionManager.getSortedSuperRegions()) {
try {
if (sr.getLocation().distance(currentLocation) < radius + regionManager.getSuperRegionType(sr.getType()).getRawRadius() &&
(sr.getType().equalsIgnoreCase(regionTypeName) || !sr.hasOwner(player.getName()))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr.getName() + " is already here.");
return true;
}
} catch (IllegalArgumentException iae) {
}
}
if (!req.isEmpty()) {
for (SuperRegion sr : regionManager.getContainingSuperRegions(currentLocation)) {
if (children.contains(sr.getType()) && sr.hasOwner(player.getName())) {
quietDestroy.add(sr.getName());
}
String rType = sr.getType();
if (!sr.hasOwner(player.getName()) && (!sr.hasMember(player.getName()) || !sr.getMember(player.getName()).contains(regionTypeName))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not permitted to build a " + regionTypeName + " inside " + sr.getName());
return true;
}
if (req.containsKey(rType)) {
int amount = req.get(rType);
if (amount < 2) {
req.remove(rType);
if (req.isEmpty()) {
break;
}
} else {
req.put(rType, amount - 1);
}
}
}
Location loc = player.getLocation();
double x = loc.getX();
double y = loc.getY();
double z = loc.getZ();
int radius1 = currentRegionType.getRawRadius();
for (Region r : regionManager.getSortedRegions()) {
Location l = r.getLocation();
if (l.getX() + radius1 < x) {
break;
}
if (l.getX() - radius1 < x && l.getY() + radius1 > y && l.getY() - radius1 < y &&
l.getZ() + radius1 > z && l.getZ() - radius1 < z && l.getWorld().equals(loc.getWorld()) && req.containsKey(r.getType())) {
if (req.get(r.getType()) < 2) {
req.remove(r.getType());
} else {
req.put(r.getType(), req.get(r.getType()) - 1);
}
}
}
if (!req.isEmpty()) {
for (Region r : regionManager.getContainingRegions(currentLocation)) {
String rType = regionManager.getRegion(r.getLocation()).getType();
if (req.containsKey(rType)) {
int amount = req.get(rType);
if (amount <= 1) {
req.remove(rType);
} else {
req.put(rType, amount - 1);
}
}
}
}
}
if (!req.isEmpty()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This area doesnt have all of the required regions.");
int j=0;
String message = ChatColor.GOLD + "";
for (String s : req.keySet()) {
if (message.length() + s.length() + 3 + req.get(s).toString().length() > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j >14) {
break;
} else {
message += req.get(s) + " " + s + ", ";
}
}
if (!req.isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
//Assimulate any child super regions
List<String> owners = new ArrayList<String>();
double balance = 0.0;
for (String s : quietDestroy) {
SuperRegion sr = regionManager.getSuperRegion(s);
for (String so : sr.getOwners()) {
if (!owners.contains(so))
owners.add(so);
}
for (String sm : sr.getMembers().keySet()) {
if (!members.containsKey(sm) && sr.getMember(sm).contains("member"))
members.put(sm, sr.getMember(sm));
}
balance += sr.getBalance();
}
//Check if more members needed to create the super-region
if (owners.size() + members.size() < currentRegionType.getPopulation()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need " + (currentRegionType.getPopulation() - owners.size() - members.size()) + " more members.");
return true;
}
for (String s : quietDestroy) {
regionManager.destroySuperRegion(s, false);
}
if (currentCharter > 0 && pendingCharters.containsKey(args[2])) {
configManager.removeCharter(args[2]);
pendingCharters.remove(args[2]);
}
String playername = player.getName();
if (!owners.contains(playername)) {
owners.add(playername);
}
if (costCheck > 0) {
econ.withdrawPlayer(player.getName(), costCheck);
}
if (heroes != null) {
Hero hero = heroes.getCharacterManager().getHero(player);
if (hero.hasParty()) {
hero.getParty().gainExp(currentRegionType.getExp(), ExperienceType.EXTERNAL, player.getLocation());
} else {
heroes.getCharacterManager().getHero(player).gainExp(currentRegionType.getExp(), ExperienceType.EXTERNAL, player.getLocation());
}
}
regionManager.addSuperRegion(args[2], currentLocation, regionTypeName, owners, members, currentRegionType.getDailyPower(), balance);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You've created a new " + args[1] + " called " + args[2]);
return true;
} else if (args.length > 0 && args[0].equalsIgnoreCase("listall")) {
if (args.length > 1) {
SuperRegionType srt = regionManager.getSuperRegionType(args[1]);
if (srt == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region type named " + args[1]);
return true;
}
String message = ChatColor.GOLD + "";
int j =0;
for (SuperRegion sr : regionManager.getSortedSuperRegions()) {
if (message.length() + sr.getName().length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += sr.getName() + ", ";
}
}
if (!message.equals(ChatColor.GOLD + "")) {
player.sendMessage(message);
}
} else {
String message = ChatColor.GOLD + "";
int j =0;
for (SuperRegion sr : regionManager.getSortedSuperRegions()) {
if (message.length() + sr.getName().length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += sr.getName() + ", ";
}
}
if (!message.equals(ChatColor.GOLD + "")) {
player.sendMessage(message);
}
}
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("withdraw")) {
if (econ == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] No econ plugin recognized");
return true;
}
double amount = 0;
try {
amount = Double.parseDouble(args[1]);
if (amount < 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Withdraw a positive amount only.");
return true;
}
} catch (Exception e) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Invalid amount /hs withdraw <amount> <superregionname>");
return true;
}
//Check if valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[2] + " is not a super-region");
return true;
}
//Check if owner or permitted member
if ((!sr.hasMember(player.getName()) || !sr.getMember(player.getName()).contains("withdraw")) && !sr.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not a member or dont have permission to withdraw");
return true;
}
//Check if bank has that money
double output = regionManager.getSuperRegionType(sr.getType()).getOutput();
if (output < 0 && sr.getBalance() - amount < -output) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You cant withdraw below the the minimum required.");
return true;
} else if (output >= 0 && sr.getBalance() - amount < 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr.getName() + " doesnt have that much money.");
return true;
}
//Withdraw the money
econ.depositPlayer(player.getName(), amount);
regionManager.addBalance(sr, -amount);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You withdrew " + amount + " in the bank of " + args[2]);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("deposit")) {
if (econ == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] No econ plugin recognized");
return true;
}
double amount = 0;
try {
amount = Double.parseDouble(args[1]);
if (amount < 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Nice try. Deposit a positive amount.");
return true;
}
} catch (Exception e) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Invalid amount /hs deposit <amount> <superregionname>");
return true;
}
//Check if player has that money
if (!econ.has(player.getName(), amount)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have that much money.");
return true;
}
//Check if valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[2] + " is not a super-region");
return true;
}
//Check if owner or member
if (!sr.hasMember(player.getName()) && !sr.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not a member of " + args[2]);
return true;
}
//Deposit the money
econ.withdrawPlayer(player.getName(), amount);
regionManager.addBalance(sr, amount);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You deposited " + amount + " in the bank of " + args[2]);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("settaxes")) {
String playername = player.getName();
//Check if the player is a owner or member of the super region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region called " + args[2]);
return true;
}
if (!sr.hasOwner(playername) && !sr.hasMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission to set taxes for " + args[2] + ".");
return true;
}
//Check if member has permission
if (sr.hasMember(playername) && !sr.getMember(playername).contains("settaxes")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission to set taxes for " + args[2] + ".");
return true;
}
//Check if valid amount
double taxes = 0;
try {
taxes = Double.parseDouble(args[1]);
double maxTax = configManager.getMaxTax();
if (taxes < 0 && (maxTax == 0 || taxes <= maxTax)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You cant set negative taxes.");
return true;
}
} catch (Exception e) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Use /hs settaxes <amount> <superregionname>.");
return true;
}
//Set the taxes
regionManager.setTaxes(sr, taxes);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You've set " + args[2] + "'s taxes to " + args[1]);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("listperms")) {
//Get target player
String playername = "";
if (args.length > 3) {
Player currentPlayer = getServer().getPlayer(args[1]);
if (currentPlayer == null) {
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] Could not find " + args[1]);
return true;
} else {
playername = currentPlayer.getName();
}
} else {
playername = player.getName();
}
String message = ChatColor.GRAY + "[HeroStronghold] " + playername + " perms for " + args[2] + ":";
String message2 = ChatColor.GOLD + "";
//Check if the player is a owner or member of the super region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region called " + args[2]);
return true;
}
if (sr.hasOwner(playername)) {
player.sendMessage(message);
player.sendMessage(message2 + "All Permissions");
return true;
} else if (sr.hasMember(playername)) {
player.sendMessage(message);
int j=0;
for (String s : sr.getMember(label)) {
if (message2.length() + s.length() + 2 > 57) {
player.sendMessage(message2);
message2 = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message2 += s + ", ";
}
}
if (!sr.getMember(label).isEmpty()) {
player.sendMessage(message2.substring(0, message2.length() - 2));
}
return true;
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " doesn't belong to that region.");
return true;
} else if (args.length > 0 && args[0].equalsIgnoreCase("listallperms")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] List of all member permissions:");
player.sendMessage(ChatColor.GRAY + "member = is a member of the super-region.");
player.sendMessage(ChatColor.GRAY + "title:<title> = player's title in channel");
player.sendMessage(ChatColor.GRAY + "addmember = lets the player use /hs addmember");
player.sendMessage(ChatColor.GRAY + "<regiontype> = lets the player build that region type");
player.sendMessage(ChatColor.GRAY + "withdraw = lets the player withdraw from the bank");
return true;
} else if (args.length > 0 && args[0].equalsIgnoreCase("ch")) {
//Check if wanting to be set to any other channel
if (args.length == 1 || args[1].equalsIgnoreCase("o") || args[1].equalsIgnoreCase("all") || args[1].equalsIgnoreCase("none")) {
dpeListener.setPlayerChannel(player, "");
return true;
}
if (args.length < 2) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] /hs ch channelname. /hs ch (to go to all chat)");
return true;
}
//Check if valid super region
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region by that name (" + args[1] + ").");
player.sendMessage(ChatColor.GRAY + "Try /hs ch to go to all chat.");
return true;
}
//Check if player is a member or owner of that super-region
String playername = player.getName();
if (!sr.hasMember(playername) && !sr.hasOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You must be a member of " + args[1] + " before joining thier channel");
return true;
}
//Set the player as being in that channel
dpeListener.setPlayerChannel(player, args[1]);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("addmember")) {
//Check if valid super region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region by that name (" + args[2] + ").");
return true;
}
//Check if player is a member or owner of that super-region
String playername = player.getName();
boolean isOwner = sr.hasOwner(playername);
boolean isMember = sr.hasMember(playername);
boolean isAdmin = HeroStronghold.perms.has(player, "herostronghold.admin");
if (!isMember && !isOwner && !isAdmin) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You arent a member of " + args[2]);
return true;
}
//Check if player has permission to invite players
if (!isAdmin && isMember && !sr.getMember(playername).contains("addmember")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need permission addmember from an owner of " + args[2]);
return true;
}
//Check if valid player
Player invitee = getServer().getPlayer(args[1]);
if (invitee == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is not online.");
return true;
}
//Check permission herostronghold.join
if (!perms.has(invitee, "herostronghold.join")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " doesnt have permission to join a super-region.");
return true;
}
//Check if has housing effect and if has enough housing
if (regionManager.getSuperRegionType(sr.getType()).hasEffect("housing") && !regionManager.hasAvailableHousing(sr)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You cant addmember people to " + sr.getName() + " until you build more housing");
}
//Send an invite
pendingInvites.put(invitee.getName(), args[2]);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You have invited " + ChatColor.GOLD + invitee.getDisplayName() + ChatColor.GRAY + " to join " + ChatColor.GOLD + args[2]);
if (invitee != null)
invitee.sendMessage(ChatColor.GOLD + "[HeroStronghold] You have been invited to join " + args[2] + ". /hs accept " + args[2]);
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("accept")) {
//Check if player has a pending invite to that super-region
if (!pendingInvites.containsKey(player.getName()) || !pendingInvites.get(player.getName()).equals(args[1])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't have an invite to " + args[1]);
return true;
}
//Check if valid super region
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region by that name (" + args[1] + ").");
return true;
}
//Check if player is a member or owner of that super-region
String playername = player.getName();
if (sr.hasMember(playername) || sr.hasOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are already a member of " + args[1]);
return true;
}
//Add the player to the super region
ArrayList<String> perm = new ArrayList<String>();
perm.add("member");
regionManager.setMember(sr, player.getName(), perm);
pendingInvites.remove(player.getName());
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] Welcome to " + args[1]);
for (String s : sr.getMembers().keySet()) {
Player p = getServer().getPlayer(s);
if (p != null) {
p.sendMessage(ChatColor.GOLD + playername + " has joined " + args[1]);
}
}
for (String s : sr.getOwners()) {
Player p = getServer().getPlayer(s);
if (p != null) {
p.sendMessage(ChatColor.GOLD + playername + " has joined " + args[1]);
}
}
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("addowner")) {
Player p = getServer().getPlayer(args[1]);
String playername = args[1];
//Check valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region named " + args[2]);
return true;
}
//Check valid player
if (p == null && !sr.hasMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[Herostronghold] There is no player online named: " + args[1]);
return true;
} else {
playername = p.getName();
}
//Check if player is an owner of that region
if (!sr.hasOwner(player.getName()) && !HeroStronghold.perms.has(player, "herostronghold.admin")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You arent an owner of " + args[2]);
return true;
}
//Check if playername is already an owner
if (sr.hasOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is already an owner of " + args[2]);
return true;
}
//Check if player is member of super-region
if (!sr.hasMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is not a member of " + args[2]);
return true;
}
regionManager.removeMember(sr, playername);
if (p != null)
p.sendMessage(ChatColor.GOLD + "[HeroStronghold] You are now an owner of " + args[2]);
for (String s : sr.getMembers().keySet()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " is now an owner of " + args[2]);
}
}
for (String s : sr.getOwners()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " is now an owner of " + args[2]);
}
}
regionManager.setOwner(sr, playername);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("remove")) {
Player p = getServer().getPlayer(args[1]);
String playername = args[1];
//Check valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region named " + args[2]);
return true;
}
//Check valid player
if (p != null) {
playername = p.getName();
}
boolean isMember = sr.hasMember(playername);
boolean isOwner = sr.hasOwner(playername);
boolean isAdmin = HeroStronghold.perms.has(player, "herostronghold.admin");
//Check if player is member or owner of super-region
if (!isMember && !isOwner) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is not a member of " + args[2]);
return true;
}
//Check if player is removing self
if (playername.equalsIgnoreCase(player.getName())) {
if (isMember) {
regionManager.removeMember(sr, playername);
} else if (isOwner) {
regionManager.setOwner(sr, playername);
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You have left " + args[2]);
for (String s : sr.getMembers().keySet()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " left " + args[2]);
}
}
for (String s : sr.getOwners()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " left " + args[2]);
}
}
return true;
}
//Check if player has remove permission
if (!sr.hasOwner(player.getName()) && !(!sr.hasMember(player.getName()) || !sr.getMember(player.getName()).contains("remove"))
&& !isAdmin) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't have permission to remove that member.");
return true;
}
if (isMember) {
regionManager.removeMember(sr, playername);
} else if (isOwner) {
regionManager.setOwner(sr, playername);
} else {
return true;
}
if (p != null)
p.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are no longer a member of " + args[2]);
for (String s : sr.getMembers().keySet()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " was removed from " + args[2]);
}
}
for (String s : sr.getOwners()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " was removed from " + args[2]);
}
}
return true;
} else if (args.length > 3 && args[0].equalsIgnoreCase("toggleperm")) {
Player p = getServer().getPlayer(args[1]);
String playername = args[1];
//Check valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[3]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region named " + args[3]);
return true;
}
//Check if player is an owner of the super region
if (!sr.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You aren't an owner of " + args[3]);
return true;
}
//Check valid player
if (p == null && !sr.hasMember(args[1])) {
player.sendMessage(ChatColor.GRAY + "[Herostronghold] There is no player named: " + args[1]);
return true;
} else if (p != null) {
playername = p.getName();
}
//Check if player is member and not owner of super-region
if (!sr.hasMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " either owns, or is not a member of " + args[3]);
return true;
}
List<String> perm = sr.getMember(playername);
if (perm.contains(args[2])) {
perm.remove(args[2]);
regionManager.setMember(sr, playername, perm);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Removed perm " + args[2] + " for " + args[1] + " in " + args[3]);
if (p != null)
p.sendMessage(ChatColor.GRAY + "[HeroStronghold] Your perm " + args[2] + " was revoked in " + args[3]);
return true;
} else {
perm.add(args[2]);
regionManager.setMember(sr, playername, perm);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Added perm " + args[2] + " for " + args[1] + " in " + args[3]);
if (p != null)
p.sendMessage(ChatColor.GRAY + "[HeroStronghold] You were granted permission " + args[2] + " in " + args[3]);
return true;
}
} else if (args.length > 0 && args[0].equalsIgnoreCase("whatshere")) {
Location loc = player.getLocation();
boolean foundRegion = false;
for (Region r : regionManager.getContainingRegions(loc)) {
foundRegion = true;
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Found Region ID: " + ChatColor.GOLD + r.getID());
String message = ChatColor.GRAY + "Type: " + r.getType();
if (!r.getOwners().isEmpty()) {
message += ", Owned by: " + r.getOwners().get(0);
}
player.sendMessage(message);
}
for (SuperRegion sr : regionManager.getContainingSuperRegions(loc)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Found Super-Region named: " + ChatColor.GOLD + sr.getName());
String message = ChatColor.GRAY + "Type: " + sr.getType();
if (!sr.getOwners().isEmpty()) {
message += ", Owned by: " + sr.getOwners().get(0);
}
player.sendMessage(message);
}
if (!foundRegion) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There are no regions here.");
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("info")) {
//Check if valid regiontype or super-regiontype
RegionType rt = regionManager.getRegionType(args[1]);
SuperRegionType srt = regionManager.getSuperRegionType(args[1]);
if (rt == null && srt == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region type called " + args[1]);
return true;
}
if (rt != null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Info for region type " + ChatColor.GOLD + args[1] + ":");
player.sendMessage(ChatColor.GRAY + "Cost: " + ChatColor.GOLD + rt.getMoneyRequirement() + ChatColor.GRAY +
", Payout: " + ChatColor.GOLD + rt.getMoneyOutput() + ChatColor.GRAY + ", Radius: " + ChatColor.GOLD + (int) Math.sqrt(rt.getRadius()));
String message = ChatColor.GRAY + "Description: " + ChatColor.GOLD;
int j=0;
if (rt.getDescription() != null) {
String tempMess = rt.getDescription();
if (tempMess.length() + message.length() <= 55) {
player.sendMessage(message + tempMess);
tempMess = null;
}
while (tempMess != null && j<12) {
if (tempMess.length() > 53) {
message += tempMess.substring(0, 53);
player.sendMessage(message);
tempMess = tempMess.substring(53);
message = ChatColor.GOLD + "";
j++;
} else {
player.sendMessage(message + tempMess);
tempMess = null;
j++;
}
}
}
message = ChatColor.GRAY + "Effects: " + ChatColor.GOLD;
if (rt.getEffects() != null) {
for (String is : rt.getEffects()) {
String addLine = is.split("\\.")[0] + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getEffects() == null || rt.getEffects().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Requirements: " + ChatColor.GOLD;
if (rt.getRequirements() != null) {
for (ItemStack is : rt.getRequirements()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getRequirements() == null || rt.getRequirements().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Reagents: " + ChatColor.GOLD;
if (rt.getReagents() != null) {
for (ItemStack is : rt.getReagents()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getReagents() == null || rt.getReagents().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "UpkeepCost: " + ChatColor.GOLD;
if (rt.getUpkeep() != null) {
for (ItemStack is : rt.getUpkeep()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getUpkeep() == null || rt.getUpkeep().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Output: " + ChatColor.GOLD;
if (rt.getOutput() != null) {
for (ItemStack is : rt.getOutput()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getOutput() == null || rt.getOutput().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
} else if (srt != null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Info for super-region type " + ChatColor.GOLD + args[1] + ":");
player.sendMessage(ChatColor.GRAY + "Cost: " + ChatColor.GOLD + srt.getMoneyRequirement() + ChatColor.GRAY +
", Payout: " + ChatColor.GOLD + srt.getOutput());
player.sendMessage(ChatColor.GRAY + "Power: " + ChatColor.GOLD + srt.getMaxPower() + " (+" + srt.getDailyPower() + "), " +
ChatColor.GRAY + "Charter: " + ChatColor.GOLD + srt.getCharter() + ChatColor.GRAY + ", Radius: " + ChatColor.GOLD + (int) Math.sqrt(srt.getRadius()));
String message = ChatColor.GRAY + "Description: " + ChatColor.GOLD;
int j=0;
if (srt.getDescription() != null) {
String tempMess = srt.getDescription();
if (tempMess.length() + message.length() <= 55) {
player.sendMessage(message + tempMess);
tempMess = null;
}
while (tempMess != null && j<12) {
if (tempMess.length() > 53) {
message += tempMess.substring(0, 53);
player.sendMessage(message);
tempMess = tempMess.substring(53);
message = ChatColor.GOLD + "";
j++;
} else {
player.sendMessage(message + tempMess);
tempMess = null;
j++;
}
}
}
message = ChatColor.GRAY + "Effects: " + ChatColor.GOLD;
if (srt.getEffects() != null) {
for (String is : srt.getEffects()) {
String addLine = is + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 11) {
message += addLine;
} else {
break;
}
}
}
if (srt == null || srt.getEffects().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Requirements: " + ChatColor.GOLD;
if (srt.getRequirements() != null) {
for (String is : srt.getRequirements().keySet()) {
String addLine = is + ":" + srt.getRequirement(is) + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (srt.getRequirements() == null || srt.getRequirements().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Evolves from: " + ChatColor.GOLD;
if (srt.getChildren() != null) {
for (String is : srt.getChildren()) {
String addLine = is + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (srt.getChildren() == null || srt.getChildren().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("addowner")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer != null) {
playername = aPlayer.getName();
}
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
Resident res = null;
boolean townyOverride = false;
boolean factionsOverride = false;
if (HeroStronghold.towny != null) {
try {
res = TownyUniverse.getDataSource().getResident(player.getName());
if (TownyUniverse.getTownBlock(loc) != null &&
(TownyUniverse.getTownBlock(loc).getTown().getMayor().equals(res) ||
TownyUniverse.getTownBlock(loc).getTown().hasAssistant(res))) {
townyOverride = true;
}
} catch (Exception ex) {
}
}
if (HeroStronghold.factions != null) {
Faction f = Board.getFactionAt(new FLocation(loc));
if (f != null) {
if (f.getFPlayerAdmin().getPlayer().getName().equals(player.getName())) {
factionsOverride = true;
} else {
for (FPlayer fp : f.getFPlayersWhereRole(Role.MODERATOR)) {
if (fp.getPlayer().getName().equals(player.getName())) {
factionsOverride = true;
break;
}
}
}
}
}
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin")) ||
townyOverride || factionsOverride) {
if (r.isOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " is already an owner of this region.");
return true;
}
if (r.isMember(playername)) {
regionManager.setMember(r, playername);
}
regionManager.setOwner(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " as an owner.");
if (aPlayer != null) {
aPlayer.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "You're now a co-owner of " + player.getDisplayName() + "'s " + r.getType());
}
return true;
} else {
boolean takeover = false;
for (SuperRegion sr : regionManager.getContainingSuperRegions(loc)) {
if (!sr.hasOwner(player.getName())) {
takeover = false;
break;
}
if (regionManager.getSuperRegionType(sr.getType()).hasEffect("control")) {
takeover = true;
}
}
if (takeover) {
if (r.isOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " is already an owner of this region.");
return true;
}
if (r.isMember(playername)) {
regionManager.setMember(r, playername);
}
regionManager.setOwner(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " as an owner.");
if (aPlayer != null) {
aPlayer.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "You're now a co-owner of " + player.getDisplayName() + "'s " + r.getType());
}
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("addmember")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer == null) {
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
playername = args[1];
} else {
playername = "sr:" + sr.getName();
}
} else {
playername = aPlayer.getName();
}
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
if (r.isMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " is already a member of this region.");
return true;
}
if (r.isOwner(playername) && !(playername.equals(player.getName()) && r.getOwners().get(0).equals(player.getName()))) {
regionManager.setOwner(r, playername);
}
regionManager.setMember(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " to the region.");
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
return true;
} else if (args.length > 2 && args[0].equals("addmemberid")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer == null) {
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
playername = args[1];
} else {
playername = "sr:" + sr.getName();
}
} else {
playername = aPlayer.getName();
}
Region r = null;
try {
r = regionManager.getRegionByID(Integer.parseInt(args[2]));
r.getType();
} catch (Exception e) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is not a valid id");
return true;
}
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
if (r.isMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " is already a member of this region.");
return true;
}
if (r.isOwner(playername) && !(playername.equals(player.getName()) && r.getOwners().get(0).equals(player.getName()))) {
regionManager.setOwner(r, playername);
}
regionManager.setMember(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " to the region.");
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
} else if (args.length > 1 && args[0].equalsIgnoreCase("whereis")) {
RegionType rt = regionManager.getRegionType(args[1]);
if (rt == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region type " + args[1]);
return true;
}
boolean found = false;
for (Region r : regionManager.getSortedRegions()) {
if (r.isOwner(player.getName()) && r.getType().equals(args[1])) {
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] " + args[1] + " at " + ((int) r.getLocation().getX())
+ ", " + ((int) r.getLocation().getY()) + ", " + ((int) r.getLocation().getZ()));
found = true;
}
}
if (!found) {
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] " + args[1] + " not found.");
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("setowner")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer != null) {
playername = aPlayer.getName();
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " must be online to setowner");
return true;
}
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
//Check if too far away
try {
if (player.getLocation().distanceSquared(aPlayer.getLocation()) > regionManager.getRegionType(r.getType()).getRawRadius()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " must be close by also.");
return true;
}
} catch (IllegalArgumentException iae) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " must be close by also.");
return true;
}
if (r.isMember(playername)) {
regionManager.setMember(r, playername);
}
regionManager.setMember(r, player.getName());
regionManager.setOwner(r, player.getName());
regionManager.setPrimaryOwner(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " as an owner.");
if (aPlayer != null) {
aPlayer.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "You're now a co-owner of " + player.getDisplayName() + "'s " + r.getType());
}
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("remove")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer != null) {
playername = aPlayer.getName();
}
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
if (r.isPrimaryOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You must use /hs setowner to change the original owner.");
return true;
}
if (!r.isMember(playername) && !r.isOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " doesn't belong to this region");
return true;
}
if (r.isMember(playername)) {
regionManager.setMember(r, playername);
} else if (r.isOwner(playername)) {
regionManager.setOwner(r, playername);
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Removed " + playername + " from the region.");
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("destroy")) {
Location loc = player.getLocation();
Location locationToDestroy = null;
for (Region r : regionManager.getContainingRegions(loc)) {
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
regionManager.destroyRegion(r.getLocation());
locationToDestroy = r.getLocation();
break;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
if (locationToDestroy != null) {
regionManager.removeRegion(locationToDestroy);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Region destroyed.");
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("destroy")) {
//Check if valid region
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region named " + args[1]);
return true;
}
//Check if owner or admin of that region
if ((perms == null || !perms.has(player, "herostronghold.admin")) && (sr.getOwners().isEmpty() || !sr.getOwners().contains(player.getName()))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not the owner of that region.");
return true;
}
regionManager.destroySuperRegion(args[1], true);
return true;
} else if (args.length > 0 && args[0].equalsIgnoreCase("list")) {
int j=0;
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] list of Region Types");
String message = ChatColor.GOLD + "";
boolean permNull = perms == null;
boolean createAll = permNull || perms.has(player, "herostronghold.create.all");
for (String s : regionManager.getRegionTypes()) {
if (createAll || permNull || perms.has(player, "herostronghold.create." + s)) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
}
for (String s : regionManager.getSuperRegionTypes()) {
if (createAll || permNull || perms.has(player, "herostronghold.create." + s)) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
}
if (!message.equals(ChatColor.GOLD + "")) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("rename")) {
//Check if valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region by that name");
return true;
}
//Check if valid name
if (args[2].length() > 16 && Util.validateFileName(args[2])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That name is too long. Use 15 characters or less");
return true;
}
//Check if player can rename the super-region
if (!sr.hasOwner(player.getName()) && !HeroStronghold.perms.has(player, "herostronghold.admin")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't have permission to rename that super-region.");
return true;
}
double cost = configManager.getRenameCost();
if (HeroStronghold.econ != null && cost > 0) {
if (!HeroStronghold.econ.has(player.getName(), cost)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] It costs " + ChatColor.RED + cost + " to rename that.");
return true;
} else {
HeroStronghold.econ.withdrawPlayer(player.getName(), cost);
}
}
regionManager.destroySuperRegion(args[1], false);
regionManager.addSuperRegion(args[2], sr.getLocation(), sr.getType(), sr.getOwners(), sr.getMembers(), sr.getPower(), sr.getBalance());
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] " + args[1] + " is now " + args[2]);
return true;
} else if (args.length > 0 && (args[0].equalsIgnoreCase("show"))) {
return true;
} else if (args.length > 0 && (args[0].equalsIgnoreCase("stats") || args[0].equalsIgnoreCase("who"))) {
if (args.length == 1) {
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] ==:|" + ChatColor.GOLD + r.getID() + " (" + r.getType() + ") " + ChatColor.GRAY + "|:==");
String message = ChatColor.GRAY + "Owners: " + ChatColor.GOLD;
int j = 0;
for (String s : r.getOwners()) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!r.getOwners().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
message = ChatColor.GRAY + "Members: " + ChatColor.GOLD;
for (String s : r.getMembers()) {
if (message.length() + 2 + s.length() > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!r.getMembers().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
return true;
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There are no regions here.");
return true;
}
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr != null) {
//TODO make revenue include all owned regions within the super region
SuperRegionType srt = regionManager.getSuperRegionType(sr.getType());
int population = sr.getOwners().size() + sr.getMembers().size();
double revenue = sr.getTaxes() * population + srt.getOutput();
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] ==:|" + ChatColor.GOLD + sr.getName() + " (" + sr.getType() + ") " + ChatColor.GRAY + "|:==");
player.sendMessage(ChatColor.GRAY + "Population: " + ChatColor.GOLD + population + ChatColor.GRAY +
" Bank: " + (sr.getBalance() < srt.getOutput() ? ChatColor.RED : ChatColor.GOLD) + sr.getBalance() + ChatColor.GRAY +
" Power: " + (sr.getPower() < srt.getDailyPower() ? ChatColor.RED : ChatColor.GOLD) + sr.getPower() +
" (+" + srt.getDailyPower() + ") / " + srt.getMaxPower());
player.sendMessage(ChatColor.GRAY + "Taxes: " + ChatColor.GOLD + sr.getTaxes()
+ ChatColor.GRAY + " Total Revenue: " + (revenue < 0 ? ChatColor.RED : ChatColor.GOLD) + revenue +
ChatColor.GRAY + " Disabled: " + (regionManager.hasAllRequiredRegions(sr) ? (ChatColor.GOLD + "false") : (ChatColor.RED + "true")));
//TODO state why the sr is disabled
if (sr.hasMember(player.getName()) || sr.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "Location: " + ChatColor.GOLD + (int) sr.getLocation().getX() + ", " + (int) sr.getLocation().getY() + ", " + (int) sr.getLocation().getZ());
}
if (sr.getTaxes() != 0) {
String message = ChatColor.GRAY + "Tax Revenue History: " + ChatColor.GOLD;
for (double d : sr.getTaxRevenue()) {
message += d + ", ";
}
if (!sr.getTaxRevenue().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
}
String message = ChatColor.GRAY + "Owners: " + ChatColor.GOLD;
int j = 0;
for (String s : sr.getOwners()) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!sr.getOwners().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
message = ChatColor.GRAY + "Members: " + ChatColor.GOLD;
for (String s : sr.getMembers().keySet()) {
if (message.length() + 2 + s.length() > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!sr.getMembers().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
message = ChatColor.GRAY + "Wars: " + ChatColor.GOLD;
for (SuperRegion srr : regionManager.getWars(sr)) {
String s = srr.getName();
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!sr.getOwners().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
return true;
}
Player p = getServer().getPlayer(args[1]);
if (p != null) {
String playername = p.getName();
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + p.getDisplayName() + " is a member of:");
String message = ChatColor.GOLD + "";
int j = 0;
for (SuperRegion sr1 : regionManager.getSortedSuperRegions()) {
if (sr1.hasOwner(playername) || sr1.hasMember(playername)) {
if (message.length() + sr1.getName().length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += sr1.getName() + ", ";
}
}
}
if (!regionManager.getSortedRegions().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Could not find player or super-region by that name");
return true;
} else if (args.length > 0 && effectCommands.contains(args[0])) {
Bukkit.getServer().getPluginManager().callEvent(new CommandEffectEvent(args, player));
return true;
} else {
//TODO add a page 3 to help for more instruction?
if (args.length > 0 && args[args.length - 1].equals("2")) {
sender.sendMessage(ChatColor.GRAY + "[HeroStronghold] by " + ChatColor.GOLD + "Multitallented" + ChatColor.GRAY + ": <> = required, () = optional" +
ChatColor.GOLD + " Page 2");
sender.sendMessage(ChatColor.GRAY + "/hs accept <name>");
sender.sendMessage(ChatColor.GRAY + "/hs rename <name> <newname>");
sender.sendMessage(ChatColor.GRAY + "/hs settaxes <amount> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs withdraw|deposit <amount> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs listperms <playername> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs listallperms");
sender.sendMessage(ChatColor.GRAY + "/hs toggleperm <playername> <perm> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs destroy (name)");
sender.sendMessage(ChatColor.GRAY + "/hs ch (channel) -- Use /hs ch for all chat");
sender.sendMessage(ChatColor.GRAY + "Google 'HeroStronghold bukkit' for more info | " + ChatColor.GOLD + "Page 2/3");
} else if (args.length > 0 && args[args.length - 1].equals("3")) {
sender.sendMessage(ChatColor.GRAY + "[HeroStronghold] by " + ChatColor.GOLD + "Multitallented" + ChatColor.GRAY + ": <> = required, () = optional" +
ChatColor.GOLD + " Page 3");
sender.sendMessage(ChatColor.GRAY + "/hs war <mysuperregion> <enemysuperregion>");
sender.sendMessage(ChatColor.GRAY + "/hs peace <mysuperregion> <enemysuperregion>");
sender.sendMessage(ChatColor.GRAY + "Google 'HeroStronghold bukkit' for more info | " + ChatColor.GOLD + "Page 3/3");
} else {
sender.sendMessage(ChatColor.GRAY + "[HeroStronghold] by " + ChatColor.GOLD + "Multitallented" + ChatColor.GRAY + ": () = optional" +
ChatColor.GOLD + " Page 1");
sender.sendMessage(ChatColor.GRAY + "/hs list");
sender.sendMessage(ChatColor.GRAY + "/hs info <regiontype|superregiontype>");
sender.sendMessage(ChatColor.GRAY + "/hs charter <superregiontype> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs charterstats <name>");
sender.sendMessage(ChatColor.GRAY + "/hs signcharter <name>");
sender.sendMessage(ChatColor.GRAY + "/hs cancelcharter <name>");
sender.sendMessage(ChatColor.GRAY + "/hs create <regiontype> (name)");
sender.sendMessage(ChatColor.GRAY + "/hs addowner|addmember|remove <playername> (name)");
sender.sendMessage(ChatColor.GRAY + "/hs whatshere");
sender.sendMessage(ChatColor.GRAY + "Google 'HeroStronghold bukkit' for more info |" + ChatColor.GOLD + " Page 1/3");
}
return true;
}
}
|
public boolean onCommand(CommandSender sender, org.bukkit.command.Command command, String label, String[] args) {
String debug = label;
for (String s : args) {
debug += " " + s;
}
System.out.println("[HeroStronghold] " + debug);
Player player = null;
try {
player = (Player) sender;
} catch (Exception e) {
}
if (args[0].equalsIgnoreCase("reload")) {
if (player != null && !(HeroStronghold.perms == null || HeroStronghold.perms.has(player, "herostronghold.admin"))) {
return true;
}
config = getConfig();
regionManager.reload();
configManager = new ConfigManager(config, this);
sender.sendMessage("[HeroStronghold] reloaded");
return true;
}
if (player == null) {
sender.sendMessage("[HeroStronghold] doesn't recognize non-player commands.");
return true;
}
if (args.length > 2 && args[0].equalsIgnoreCase("war")) {
//hs war mySR urSR
//Check for valid super-regions
SuperRegion sr1 = regionManager.getSuperRegion(args[1]);
SuperRegion sr2 = regionManager.getSuperRegion(args[2]);
if (sr1 == null || sr2 == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That isn't a valid super-region.");
return true;
}
//Check if already at war
if (regionManager.hasWar(sr1, sr2)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr1.getName() + " is already at war!");
return true;
}
//Check owner
if (!sr1.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not an owner of " + sr1.getName());
return true;
}
//Calculate Cost
ConfigManager cm = getConfigManager();
if (!cm.getUseWar()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This command is disabled in config.yml");
return true;
}
double cost = cm.getDeclareWarBase() + cm.getDeclareWarPer() * (sr1.getOwners().size() + sr1.getMembers().size() +
sr2.getOwners().size() + sr2.getMembers().size());
//Check money
if (HeroStronghold.econ != null) {
if (sr1.getBalance() < cost) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr1.getName() + " doesn't have enough money to war with " + sr2.getName());
return true;
} else {
regionManager.addBalance(sr1, -1 * cost);
}
}
regionManager.setWar(sr1, sr2);
final SuperRegion sr1a = sr1;
final SuperRegion sr2a = sr2;
new Runnable() {
@Override
public void run()
{
getServer().broadcastMessage(ChatColor.RED + "[HeroStronghold] " + sr1a.getName() + " has declared war on " + sr2a.getName() + "!");
}
}.run();
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("peace")) {
//hs peace mySR urSR
//Check for valid super-regions
SuperRegion sr1 = regionManager.getSuperRegion(args[1]);
SuperRegion sr2 = regionManager.getSuperRegion(args[2]);
if (sr1 == null || sr2 == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That isn't a valid super-region.");
return true;
}
//Check if already at war
if (!regionManager.hasWar(sr1, sr2)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr1.getName() + " isn't at war.");
return true;
}
//Check owner
if (!sr1.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not an owner of " + sr1.getName());
return true;
}
//Calculate Cost
ConfigManager cm = getConfigManager();
if (!cm.getUseWar()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This command is disabled in config.yml");
return true;
}
double cost = cm.getMakePeaceBase() + cm.getMakePeacePer() * (sr1.getOwners().size() + sr1.getMembers().size() +
sr2.getOwners().size() + sr2.getMembers().size());
//Check money
if (HeroStronghold.econ != null) {
if (sr1.getBalance() < cost) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr1.getName() + " doesn't have enough money to make peace with " + sr2.getName());
return true;
} else {
regionManager.addBalance(sr1, -1 * cost);
}
}
regionManager.setWar(sr1, sr2);
final SuperRegion sr1a = sr1;
final SuperRegion sr2a = sr2;
new Runnable() {
@Override
public void run()
{
getServer().broadcastMessage(ChatColor.RED + "[HeroStronghold] " + sr1a.getName() + " has made peace with " + sr2a.getName() + "!");
}
}.run();
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("charter")) {
//Check if valid super region
SuperRegionType currentRegionType = regionManager.getSuperRegionType(args[1]);
if (currentRegionType == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " isnt a valid region type");
int j=0;
String message = ChatColor.GOLD + "";
for (String s : regionManager.getSuperRegionTypes()) {
if (perms == null || (perms.has(player, "herostronghold.create.all") ||
perms.has(player, "herostronghold.create." + s))) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message + ", ");
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += ", " + s;
}
}
}
if (!message.equals(ChatColor.GOLD + "")) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
String regionTypeName = args[1].toLowerCase();
//Permission Check
if (perms != null && !perms.has(player, "herostronghold.create.all") &&
!perms.has(player, "herostronghold.create." + regionTypeName)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] you dont have permission to create a " + regionTypeName);
return true;
}
//Make sure the super-region requires a Charter
if (currentRegionType.getCharter() <= 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " doesnt require a charter. /hs create " + args[1]);
return true;
}
//Make sure the name isn't too long
if (args[2].length() > 15) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Sorry but that name is too long. (16 max)");
return true;
}
//Check if valid filename
if (!Util.validateFileName(args[2])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Sorry but that is an invalid filename.");
return true;
}
//Check if valid name
if (pendingCharters.containsKey(args[2].toLowerCase())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is already a charter or region with that name.");
return true;
}
if (getServer().getPlayerExact(args[2]) != null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Dont name a super-region after a player");
return true;
}
//Check if allowed super-region
if (regionManager.getSuperRegion(args[2]) != null && (!regionManager.getSuperRegion(args[2]).hasOwner(player.getName())
|| regionManager.getSuperRegion(args[2]).getType().equalsIgnoreCase(args[1]))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That exact super-region already exists.");
return true;
}
//Add the charter
List<String> tempList = new ArrayList<String>();
tempList.add(args[1]);
tempList.add(player.getName());
pendingCharters.put(args[2].toLowerCase(), tempList);
configManager.writeToCharter(args[2].toLowerCase(), tempList);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] Youve successfully created a charter for " + args[2]);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] Get other people to type /hs signcharter " + args[2] + " to get started.");
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("charterstats")) {
//Check if valid charter
if (!pendingCharters.containsKey(args[1].toLowerCase())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " isn't a valid charter type.");
return true;
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " signatures: ");
int j=0;
String message = ChatColor.GOLD + "";
List<String> charter = pendingCharters.get(args[1]);
if (charter != null) {
for (String s : charter) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!charter.isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
} else {
player.sendMessage(ChatColor.RED + "[HeroStronghold] There was an error loading that charter");
warning("Failed to load charter " + args[1] + ".yml");
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("signcharter")) {
//Check if valid name
if (!pendingCharters.containsKey(args[1].toLowerCase())) {
player.sendMessage(ChatColor.GRAY + "[Herostronghold] There is no charter for " + args[1]);
return true;
}
//Check permission
if (perms != null && !perms.has(player, "herostronghold.join")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission to sign a charter.");
return true;
}
//Sign Charter
List<String> charter = pendingCharters.get(args[1].toLowerCase());
//Check if the player has already signed the charter once
if (charter.contains(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You've already signed this charter.");
return true;
}
charter.add(player.getName());
configManager.writeToCharter(args[1], charter);
pendingCharters.put(args[1], charter);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You just signed the charter for " + args[1]);
int remaining = 0;
SuperRegionType srt = regionManager.getSuperRegionType(charter.get(0));
if (srt != null) {
remaining = srt.getCharter() - charter.size() + 1;
}
if (remaining > 0) {
player.sendMessage(ChatColor.GOLD + "" + remaining + " signatures to go!");
}
Player owner = getServer().getPlayer(charter.get(1));
if (owner != null && owner.isOnline()) {
owner.sendMessage(ChatColor.GOLD + "[HeroStronghold] " + player.getDisplayName() + " just signed your charter for " + args[1]);
if (remaining > 0) {
owner.sendMessage(ChatColor.GOLD + "" + remaining + " signatures to go!");
}
}
return true;
} else if (args.length > 1 && args[0].equals("cancelcharter")) {
if (!pendingCharters.containsKey(args[1].toLowerCase())) {
player.sendMessage(ChatColor.GRAY + "[Herostronghold] There is no charter for " + args[1]);
return true;
}
if (pendingCharters.get(args[1]).size() < 2 || !pendingCharters.get(args[1]).get(1).equals(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are the not owner of this charter.");
return true;
}
configManager.removeCharter(args[1]);
pendingCharters.remove(args[1]);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You have canceled the charter for " + args[1]);
return true;
} else if (args.length == 2 && args[0].equalsIgnoreCase("create")) {
String regionName = args[1];
//Permission Check
boolean nullPerms = perms == null;
boolean createAll = nullPerms || perms.has(player, "herostronghold.create.all");
if (!(nullPerms || createAll || perms.has(player, "herostronghold.create." + regionName))) {
//TODO add limited quantity permissions here
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] you dont have permission to create a " + regionName);
return true;
}
Location currentLocation = player.getLocation();
//Check if player is standing someplace where a chest can be placed.
Block currentBlock = currentLocation.getBlock();
if (currentBlock.getTypeId() != 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] please stand someplace where a chest can be placed.");
return true;
}
RegionType currentRegionType = regionManager.getRegionType(regionName);
if (currentRegionType == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + regionName + " isnt a valid region type");
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Try /hs create " + regionName + " <insert_name_here>");
return true;
}
//Check if player can afford to create this herostronghold
double costCheck = 0;
if (econ != null) {
double cost = currentRegionType.getMoneyRequirement();
if (econ.getBalance(player.getName()) < cost) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need $" + cost + " to make this type of structure.");
return true;
} else {
costCheck = cost;
}
}
//Check if over max number of regions of that type
if (regionManager.isAtMaxRegions(player, currentRegionType)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission to build more " + currentRegionType.getName());
return true;
}
//Check if too close to other HeroStrongholds
if (!regionManager.getContainingBuildRegions(currentLocation).isEmpty()) {
player.sendMessage (ChatColor.GRAY + "[HeroStronghold] You are too close to another HeroStronghold");
return true;
}
//Check if in a super region and if has permission to make that region
String playername = player.getName();
List<String> reqSuperRegion = currentRegionType.getSuperRegions();
boolean meetsReqs = reqSuperRegion == null || reqSuperRegion.isEmpty();
for (SuperRegion sr : regionManager.getContainingSuperRegions(currentLocation)) {
if (!meetsReqs && reqSuperRegion != null && reqSuperRegion.contains(sr.getType())) {
meetsReqs = true;
}
if (!sr.hasOwner(playername)) {
if (!sr.hasMember(playername) || !sr.getMember(playername).contains(regionName)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission from an owner of " + sr.getName()
+ " to create a " + regionName + " here");
return true;
}
}
}
if (!meetsReqs) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are required to build this " + regionName + " in a:");
String message = ChatColor.GOLD + "";
int j=0;
for (String s : reqSuperRegion) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!reqSuperRegion.isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
//Prepare a requirements checklist
ArrayList<ItemStack> requirements = currentRegionType.getRequirements();
Map<Integer, Integer> reqMap = null;
if (!requirements.isEmpty()) {
reqMap = new HashMap<Integer, Integer>();
for (ItemStack currentIS : requirements) {
reqMap.put(new Integer(currentIS.getTypeId()), new Integer(currentIS.getAmount()));
}
//Check the area for required blocks
int radius = (int) Math.sqrt(currentRegionType.getBuildRadius());
int lowerLeftX = (int) currentLocation.getX() - radius;
int lowerLeftY = (int) currentLocation.getY() - radius;
lowerLeftY = lowerLeftY < 0 ? 0 : lowerLeftY;
int lowerLeftZ = (int) currentLocation.getZ() - radius;
int upperRightX = (int) currentLocation.getX() + radius;
int upperRightY = (int) currentLocation.getY() + radius;
upperRightY = upperRightY > 255 ? 255 : upperRightY;
int upperRightZ = (int) currentLocation.getZ() + radius;
World world = currentLocation.getWorld();
outer: for (int x=lowerLeftX; x<upperRightX; x++) {
for (int z=lowerLeftZ; z<upperRightZ; z++) {
for (int y=lowerLeftY; y<upperRightY; y++) {
int type = world.getBlockTypeIdAt(x, y, z);
if (type != 0 && reqMap.containsKey(type)) {
if (reqMap.get(type) < 2) {
reqMap.remove(type);
if (reqMap.isEmpty()) {
break outer;
}
} else {
reqMap.put(type, reqMap.get(type) - 1);
}
}
}
}
}
}
if (reqMap != null && !reqMap.isEmpty()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] you don't have all of the required blocks in this structure.");
String message = ChatColor.GOLD + "";
int j=0;
for (int type : reqMap.keySet()) {
int reqAmount = reqMap.get(type);
String reqType = Material.getMaterial(type).name();
if (message.length() + reqAmount + reqType.length() + 3 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += reqAmount + ":" + reqType + ", ";
}
}
if (!reqMap.isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
//Create chest at players feet for tracking reagents and removing upkeep items
currentBlock.setType(Material.CHEST);
ArrayList<String> owners = new ArrayList<String>();
owners.add(player.getName());
if (costCheck > 0) {
econ.withdrawPlayer(player.getName(), costCheck);
}
if (heroes != null) {
heroes.getCharacterManager().getHero(player).gainExp(currentRegionType.getExp(), ExperienceType.EXTERNAL, player.getLocation());
}
regionManager.addRegion(currentLocation, regionName, owners);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "You successfully create a " + ChatColor.RED + regionName);
//Tell the player what reagents are required for it to work
String message = ChatColor.GOLD + "Reagents: ";
if (currentRegionType.getReagents() != null) {
int j=0;
for (ItemStack is : currentRegionType.getReagents()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j < 14) {
message += addLine;
} else {
break;
}
}
}
if (currentRegionType.getReagents() == null || currentRegionType.getReagents().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("create")) {
//Check if valid name (further name checking later)
if (args[2].length() > 16 || !Util.validateFileName(args[2])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That name is invalid.");
return true;
}
if (getServer().getPlayerExact(args[2]) != null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Dont name a super-region after a player.");
return true;
}
String regionTypeName = args[1];
//Permission Check
if (perms != null && !perms.has(player, "herostronghold.create.all") &&
!perms.has(player, "herostronghold.create." + regionTypeName)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] you dont have permission to create a " + regionTypeName);
return true;
}
//Check if valid super region
Location currentLocation = player.getLocation();
SuperRegionType currentRegionType = regionManager.getSuperRegionType(regionTypeName);
if (currentRegionType == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + regionTypeName + " isnt a valid region type");
int j=0;
String message = ChatColor.GOLD + "";
for (String s : regionManager.getSuperRegionTypes()) {
if (perms == null || (perms.has(player, "herostronghold.create.all") ||
perms.has(player, "herostronghold.create." + s))) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
}
if (!regionManager.getSuperRegionTypes().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
//Check if player can afford to create this herostronghold
double costCheck = 0;
if (econ != null) {
double cost = currentRegionType.getMoneyRequirement();
if (econ.getBalance(player.getName()) < cost) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need $" + cost + " to make this type of region.");
return true;
} else {
costCheck = cost;
}
}
Map<String, List<String>> members = new HashMap<String, List<String>>();
int currentCharter = currentRegionType.getCharter();
//Make sure the super-region has a valid charter
if (!HeroStronghold.perms.has(player, "herostronghold.admin")) {
if (currentCharter > 0) {
try {
if (!pendingCharters.containsKey(args[2])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need to start a charter first. /hs charter " + args[1] + " " + args[2]);
return true;
} else if (pendingCharters.get(args[2]).size() <= currentCharter) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need " + currentCharter + " signature(s). /hs signcharter " + args[2]);
return true;
} else if (!pendingCharters.get(args[2]).get(0).equalsIgnoreCase(args[1]) ||
!pendingCharters.get(args[2]).get(1).equalsIgnoreCase(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] The charter for this name is for a different region type or owner.");
player.sendMessage(ChatColor.GRAY + "Owner: " + pendingCharters.get(args[2]).get(1) + ", Type: " + pendingCharters.get(args[2]).get(0));
return true;
} else {
int i =0;
for (String s : pendingCharters.get(args[2])) {
ArrayList<String> tempArray = new ArrayList<String>();
tempArray.add("member");
if (i > 2) {
members.put(s, tempArray);
} else {
i++;
}
}
}
} catch (Exception e) {
warning("Possible failure to find correct charter for " + args[2]);
}
}
} else if (pendingCharters.containsKey(args[2])) {
if (currentCharter > 0) {
try {
if (pendingCharters.get(args[2]).size() <= currentCharter) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need " + currentCharter + " signature(s). /hs signcharter " + args[2]);
return true;
} else if (!pendingCharters.get(args[2]).get(0).equalsIgnoreCase(args[1]) ||
!pendingCharters.get(args[2]).get(1).equalsIgnoreCase(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] The charter for this name is for a different region type or owner.");
player.sendMessage(ChatColor.GRAY + "Owner: " + pendingCharters.get(args[2]).get(1) + ", Type: " + pendingCharters.get(args[2]).get(0));
return true;
} else {
int i =0;
for (String s : pendingCharters.get(args[2])) {
ArrayList<String> tempArray = new ArrayList<String>();
tempArray.add("member");
if (i > 2) {
members.put(s, tempArray);
} else {
i++;
}
}
}
} catch (Exception e) {
warning("Possible failure to find correct charter for " + args[2]);
}
}
}
Map<String, Integer> requirements = currentRegionType.getRequirements();
HashMap<String, Integer> req = new HashMap<String, Integer>();
for (String s : currentRegionType.getRequirements().keySet()) {
req.put(new String(s), new Integer(requirements.get(s)));
}
//Check for required regions
List<String> children = currentRegionType.getChildren();
if (children != null) {
for (String s : children) {
if (!req.containsKey(s))
req.put(new String(s), 1);
}
}
//Check if there already is a super-region by that name, but not if it's one of the child regions
if (regionManager.getSuperRegion(args[2]) != null && (children == null || !children.contains(regionManager.getSuperRegion(args[2]).getType()))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is already a super-region by that name.");
return true;
}
List<String> quietDestroy = new ArrayList<String>();
int radius = (int) currentRegionType.getRawRadius();
//Check if there is an overlapping super-region of the same type
for (SuperRegion sr : regionManager.getSortedSuperRegions()) {
try {
if (sr.getLocation().distance(currentLocation) < radius + regionManager.getSuperRegionType(sr.getType()).getRawRadius() &&
(sr.getType().equalsIgnoreCase(regionTypeName) || !sr.hasOwner(player.getName()))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr.getName() + " is already here.");
return true;
}
} catch (IllegalArgumentException iae) {
}
}
if (!req.isEmpty()) {
for (SuperRegion sr : regionManager.getContainingSuperRegions(currentLocation)) {
if (children.contains(sr.getType()) && sr.hasOwner(player.getName())) {
quietDestroy.add(sr.getName());
}
String rType = sr.getType();
if (!sr.hasOwner(player.getName()) && (!sr.hasMember(player.getName()) || !sr.getMember(player.getName()).contains(regionTypeName))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not permitted to build a " + regionTypeName + " inside " + sr.getName());
return true;
}
if (req.containsKey(rType)) {
int amount = req.get(rType);
if (amount < 2) {
req.remove(rType);
if (req.isEmpty()) {
break;
}
} else {
req.put(rType, amount - 1);
}
}
}
Location loc = player.getLocation();
double x = loc.getX();
double y = loc.getY();
double z = loc.getZ();
int radius1 = currentRegionType.getRawRadius();
for (Region r : regionManager.getSortedRegions()) {
Location l = r.getLocation();
if (l.getX() + radius1 < x) {
break;
}
if (l.getX() - radius1 < x && l.getY() + radius1 > y && l.getY() - radius1 < y &&
l.getZ() + radius1 > z && l.getZ() - radius1 < z && l.getWorld().equals(loc.getWorld()) && req.containsKey(r.getType())) {
if (req.get(r.getType()) < 2) {
req.remove(r.getType());
} else {
req.put(r.getType(), req.get(r.getType()) - 1);
}
}
}
if (!req.isEmpty()) {
for (Region r : regionManager.getContainingRegions(currentLocation)) {
String rType = regionManager.getRegion(r.getLocation()).getType();
if (req.containsKey(rType)) {
int amount = req.get(rType);
if (amount <= 1) {
req.remove(rType);
} else {
req.put(rType, amount - 1);
}
}
}
}
}
if (!req.isEmpty()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This area doesnt have all of the required regions.");
int j=0;
String message = ChatColor.GOLD + "";
for (String s : req.keySet()) {
if (message.length() + s.length() + 3 + req.get(s).toString().length() > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j >14) {
break;
} else {
message += req.get(s) + " " + s + ", ";
}
}
if (!req.isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
//Assimulate any child super regions
List<String> owners = new ArrayList<String>();
double balance = 0.0;
for (String s : quietDestroy) {
SuperRegion sr = regionManager.getSuperRegion(s);
for (String so : sr.getOwners()) {
if (!owners.contains(so))
owners.add(so);
}
for (String sm : sr.getMembers().keySet()) {
if (!members.containsKey(sm) && sr.getMember(sm).contains("member"))
members.put(sm, sr.getMember(sm));
}
balance += sr.getBalance();
}
//Check if more members needed to create the super-region
if (owners.size() + members.size() < currentRegionType.getPopulation()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need " + (currentRegionType.getPopulation() - owners.size() - members.size()) + " more members.");
return true;
}
for (String s : quietDestroy) {
regionManager.destroySuperRegion(s, false);
}
if (currentCharter > 0 && pendingCharters.containsKey(args[2])) {
configManager.removeCharter(args[2]);
pendingCharters.remove(args[2]);
}
String playername = player.getName();
if (!owners.contains(playername)) {
owners.add(playername);
}
if (costCheck > 0) {
econ.withdrawPlayer(player.getName(), costCheck);
}
if (heroes != null) {
Hero hero = heroes.getCharacterManager().getHero(player);
if (hero.hasParty()) {
hero.getParty().gainExp(currentRegionType.getExp(), ExperienceType.EXTERNAL, player.getLocation());
} else {
heroes.getCharacterManager().getHero(player).gainExp(currentRegionType.getExp(), ExperienceType.EXTERNAL, player.getLocation());
}
}
regionManager.addSuperRegion(args[2], currentLocation, regionTypeName, owners, members, currentRegionType.getDailyPower(), balance);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You've created a new " + args[1] + " called " + args[2]);
return true;
} else if (args.length > 0 && args[0].equalsIgnoreCase("listall")) {
if (args.length > 1) {
SuperRegionType srt = regionManager.getSuperRegionType(args[1]);
if (srt == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region type named " + args[1]);
return true;
}
String message = ChatColor.GOLD + "";
int j =0;
for (SuperRegion sr : regionManager.getSortedSuperRegions()) {
if (message.length() + sr.getName().length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += sr.getName() + ", ";
}
}
if (!message.equals(ChatColor.GOLD + "")) {
player.sendMessage(message);
}
} else {
String message = ChatColor.GOLD + "";
int j =0;
for (SuperRegion sr : regionManager.getSortedSuperRegions()) {
if (message.length() + sr.getName().length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += sr.getName() + ", ";
}
}
if (!message.equals(ChatColor.GOLD + "")) {
player.sendMessage(message);
}
}
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("withdraw")) {
if (econ == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] No econ plugin recognized");
return true;
}
double amount = 0;
try {
amount = Double.parseDouble(args[1]);
if (amount < 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Withdraw a positive amount only.");
return true;
}
} catch (Exception e) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Invalid amount /hs withdraw <amount> <superregionname>");
return true;
}
//Check if valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[2] + " is not a super-region");
return true;
}
//Check if owner or permitted member
if ((!sr.hasMember(player.getName()) || !sr.getMember(player.getName()).contains("withdraw")) && !sr.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not a member or dont have permission to withdraw");
return true;
}
//Check if bank has that money
double output = regionManager.getSuperRegionType(sr.getType()).getOutput();
if (output < 0 && sr.getBalance() - amount < -output) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You cant withdraw below the the minimum required.");
return true;
} else if (output >= 0 && sr.getBalance() - amount < 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + sr.getName() + " doesnt have that much money.");
return true;
}
//Withdraw the money
econ.depositPlayer(player.getName(), amount);
regionManager.addBalance(sr, -amount);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You withdrew " + amount + " in the bank of " + args[2]);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("deposit")) {
if (econ == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] No econ plugin recognized");
return true;
}
double amount = 0;
try {
amount = Double.parseDouble(args[1]);
if (amount < 0) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Nice try. Deposit a positive amount.");
return true;
}
} catch (Exception e) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Invalid amount /hs deposit <amount> <superregionname>");
return true;
}
//Check if player has that money
if (!econ.has(player.getName(), amount)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have that much money.");
return true;
}
//Check if valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[2] + " is not a super-region");
return true;
}
//Check if owner or member
if (!sr.hasMember(player.getName()) && !sr.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not a member of " + args[2]);
return true;
}
//Deposit the money
econ.withdrawPlayer(player.getName(), amount);
regionManager.addBalance(sr, amount);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You deposited " + amount + " in the bank of " + args[2]);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("settaxes")) {
String playername = player.getName();
//Check if the player is a owner or member of the super region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region called " + args[2]);
return true;
}
if (!sr.hasOwner(playername) && !sr.hasMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission to set taxes for " + args[2] + ".");
return true;
}
//Check if member has permission
if (sr.hasMember(playername) && !sr.getMember(playername).contains("settaxes")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You dont have permission to set taxes for " + args[2] + ".");
return true;
}
//Check if valid amount
double taxes = 0;
try {
taxes = Double.parseDouble(args[1]);
double maxTax = configManager.getMaxTax();
System.out.println(maxTax);
if (taxes < 0 || taxes > maxTax) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You cant set taxes that high/low.");
return true;
}
} catch (Exception e) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Use /hs settaxes <amount> <superregionname>.");
return true;
}
//Set the taxes
regionManager.setTaxes(sr, taxes);
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] You've set " + args[2] + "'s taxes to " + args[1]);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("listperms")) {
//Get target player
String playername = "";
if (args.length > 3) {
Player currentPlayer = getServer().getPlayer(args[1]);
if (currentPlayer == null) {
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] Could not find " + args[1]);
return true;
} else {
playername = currentPlayer.getName();
}
} else {
playername = player.getName();
}
String message = ChatColor.GRAY + "[HeroStronghold] " + playername + " perms for " + args[2] + ":";
String message2 = ChatColor.GOLD + "";
//Check if the player is a owner or member of the super region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region called " + args[2]);
return true;
}
if (sr.hasOwner(playername)) {
player.sendMessage(message);
player.sendMessage(message2 + "All Permissions");
return true;
} else if (sr.hasMember(playername)) {
player.sendMessage(message);
int j=0;
for (String s : sr.getMember(label)) {
if (message2.length() + s.length() + 2 > 57) {
player.sendMessage(message2);
message2 = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message2 += s + ", ";
}
}
if (!sr.getMember(label).isEmpty()) {
player.sendMessage(message2.substring(0, message2.length() - 2));
}
return true;
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " doesn't belong to that region.");
return true;
} else if (args.length > 0 && args[0].equalsIgnoreCase("listallperms")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] List of all member permissions:");
player.sendMessage(ChatColor.GRAY + "member = is a member of the super-region.");
player.sendMessage(ChatColor.GRAY + "title:<title> = player's title in channel");
player.sendMessage(ChatColor.GRAY + "addmember = lets the player use /hs addmember");
player.sendMessage(ChatColor.GRAY + "<regiontype> = lets the player build that region type");
player.sendMessage(ChatColor.GRAY + "withdraw = lets the player withdraw from the bank");
return true;
} else if (args.length > 0 && args[0].equalsIgnoreCase("ch")) {
//Check if wanting to be set to any other channel
if (args.length == 1 || args[1].equalsIgnoreCase("o") || args[1].equalsIgnoreCase("all") || args[1].equalsIgnoreCase("none")) {
dpeListener.setPlayerChannel(player, "");
return true;
}
if (args.length < 2) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] /hs ch channelname. /hs ch (to go to all chat)");
return true;
}
//Check if valid super region
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region by that name (" + args[1] + ").");
player.sendMessage(ChatColor.GRAY + "Try /hs ch to go to all chat.");
return true;
}
//Check if player is a member or owner of that super-region
String playername = player.getName();
if (!sr.hasMember(playername) && !sr.hasOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You must be a member of " + args[1] + " before joining thier channel");
return true;
}
//Set the player as being in that channel
dpeListener.setPlayerChannel(player, args[1]);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("addmember")) {
//Check if valid super region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region by that name (" + args[2] + ").");
return true;
}
//Check if player is a member or owner of that super-region
String playername = player.getName();
boolean isOwner = sr.hasOwner(playername);
boolean isMember = sr.hasMember(playername);
boolean isAdmin = HeroStronghold.perms.has(player, "herostronghold.admin");
if (!isMember && !isOwner && !isAdmin) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You arent a member of " + args[2]);
return true;
}
//Check if player has permission to invite players
if (!isAdmin && isMember && !sr.getMember(playername).contains("addmember")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You need permission addmember from an owner of " + args[2]);
return true;
}
//Check if valid player
Player invitee = getServer().getPlayer(args[1]);
if (invitee == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is not online.");
return true;
}
//Check permission herostronghold.join
if (!perms.has(invitee, "herostronghold.join")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " doesnt have permission to join a super-region.");
return true;
}
//Check if has housing effect and if has enough housing
if (regionManager.getSuperRegionType(sr.getType()).hasEffect("housing") && !regionManager.hasAvailableHousing(sr)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You cant addmember people to " + sr.getName() + " until you build more housing");
}
//Send an invite
pendingInvites.put(invitee.getName(), args[2]);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You have invited " + ChatColor.GOLD + invitee.getDisplayName() + ChatColor.GRAY + " to join " + ChatColor.GOLD + args[2]);
if (invitee != null)
invitee.sendMessage(ChatColor.GOLD + "[HeroStronghold] You have been invited to join " + args[2] + ". /hs accept " + args[2]);
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("accept")) {
//Check if player has a pending invite to that super-region
if (!pendingInvites.containsKey(player.getName()) || !pendingInvites.get(player.getName()).equals(args[1])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't have an invite to " + args[1]);
return true;
}
//Check if valid super region
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region by that name (" + args[1] + ").");
return true;
}
//Check if player is a member or owner of that super-region
String playername = player.getName();
if (sr.hasMember(playername) || sr.hasOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are already a member of " + args[1]);
return true;
}
//Add the player to the super region
ArrayList<String> perm = new ArrayList<String>();
perm.add("member");
regionManager.setMember(sr, player.getName(), perm);
pendingInvites.remove(player.getName());
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] Welcome to " + args[1]);
for (String s : sr.getMembers().keySet()) {
Player p = getServer().getPlayer(s);
if (p != null) {
p.sendMessage(ChatColor.GOLD + playername + " has joined " + args[1]);
}
}
for (String s : sr.getOwners()) {
Player p = getServer().getPlayer(s);
if (p != null) {
p.sendMessage(ChatColor.GOLD + playername + " has joined " + args[1]);
}
}
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("addowner")) {
Player p = getServer().getPlayer(args[1]);
String playername = args[1];
//Check valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region named " + args[2]);
return true;
}
//Check valid player
if (p == null && !sr.hasMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[Herostronghold] There is no player online named: " + args[1]);
return true;
} else {
playername = p.getName();
}
//Check if player is an owner of that region
if (!sr.hasOwner(player.getName()) && !HeroStronghold.perms.has(player, "herostronghold.admin")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You arent an owner of " + args[2]);
return true;
}
//Check if playername is already an owner
if (sr.hasOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is already an owner of " + args[2]);
return true;
}
//Check if player is member of super-region
if (!sr.hasMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is not a member of " + args[2]);
return true;
}
regionManager.removeMember(sr, playername);
if (p != null)
p.sendMessage(ChatColor.GOLD + "[HeroStronghold] You are now an owner of " + args[2]);
for (String s : sr.getMembers().keySet()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " is now an owner of " + args[2]);
}
}
for (String s : sr.getOwners()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " is now an owner of " + args[2]);
}
}
regionManager.setOwner(sr, playername);
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("remove")) {
Player p = getServer().getPlayer(args[1]);
String playername = args[1];
//Check valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[2]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region named " + args[2]);
return true;
}
//Check valid player
if (p != null) {
playername = p.getName();
}
boolean isMember = sr.hasMember(playername);
boolean isOwner = sr.hasOwner(playername);
boolean isAdmin = HeroStronghold.perms.has(player, "herostronghold.admin");
//Check if player is member or owner of super-region
if (!isMember && !isOwner) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is not a member of " + args[2]);
return true;
}
//Check if player is removing self
if (playername.equalsIgnoreCase(player.getName())) {
if (isMember) {
regionManager.removeMember(sr, playername);
} else if (isOwner) {
regionManager.setOwner(sr, playername);
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You have left " + args[2]);
for (String s : sr.getMembers().keySet()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " left " + args[2]);
}
}
for (String s : sr.getOwners()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " left " + args[2]);
}
}
return true;
}
//Check if player has remove permission
if (!sr.hasOwner(player.getName()) && !(!sr.hasMember(player.getName()) || !sr.getMember(player.getName()).contains("remove"))
&& !isAdmin) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't have permission to remove that member.");
return true;
}
if (isMember) {
regionManager.removeMember(sr, playername);
} else if (isOwner) {
regionManager.setOwner(sr, playername);
} else {
return true;
}
if (p != null)
p.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are no longer a member of " + args[2]);
for (String s : sr.getMembers().keySet()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " was removed from " + args[2]);
}
}
for (String s : sr.getOwners()) {
Player pl = getServer().getPlayer(s);
if (pl != null) {
pl.sendMessage(ChatColor.GOLD + playername + " was removed from " + args[2]);
}
}
return true;
} else if (args.length > 3 && args[0].equalsIgnoreCase("toggleperm")) {
Player p = getServer().getPlayer(args[1]);
String playername = args[1];
//Check valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[3]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region named " + args[3]);
return true;
}
//Check if player is an owner of the super region
if (!sr.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You aren't an owner of " + args[3]);
return true;
}
//Check valid player
if (p == null && !sr.hasMember(args[1])) {
player.sendMessage(ChatColor.GRAY + "[Herostronghold] There is no player named: " + args[1]);
return true;
} else if (p != null) {
playername = p.getName();
}
//Check if player is member and not owner of super-region
if (!sr.hasMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " either owns, or is not a member of " + args[3]);
return true;
}
List<String> perm = sr.getMember(playername);
if (perm.contains(args[2])) {
perm.remove(args[2]);
regionManager.setMember(sr, playername, perm);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Removed perm " + args[2] + " for " + args[1] + " in " + args[3]);
if (p != null)
p.sendMessage(ChatColor.GRAY + "[HeroStronghold] Your perm " + args[2] + " was revoked in " + args[3]);
return true;
} else {
perm.add(args[2]);
regionManager.setMember(sr, playername, perm);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Added perm " + args[2] + " for " + args[1] + " in " + args[3]);
if (p != null)
p.sendMessage(ChatColor.GRAY + "[HeroStronghold] You were granted permission " + args[2] + " in " + args[3]);
return true;
}
} else if (args.length > 0 && args[0].equalsIgnoreCase("whatshere")) {
Location loc = player.getLocation();
boolean foundRegion = false;
for (Region r : regionManager.getContainingRegions(loc)) {
foundRegion = true;
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Found Region ID: " + ChatColor.GOLD + r.getID());
String message = ChatColor.GRAY + "Type: " + r.getType();
if (!r.getOwners().isEmpty()) {
message += ", Owned by: " + r.getOwners().get(0);
}
player.sendMessage(message);
}
for (SuperRegion sr : regionManager.getContainingSuperRegions(loc)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Found Super-Region named: " + ChatColor.GOLD + sr.getName());
String message = ChatColor.GRAY + "Type: " + sr.getType();
if (!sr.getOwners().isEmpty()) {
message += ", Owned by: " + sr.getOwners().get(0);
}
player.sendMessage(message);
}
if (!foundRegion) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There are no regions here.");
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("info")) {
//Check if valid regiontype or super-regiontype
RegionType rt = regionManager.getRegionType(args[1]);
SuperRegionType srt = regionManager.getSuperRegionType(args[1]);
if (rt == null && srt == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region type called " + args[1]);
return true;
}
if (rt != null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Info for region type " + ChatColor.GOLD + args[1] + ":");
player.sendMessage(ChatColor.GRAY + "Cost: " + ChatColor.GOLD + rt.getMoneyRequirement() + ChatColor.GRAY +
", Payout: " + ChatColor.GOLD + rt.getMoneyOutput() + ChatColor.GRAY + ", Radius: " + ChatColor.GOLD + (int) Math.sqrt(rt.getRadius()));
String message = ChatColor.GRAY + "Description: " + ChatColor.GOLD;
int j=0;
if (rt.getDescription() != null) {
String tempMess = rt.getDescription();
if (tempMess.length() + message.length() <= 55) {
player.sendMessage(message + tempMess);
tempMess = null;
}
while (tempMess != null && j<12) {
if (tempMess.length() > 53) {
message += tempMess.substring(0, 53);
player.sendMessage(message);
tempMess = tempMess.substring(53);
message = ChatColor.GOLD + "";
j++;
} else {
player.sendMessage(message + tempMess);
tempMess = null;
j++;
}
}
}
message = ChatColor.GRAY + "Effects: " + ChatColor.GOLD;
if (rt.getEffects() != null) {
for (String is : rt.getEffects()) {
String addLine = is.split("\\.")[0] + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getEffects() == null || rt.getEffects().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Requirements: " + ChatColor.GOLD;
if (rt.getRequirements() != null) {
for (ItemStack is : rt.getRequirements()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getRequirements() == null || rt.getRequirements().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Reagents: " + ChatColor.GOLD;
if (rt.getReagents() != null) {
for (ItemStack is : rt.getReagents()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getReagents() == null || rt.getReagents().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "UpkeepCost: " + ChatColor.GOLD;
if (rt.getUpkeep() != null) {
for (ItemStack is : rt.getUpkeep()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getUpkeep() == null || rt.getUpkeep().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Output: " + ChatColor.GOLD;
if (rt.getOutput() != null) {
for (ItemStack is : rt.getOutput()) {
String addLine = is.getAmount() + ":" + is.getType().name() + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (rt.getOutput() == null || rt.getOutput().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
} else if (srt != null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Info for super-region type " + ChatColor.GOLD + args[1] + ":");
player.sendMessage(ChatColor.GRAY + "Cost: " + ChatColor.GOLD + srt.getMoneyRequirement() + ChatColor.GRAY +
", Payout: " + ChatColor.GOLD + srt.getOutput());
player.sendMessage(ChatColor.GRAY + "Power: " + ChatColor.GOLD + srt.getMaxPower() + " (+" + srt.getDailyPower() + "), " +
ChatColor.GRAY + "Charter: " + ChatColor.GOLD + srt.getCharter() + ChatColor.GRAY + ", Radius: " + ChatColor.GOLD + (int) Math.sqrt(srt.getRadius()));
String message = ChatColor.GRAY + "Description: " + ChatColor.GOLD;
int j=0;
if (srt.getDescription() != null) {
String tempMess = srt.getDescription();
if (tempMess.length() + message.length() <= 55) {
player.sendMessage(message + tempMess);
tempMess = null;
}
while (tempMess != null && j<12) {
if (tempMess.length() > 53) {
message += tempMess.substring(0, 53);
player.sendMessage(message);
tempMess = tempMess.substring(53);
message = ChatColor.GOLD + "";
j++;
} else {
player.sendMessage(message + tempMess);
tempMess = null;
j++;
}
}
}
message = ChatColor.GRAY + "Effects: " + ChatColor.GOLD;
if (srt.getEffects() != null) {
for (String is : srt.getEffects()) {
String addLine = is + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 11) {
message += addLine;
} else {
break;
}
}
}
if (srt == null || srt.getEffects().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Requirements: " + ChatColor.GOLD;
if (srt.getRequirements() != null) {
for (String is : srt.getRequirements().keySet()) {
String addLine = is + ":" + srt.getRequirement(is) + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (srt.getRequirements() == null || srt.getRequirements().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
message = ChatColor.GRAY + "Evolves from: " + ChatColor.GOLD;
if (srt.getChildren() != null) {
for (String is : srt.getChildren()) {
String addLine = is + ", ";
if (message.length() + addLine.length() > 55) {
player.sendMessage(message.substring(0, message.length() - 2));
message = ChatColor.GOLD + "";
j++;
}
if (j < 12) {
message += addLine;
} else {
break;
}
}
}
if (srt.getChildren() == null || srt.getChildren().isEmpty()) {
message += "None";
player.sendMessage(message);
} else {
player.sendMessage(message.substring(0, message.length()-2));
}
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("addowner")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer != null) {
playername = aPlayer.getName();
}
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
Resident res = null;
boolean townyOverride = false;
boolean factionsOverride = false;
if (HeroStronghold.towny != null) {
try {
res = TownyUniverse.getDataSource().getResident(player.getName());
if (TownyUniverse.getTownBlock(loc) != null &&
(TownyUniverse.getTownBlock(loc).getTown().getMayor().equals(res) ||
TownyUniverse.getTownBlock(loc).getTown().hasAssistant(res))) {
townyOverride = true;
}
} catch (Exception ex) {
}
}
if (HeroStronghold.factions != null) {
Faction f = Board.getFactionAt(new FLocation(loc));
if (f != null) {
if (f.getFPlayerAdmin().getPlayer().getName().equals(player.getName())) {
factionsOverride = true;
} else {
for (FPlayer fp : f.getFPlayersWhereRole(Role.MODERATOR)) {
if (fp.getPlayer().getName().equals(player.getName())) {
factionsOverride = true;
break;
}
}
}
}
}
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin")) ||
townyOverride || factionsOverride) {
if (r.isOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " is already an owner of this region.");
return true;
}
if (r.isMember(playername)) {
regionManager.setMember(r, playername);
}
regionManager.setOwner(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " as an owner.");
if (aPlayer != null) {
aPlayer.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "You're now a co-owner of " + player.getDisplayName() + "'s " + r.getType());
}
return true;
} else {
boolean takeover = false;
for (SuperRegion sr : regionManager.getContainingSuperRegions(loc)) {
if (!sr.hasOwner(player.getName())) {
takeover = false;
break;
}
if (regionManager.getSuperRegionType(sr.getType()).hasEffect("control")) {
takeover = true;
}
}
if (takeover) {
if (r.isOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " is already an owner of this region.");
return true;
}
if (r.isMember(playername)) {
regionManager.setMember(r, playername);
}
regionManager.setOwner(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " as an owner.");
if (aPlayer != null) {
aPlayer.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "You're now a co-owner of " + player.getDisplayName() + "'s " + r.getType());
}
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("addmember")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer == null) {
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
playername = args[1];
} else {
playername = "sr:" + sr.getName();
}
} else {
playername = aPlayer.getName();
}
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
if (r.isMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " is already a member of this region.");
return true;
}
if (r.isOwner(playername) && !(playername.equals(player.getName()) && r.getOwners().get(0).equals(player.getName()))) {
regionManager.setOwner(r, playername);
}
regionManager.setMember(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " to the region.");
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
return true;
} else if (args.length > 2 && args[0].equals("addmemberid")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer == null) {
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
playername = args[1];
} else {
playername = "sr:" + sr.getName();
}
} else {
playername = aPlayer.getName();
}
Region r = null;
try {
r = regionManager.getRegionByID(Integer.parseInt(args[2]));
r.getType();
} catch (Exception e) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + args[1] + " is not a valid id");
return true;
}
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
if (r.isMember(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " is already a member of this region.");
return true;
}
if (r.isOwner(playername) && !(playername.equals(player.getName()) && r.getOwners().get(0).equals(player.getName()))) {
regionManager.setOwner(r, playername);
}
regionManager.setMember(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " to the region.");
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
} else if (args.length > 1 && args[0].equalsIgnoreCase("whereis")) {
RegionType rt = regionManager.getRegionType(args[1]);
if (rt == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region type " + args[1]);
return true;
}
boolean found = false;
for (Region r : regionManager.getSortedRegions()) {
if (r.isOwner(player.getName()) && r.getType().equals(args[1])) {
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] " + args[1] + " at " + ((int) r.getLocation().getX())
+ ", " + ((int) r.getLocation().getY()) + ", " + ((int) r.getLocation().getZ()));
found = true;
}
}
if (!found) {
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] " + args[1] + " not found.");
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("setowner")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer != null) {
playername = aPlayer.getName();
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " must be online to setowner");
return true;
}
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
//Check if too far away
try {
if (player.getLocation().distanceSquared(aPlayer.getLocation()) > regionManager.getRegionType(r.getType()).getRawRadius()) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " must be close by also.");
return true;
}
} catch (IllegalArgumentException iae) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " must be close by also.");
return true;
}
if (r.isMember(playername)) {
regionManager.setMember(r, playername);
}
regionManager.setMember(r, player.getName());
regionManager.setOwner(r, player.getName());
regionManager.setPrimaryOwner(r, playername);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Added " + playername + " as an owner.");
if (aPlayer != null) {
aPlayer.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "You're now a co-owner of " + player.getDisplayName() + "'s " + r.getType());
}
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("remove")) {
String playername = args[1];
Player aPlayer = getServer().getPlayer(playername);
if (aPlayer != null) {
playername = aPlayer.getName();
}
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
if (r.isPrimaryOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You must use /hs setowner to change the original owner.");
return true;
}
if (!r.isMember(playername) && !r.isOwner(playername)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + playername + " doesn't belong to this region");
return true;
}
if (r.isMember(playername)) {
regionManager.setMember(r, playername);
} else if (r.isOwner(playername)) {
regionManager.setOwner(r, playername);
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + ChatColor.WHITE + "Removed " + playername + " from the region.");
return true;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("destroy")) {
Location loc = player.getLocation();
Location locationToDestroy = null;
for (Region r : regionManager.getContainingRegions(loc)) {
if (r.isOwner(player.getName()) || (perms != null && perms.has(player, "herostronghold.admin"))) {
regionManager.destroyRegion(r.getLocation());
locationToDestroy = r.getLocation();
break;
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't own this region.");
return true;
}
}
if (locationToDestroy != null) {
regionManager.removeRegion(locationToDestroy);
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Region destroyed.");
} else {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You're not standing in a region.");
}
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("destroy")) {
//Check if valid region
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no region named " + args[1]);
return true;
}
//Check if owner or admin of that region
if ((perms == null || !perms.has(player, "herostronghold.admin")) && (sr.getOwners().isEmpty() || !sr.getOwners().contains(player.getName()))) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You are not the owner of that region.");
return true;
}
regionManager.destroySuperRegion(args[1], true);
return true;
} else if (args.length > 0 && args[0].equalsIgnoreCase("list")) {
int j=0;
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] list of Region Types");
String message = ChatColor.GOLD + "";
boolean permNull = perms == null;
boolean createAll = permNull || perms.has(player, "herostronghold.create.all");
for (String s : regionManager.getRegionTypes()) {
if (createAll || permNull || perms.has(player, "herostronghold.create." + s)) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
}
for (String s : regionManager.getSuperRegionTypes()) {
if (createAll || permNull || perms.has(player, "herostronghold.create." + s)) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
}
if (!message.equals(ChatColor.GOLD + "")) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
} else if (args.length > 2 && args[0].equalsIgnoreCase("rename")) {
//Check if valid super-region
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr == null) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There is no super-region by that name");
return true;
}
//Check if valid name
if (args[2].length() > 16 && Util.validateFileName(args[2])) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] That name is too long. Use 15 characters or less");
return true;
}
//Check if player can rename the super-region
if (!sr.hasOwner(player.getName()) && !HeroStronghold.perms.has(player, "herostronghold.admin")) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] You don't have permission to rename that super-region.");
return true;
}
double cost = configManager.getRenameCost();
if (HeroStronghold.econ != null && cost > 0) {
if (!HeroStronghold.econ.has(player.getName(), cost)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] It costs " + ChatColor.RED + cost + " to rename that.");
return true;
} else {
HeroStronghold.econ.withdrawPlayer(player.getName(), cost);
}
}
regionManager.destroySuperRegion(args[1], false);
regionManager.addSuperRegion(args[2], sr.getLocation(), sr.getType(), sr.getOwners(), sr.getMembers(), sr.getPower(), sr.getBalance());
player.sendMessage(ChatColor.GOLD + "[HeroStronghold] " + args[1] + " is now " + args[2]);
return true;
} else if (args.length > 0 && (args[0].equalsIgnoreCase("show"))) {
return true;
} else if (args.length > 0 && (args[0].equalsIgnoreCase("stats") || args[0].equalsIgnoreCase("who"))) {
if (args.length == 1) {
Location loc = player.getLocation();
for (Region r : regionManager.getContainingBuildRegions(loc)) {
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] ==:|" + ChatColor.GOLD + r.getID() + " (" + r.getType() + ") " + ChatColor.GRAY + "|:==");
String message = ChatColor.GRAY + "Owners: " + ChatColor.GOLD;
int j = 0;
for (String s : r.getOwners()) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!r.getOwners().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
message = ChatColor.GRAY + "Members: " + ChatColor.GOLD;
for (String s : r.getMembers()) {
if (message.length() + 2 + s.length() > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!r.getMembers().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
return true;
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] There are no regions here.");
return true;
}
SuperRegion sr = regionManager.getSuperRegion(args[1]);
if (sr != null) {
//TODO make revenue include all owned regions within the super region
SuperRegionType srt = regionManager.getSuperRegionType(sr.getType());
int population = sr.getOwners().size() + sr.getMembers().size();
double revenue = sr.getTaxes() * population + srt.getOutput();
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] ==:|" + ChatColor.GOLD + sr.getName() + " (" + sr.getType() + ") " + ChatColor.GRAY + "|:==");
player.sendMessage(ChatColor.GRAY + "Population: " + ChatColor.GOLD + population + ChatColor.GRAY +
" Bank: " + (sr.getBalance() < srt.getOutput() ? ChatColor.RED : ChatColor.GOLD) + sr.getBalance() + ChatColor.GRAY +
" Power: " + (sr.getPower() < srt.getDailyPower() ? ChatColor.RED : ChatColor.GOLD) + sr.getPower() +
" (+" + srt.getDailyPower() + ") / " + srt.getMaxPower());
player.sendMessage(ChatColor.GRAY + "Taxes: " + ChatColor.GOLD + sr.getTaxes()
+ ChatColor.GRAY + " Total Revenue: " + (revenue < 0 ? ChatColor.RED : ChatColor.GOLD) + revenue +
ChatColor.GRAY + " Disabled: " + (regionManager.hasAllRequiredRegions(sr) ? (ChatColor.GOLD + "false") : (ChatColor.RED + "true")));
//TODO state why the sr is disabled
if (sr.hasMember(player.getName()) || sr.hasOwner(player.getName())) {
player.sendMessage(ChatColor.GRAY + "Location: " + ChatColor.GOLD + (int) sr.getLocation().getX() + ", " + (int) sr.getLocation().getY() + ", " + (int) sr.getLocation().getZ());
}
if (sr.getTaxes() != 0) {
String message = ChatColor.GRAY + "Tax Revenue History: " + ChatColor.GOLD;
for (double d : sr.getTaxRevenue()) {
message += d + ", ";
}
if (!sr.getTaxRevenue().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
}
String message = ChatColor.GRAY + "Owners: " + ChatColor.GOLD;
int j = 0;
for (String s : sr.getOwners()) {
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!sr.getOwners().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
message = ChatColor.GRAY + "Members: " + ChatColor.GOLD;
for (String s : sr.getMembers().keySet()) {
if (message.length() + 2 + s.length() > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!sr.getMembers().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
message = ChatColor.GRAY + "Wars: " + ChatColor.GOLD;
for (SuperRegion srr : regionManager.getWars(sr)) {
String s = srr.getName();
if (message.length() + s.length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += s + ", ";
}
}
if (!sr.getOwners().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
} else {
player.sendMessage(message);
}
return true;
}
Player p = getServer().getPlayer(args[1]);
if (p != null) {
String playername = p.getName();
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] " + p.getDisplayName() + " is a member of:");
String message = ChatColor.GOLD + "";
int j = 0;
for (SuperRegion sr1 : regionManager.getSortedSuperRegions()) {
if (sr1.hasOwner(playername) || sr1.hasMember(playername)) {
if (message.length() + sr1.getName().length() + 2 > 55) {
player.sendMessage(message);
message = ChatColor.GOLD + "";
j++;
}
if (j > 14) {
break;
} else {
message += sr1.getName() + ", ";
}
}
}
if (!regionManager.getSortedRegions().isEmpty()) {
player.sendMessage(message.substring(0, message.length() - 2));
}
return true;
}
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] Could not find player or super-region by that name");
return true;
} else if (args.length > 0 && effectCommands.contains(args[0])) {
Bukkit.getServer().getPluginManager().callEvent(new CommandEffectEvent(args, player));
return true;
} else {
//TODO add a page 3 to help for more instruction?
if (args.length > 0 && args[args.length - 1].equals("2")) {
sender.sendMessage(ChatColor.GRAY + "[HeroStronghold] by " + ChatColor.GOLD + "Multitallented" + ChatColor.GRAY + ": <> = required, () = optional" +
ChatColor.GOLD + " Page 2");
sender.sendMessage(ChatColor.GRAY + "/hs accept <name>");
sender.sendMessage(ChatColor.GRAY + "/hs rename <name> <newname>");
sender.sendMessage(ChatColor.GRAY + "/hs settaxes <amount> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs withdraw|deposit <amount> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs listperms <playername> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs listallperms");
sender.sendMessage(ChatColor.GRAY + "/hs toggleperm <playername> <perm> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs destroy (name)");
sender.sendMessage(ChatColor.GRAY + "/hs ch (channel) -- Use /hs ch for all chat");
sender.sendMessage(ChatColor.GRAY + "Google 'HeroStronghold bukkit' for more info | " + ChatColor.GOLD + "Page 2/3");
} else if (args.length > 0 && args[args.length - 1].equals("3")) {
sender.sendMessage(ChatColor.GRAY + "[HeroStronghold] by " + ChatColor.GOLD + "Multitallented" + ChatColor.GRAY + ": <> = required, () = optional" +
ChatColor.GOLD + " Page 3");
sender.sendMessage(ChatColor.GRAY + "/hs war <mysuperregion> <enemysuperregion>");
sender.sendMessage(ChatColor.GRAY + "/hs peace <mysuperregion> <enemysuperregion>");
sender.sendMessage(ChatColor.GRAY + "Google 'HeroStronghold bukkit' for more info | " + ChatColor.GOLD + "Page 3/3");
} else {
sender.sendMessage(ChatColor.GRAY + "[HeroStronghold] by " + ChatColor.GOLD + "Multitallented" + ChatColor.GRAY + ": () = optional" +
ChatColor.GOLD + " Page 1");
sender.sendMessage(ChatColor.GRAY + "/hs list");
sender.sendMessage(ChatColor.GRAY + "/hs info <regiontype|superregiontype>");
sender.sendMessage(ChatColor.GRAY + "/hs charter <superregiontype> <name>");
sender.sendMessage(ChatColor.GRAY + "/hs charterstats <name>");
sender.sendMessage(ChatColor.GRAY + "/hs signcharter <name>");
sender.sendMessage(ChatColor.GRAY + "/hs cancelcharter <name>");
sender.sendMessage(ChatColor.GRAY + "/hs create <regiontype> (name)");
sender.sendMessage(ChatColor.GRAY + "/hs addowner|addmember|remove <playername> (name)");
sender.sendMessage(ChatColor.GRAY + "/hs whatshere");
sender.sendMessage(ChatColor.GRAY + "Google 'HeroStronghold bukkit' for more info |" + ChatColor.GOLD + " Page 1/3");
}
return true;
}
}
|
diff --git a/plugins/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java b/plugins/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java
index fc483195a..108d859fe 100644
--- a/plugins/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java
+++ b/plugins/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java
@@ -1,998 +1,999 @@
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.engine.emitter.postscript;
import java.awt.Color;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import org.eclipse.birt.report.engine.emitter.postscript.truetypefont.ITrueTypeWriter;
import org.eclipse.birt.report.engine.emitter.postscript.truetypefont.TrueTypeFont;
import org.eclipse.birt.report.engine.emitter.postscript.util.FileUtil;
import org.eclipse.birt.report.engine.layout.emitter.util.BackgroundImageLayout;
import org.eclipse.birt.report.engine.layout.emitter.util.Position;
import org.eclipse.birt.report.engine.layout.pdf.font.FontHandler;
import org.eclipse.birt.report.engine.layout.pdf.font.FontInfo;
import org.w3c.dom.css.CSSValue;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.FontFactoryImp;
import com.lowagie.text.pdf.BaseFont;
public class PostscriptWriter
{
/** This is a possible value of a base 14 type 1 font */
public static final String COURIER = BaseFont.COURIER;
/** This is a possible value of a base 14 type 1 font */
public static final String COURIER_BOLD = BaseFont.COURIER_BOLD;
/** This is a possible value of a base 14 type 1 font */
public static final String COURIER_OBLIQUE = BaseFont.COURIER_OBLIQUE;
/** This is a possible value of a base 14 type 1 font */
public static final String COURIER_BOLDOBLIQUE = BaseFont.COURIER_BOLDOBLIQUE;
/** This is a possible value of a base 14 type 1 font */
public static final String HELVETICA = BaseFont.HELVETICA;
/** This is a possible value of a base 14 type 1 font */
public static final String HELVETICA_BOLD = BaseFont.HELVETICA_BOLD;
/** This is a possible value of a base 14 type 1 font */
public static final String HELVETICA_OBLIQUE = BaseFont.HELVETICA_OBLIQUE;
/** This is a possible value of a base 14 type 1 font */
public static final String HELVETICA_BOLDOBLIQUE = BaseFont.HELVETICA_BOLDOBLIQUE;
/** This is a possible value of a base 14 type 1 font */
public static final String SYMBOL = BaseFont.SYMBOL;
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES = "Times";
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES_ROMAN = BaseFont.TIMES_ROMAN;
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES_BOLD = BaseFont.TIMES_BOLD;
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES_ITALIC = BaseFont.TIMES_ITALIC;
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES_BOLDITALIC = BaseFont.TIMES_BOLDITALIC;
/** This is a possible value of a base 14 type 1 font */
public static final String ZAPFDINGBATS = BaseFont.ZAPFDINGBATS;
/**
* Default page height.
*/
final protected static int DEFAULT_PAGE_HEIGHT = 792;
/**
* Default page width.
*/
final protected static int DEFAULT_PAGE_WIDTH = 612;
/**
* Table mapping decimal numbers to hexadecimal numbers.
*/
final protected static byte hd[] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/**
* Output stream where postscript to be output.
*/
protected PrintStream out = System.out;
/**
* The current color
*/
protected Color clr = Color.white;
/**
* The current font
*/
protected Font font = new Font( Font.HELVETICA, 12, Font.NORMAL );
/**
* Current page index with 1 as default value.
*/
private int pageIndex = 1;
/**
* Height of current page.
*/
private float pageHeight = DEFAULT_PAGE_HEIGHT;
private static Set intrinsicFonts = new HashSet( );
static
{
intrinsicFonts.add( COURIER );
intrinsicFonts.add( COURIER_BOLD );
intrinsicFonts.add( COURIER_OBLIQUE );
intrinsicFonts.add( COURIER_BOLDOBLIQUE );
intrinsicFonts.add( HELVETICA );
intrinsicFonts.add( HELVETICA_BOLD );
intrinsicFonts.add( HELVETICA_OBLIQUE );
intrinsicFonts.add( HELVETICA_BOLDOBLIQUE );
intrinsicFonts.add( SYMBOL );
intrinsicFonts.add( TIMES );
intrinsicFonts.add( TIMES_ROMAN );
intrinsicFonts.add( TIMES_BOLD );
intrinsicFonts.add( TIMES_ITALIC );
intrinsicFonts.add( TIMES_BOLDITALIC );
intrinsicFonts.add( ZAPFDINGBATS );
}
public static boolean isIntrinsicFont( String fontName )
{
return intrinsicFonts.contains( fontName );
}
/**
* Constructor.
*
* @param out
* Output stream for PostScript output.
* @param title
* title of the postscript document.
*/
public PostscriptWriter( OutputStream o, String title )
{
out = new PrintStream( o );
emitProlog( title );
FontHandler.prepareFonts( );
}
public void clipRect( float x, float y, float width, float height )
{
y = transformY( y );
out.println( x + " " + y + " moveto" );
out.println( ( x + width ) + " " + y + " lineto" );
out.println( ( x + width ) + " " + ( y - height ) + " lineto" );
out.println( x + " " + ( y - height ) + " lineto" );
out.println( x + " " + y + " lineto" );
out.println( "closepath eoclip newpath" );
}
public void clipSave()
{
out.println( "gsave" );
}
public void clipRestore()
{
out.println( "grestore" );
}
/**
* Draws a image.
*
* @param imageStream
* the source input stream of the image.
* @param x
* the x position.
* @param y
* the y position.
* @param width
* the image width.
* @param height
* the image height.
* @throws IOException
*/
public void drawImage( InputStream imageStream, float x, float y,
float width, float height ) throws Exception
{
Image image = ImageIO.read( imageStream );
drawImage( image, x, y, width, height, null );
}
/**
* Draws a image with specified image data, position, size and background
* color.
*
* @param image
* the source image data.
* @param x
* the x position.
* @param y
* the y position.
* @param width
* the image width.
* @param height
* the image height.
* @param bgcolor
* the background color.
* @throws Exception
*/
public void drawImage( Image image, float x, float y, float width,
float height, Color bgcolor ) throws Exception
{
if ( image == null )
{
throw new IllegalArgumentException( "null image." );
}
ImageSource imageSource = getImageSource( image );
drawImage( imageSource, x, y, width, height, bgcolor );
}
private ArrayImageSource getImageSource( Image image ) throws IOException
{
ImageIcon imageIcon = new ImageIcon( image );
int w = imageIcon.getIconWidth( );
int h = imageIcon.getIconHeight( );
int[] pixels = new int[w * h];
try
{
PixelGrabber pg = new PixelGrabber( image, 0, 0, w, h, pixels, 0, w );
pg.grabPixels( );
if ( ( pg.getStatus( ) & ImageObserver.ABORT ) != 0 )
{
throw new IOException( "failed to load image contents" );
}
}
catch ( InterruptedException e )
{
throw new IOException( "image load interrupted" );
}
ArrayImageSource imageSource = new ArrayImageSource( w, h, pixels );
return imageSource;
}
private void drawImage( ImageSource imageSource, float x, float y,
float width, float height, Color bgcolor )
{
int originalWidth = imageSource.getWidth( );
int originalHeight = imageSource.getHeight( );
y = transformY( y );
gSave( );
out.println( "% build a temporary dictionary" );
out.println( "20 dict begin" );
out.print( "/pix " );
out.print( originalWidth * 3 );
out.println( " string def" );
out.println( "% define space for color conversions" );
out.print( "/grays " );
out.print( originalWidth );
out.println( " string def % space for gray scale line" );
out.println( "% lower left corner" );
out.print( x );
out.print( " " );
out.print( y );
out.println( " translate" );
if ( height == 0 || width == 0 )
{
height = originalHeight;
width = originalWidth;
}
out.println( "% size of image" );
out.print( width );
out.print( " " );
out.print( height );
out.println( " scale" );
out.print( originalWidth );
out.print( " " );
out.print( originalHeight );
out.println( " 8" );
out.print( "[" );
out.print( originalWidth );
out.print( " 0 0 -" );
out.print( originalHeight );
out.print( " 0 " );
out.print( 0 );
out.println( "]" );
out.println( "{currentfile pix readhexstring pop}" );
out.println( "false 3 colorimage" );
out.println( "" );
- byte[] sb = new byte[originalHeight * originalWidth * 6];
+ byte[] sb = new byte[originalWidth * 6];
int offset = 0;
for ( int i = 0; i < originalHeight; i++ )
{
if ( bgcolor == null )
{
for ( int j = 0; j < originalWidth; j++ )
{
int pixel = imageSource.getRGB( j, i );
int alpha = ( pixel >> 24 ) & 0xff;
int red = ( pixel >> 16 ) & 0xff;
int green = ( pixel >> 8 ) & 0xff;
int blue = pixel & 0xff;
red = transferColor( alpha, red );
green = transferColor( alpha, green );
blue = transferColor( alpha, blue );
offset = toBytes( offset, sb, red );
offset = toBytes( offset, sb, green );
offset = toBytes( offset, sb, blue );
}
+ offset = 0;
+ out.println( new String( sb ) );
}
else
{
// TODO:implement or remove it.
}
}
- out.println( new String( sb ) );
out.println( "" );
out.println( "end" );
gRestore( );
}
private int transferColor( int alpha, int color )
{
return 255 - (255 - color) * alpha / 255;
}
private int toBytes( int offset, byte[] buffer, int value )
{
buffer[offset++] = hd[( ( value & 0xF0 ) >> 4 )];
buffer[offset++] = hd[( value & 0xF )];
return offset;
}
protected void drawRect( float x, float y, float width, float height,
boolean fill )
{
drawRawRect( x, y, width, height );
if ( fill )
out.println( "fill" );
else
out.println( "stroke" );
}
private void drawRawRect( float x, float y, float width, float height )
{
y = transformY( y ) - height;
out.print( x );
out.print( " " );
out.print( y );
out.println( " moveto " );
out.print( width );
out.print( " " );
out.print( 0 );
out.println( " rlineto " );
out.print( 0 );
out.print( " " );
out.print( height );
out.println( " rlineto " );
out.print( -width );
out.print( " " );
out.print( 0 );
out.println( " rlineto " );
out.print( 0 );
out.print( " " );
out.print( -height );
out.println( " rlineto " );
}
/**
* Draws background image in a rectangle area with specified repeat pattern.
* <br>
* <br>
* The repeat mode can be: <table border="solid">
* <tr>
* <td align="center"><B>Name</td>
* <td align="center"><B>What for</td>
* </tr>
* <tr>
* <td>no-repeat</td>
* <td>Don't repeat.</td>
* </tr>
* <tr>
* <td>repeat-x</td>
* <td>Only repeat on x orientation.</td>
* </tr>
* <tr>
* <td>repeat-y</td>
* <td>Only repeat on y orientation.</td>
* </tr>
* <tr>
* <td>repeat</td>
* <td>Repeat on x and y orientation.</td>
* </tr>
* </table>
*
* @param imageURI
* the uri of the background image.
* @param x
* the x coordinate of the rectangle area.
* @param y
* the y coordinate of the rectangle area.
* @param width
* the width of the rectangle area.
* @param height
* the height of the rectangle area.
* @param positionX
* the initial x position of the background image.
* @param positionY
* the initial y position of the background image.
* @param repeat
* the repeat mode.
* @throws IOException
* when the iamge cann't be read from the url.
*/
public void drawBackgroundImage( String imageURI, float x, float y,
float width, float height, float positionX, float positionY,
String repeat ) throws IOException
{
URL url = new URL( imageURI );
InputStream imageStream = null;
try
{
imageStream = url.openStream( );
Image image = ImageIO.read( imageStream );
ImageSource imageSource = getImageSource( image );
Position areaPosition = new Position( x, y );
Position areaSize = new Position( width, height );
Position imagePosition = new Position( x + positionX, y + positionY );
// TODO: need to confirm the tansformation from unit pixel to
// pointer.
Position imageSize = new Position( imageSource.getWidth( ),
imageSource.getHeight( ) );
BackgroundImageLayout layout = new BackgroundImageLayout(
areaPosition, areaSize, imagePosition, imageSize );
Collection positions = layout.getImagePositions( repeat );
gSave( );
out.println( "clipsave" );
setColor( Color.WHITE );
out.println( "newpath" );
drawRawRect( x, y, width, height );
out.println( "closepath clip" );
Iterator iterator = positions.iterator( );
while ( iterator.hasNext( ) )
{
Position position = (Position) iterator.next( );
drawImage( imageSource, position.getX( ), position.getY( ),
imageSize.getX( ), imageSize.getY( ), null );
}
out.println( "cliprestore" );
gRestore( );
}
finally
{
if ( imageStream != null )
{
imageStream.close( );
imageStream = null;
}
}
}
/**
* Draws a line from (startX, startY) to (endX, endY).
*
* @param startX
* the x coordinate of start point.
* @param startY
* the y coordinate of start point.
* @param endX
* the x coordinate of end point.
* @param endY
* the y coordinate of end point.
*/
public void drawLine( float startX, float startY, float endX, float endY )
{
startY = transformY( startY );
endY = transformY( endY );
out.print( startX );
out.print( " " );
out.print( startY );
out.print( " moveto " );
out.print( endX );
out.print( " " );
out.print( endY );
out.println( " lineto stroke" );
}
/**
* Draws a line from (startX, startY) to (endX, endY) with specified line
* width, color and line style.
*
* Line style can be "dotted", "dash", and "double".
*
* @param startX
* the x coordinate of start point.
* @param startY
* the y coordinate of start point.
* @param endX
* the x coordinate of end point.
* @param endY
* the y coordinate of end point.
* @param width
* the line width.
* @param color
* the color.
* @param lineStyle
* the line style.
*/
public void drawLine( float startX, float startY, float endX, float endY,
float width, Color color, String lineStyle )
{
if ( null == color || 0f == width
|| "none".equalsIgnoreCase( lineStyle ) ) //$NON-NLS-1$
{
return;
}
// double is not supported.
if ( "double".equalsIgnoreCase( lineStyle ) ) //$NON-NLS-1$
{
return;
}
gSave( );
if ( color != null )
{
setColor( color );
}
setLineWidth( width );
if ( "dashed".equalsIgnoreCase( lineStyle ) ) //$NON-NLS-1$
{
setDashLine( width );
}
else if ( "dotted".equalsIgnoreCase( lineStyle ) ) //$NON-NLS-1$
{
setDottedLine( width );
}
drawLine( startX, startY, endX, endY );
gRestore( );
}
private void gRestore( )
{
out.println( "grestore" );
}
private void gSave( )
{
out.println( "gsave" );
}
private void setLineWidth( float lineWidth )
{
out.print( lineWidth );
out.println( " setlinewidth" );
}
private void setDashLine( float lineWidth )
{
int width = (int) Math.ceil( lineWidth );
out.println( "[" + 3 * width + " " + 2 * width + "] 0 setdash" );
}
private void setDottedLine( float lineWidth )
{
int width = (int) Math.ceil( lineWidth );
out.println( "[" + width + "] 0 setdash" );
}
private Map trueTypeFontWriters = new HashMap( );
public void drawRect( int x, int y, int width, int height )
{
out.println( "%drawRect" );
drawRect( x, y, width, height, false );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.postscript.IWriter#drawString(java.lang.String,
* int, int, org.eclipse.birt.report.engine.layout.pdf.font.FontInfo,
* float, float, java.awt.Color, boolean, boolean, boolean)
*/
public void drawString( String str, float x, float y, FontInfo fontInfo,
float letterSpacing, float wordSpacing, Color color,
boolean linethrough, boolean overline, boolean underline,
CSSValue align )
{
y = transformY( y );
gSave( );
String text = str;
if ( fontInfo != null )
{
BaseFont baseFont = fontInfo.getBaseFont( );
String fontName = baseFont.getPostscriptFontName( );
text = applyFont( fontName, fontInfo.getFontStyle( ), fontInfo
.getFontSize( ), text );
}
color = color == null ? Color.black : color;
setColor( color );
out.print( x );
out.print( " " );
out.print( y );
out.print( " moveto " );
out.print( wordSpacing );
out.print( " 0 8#040 " );
out.print( letterSpacing );
out.print( " 0 " );
out.print( text );
out.println( " awidthshow stroke" );
gRestore( );
}
/**
* Top of every PS file
*/
protected void emitProlog( String title )
{
out.println( "%!PS-Adobe-3.0" );
if ( title != null )
{
out.println( "%%Title: " + title );
}
out.println( "% (C)2006 Actuate Inc." );
setFont( font );
}
public void fillRect( float x, float y, float width, float height,
Color color )
{
gSave( );
setColor( color );
out.println( "%fillRect" );
drawRect( x, y, width, height, true );
gRestore( );
}
/**
* Disposes of this graphics context once it is no longer referenced.
*
* @see #dispose
*/
public void finalize( )
{
dispose( );
}
public void dispose( )
{
out.println( "%dispose" );
}
public Color getColor( )
{
return clr;
}
public Font getFont( )
{
return font;
}
public void scale( float sx, float sy )
{
out.print( sx );
out.print( " " );
out.print( sy );
out.println( " scale" );
}
public void setColor( Color c )
{
if ( c == null )
{
return;
}
out.print( c.getRed( ) / 255.0 );
out.print( " " );
out.print( c.getGreen( ) / 255.0 );
out.print( " " );
out.print( c.getBlue( ) / 255.0 );
out.println( " setrgbcolor" );
}
public void setFont( Font f )
{
if ( f != null )
{
this.font = f;
String javaName = font.getFamilyname( );
int javaStyle = font.style( );
setFont( javaName, javaStyle );
}
}
private void setFont( String psName, float size )
{
out.println( "/" + psName + " findfont" );
out.print( size );
out.println( " scalefont setfont" );
}
private String applyFont( String fontName, int fontStyle, float fontSize,
String text )
{
if ( isIntrinsicFont( fontName ) )
{
return applyIntrinsicFont( fontName, fontStyle, fontSize, text );
}
else
{
try
{
String fontPath = getFontPath( fontName );
if ( fontPath == null )
{
return applyIntrinsicFont( fontName, fontStyle, fontSize, text );
}
ITrueTypeWriter trueTypeWriter = getTrueTypeFontWriter( fontPath );
//Space can't be included in a identity.
String displayName = fontName.replace( ' ', '_' );
trueTypeWriter.useDisplayName( displayName );
trueTypeWriter.ensureGlyphsAvailable( text );
setFont( displayName, fontSize );
return toHexString( text );
}
catch ( Exception e )
{
e.printStackTrace( );
}
return null;
}
}
private String applyIntrinsicFont( String fontName, int fontStyle, float fontSize, String text )
{
setFont( fontName, fontSize );
if ( text.endsWith( "\\" ) )
{
text = text + "\\";
}
text = text.replaceAll( "\\)", "\\\\)" );
return ( "(" + text + ")" );
}
private String toHexString( String text )
{
StringBuffer buffer = new StringBuffer( );
buffer.append( '<' );
for ( int i = 0; i < text.length( ); i++ )
{
buffer.append( toHexString( text.charAt( i ) ) );
}
buffer.append( '>' );
return buffer.toString( );
}
private String toHexString( char c )
{
final String[] padding = {"0", "00", "000"};
String result = Integer.toHexString( c );
if ( result.length( ) < 4 )
{
result = padding[3 - result.length( )] + result;
}
return result;
}
private ITrueTypeWriter getTrueTypeFontWriter( String fontPath )
throws DocumentException, IOException
{
File file = new File( fontPath );
ITrueTypeWriter trueTypeWriter = (ITrueTypeWriter) trueTypeFontWriters
.get( file );
if ( trueTypeWriter != null )
{
return trueTypeWriter;
}
else
{
TrueTypeFont ttFont = TrueTypeFont.getInstance( fontPath );
trueTypeWriter = ttFont.getTrueTypeWriter( out );
trueTypeWriter.initialize( );
trueTypeFontWriters.put( file, trueTypeWriter );
return trueTypeWriter;
}
}
private String getFontPath( String fontName )
{
try
{
FontFactoryImp fontImpl = FontFactory.getFontImp( );
Properties trueTypeFonts = (Properties) getField(
FontFactoryImp.class, "trueTypeFonts", fontImpl );
String fontPath = trueTypeFonts.getProperty( fontName.toLowerCase( ) );
return fontPath;
}
catch ( Exception e )
{
e.printStackTrace( );
}
return null;
}
private Object getField( Class fontFactoryClass, String fieldName,
Object instaces ) throws NoSuchFieldException,
IllegalAccessException
{
Field fldTrueTypeFonts = fontFactoryClass.getDeclaredField( fieldName );
fldTrueTypeFonts.setAccessible( true );
Object field = fldTrueTypeFonts.get( instaces );
return field;
}
/**
* Returns a String object representing this Graphic's value.
*/
public String toString( )
{
return getClass( ).getName( ) + "[font=" + getFont( ) + ",color="
+ getColor( ) + "]";
}
/**
* Flip Y coords so Postscript looks like Java
*/
protected float transformY( float y )
{
return pageHeight - y;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.postscript.IWriter#translate(int,
* int)
*/
public void translate( int x, int y )
{
out.print( x );
out.print( " " );
out.print( y );
out.println( " translate" );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.postscript.IWriter#startRenderer()
*/
public void startRenderer( ) throws IOException
{
FileUtil.load(
"org/eclipse/birt/report/engine/emitter/postscript/header.ps",
out );
}
public void fillPage( Color color )
{
if ( color == null )
{
return;
}
gSave( );
setColor( color );
out.println( "clippath fill" );
gRestore( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.postscript.IWriter#startPage(float,
* float)
*/
public void startPage( float pageWidth, float pageHeight )
{
this.pageHeight = pageHeight;
out.println( "%%Page: " + pageIndex + " " + pageIndex );
out.println( "%%PageBoundingBox: 0 0 " + (int) Math.round( pageWidth )
+ " " + (int) Math.round( pageHeight ) );
out.println( "%%BeginPage" );
++pageIndex;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.postscript.IWriter#endPage()
*/
public void endPage( )
{
out.println( "showpage" );
out.println( "%%PageTrailer" );
out.println( "%%EndPage" );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.postscript.IWriter#stopRenderer()
*/
public void stopRenderer( ) throws IOException
{
out.println( "%%Trailer" );
out.println( "%%Pages: " + ( pageIndex - 1 ) );
out.println( "%%EOF" );
out.flush( );
}
public abstract class ImageSource
{
protected int height;
protected int width;
public ImageSource( int width, int height )
{
this.width = width;
this.height = height;
}
public int getHeight( )
{
return height;
}
public int getWidth( )
{
return width;
}
public abstract int getRGB( int x, int y );
}
public class ArrayImageSource extends ImageSource
{
private int[] imageSource;
public ArrayImageSource( int width, int height, int[] imageSource )
{
super( width, height );
this.imageSource = imageSource;
}
public int getRGB( int x, int y )
{
return imageSource[y * width + x];
}
}
}
| false | true |
private void drawImage( ImageSource imageSource, float x, float y,
float width, float height, Color bgcolor )
{
int originalWidth = imageSource.getWidth( );
int originalHeight = imageSource.getHeight( );
y = transformY( y );
gSave( );
out.println( "% build a temporary dictionary" );
out.println( "20 dict begin" );
out.print( "/pix " );
out.print( originalWidth * 3 );
out.println( " string def" );
out.println( "% define space for color conversions" );
out.print( "/grays " );
out.print( originalWidth );
out.println( " string def % space for gray scale line" );
out.println( "% lower left corner" );
out.print( x );
out.print( " " );
out.print( y );
out.println( " translate" );
if ( height == 0 || width == 0 )
{
height = originalHeight;
width = originalWidth;
}
out.println( "% size of image" );
out.print( width );
out.print( " " );
out.print( height );
out.println( " scale" );
out.print( originalWidth );
out.print( " " );
out.print( originalHeight );
out.println( " 8" );
out.print( "[" );
out.print( originalWidth );
out.print( " 0 0 -" );
out.print( originalHeight );
out.print( " 0 " );
out.print( 0 );
out.println( "]" );
out.println( "{currentfile pix readhexstring pop}" );
out.println( "false 3 colorimage" );
out.println( "" );
byte[] sb = new byte[originalHeight * originalWidth * 6];
int offset = 0;
for ( int i = 0; i < originalHeight; i++ )
{
if ( bgcolor == null )
{
for ( int j = 0; j < originalWidth; j++ )
{
int pixel = imageSource.getRGB( j, i );
int alpha = ( pixel >> 24 ) & 0xff;
int red = ( pixel >> 16 ) & 0xff;
int green = ( pixel >> 8 ) & 0xff;
int blue = pixel & 0xff;
red = transferColor( alpha, red );
green = transferColor( alpha, green );
blue = transferColor( alpha, blue );
offset = toBytes( offset, sb, red );
offset = toBytes( offset, sb, green );
offset = toBytes( offset, sb, blue );
}
}
else
{
// TODO:implement or remove it.
}
}
out.println( new String( sb ) );
out.println( "" );
out.println( "end" );
gRestore( );
}
|
private void drawImage( ImageSource imageSource, float x, float y,
float width, float height, Color bgcolor )
{
int originalWidth = imageSource.getWidth( );
int originalHeight = imageSource.getHeight( );
y = transformY( y );
gSave( );
out.println( "% build a temporary dictionary" );
out.println( "20 dict begin" );
out.print( "/pix " );
out.print( originalWidth * 3 );
out.println( " string def" );
out.println( "% define space for color conversions" );
out.print( "/grays " );
out.print( originalWidth );
out.println( " string def % space for gray scale line" );
out.println( "% lower left corner" );
out.print( x );
out.print( " " );
out.print( y );
out.println( " translate" );
if ( height == 0 || width == 0 )
{
height = originalHeight;
width = originalWidth;
}
out.println( "% size of image" );
out.print( width );
out.print( " " );
out.print( height );
out.println( " scale" );
out.print( originalWidth );
out.print( " " );
out.print( originalHeight );
out.println( " 8" );
out.print( "[" );
out.print( originalWidth );
out.print( " 0 0 -" );
out.print( originalHeight );
out.print( " 0 " );
out.print( 0 );
out.println( "]" );
out.println( "{currentfile pix readhexstring pop}" );
out.println( "false 3 colorimage" );
out.println( "" );
byte[] sb = new byte[originalWidth * 6];
int offset = 0;
for ( int i = 0; i < originalHeight; i++ )
{
if ( bgcolor == null )
{
for ( int j = 0; j < originalWidth; j++ )
{
int pixel = imageSource.getRGB( j, i );
int alpha = ( pixel >> 24 ) & 0xff;
int red = ( pixel >> 16 ) & 0xff;
int green = ( pixel >> 8 ) & 0xff;
int blue = pixel & 0xff;
red = transferColor( alpha, red );
green = transferColor( alpha, green );
blue = transferColor( alpha, blue );
offset = toBytes( offset, sb, red );
offset = toBytes( offset, sb, green );
offset = toBytes( offset, sb, blue );
}
offset = 0;
out.println( new String( sb ) );
}
else
{
// TODO:implement or remove it.
}
}
out.println( "" );
out.println( "end" );
gRestore( );
}
|
diff --git a/Server/VoiceServer.java b/Server/VoiceServer.java
index 0ba4c4a..cf51652 100644
--- a/Server/VoiceServer.java
+++ b/Server/VoiceServer.java
@@ -1,81 +1,81 @@
import java.util.*;
import java.io.*;
import java.net.*;
public class VoiceServer implements Runnable
{
private int _port = 0;
ArrayList<VoiceServerConnection> _connections = null;
VoiceServer(int port)
{
_port = port;
_connections = new ArrayList<VoiceServerConnection>();
}
public void run()
{
System.out.println("Voice Server started.");
try
{
// create a socket for handling incoming requests
DatagramSocket serverSocket = new DatagramSocket(_port);
while(true)
{
// receive the incoming packet
byte[] buffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(receivePacket);
// extract the byte stream data
buffer = receivePacket.getData();
// extract the IP address and port number
InetAddress ipAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
// if this is a new connection, store it in our list
VoiceServerConnection target = null;
for (VoiceServerConnection c : _connections)
{
- if ((c.getIPAddress().toString(ipAddress)) &&
+ if ((c.getIPAddress().toString().equals(ipAddress)) &&
(c.getPort() == port))
{
target = c;
break;
}
}
if (target == null)
{
VoiceServerConnection vsc = new VoiceServerConnection(ipAddress, port);
_connections.add(vsc);
}
// send the packet data
for (VoiceServerConnection c : _connections)
{
try
{
- if (!(c.getIPAddress().toString(ipAddress))) // we don't need to hear our own audio
+ if (!(c.getIPAddress().toString().equals(ipAddress))) // we don't need to hear our own audio
{
DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, c.getIPAddress(), c.getPort());
serverSocket.send(sendPacket);
}
}
catch (IOException ex)
{
// TODO: handle this exception
}
}
}
}
catch (IOException ex)
{
// TODO: handle this exception
}
}
}
| false | true |
public void run()
{
System.out.println("Voice Server started.");
try
{
// create a socket for handling incoming requests
DatagramSocket serverSocket = new DatagramSocket(_port);
while(true)
{
// receive the incoming packet
byte[] buffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(receivePacket);
// extract the byte stream data
buffer = receivePacket.getData();
// extract the IP address and port number
InetAddress ipAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
// if this is a new connection, store it in our list
VoiceServerConnection target = null;
for (VoiceServerConnection c : _connections)
{
if ((c.getIPAddress().toString(ipAddress)) &&
(c.getPort() == port))
{
target = c;
break;
}
}
if (target == null)
{
VoiceServerConnection vsc = new VoiceServerConnection(ipAddress, port);
_connections.add(vsc);
}
// send the packet data
for (VoiceServerConnection c : _connections)
{
try
{
if (!(c.getIPAddress().toString(ipAddress))) // we don't need to hear our own audio
{
DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, c.getIPAddress(), c.getPort());
serverSocket.send(sendPacket);
}
}
catch (IOException ex)
{
// TODO: handle this exception
}
}
}
}
catch (IOException ex)
{
// TODO: handle this exception
}
}
|
public void run()
{
System.out.println("Voice Server started.");
try
{
// create a socket for handling incoming requests
DatagramSocket serverSocket = new DatagramSocket(_port);
while(true)
{
// receive the incoming packet
byte[] buffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(receivePacket);
// extract the byte stream data
buffer = receivePacket.getData();
// extract the IP address and port number
InetAddress ipAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
// if this is a new connection, store it in our list
VoiceServerConnection target = null;
for (VoiceServerConnection c : _connections)
{
if ((c.getIPAddress().toString().equals(ipAddress)) &&
(c.getPort() == port))
{
target = c;
break;
}
}
if (target == null)
{
VoiceServerConnection vsc = new VoiceServerConnection(ipAddress, port);
_connections.add(vsc);
}
// send the packet data
for (VoiceServerConnection c : _connections)
{
try
{
if (!(c.getIPAddress().toString().equals(ipAddress))) // we don't need to hear our own audio
{
DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, c.getIPAddress(), c.getPort());
serverSocket.send(sendPacket);
}
}
catch (IOException ex)
{
// TODO: handle this exception
}
}
}
}
catch (IOException ex)
{
// TODO: handle this exception
}
}
|
diff --git a/android/BeyondAR_Examples/src/com/beyondar/example/CustomWorldHelper.java b/android/BeyondAR_Examples/src/com/beyondar/example/CustomWorldHelper.java
index cbaca99..21fbba1 100644
--- a/android/BeyondAR_Examples/src/com/beyondar/example/CustomWorldHelper.java
+++ b/android/BeyondAR_Examples/src/com/beyondar/example/CustomWorldHelper.java
@@ -1,103 +1,103 @@
/*
* Copyright (C) 2013 BeyondAR
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.beyondar.example;
import android.content.Context;
import com.beyondar.android.world.GeoObject;
import com.beyondar.android.world.World;
public class CustomWorldHelper {
public static World sharedWorld;
public static World generateObjects(Context context) {
if (sharedWorld != null){
return sharedWorld;
}
sharedWorld = new World(context);
// The user can set the default bitmap. This is useful if you are
// loading images form Internet and the connection get lost
sharedWorld.setDefaultBitmap(R.drawable.beyondar_default_unknow_icon);
// User position (you can change it using the GPS listeners form Android
// API)
sharedWorld.setGeoPosition(41.26533734214473d, 1.925848038959814d);
// Create an object with an image in the app resources.
GeoObject go1 = new GeoObject(1l);
go1.setGeoPosition(41.26523339794433d, 1.926036406654116d);
go1.setImageResource(R.drawable.creature_1);
go1.setName("Creature 1");
// Is it also possible to load the image asynchronously form internet
GeoObject go2 = new GeoObject(2l);
go2.setGeoPosition(41.26518966360719d, 1.92582424468222d);
go2.setImageUri("http://beyondar.com/sites/default/files/logo_reduced.png");
go2.setName("Online image");
// Also possible to get images from the SDcard
GeoObject go3 = new GeoObject(3l);
go3.setGeoPosition(41.26550959641445d, 1.925873388087619d);
go3.setImageUri("/sdcard/TheAvengers_IronMan.jpeg");
go3.setName("IronMan from sdcard");
// And the same goes for the app assets
GeoObject go4 = new GeoObject(4l);
go4.setGeoPosition(41.26518862002349d, 1.925662767707665d);
go4.setImageUri("assets://creature_7.png");
go4.setName("Image from assets");
GeoObject go5 = new GeoObject(5l);
go5.setGeoPosition(41.26553066234138d, 1.925777906882577d);
go5.setImageResource(R.drawable.creature_5);
go5.setName("Creature 5");
GeoObject go6 = new GeoObject(6l);
go6.setGeoPosition(41.26496218466268d, 1.925250806050688d);
go6.setImageResource(R.drawable.creature_6);
go6.setName("Creature 6");
GeoObject go7 = new GeoObject(7l);
go7.setGeoPosition(41.26581776104766d, 1.925932313852319d);
go7.setImageResource(R.drawable.creature_2);
go7.setName("Creature 2");
GeoObject go8 = new GeoObject(8l);
go8.setGeoPosition(41.26534261025682d, 1.926164369775198d);
go8.setImageResource(R.drawable.rectangle);
go8.setName("Object 8");
GeoObject go9 = new GeoObject(9l);
go9.setGeoPosition(41.26530734214473d, 1.925808038959814d);
go9.setImageResource(R.drawable.creature_4);
go9.setName("Creature 88884");
-// sharedWorld.addBeyondarObject(go1);
-// sharedWorld.addBeyondarObject(go2);
-// sharedWorld.addBeyondarObject(go3);
-// sharedWorld.addBeyondarObject(go4);
-// sharedWorld.addBeyondarObject(go5);
-// sharedWorld.addBeyondarObject(go6);
-// sharedWorld.addBeyondarObject(go7);
-// sharedWorld.addBeyondarObject(go8);
-// sharedWorld.addBeyondarObject(go9);
+ sharedWorld.addBeyondarObject(go1);
+ sharedWorld.addBeyondarObject(go2);
+ sharedWorld.addBeyondarObject(go3);
+ sharedWorld.addBeyondarObject(go4);
+ sharedWorld.addBeyondarObject(go5);
+ sharedWorld.addBeyondarObject(go6);
+ sharedWorld.addBeyondarObject(go7);
+ sharedWorld.addBeyondarObject(go8);
+ sharedWorld.addBeyondarObject(go9);
return sharedWorld;
}
}
| true | true |
public static World generateObjects(Context context) {
if (sharedWorld != null){
return sharedWorld;
}
sharedWorld = new World(context);
// The user can set the default bitmap. This is useful if you are
// loading images form Internet and the connection get lost
sharedWorld.setDefaultBitmap(R.drawable.beyondar_default_unknow_icon);
// User position (you can change it using the GPS listeners form Android
// API)
sharedWorld.setGeoPosition(41.26533734214473d, 1.925848038959814d);
// Create an object with an image in the app resources.
GeoObject go1 = new GeoObject(1l);
go1.setGeoPosition(41.26523339794433d, 1.926036406654116d);
go1.setImageResource(R.drawable.creature_1);
go1.setName("Creature 1");
// Is it also possible to load the image asynchronously form internet
GeoObject go2 = new GeoObject(2l);
go2.setGeoPosition(41.26518966360719d, 1.92582424468222d);
go2.setImageUri("http://beyondar.com/sites/default/files/logo_reduced.png");
go2.setName("Online image");
// Also possible to get images from the SDcard
GeoObject go3 = new GeoObject(3l);
go3.setGeoPosition(41.26550959641445d, 1.925873388087619d);
go3.setImageUri("/sdcard/TheAvengers_IronMan.jpeg");
go3.setName("IronMan from sdcard");
// And the same goes for the app assets
GeoObject go4 = new GeoObject(4l);
go4.setGeoPosition(41.26518862002349d, 1.925662767707665d);
go4.setImageUri("assets://creature_7.png");
go4.setName("Image from assets");
GeoObject go5 = new GeoObject(5l);
go5.setGeoPosition(41.26553066234138d, 1.925777906882577d);
go5.setImageResource(R.drawable.creature_5);
go5.setName("Creature 5");
GeoObject go6 = new GeoObject(6l);
go6.setGeoPosition(41.26496218466268d, 1.925250806050688d);
go6.setImageResource(R.drawable.creature_6);
go6.setName("Creature 6");
GeoObject go7 = new GeoObject(7l);
go7.setGeoPosition(41.26581776104766d, 1.925932313852319d);
go7.setImageResource(R.drawable.creature_2);
go7.setName("Creature 2");
GeoObject go8 = new GeoObject(8l);
go8.setGeoPosition(41.26534261025682d, 1.926164369775198d);
go8.setImageResource(R.drawable.rectangle);
go8.setName("Object 8");
GeoObject go9 = new GeoObject(9l);
go9.setGeoPosition(41.26530734214473d, 1.925808038959814d);
go9.setImageResource(R.drawable.creature_4);
go9.setName("Creature 88884");
// sharedWorld.addBeyondarObject(go1);
// sharedWorld.addBeyondarObject(go2);
// sharedWorld.addBeyondarObject(go3);
// sharedWorld.addBeyondarObject(go4);
// sharedWorld.addBeyondarObject(go5);
// sharedWorld.addBeyondarObject(go6);
// sharedWorld.addBeyondarObject(go7);
// sharedWorld.addBeyondarObject(go8);
// sharedWorld.addBeyondarObject(go9);
return sharedWorld;
}
|
public static World generateObjects(Context context) {
if (sharedWorld != null){
return sharedWorld;
}
sharedWorld = new World(context);
// The user can set the default bitmap. This is useful if you are
// loading images form Internet and the connection get lost
sharedWorld.setDefaultBitmap(R.drawable.beyondar_default_unknow_icon);
// User position (you can change it using the GPS listeners form Android
// API)
sharedWorld.setGeoPosition(41.26533734214473d, 1.925848038959814d);
// Create an object with an image in the app resources.
GeoObject go1 = new GeoObject(1l);
go1.setGeoPosition(41.26523339794433d, 1.926036406654116d);
go1.setImageResource(R.drawable.creature_1);
go1.setName("Creature 1");
// Is it also possible to load the image asynchronously form internet
GeoObject go2 = new GeoObject(2l);
go2.setGeoPosition(41.26518966360719d, 1.92582424468222d);
go2.setImageUri("http://beyondar.com/sites/default/files/logo_reduced.png");
go2.setName("Online image");
// Also possible to get images from the SDcard
GeoObject go3 = new GeoObject(3l);
go3.setGeoPosition(41.26550959641445d, 1.925873388087619d);
go3.setImageUri("/sdcard/TheAvengers_IronMan.jpeg");
go3.setName("IronMan from sdcard");
// And the same goes for the app assets
GeoObject go4 = new GeoObject(4l);
go4.setGeoPosition(41.26518862002349d, 1.925662767707665d);
go4.setImageUri("assets://creature_7.png");
go4.setName("Image from assets");
GeoObject go5 = new GeoObject(5l);
go5.setGeoPosition(41.26553066234138d, 1.925777906882577d);
go5.setImageResource(R.drawable.creature_5);
go5.setName("Creature 5");
GeoObject go6 = new GeoObject(6l);
go6.setGeoPosition(41.26496218466268d, 1.925250806050688d);
go6.setImageResource(R.drawable.creature_6);
go6.setName("Creature 6");
GeoObject go7 = new GeoObject(7l);
go7.setGeoPosition(41.26581776104766d, 1.925932313852319d);
go7.setImageResource(R.drawable.creature_2);
go7.setName("Creature 2");
GeoObject go8 = new GeoObject(8l);
go8.setGeoPosition(41.26534261025682d, 1.926164369775198d);
go8.setImageResource(R.drawable.rectangle);
go8.setName("Object 8");
GeoObject go9 = new GeoObject(9l);
go9.setGeoPosition(41.26530734214473d, 1.925808038959814d);
go9.setImageResource(R.drawable.creature_4);
go9.setName("Creature 88884");
sharedWorld.addBeyondarObject(go1);
sharedWorld.addBeyondarObject(go2);
sharedWorld.addBeyondarObject(go3);
sharedWorld.addBeyondarObject(go4);
sharedWorld.addBeyondarObject(go5);
sharedWorld.addBeyondarObject(go6);
sharedWorld.addBeyondarObject(go7);
sharedWorld.addBeyondarObject(go8);
sharedWorld.addBeyondarObject(go9);
return sharedWorld;
}
|
diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/repository/PerfTestRepositoryTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/repository/PerfTestRepositoryTest.java
index 9314f995..6e78387d 100644
--- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/repository/PerfTestRepositoryTest.java
+++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/repository/PerfTestRepositoryTest.java
@@ -1,35 +1,35 @@
package org.ngrinder.perftest.repository;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.ngrinder.AbstractNGNinderTransactionalTest;
import org.ngrinder.perftest.model.PerfTest;
import org.ngrinder.perftest.model.Status;
import org.springframework.beans.factory.annotation.Autowired;
public class PerfTestRepositoryTest extends AbstractNGNinderTransactionalTest {
@Autowired
public PerfTestRepository repo;
@Test
public void testPerfTest() {
// Given 3 tests with different status
PerfTest entity = new PerfTest();
entity.setStatus(Status.FINISHED);
repo.save(entity);
PerfTest entity2 = new PerfTest();
entity2.setStatus(Status.CANCELED);
repo.save(entity2);
PerfTest entity3 = new PerfTest();
entity3.setStatus(Status.READY);
repo.save(entity3);
// Then all should be 3
assertThat(repo.findAll().size(), is(3));
// Then finished and canceled perftest should 2
- assertThat(repo.findAll(PerfTest.statusSetEqual(Status.FINISHED, Status.CANCELED)).size(), is(2));
+ assertThat(repo.findAll(PerfTestSpecification.statusSetEqual(Status.FINISHED, Status.CANCELED)).size(), is(2));
}
}
| true | true |
public void testPerfTest() {
// Given 3 tests with different status
PerfTest entity = new PerfTest();
entity.setStatus(Status.FINISHED);
repo.save(entity);
PerfTest entity2 = new PerfTest();
entity2.setStatus(Status.CANCELED);
repo.save(entity2);
PerfTest entity3 = new PerfTest();
entity3.setStatus(Status.READY);
repo.save(entity3);
// Then all should be 3
assertThat(repo.findAll().size(), is(3));
// Then finished and canceled perftest should 2
assertThat(repo.findAll(PerfTest.statusSetEqual(Status.FINISHED, Status.CANCELED)).size(), is(2));
}
|
public void testPerfTest() {
// Given 3 tests with different status
PerfTest entity = new PerfTest();
entity.setStatus(Status.FINISHED);
repo.save(entity);
PerfTest entity2 = new PerfTest();
entity2.setStatus(Status.CANCELED);
repo.save(entity2);
PerfTest entity3 = new PerfTest();
entity3.setStatus(Status.READY);
repo.save(entity3);
// Then all should be 3
assertThat(repo.findAll().size(), is(3));
// Then finished and canceled perftest should 2
assertThat(repo.findAll(PerfTestSpecification.statusSetEqual(Status.FINISHED, Status.CANCELED)).size(), is(2));
}
|
diff --git a/activemq-cpp/openwire-scripts/AmqCppClassesGenerator.java b/activemq-cpp/openwire-scripts/AmqCppClassesGenerator.java
index 8c0d9c20..2151daf8 100644
--- a/activemq-cpp/openwire-scripts/AmqCppClassesGenerator.java
+++ b/activemq-cpp/openwire-scripts/AmqCppClassesGenerator.java
@@ -1,350 +1,356 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.tool;
import java.io.File;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import org.codehaus.jam.JClass;
import org.codehaus.jam.JProperty;
/**
*
* @version $Revision: 409828 $
*/
public class AmqCppClassesGenerator extends MultiSourceGenerator {
protected String targetDir="./src/main";
public Object run() {
filePostFix = getFilePostFix();
if (destDir == null) {
destDir = new File(
targetDir+"/activemq/connector/openwire/commands");
}
return super.run();
}
protected String getFilePostFix() {
return ".cpp";
}
protected String getProperBaseClassName( String className, String baseClass ) {
if( baseClass == null || className == null ) {
return null;
}
// The C++ BaseCommand class is a template, which requires either
// transport::Command, or transport::Response.
if( className.equals( "Response" ) ) {
return "BaseCommand<transport::Response>";
} else if( baseClass.equals( "BaseCommand" ) ) {
return "BaseCommand<transport::Command>";
}
// No change.
return baseClass;
}
public String toCppType(JClass type) {
String name = type.getSimpleName();
if (name.equals("String")) {
return "std::string";
}
else if( type.isArrayType() ) {
if( name.equals( "byte[]" ) )
name = "unsigned char[]";
JClass arrayClass = type.getArrayComponentType();
if( arrayClass.isPrimitiveType() ) {
return "std::vector<" + name.substring(0, name.length()-2) + ">";
} else {
return "std::vector<" + name.substring(0, name.length()-2) + "*>";
}
}
else if( name.equals( "Throwable" ) || name.equals( "Exception" ) ) {
return "BrokerError";
}
else if( name.equals("BaseDataStructure" ) ){
return "DataStructure";
}
else if( name.equals("ByteSequence") ) {
return "std::vector<unsigned char>";
}
else if( name.equals("boolean") ) {
return "bool";
}
else if( name.equals("long") ) {
return "long long";
}
else if( name.equals("byte") ) {
return "unsigned char";
}
else if( !type.isPrimitiveType() ) {
return name;
}
else {
return name;
}
}
/**
* Converts the Java type to a C++ default value
*/
public String toCppDefaultValue(JClass type) {
String name = type.getSimpleName();
if (name.equals("boolean")) {
return "false";
} else if( name.equals("String") ) {
return "\"\"";
} else if( !type.isPrimitiveType() ) {
return "NULL";
} else {
return "0";
}
}
protected void generateLicence(PrintWriter out) {
out.println("/*");
out.println(" * Licensed to the Apache Software Foundation (ASF) under one or more");
out.println(" * contributor license agreements. See the NOTICE file distributed with");
out.println(" * this work for additional information regarding copyright ownership.");
out.println(" * The ASF licenses this file to You under the Apache License, Version 2.0");
out.println(" * (the \"License\"); you may not use this file except in compliance with");
out.println(" * the License. You may obtain a copy of the License at");
out.println(" *");
out.println(" * http://www.apache.org/licenses/LICENSE-2.0");
out.println(" *");
out.println(" * Unless required by applicable law or agreed to in writing, software");
out.println(" * distributed under the License is distributed on an \"AS IS\" BASIS,");
out.println(" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.");
out.println(" * See the License for the specific language governing permissions and");
out.println(" * limitations under the License.");
out.println(" */");
}
protected void generateFile(PrintWriter out) throws Exception {
generateLicence(out);
out.println("#include <activemq/connector/openwire/commands/"+className+".h>");
out.println("#include <activemq/exceptions/NullPointerException.h>");
out.println("");
out.println("using namespace std;");
out.println("using namespace activemq;");
out.println("using namespace activemq::exceptions;");
out.println("using namespace activemq::connector;");
out.println("using namespace activemq::connector::openwire;");
out.println("using namespace activemq::connector::openwire::commands;");
out.println("");
out.println("/*");
out.println(" *");
out.println(" * Command and marshaling code for OpenWire format for "+className+"");
out.println(" *");
out.println(" *");
out.println(" * NOTE!: This file is autogenerated - do not modify!");
out.println(" * if you need to make a change, please see the Java Classes in the");
out.println(" * activemq-core module");
out.println(" *");
out.println(" */");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+className+"::"+className+"()");
out.println("{");
List properties = getProperties();
for (Iterator iter = properties.iterator(); iter.hasNext();) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String value = toCppDefaultValue(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
if( !type.startsWith("std::vector") ) {
out.println(" this->"+parameterName+" = "+value+";");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+className+"::~"+className+"()");
out.println("{");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
if( property.getType().isPrimitiveType() ||
property.getType().getSimpleName().equals("String") ) {
continue;
}
if( !type.startsWith("std::vector" ) ) {
out.println(" delete this->" + parameterName + ";");
} else if( type.contains( "*" ) ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < " + parameterName + ".size(); ++i" + parameterName + " ) {");
out.println(" delete " + parameterName + "[i" + parameterName + "];");
out.println(" }");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("DataStructure* "+className+"::cloneDataStructure() const {");
String newInstance = decapitalize( className );
out.println(" "+className+"* "+newInstance+" = new "+className+"();");
out.println("");
out.println(" // Copy the data from the base class or classes");
out.println(" "+newInstance+"->copyDataStructure( this );");
out.println("");
out.println(" return "+newInstance+";");
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("void "+className+"::copyDataStructure( const DataStructure* src ) {");
out.println("");
if( baseClass != null ) {
out.println(" // Copy the data of the base class or classes");
out.println(" "+getProperBaseClassName( className, baseClass )+"::copyDataStructure( src );");
out.println("");
}
out.println(" const "+className+"* srcPtr = dynamic_cast<const "+className+"*>( src );");
out.println("");
out.println(" if( srcPtr == NULL || src == NULL ) {");
out.println(" ");
out.println(" throw exceptions::NullPointerException(");
out.println(" __FILE__, __LINE__,");
out.println(" \""+className+"::copyDataStructure - src is NULL or invalid\" );");
out.println(" }");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String constNess = "";
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
if( property.getType().isPrimitiveType() ||
type.equals("std::string") ||
property.getType().getSimpleName().equals("ByteSequence") ){
out.println(" this->"+setter+"( srcPtr->"+getter+"() );");
} else if( property.getType().isArrayType() &&
!property.getType().getArrayComponentType().isPrimitiveType() ) {
String arrayType = property.getType().getArrayComponentType().getSimpleName();
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < srcPtr->"+getter+"().size(); ++i" + parameterName + " ) {");
- out.println(" this->"+getter+"().push_back( ");
- out.println(" dynamic_cast<"+arrayType+"*>( ");
- out.println(" srcPtr->"+getter+"()[i"+parameterName+"]->cloneDataStructure() ) );");
+ out.println(" if( srcPtr->"+getter+"()[i"+parameterName+"] != NULL ) {");
+ out.println(" this->"+getter+"().push_back( ");
+ out.println(" dynamic_cast<"+arrayType+"*>( ");
+ out.println(" srcPtr->"+getter+"()[i"+parameterName+"]->cloneDataStructure() ) );");
+ out.println(" } else {");
+ out.println(" this->"+getter+"().push_back( NULL );");
+ out.println(" }");
out.println(" }");
} else if( property.getType().isArrayType() &&
property.getType().getArrayComponentType().isPrimitiveType() ) {
out.println(" this->"+setter+"( srcPtr->"+getter+"() );");
} else {
- out.println(" this->"+setter+"( ");
- out.println(" dynamic_cast<"+type+"*>( ");
- out.println(" srcPtr->"+getter+"()->cloneDataStructure() ) );");
+ out.println(" if( srcPtr->"+getter+"() != NULL ) {");
+ out.println(" this->"+setter+"( ");
+ out.println(" dynamic_cast<"+type+"*>( ");
+ out.println(" srcPtr->"+getter+"()->cloneDataStructure() ) );");
+ out.println(" }");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("unsigned char "+className+"::getDataStructureType() const {");
out.println(" return "+className+"::ID_" + className.toUpperCase() + "; ");
out.println("}");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
String constNess = "";
if( !property.getType().isPrimitiveType() &&
!property.getType().getSimpleName().equals("ByteSequence") &&
!property.getType().getSimpleName().equals("String") &&
!type.startsWith("std::vector") ) {
type = type + "*";
} else if( property.getType().getSimpleName().equals("String") ||
type.startsWith( "std::vector") ) {
type = type + "&";
constNess = "const ";
}
out.println("");
if( property.getType().isPrimitiveType() ) {
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(type+" "+className+"::"+getter+"() const {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
} else {
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("const "+type+" "+className+"::"+getter+"() const {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+type+" "+className+"::"+getter+"() {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
}
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("void " + className + "::" + setter+"(" + constNess + type+ " " + parameterName +" ) {");
out.println(" this->"+parameterName+" = "+parameterName+";");
out.println("}");
}
out.println("");
}
public String getTargetDir() {
return targetDir;
}
public void setTargetDir(String targetDir) {
this.targetDir = targetDir;
}
}
| false | true |
protected void generateFile(PrintWriter out) throws Exception {
generateLicence(out);
out.println("#include <activemq/connector/openwire/commands/"+className+".h>");
out.println("#include <activemq/exceptions/NullPointerException.h>");
out.println("");
out.println("using namespace std;");
out.println("using namespace activemq;");
out.println("using namespace activemq::exceptions;");
out.println("using namespace activemq::connector;");
out.println("using namespace activemq::connector::openwire;");
out.println("using namespace activemq::connector::openwire::commands;");
out.println("");
out.println("/*");
out.println(" *");
out.println(" * Command and marshaling code for OpenWire format for "+className+"");
out.println(" *");
out.println(" *");
out.println(" * NOTE!: This file is autogenerated - do not modify!");
out.println(" * if you need to make a change, please see the Java Classes in the");
out.println(" * activemq-core module");
out.println(" *");
out.println(" */");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+className+"::"+className+"()");
out.println("{");
List properties = getProperties();
for (Iterator iter = properties.iterator(); iter.hasNext();) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String value = toCppDefaultValue(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
if( !type.startsWith("std::vector") ) {
out.println(" this->"+parameterName+" = "+value+";");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+className+"::~"+className+"()");
out.println("{");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
if( property.getType().isPrimitiveType() ||
property.getType().getSimpleName().equals("String") ) {
continue;
}
if( !type.startsWith("std::vector" ) ) {
out.println(" delete this->" + parameterName + ";");
} else if( type.contains( "*" ) ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < " + parameterName + ".size(); ++i" + parameterName + " ) {");
out.println(" delete " + parameterName + "[i" + parameterName + "];");
out.println(" }");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("DataStructure* "+className+"::cloneDataStructure() const {");
String newInstance = decapitalize( className );
out.println(" "+className+"* "+newInstance+" = new "+className+"();");
out.println("");
out.println(" // Copy the data from the base class or classes");
out.println(" "+newInstance+"->copyDataStructure( this );");
out.println("");
out.println(" return "+newInstance+";");
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("void "+className+"::copyDataStructure( const DataStructure* src ) {");
out.println("");
if( baseClass != null ) {
out.println(" // Copy the data of the base class or classes");
out.println(" "+getProperBaseClassName( className, baseClass )+"::copyDataStructure( src );");
out.println("");
}
out.println(" const "+className+"* srcPtr = dynamic_cast<const "+className+"*>( src );");
out.println("");
out.println(" if( srcPtr == NULL || src == NULL ) {");
out.println(" ");
out.println(" throw exceptions::NullPointerException(");
out.println(" __FILE__, __LINE__,");
out.println(" \""+className+"::copyDataStructure - src is NULL or invalid\" );");
out.println(" }");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String constNess = "";
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
if( property.getType().isPrimitiveType() ||
type.equals("std::string") ||
property.getType().getSimpleName().equals("ByteSequence") ){
out.println(" this->"+setter+"( srcPtr->"+getter+"() );");
} else if( property.getType().isArrayType() &&
!property.getType().getArrayComponentType().isPrimitiveType() ) {
String arrayType = property.getType().getArrayComponentType().getSimpleName();
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < srcPtr->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" this->"+getter+"().push_back( ");
out.println(" dynamic_cast<"+arrayType+"*>( ");
out.println(" srcPtr->"+getter+"()[i"+parameterName+"]->cloneDataStructure() ) );");
out.println(" }");
} else if( property.getType().isArrayType() &&
property.getType().getArrayComponentType().isPrimitiveType() ) {
out.println(" this->"+setter+"( srcPtr->"+getter+"() );");
} else {
out.println(" this->"+setter+"( ");
out.println(" dynamic_cast<"+type+"*>( ");
out.println(" srcPtr->"+getter+"()->cloneDataStructure() ) );");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("unsigned char "+className+"::getDataStructureType() const {");
out.println(" return "+className+"::ID_" + className.toUpperCase() + "; ");
out.println("}");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
String constNess = "";
if( !property.getType().isPrimitiveType() &&
!property.getType().getSimpleName().equals("ByteSequence") &&
!property.getType().getSimpleName().equals("String") &&
!type.startsWith("std::vector") ) {
type = type + "*";
} else if( property.getType().getSimpleName().equals("String") ||
type.startsWith( "std::vector") ) {
type = type + "&";
constNess = "const ";
}
out.println("");
if( property.getType().isPrimitiveType() ) {
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(type+" "+className+"::"+getter+"() const {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
} else {
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("const "+type+" "+className+"::"+getter+"() const {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+type+" "+className+"::"+getter+"() {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
}
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("void " + className + "::" + setter+"(" + constNess + type+ " " + parameterName +" ) {");
out.println(" this->"+parameterName+" = "+parameterName+";");
out.println("}");
}
out.println("");
}
|
protected void generateFile(PrintWriter out) throws Exception {
generateLicence(out);
out.println("#include <activemq/connector/openwire/commands/"+className+".h>");
out.println("#include <activemq/exceptions/NullPointerException.h>");
out.println("");
out.println("using namespace std;");
out.println("using namespace activemq;");
out.println("using namespace activemq::exceptions;");
out.println("using namespace activemq::connector;");
out.println("using namespace activemq::connector::openwire;");
out.println("using namespace activemq::connector::openwire::commands;");
out.println("");
out.println("/*");
out.println(" *");
out.println(" * Command and marshaling code for OpenWire format for "+className+"");
out.println(" *");
out.println(" *");
out.println(" * NOTE!: This file is autogenerated - do not modify!");
out.println(" * if you need to make a change, please see the Java Classes in the");
out.println(" * activemq-core module");
out.println(" *");
out.println(" */");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+className+"::"+className+"()");
out.println("{");
List properties = getProperties();
for (Iterator iter = properties.iterator(); iter.hasNext();) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String value = toCppDefaultValue(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
if( !type.startsWith("std::vector") ) {
out.println(" this->"+parameterName+" = "+value+";");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+className+"::~"+className+"()");
out.println("{");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
if( property.getType().isPrimitiveType() ||
property.getType().getSimpleName().equals("String") ) {
continue;
}
if( !type.startsWith("std::vector" ) ) {
out.println(" delete this->" + parameterName + ";");
} else if( type.contains( "*" ) ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < " + parameterName + ".size(); ++i" + parameterName + " ) {");
out.println(" delete " + parameterName + "[i" + parameterName + "];");
out.println(" }");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("DataStructure* "+className+"::cloneDataStructure() const {");
String newInstance = decapitalize( className );
out.println(" "+className+"* "+newInstance+" = new "+className+"();");
out.println("");
out.println(" // Copy the data from the base class or classes");
out.println(" "+newInstance+"->copyDataStructure( this );");
out.println("");
out.println(" return "+newInstance+";");
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("void "+className+"::copyDataStructure( const DataStructure* src ) {");
out.println("");
if( baseClass != null ) {
out.println(" // Copy the data of the base class or classes");
out.println(" "+getProperBaseClassName( className, baseClass )+"::copyDataStructure( src );");
out.println("");
}
out.println(" const "+className+"* srcPtr = dynamic_cast<const "+className+"*>( src );");
out.println("");
out.println(" if( srcPtr == NULL || src == NULL ) {");
out.println(" ");
out.println(" throw exceptions::NullPointerException(");
out.println(" __FILE__, __LINE__,");
out.println(" \""+className+"::copyDataStructure - src is NULL or invalid\" );");
out.println(" }");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String constNess = "";
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
if( property.getType().isPrimitiveType() ||
type.equals("std::string") ||
property.getType().getSimpleName().equals("ByteSequence") ){
out.println(" this->"+setter+"( srcPtr->"+getter+"() );");
} else if( property.getType().isArrayType() &&
!property.getType().getArrayComponentType().isPrimitiveType() ) {
String arrayType = property.getType().getArrayComponentType().getSimpleName();
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < srcPtr->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" if( srcPtr->"+getter+"()[i"+parameterName+"] != NULL ) {");
out.println(" this->"+getter+"().push_back( ");
out.println(" dynamic_cast<"+arrayType+"*>( ");
out.println(" srcPtr->"+getter+"()[i"+parameterName+"]->cloneDataStructure() ) );");
out.println(" } else {");
out.println(" this->"+getter+"().push_back( NULL );");
out.println(" }");
out.println(" }");
} else if( property.getType().isArrayType() &&
property.getType().getArrayComponentType().isPrimitiveType() ) {
out.println(" this->"+setter+"( srcPtr->"+getter+"() );");
} else {
out.println(" if( srcPtr->"+getter+"() != NULL ) {");
out.println(" this->"+setter+"( ");
out.println(" dynamic_cast<"+type+"*>( ");
out.println(" srcPtr->"+getter+"()->cloneDataStructure() ) );");
out.println(" }");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("unsigned char "+className+"::getDataStructureType() const {");
out.println(" return "+className+"::ID_" + className.toUpperCase() + "; ");
out.println("}");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
String constNess = "";
if( !property.getType().isPrimitiveType() &&
!property.getType().getSimpleName().equals("ByteSequence") &&
!property.getType().getSimpleName().equals("String") &&
!type.startsWith("std::vector") ) {
type = type + "*";
} else if( property.getType().getSimpleName().equals("String") ||
type.startsWith( "std::vector") ) {
type = type + "&";
constNess = "const ";
}
out.println("");
if( property.getType().isPrimitiveType() ) {
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(type+" "+className+"::"+getter+"() const {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
} else {
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("const "+type+" "+className+"::"+getter+"() const {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+type+" "+className+"::"+getter+"() {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
}
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("void " + className + "::" + setter+"(" + constNess + type+ " " + parameterName +" ) {");
out.println(" this->"+parameterName+" = "+parameterName+";");
out.println("}");
}
out.println("");
}
|
diff --git a/src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataNode.java b/src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataNode.java
index 5b452ec11..8cc9d5d12 100644
--- a/src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataNode.java
+++ b/src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataNode.java
@@ -1,1518 +1,1518 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.datanode;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.BlockListAsLongs;
import org.apache.hadoop.hdfs.protocol.ClientDatanodeProtocol;
import org.apache.hadoop.hdfs.protocol.DataTransferProtocol;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.FSConstants;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.UnregisteredDatanodeException;
import org.apache.hadoop.hdfs.server.common.HdfsConstants.StartupOption;
import org.apache.hadoop.hdfs.server.common.HdfsConstants;
import org.apache.hadoop.hdfs.server.common.GenerationStamp;
import org.apache.hadoop.hdfs.server.common.IncorrectVersionException;
import org.apache.hadoop.hdfs.server.common.Storage;
import org.apache.hadoop.hdfs.server.datanode.metrics.DataNodeMetrics;
import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
import org.apache.hadoop.hdfs.server.namenode.FileChecksumServlets;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.namenode.StreamFile;
import org.apache.hadoop.hdfs.server.protocol.BlockCommand;
import org.apache.hadoop.hdfs.server.protocol.BlockMetaDataInfo;
import org.apache.hadoop.hdfs.server.protocol.DatanodeCommand;
import org.apache.hadoop.hdfs.server.protocol.DatanodeProtocol;
import org.apache.hadoop.hdfs.server.protocol.DatanodeRegistration;
import org.apache.hadoop.hdfs.server.protocol.DisallowedDatanodeException;
import org.apache.hadoop.hdfs.server.protocol.InterDatanodeProtocol;
import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo;
import org.apache.hadoop.hdfs.server.protocol.UpgradeCommand;
import org.apache.hadoop.http.HttpServer;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.ipc.Server;
import org.apache.hadoop.net.DNS;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.util.Daemon;
import org.apache.hadoop.util.DiskChecker;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.DiskChecker.DiskErrorException;
import org.apache.hadoop.util.DiskChecker.DiskOutOfSpaceException;
/**********************************************************
* DataNode is a class (and program) that stores a set of
* blocks for a DFS deployment. A single deployment can
* have one or many DataNodes. Each DataNode communicates
* regularly with a single NameNode. It also communicates
* with client code and other DataNodes from time to time.
*
* DataNodes store a series of named blocks. The DataNode
* allows client code to read these blocks, or to write new
* block data. The DataNode may also, in response to instructions
* from its NameNode, delete blocks or copy blocks to/from other
* DataNodes.
*
* The DataNode maintains just one critical table:
* block-> stream of bytes (of BLOCK_SIZE or less)
*
* This info is stored on a local disk. The DataNode
* reports the table's contents to the NameNode upon startup
* and every so often afterwards.
*
* DataNodes spend their lives in an endless loop of asking
* the NameNode for something to do. A NameNode cannot connect
* to a DataNode directly; a NameNode simply returns values from
* functions invoked by a DataNode.
*
* DataNodes maintain an open server socket so that client code
* or other DataNodes can read/write data. The host/port for
* this server is reported to the NameNode, which then sends that
* information to clients or other DataNodes that might be interested.
*
**********************************************************/
public class DataNode extends Configured
implements InterDatanodeProtocol, ClientDatanodeProtocol, FSConstants, Runnable {
public static final Log LOG = LogFactory.getLog(DataNode.class);
public static final String DN_CLIENTTRACE_FORMAT =
"src: %s" + // src IP
", dest: %s" + // dst IP
", bytes: %s" + // byte count
", op: %s" + // operation
", cliID: %s" + // DFSClient id
", srvID: %s" + // DatanodeRegistration
", blockid: %s"; // block id
static final Log ClientTraceLog =
LogFactory.getLog(DataNode.class.getName() + ".clienttrace");
/**
* Use {@link NetUtils#createSocketAddr(String)} instead.
*/
@Deprecated
public static InetSocketAddress createSocketAddr(String target
) throws IOException {
return NetUtils.createSocketAddr(target);
}
public DatanodeProtocol namenode = null;
public FSDatasetInterface data = null;
public DatanodeRegistration dnRegistration = null;
volatile boolean shouldRun = true;
private LinkedList<Block> receivedBlockList = new LinkedList<Block>();
/** list of blocks being recovered */
private final Map<Block, Block> ongoingRecovery = new HashMap<Block, Block>();
private LinkedList<String> delHints = new LinkedList<String>();
public final static String EMPTY_DEL_HINT = "";
int xmitsInProgress = 0;
Daemon dataXceiverServer = null;
ThreadGroup threadGroup = null;
long blockReportInterval;
//disallow the sending of BR before instructed to do so
long lastBlockReport = 0;
boolean resetBlockReportTime = true;
long initialBlockReportDelay = BLOCKREPORT_INITIAL_DELAY * 1000L;
long lastHeartbeat = 0;
long heartBeatInterval;
private DataStorage storage = null;
private HttpServer infoServer = null;
DataNodeMetrics myMetrics;
private static InetSocketAddress nameNodeAddr;
private InetSocketAddress selfAddr;
private static DataNode datanodeObject = null;
private Thread dataNodeThread = null;
String machineName;
private static String dnThreadName;
int socketTimeout;
int socketWriteTimeout = 0;
boolean transferToAllowed = true;
int writePacketSize = 0;
public DataBlockScanner blockScanner = null;
public Daemon blockScannerThread = null;
private static final Random R = new Random();
// For InterDataNodeProtocol
public Server ipcServer;
/**
* Current system time.
* @return current time in msec.
*/
static long now() {
return System.currentTimeMillis();
}
/**
* Create the DataNode given a configuration and an array of dataDirs.
* 'dataDirs' is where the blocks are stored.
*/
DataNode(Configuration conf,
AbstractList<File> dataDirs) throws IOException {
super(conf);
datanodeObject = this;
try {
startDataNode(conf, dataDirs);
} catch (IOException ie) {
shutdown();
throw ie;
}
}
/**
* This method starts the data node with the specified conf.
*
* @param conf - the configuration
* if conf's CONFIG_PROPERTY_SIMULATED property is set
* then a simulated storage based data node is created.
*
* @param dataDirs - only for a non-simulated storage data node
* @throws IOException
*/
void startDataNode(Configuration conf,
AbstractList<File> dataDirs
) throws IOException {
// use configured nameserver & interface to get local hostname
if (conf.get("slave.host.name") != null) {
machineName = conf.get("slave.host.name");
}
if (machineName == null) {
machineName = DNS.getDefaultHost(
conf.get("dfs.datanode.dns.interface","default"),
conf.get("dfs.datanode.dns.nameserver","default"));
}
InetSocketAddress nameNodeAddr = NameNode.getAddress(conf);
this.socketTimeout = conf.getInt("dfs.socket.timeout",
HdfsConstants.READ_TIMEOUT);
this.socketWriteTimeout = conf.getInt("dfs.datanode.socket.write.timeout",
HdfsConstants.WRITE_TIMEOUT);
/* Based on results on different platforms, we might need set the default
* to false on some of them. */
this.transferToAllowed = conf.getBoolean("dfs.datanode.transferTo.allowed",
true);
this.writePacketSize = conf.getInt("dfs.write.packet.size", 64*1024);
String address =
NetUtils.getServerAddress(conf,
"dfs.datanode.bindAddress",
"dfs.datanode.port",
"dfs.datanode.address");
InetSocketAddress socAddr = NetUtils.createSocketAddr(address);
int tmpPort = socAddr.getPort();
storage = new DataStorage();
// construct registration
this.dnRegistration = new DatanodeRegistration(machineName + ":" + tmpPort);
// connect to name node
this.namenode = (DatanodeProtocol)
RPC.waitForProxy(DatanodeProtocol.class,
DatanodeProtocol.versionID,
nameNodeAddr,
conf);
// get version and id info from the name-node
NamespaceInfo nsInfo = handshake();
StartupOption startOpt = getStartupOption(conf);
assert startOpt != null : "Startup option must be set.";
boolean simulatedFSDataset =
conf.getBoolean("dfs.datanode.simulateddatastorage", false);
if (simulatedFSDataset) {
setNewStorageID(dnRegistration);
dnRegistration.storageInfo.layoutVersion = FSConstants.LAYOUT_VERSION;
dnRegistration.storageInfo.namespaceID = nsInfo.namespaceID;
// it would have been better to pass storage as a parameter to
// constructor below - need to augment ReflectionUtils used below.
conf.set("StorageId", dnRegistration.getStorageID());
try {
//Equivalent of following (can't do because Simulated is in test dir)
// this.data = new SimulatedFSDataset(conf);
this.data = (FSDatasetInterface) ReflectionUtils.newInstance(
Class.forName("org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset"), conf);
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.stringifyException(e));
}
} else { // real storage
// read storage info, lock data dirs and transition fs state if necessary
storage.recoverTransitionRead(nsInfo, dataDirs, startOpt);
// adjust
this.dnRegistration.setStorageInfo(storage);
// initialize data node internal structure
this.data = new FSDataset(storage, conf);
}
// find free port
ServerSocket ss = (socketWriteTimeout > 0) ?
ServerSocketChannel.open().socket() : new ServerSocket();
Server.bind(ss, socAddr, 0);
ss.setReceiveBufferSize(DEFAULT_DATA_SOCKET_SIZE);
// adjust machine name with the actual port
tmpPort = ss.getLocalPort();
selfAddr = new InetSocketAddress(ss.getInetAddress().getHostAddress(),
tmpPort);
this.dnRegistration.setName(machineName + ":" + tmpPort);
LOG.info("Opened info server at " + tmpPort);
this.threadGroup = new ThreadGroup("dataXceiverServer");
this.dataXceiverServer = new Daemon(threadGroup,
new DataXceiverServer(ss, conf, this));
this.threadGroup.setDaemon(true); // auto destroy when empty
this.blockReportInterval =
conf.getLong("dfs.blockreport.intervalMsec", BLOCKREPORT_INTERVAL);
this.initialBlockReportDelay = conf.getLong("dfs.blockreport.initialDelay",
BLOCKREPORT_INITIAL_DELAY)* 1000L;
if (this.initialBlockReportDelay >= blockReportInterval) {
this.initialBlockReportDelay = 0;
LOG.info("dfs.blockreport.initialDelay is greater than " +
"dfs.blockreport.intervalMsec." + " Setting initial delay to 0 msec:");
}
this.heartBeatInterval = conf.getLong("dfs.heartbeat.interval", HEARTBEAT_INTERVAL) * 1000L;
DataNode.nameNodeAddr = nameNodeAddr;
//initialize periodic block scanner
String reason = null;
if (conf.getInt("dfs.datanode.scan.period.hours", 0) < 0) {
reason = "verification is turned off by configuration";
} else if ( !(data instanceof FSDataset) ) {
reason = "verifcation is supported only with FSDataset";
}
if ( reason == null ) {
blockScanner = new DataBlockScanner(this, (FSDataset)data, conf);
} else {
LOG.info("Periodic Block Verification is disabled because " +
reason + ".");
}
//create a servlet to serve full-file content
String infoAddr =
NetUtils.getServerAddress(conf,
"dfs.datanode.info.bindAddress",
"dfs.datanode.info.port",
"dfs.datanode.http.address");
InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
String infoHost = infoSocAddr.getHostName();
int tmpInfoPort = infoSocAddr.getPort();
this.infoServer = new HttpServer("datanode", infoHost, tmpInfoPort,
tmpInfoPort == 0, conf);
InetSocketAddress secInfoSocAddr = NetUtils.createSocketAddr(
conf.get("dfs.datanode.https.address", infoHost + ":" + 0));
Configuration sslConf = new Configuration(conf);
sslConf.addResource(conf.get("https.keystore.info.rsrc", "sslinfo.xml"));
String keyloc = sslConf.get("https.keystore.location");
if (null != keyloc) {
this.infoServer.addSslListener(secInfoSocAddr, keyloc,
sslConf.get("https.keystore.password", ""),
sslConf.get("https.keystore.keypassword", ""));
}
this.infoServer.addInternalServlet(null, "/streamFile/*", StreamFile.class);
this.infoServer.addInternalServlet(null, "/getFileChecksum/*",
FileChecksumServlets.GetServlet.class);
this.infoServer.setAttribute("datanode.blockScanner", blockScanner);
this.infoServer.addServlet(null, "/blockScannerReport",
DataBlockScanner.Servlet.class);
this.infoServer.start();
// adjust info port
this.dnRegistration.setInfoPort(this.infoServer.getPort());
- myMetrics = new DataNodeMetrics(conf, dnRegistration.getName());
+ myMetrics = new DataNodeMetrics(conf, dnRegistration.getStorageID());
//init ipc server
InetSocketAddress ipcAddr = NetUtils.createSocketAddr(
conf.get("dfs.datanode.ipc.address"));
ipcServer = RPC.getServer(this, ipcAddr.getHostName(), ipcAddr.getPort(),
conf.getInt("dfs.datanode.handler.count", 3), false, conf);
ipcServer.start();
dnRegistration.setIpcPort(ipcServer.getListenerAddress().getPort());
LOG.info("dnRegistration = " + dnRegistration);
}
/**
* Creates either NIO or regular depending on socketWriteTimeout.
*/
protected Socket newSocket() throws IOException {
return (socketWriteTimeout > 0) ?
SocketChannel.open().socket() : new Socket();
}
private NamespaceInfo handshake() throws IOException {
NamespaceInfo nsInfo = new NamespaceInfo();
while (shouldRun) {
try {
nsInfo = namenode.versionRequest();
break;
} catch(SocketTimeoutException e) { // namenode is busy
LOG.info("Problem connecting to server: " + getNameNodeAddr());
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {}
}
}
String errorMsg = null;
// verify build version
if( ! nsInfo.getBuildVersion().equals( Storage.getBuildVersion() )) {
errorMsg = "Incompatible build versions: namenode BV = "
+ nsInfo.getBuildVersion() + "; datanode BV = "
+ Storage.getBuildVersion();
LOG.fatal( errorMsg );
try {
namenode.errorReport( dnRegistration,
DatanodeProtocol.NOTIFY, errorMsg );
} catch( SocketTimeoutException e ) { // namenode is busy
LOG.info("Problem connecting to server: " + getNameNodeAddr());
}
throw new IOException( errorMsg );
}
assert FSConstants.LAYOUT_VERSION == nsInfo.getLayoutVersion() :
"Data-node and name-node layout versions must be the same."
+ "Expected: "+ FSConstants.LAYOUT_VERSION + " actual "+ nsInfo.getLayoutVersion();
return nsInfo;
}
/** Return the DataNode object
*
*/
public static DataNode getDataNode() {
return datanodeObject;
}
public static InterDatanodeProtocol createInterDataNodeProtocolProxy(
DatanodeID datanodeid, Configuration conf) throws IOException {
InetSocketAddress addr = NetUtils.createSocketAddr(
datanodeid.getHost() + ":" + datanodeid.getIpcPort());
if (InterDatanodeProtocol.LOG.isDebugEnabled()) {
InterDatanodeProtocol.LOG.info("InterDatanodeProtocol addr=" + addr);
}
return (InterDatanodeProtocol)RPC.waitForProxy(InterDatanodeProtocol.class,
InterDatanodeProtocol.versionID, addr, conf);
}
public InetSocketAddress getNameNodeAddr() {
return nameNodeAddr;
}
public InetSocketAddress getSelfAddr() {
return selfAddr;
}
DataNodeMetrics getMetrics() {
return myMetrics;
}
/**
* Return the namenode's identifier
*/
public String getNamenode() {
//return namenode.toString();
return "<namenode>";
}
public static void setNewStorageID(DatanodeRegistration dnReg) {
/* Return
* "DS-randInt-ipaddr-currentTimeMillis"
* It is considered extermely rare for all these numbers to match
* on a different machine accidentally for the following
* a) SecureRandom(INT_MAX) is pretty much random (1 in 2 billion), and
* b) Good chance ip address would be different, and
* c) Even on the same machine, Datanode is designed to use different ports.
* d) Good chance that these are started at different times.
* For a confict to occur all the 4 above have to match!.
* The format of this string can be changed anytime in future without
* affecting its functionality.
*/
String ip = "unknownIP";
try {
ip = DNS.getDefaultIP("default");
} catch (UnknownHostException ignored) {
LOG.warn("Could not find ip address of \"default\" inteface.");
}
int rand = 0;
try {
rand = SecureRandom.getInstance("SHA1PRNG").nextInt(Integer.MAX_VALUE);
} catch (NoSuchAlgorithmException e) {
LOG.warn("Could not use SecureRandom");
rand = R.nextInt(Integer.MAX_VALUE);
}
dnReg.storageID = "DS-" + rand + "-"+ ip + "-" + dnReg.getPort() + "-" +
System.currentTimeMillis();
}
/**
* Register datanode
* <p>
* The datanode needs to register with the namenode on startup in order
* 1) to report which storage it is serving now and
* 2) to receive a registrationID
* issued by the namenode to recognize registered datanodes.
*
* @see FSNamesystem#registerDatanode(DatanodeRegistration)
* @throws IOException
*/
private void register() throws IOException {
if (dnRegistration.getStorageID().equals("")) {
setNewStorageID(dnRegistration);
}
while(shouldRun) {
try {
// reset name to machineName. Mainly for web interface.
dnRegistration.name = machineName + ":" + dnRegistration.getPort();
dnRegistration = namenode.register(dnRegistration);
break;
} catch(SocketTimeoutException e) { // namenode is busy
LOG.info("Problem connecting to server: " + getNameNodeAddr());
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {}
}
}
assert ("".equals(storage.getStorageID())
&& !"".equals(dnRegistration.getStorageID()))
|| storage.getStorageID().equals(dnRegistration.getStorageID()) :
"New storageID can be assigned only if data-node is not formatted";
if (storage.getStorageID().equals("")) {
storage.setStorageID(dnRegistration.getStorageID());
storage.writeAll();
LOG.info("New storage id " + dnRegistration.getStorageID()
+ " is assigned to data-node " + dnRegistration.getName());
}
if(! storage.getStorageID().equals(dnRegistration.getStorageID())) {
throw new IOException("Inconsistent storage IDs. Name-node returned "
+ dnRegistration.getStorageID()
+ ". Expecting " + storage.getStorageID());
}
// random short delay - helps scatter the BR from all DNs
scheduleBlockReport(initialBlockReportDelay);
}
/**
* Shut down this instance of the datanode.
* Returns only after shutdown is complete.
*/
public void shutdown() {
if (infoServer != null) {
try {
infoServer.stop();
} catch (Exception e) {
}
}
if (ipcServer != null) {
ipcServer.stop();
}
this.shouldRun = false;
if (dataXceiverServer != null) {
((DataXceiverServer) this.dataXceiverServer.getRunnable()).kill();
this.dataXceiverServer.interrupt();
// wait for all data receiver threads to exit
if (this.threadGroup != null) {
while (true) {
this.threadGroup.interrupt();
LOG.info("Waiting for threadgroup to exit, active threads is " +
this.threadGroup.activeCount());
if (this.threadGroup.activeCount() == 0) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
}
RPC.stopProxy(namenode); // stop the RPC threads
if(upgradeManager != null)
upgradeManager.shutdownUpgrade();
if (blockScanner != null)
blockScanner.shutdown();
if (blockScannerThread != null)
blockScannerThread.interrupt();
if (storage != null) {
try {
this.storage.unlockAll();
} catch (IOException ie) {
}
}
if (dataNodeThread != null) {
dataNodeThread.interrupt();
try {
dataNodeThread.join();
} catch (InterruptedException ie) {
}
}
if (data != null) {
data.shutdown();
}
if (myMetrics != null) {
myMetrics.shutdown();
}
}
/* Check if there is no space in disk or the disk is read-only
* when IOException occurs.
* If so, handle the error */
protected void checkDiskError( IOException e ) throws IOException {
if (e.getMessage().startsWith("No space left on device")) {
throw new DiskOutOfSpaceException("No space left on device");
} else {
checkDiskError();
}
}
/* Check if there is no disk space and if so, handle the error*/
protected void checkDiskError( ) throws IOException {
try {
data.checkDataDir();
} catch(DiskErrorException de) {
handleDiskError(de.getMessage());
}
}
private void handleDiskError(String errMsgr) {
LOG.warn("DataNode is shutting down.\n" + errMsgr);
try {
namenode.errorReport(
dnRegistration, DatanodeProtocol.DISK_ERROR, errMsgr);
} catch(IOException ignored) {
}
shutdown();
}
/** Number of concurrent xceivers per node. */
int getXceiverCount() {
return threadGroup == null ? 0 : threadGroup.activeCount();
}
/**
* Main loop for the DataNode. Runs until shutdown,
* forever calling remote NameNode functions.
*/
public void offerService() throws Exception {
LOG.info("using BLOCKREPORT_INTERVAL of " + blockReportInterval + "msec" +
" Initial delay: " + initialBlockReportDelay + "msec");
//
// Now loop for a long time....
//
while (shouldRun) {
try {
long startTime = now();
//
// Every so often, send heartbeat or block-report
//
if (startTime - lastHeartbeat > heartBeatInterval) {
//
// All heartbeat messages include following info:
// -- Datanode name
// -- data transfer port
// -- Total capacity
// -- Bytes remaining
//
lastHeartbeat = startTime;
DatanodeCommand cmd = namenode.sendHeartbeat(dnRegistration,
data.getCapacity(),
data.getDfsUsed(),
data.getRemaining(),
xmitsInProgress,
getXceiverCount());
myMetrics.heartbeats.inc(now() - startTime);
//LOG.info("Just sent heartbeat, with name " + localName);
if (!processCommand(cmd))
continue;
}
// check if there are newly received blocks
Block [] blockArray=null;
String [] delHintArray=null;
synchronized(receivedBlockList) {
synchronized(delHints) {
int numBlocks = receivedBlockList.size();
if (numBlocks > 0) {
if(numBlocks!=delHints.size()) {
LOG.warn("Panic: receiveBlockList and delHints are not of the same length" );
}
//
// Send newly-received blockids to namenode
//
blockArray = receivedBlockList.toArray(new Block[numBlocks]);
delHintArray = delHints.toArray(new String[numBlocks]);
}
}
}
if (blockArray != null) {
if(delHintArray == null || delHintArray.length != blockArray.length ) {
LOG.warn("Panic: block array & delHintArray are not the same" );
}
namenode.blockReceived(dnRegistration, blockArray, delHintArray);
synchronized (receivedBlockList) {
synchronized (delHints) {
for(int i=0; i<blockArray.length; i++) {
receivedBlockList.remove(blockArray[i]);
delHints.remove(delHintArray[i]);
}
}
}
}
// send block report
if (startTime - lastBlockReport > blockReportInterval) {
//
// Send latest blockinfo report if timer has expired.
// Get back a list of local block(s) that are obsolete
// and can be safely GC'ed.
//
long brStartTime = now();
Block[] bReport = data.getBlockReport();
DatanodeCommand cmd = namenode.blockReport(dnRegistration,
BlockListAsLongs.convertToArrayLongs(bReport));
long brTime = now() - brStartTime;
myMetrics.blockReports.inc(brTime);
LOG.info("BlockReport of " + bReport.length +
" blocks got processed in " + brTime + " msecs");
//
// If we have sent the first block report, then wait a random
// time before we start the periodic block reports.
//
if (resetBlockReportTime) {
lastBlockReport = startTime - R.nextInt((int)(blockReportInterval));
resetBlockReportTime = false;
} else {
lastBlockReport = startTime;
}
processCommand(cmd);
}
// start block scanner
if (blockScanner != null && blockScannerThread == null &&
upgradeManager.isUpgradeCompleted()) {
LOG.info("Starting Periodic block scanner.");
blockScannerThread = new Daemon(blockScanner);
blockScannerThread.start();
}
//
// There is no work to do; sleep until hearbeat timer elapses,
// or work arrives, and then iterate again.
//
long waitTime = heartBeatInterval - (System.currentTimeMillis() - lastHeartbeat);
synchronized(receivedBlockList) {
if (waitTime > 0 && receivedBlockList.size() == 0) {
try {
receivedBlockList.wait(waitTime);
} catch (InterruptedException ie) {
}
}
} // synchronized
} catch(RemoteException re) {
String reClass = re.getClassName();
if (UnregisteredDatanodeException.class.getName().equals(reClass) ||
DisallowedDatanodeException.class.getName().equals(reClass) ||
IncorrectVersionException.class.getName().equals(reClass)) {
LOG.warn("DataNode is shutting down: " +
StringUtils.stringifyException(re));
shutdown();
return;
}
LOG.warn(StringUtils.stringifyException(re));
} catch (IOException e) {
LOG.warn(StringUtils.stringifyException(e));
}
} // while (shouldRun)
} // offerService
/**
*
* @param cmd
* @return true if further processing may be required or false otherwise.
* @throws IOException
*/
private boolean processCommand(DatanodeCommand cmd) throws IOException {
if (cmd == null)
return true;
final BlockCommand bcmd = cmd instanceof BlockCommand? (BlockCommand)cmd: null;
switch(cmd.getAction()) {
case DatanodeProtocol.DNA_TRANSFER:
// Send a copy of a block to another datanode
transferBlocks(bcmd.getBlocks(), bcmd.getTargets());
myMetrics.blocksReplicated.inc(bcmd.getBlocks().length);
break;
case DatanodeProtocol.DNA_INVALIDATE:
//
// Some local block(s) are obsolete and can be
// safely garbage-collected.
//
Block toDelete[] = bcmd.getBlocks();
try {
if (blockScanner != null) {
blockScanner.deleteBlocks(toDelete);
}
data.invalidate(toDelete);
} catch(IOException e) {
checkDiskError();
throw e;
}
myMetrics.blocksRemoved.inc(toDelete.length);
break;
case DatanodeProtocol.DNA_SHUTDOWN:
// shut down the data node
this.shutdown();
return false;
case DatanodeProtocol.DNA_REGISTER:
// namenode requested a registration - at start or if NN lost contact
LOG.info("DatanodeCommand action: DNA_REGISTER");
register();
break;
case DatanodeProtocol.DNA_FINALIZE:
storage.finalizeUpgrade();
break;
case UpgradeCommand.UC_ACTION_START_UPGRADE:
// start distributed upgrade here
processDistributedUpgradeCommand((UpgradeCommand)cmd);
break;
case DatanodeProtocol.DNA_RECOVERBLOCK:
recoverBlocks(bcmd.getBlocks(), bcmd.getTargets());
break;
default:
LOG.warn("Unknown DatanodeCommand action: " + cmd.getAction());
}
return true;
}
// Distributed upgrade manager
UpgradeManagerDatanode upgradeManager = new UpgradeManagerDatanode(this);
private void processDistributedUpgradeCommand(UpgradeCommand comm
) throws IOException {
assert upgradeManager != null : "DataNode.upgradeManager is null.";
upgradeManager.processUpgradeCommand(comm);
}
/**
* Start distributed upgrade if it should be initiated by the data-node.
*/
private void startDistributedUpgradeIfNeeded() throws IOException {
UpgradeManagerDatanode um = DataNode.getDataNode().upgradeManager;
assert um != null : "DataNode.upgradeManager is null.";
if(!um.getUpgradeState())
return;
um.setUpgradeState(false, um.getUpgradeVersion());
um.startUpgrade();
return;
}
private void transferBlocks( Block blocks[],
DatanodeInfo xferTargets[][]
) throws IOException {
for (int i = 0; i < blocks.length; i++) {
if (!data.isValidBlock(blocks[i])) {
String errStr = "Can't send invalid block " + blocks[i];
LOG.info(errStr);
namenode.errorReport(dnRegistration,
DatanodeProtocol.INVALID_BLOCK,
errStr);
break;
}
int numTargets = xferTargets[i].length;
if (numTargets > 0) {
if (LOG.isInfoEnabled()) {
StringBuilder xfersBuilder = new StringBuilder();
for (int j = 0; j < numTargets; j++) {
DatanodeInfo nodeInfo = xferTargets[i][j];
xfersBuilder.append(nodeInfo.getName());
if (j < (numTargets - 1)) {
xfersBuilder.append(", ");
}
}
String xfersTo = xfersBuilder.toString();
LOG.info(dnRegistration + " Starting thread to transfer block " +
blocks[i] + " to " + xfersTo);
}
new Daemon(new DataTransfer(xferTargets[i], blocks[i], this)).start();
}
}
}
/*
* Informing the name node could take a long long time! Should we wait
* till namenode is informed before responding with success to the
* client? For now we don't.
*/
protected void notifyNamenodeReceivedBlock(Block block, String delHint) {
if(block==null || delHint==null) {
throw new IllegalArgumentException(block==null?"Block is null":"delHint is null");
}
synchronized (receivedBlockList) {
synchronized (delHints) {
receivedBlockList.add(block);
delHints.add(delHint);
receivedBlockList.notifyAll();
}
}
}
/* ********************************************************************
Protocol when a client reads data from Datanode (Cur Ver: 9):
Client's Request :
=================
Processed in DataXceiver:
+----------------------------------------------+
| Common Header | 1 byte OP == OP_READ_BLOCK |
+----------------------------------------------+
Processed in readBlock() :
+-------------------------------------------------------------------------+
| 8 byte Block ID | 8 byte genstamp | 8 byte start offset | 8 byte length |
+-------------------------------------------------------------------------+
| vInt length | <DFSClient id> |
+-----------------------------------+
Client sends optional response only at the end of receiving data.
DataNode Response :
===================
In readBlock() :
If there is an error while initializing BlockSender :
+---------------------------+
| 2 byte OP_STATUS_ERROR | and connection will be closed.
+---------------------------+
Otherwise
+---------------------------+
| 2 byte OP_STATUS_SUCCESS |
+---------------------------+
Actual data, sent by BlockSender.sendBlock() :
ChecksumHeader :
+--------------------------------------------------+
| 1 byte CHECKSUM_TYPE | 4 byte BYTES_PER_CHECKSUM |
+--------------------------------------------------+
Followed by actual data in the form of PACKETS:
+------------------------------------+
| Sequence of data PACKETs .... |
+------------------------------------+
A "PACKET" is defined further below.
The client reads data until it receives a packet with
"LastPacketInBlock" set to true or with a zero length. If there is
no checksum error, it replies to DataNode with OP_STATUS_CHECKSUM_OK:
Client optional response at the end of data transmission :
+------------------------------+
| 2 byte OP_STATUS_CHECKSUM_OK |
+------------------------------+
PACKET : Contains a packet header, checksum and data. Amount of data
======== carried is set by BUFFER_SIZE.
+-----------------------------------------------------+
| 4 byte packet length (excluding packet header) |
+-----------------------------------------------------+
| 8 byte offset in the block | 8 byte sequence number |
+-----------------------------------------------------+
| 1 byte isLastPacketInBlock |
+-----------------------------------------------------+
| 4 byte Length of actual data |
+-----------------------------------------------------+
| x byte checksum data. x is defined below |
+-----------------------------------------------------+
| actual data ...... |
+-----------------------------------------------------+
x = (length of data + BYTE_PER_CHECKSUM - 1)/BYTES_PER_CHECKSUM *
CHECKSUM_SIZE
CHECKSUM_SIZE depends on CHECKSUM_TYPE (usually, 4 for CRC32)
The above packet format is used while writing data to DFS also.
Not all the fields might be used while reading.
************************************************************************ */
/** Header size for a packet */
public static final int PKT_HEADER_LEN = ( 4 + /* Packet payload length */
8 + /* offset in block */
8 + /* seqno */
1 /* isLastPacketInBlock */);
/**
* Used for transferring a block of data. This class
* sends a piece of data to another DataNode.
*/
class DataTransfer implements Runnable {
DatanodeInfo targets[];
Block b;
DataNode datanode;
/**
* Connect to the first item in the target list. Pass along the
* entire target list, the block, and the data.
*/
public DataTransfer(DatanodeInfo targets[], Block b, DataNode datanode) throws IOException {
this.targets = targets;
this.b = b;
this.datanode = datanode;
}
/**
* Do the deed, write the bytes
*/
public void run() {
xmitsInProgress++;
Socket sock = null;
DataOutputStream out = null;
BlockSender blockSender = null;
try {
InetSocketAddress curTarget =
NetUtils.createSocketAddr(targets[0].getName());
sock = newSocket();
NetUtils.connect(sock, curTarget, socketTimeout);
sock.setSoTimeout(targets.length * socketTimeout);
long writeTimeout = socketWriteTimeout +
HdfsConstants.WRITE_TIMEOUT_EXTENSION * (targets.length-1);
OutputStream baseStream = NetUtils.getOutputStream(sock, writeTimeout);
out = new DataOutputStream(new BufferedOutputStream(baseStream,
SMALL_BUFFER_SIZE));
blockSender = new BlockSender(b, 0, -1, false, false, false,
datanode);
DatanodeInfo srcNode = new DatanodeInfo(dnRegistration);
//
// Header info
//
out.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION);
out.writeByte(DataTransferProtocol.OP_WRITE_BLOCK);
out.writeLong(b.getBlockId());
out.writeLong(b.getGenerationStamp());
out.writeInt(0); // no pipelining
out.writeBoolean(false); // not part of recovery
Text.writeString(out, ""); // client
out.writeBoolean(true); // sending src node information
srcNode.write(out); // Write src node DatanodeInfo
// write targets
out.writeInt(targets.length - 1);
for (int i = 1; i < targets.length; i++) {
targets[i].write(out);
}
// send data & checksum
blockSender.sendBlock(out, baseStream, null);
// no response necessary
LOG.info(dnRegistration + ":Transmitted block " + b + " to " + curTarget);
} catch (IOException ie) {
LOG.warn(dnRegistration + ":Failed to transfer " + b + " to " + targets[0].getName()
+ " got " + StringUtils.stringifyException(ie));
} finally {
IOUtils.closeStream(blockSender);
IOUtils.closeStream(out);
IOUtils.closeSocket(sock);
xmitsInProgress--;
}
}
}
/**
* No matter what kind of exception we get, keep retrying to offerService().
* That's the loop that connects to the NameNode and provides basic DataNode
* functionality.
*
* Only stop when "shouldRun" is turned off (which can only happen at shutdown).
*/
public void run() {
LOG.info(dnRegistration + "In DataNode.run, data = " + data);
// start dataXceiveServer
dataXceiverServer.start();
while (shouldRun) {
try {
startDistributedUpgradeIfNeeded();
offerService();
} catch (Exception ex) {
LOG.error("Exception: " + StringUtils.stringifyException(ex));
if (shouldRun) {
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
}
}
}
// wait for dataXceiveServer to terminate
try {
this.dataXceiverServer.join();
} catch (InterruptedException ie) {
}
LOG.info(dnRegistration + ":Finishing DataNode in: "+data);
shutdown();
}
/** Start a single datanode daemon and wait for it to finish.
* If this thread is specifically interrupted, it will stop waiting.
*/
public static void runDatanodeDaemon(DataNode dn) throws IOException {
if (dn != null) {
//register datanode
dn.register();
dn.dataNodeThread = new Thread(dn, dnThreadName);
dn.dataNodeThread.setDaemon(true); // needed for JUnit testing
dn.dataNodeThread.start();
}
}
/** Instantiate a single datanode object. This must be run by invoking
* {@link DataNode#runDatanodeDaemon(DataNode)} subsequently.
*/
public static DataNode instantiateDataNode(String args[],
Configuration conf) throws IOException {
if (conf == null)
conf = new Configuration();
if (!parseArguments(args, conf)) {
printUsage();
return null;
}
if (conf.get("dfs.network.script") != null) {
LOG.error("This configuration for rack identification is not supported" +
" anymore. RackID resolution is handled by the NameNode.");
System.exit(-1);
}
String[] dataDirs = conf.getStrings("dfs.data.dir");
dnThreadName = "DataNode: [" +
StringUtils.arrayToString(dataDirs) + "]";
return makeInstance(dataDirs, conf);
}
/** Instantiate & Start a single datanode daemon and wait for it to finish.
* If this thread is specifically interrupted, it will stop waiting.
*/
public static DataNode createDataNode(String args[],
Configuration conf) throws IOException {
DataNode dn = instantiateDataNode(args, conf);
runDatanodeDaemon(dn);
return dn;
}
void join() {
if (dataNodeThread != null) {
try {
dataNodeThread.join();
} catch (InterruptedException e) {}
}
}
/**
* Make an instance of DataNode after ensuring that at least one of the
* given data directories (and their parent directories, if necessary)
* can be created.
* @param dataDirs List of directories, where the new DataNode instance should
* keep its files.
* @param conf Configuration instance to use.
* @return DataNode instance for given list of data dirs and conf, or null if
* no directory from this directory list can be created.
* @throws IOException
*/
public static DataNode makeInstance(String[] dataDirs, Configuration conf)
throws IOException {
ArrayList<File> dirs = new ArrayList<File>();
for (int i = 0; i < dataDirs.length; i++) {
File data = new File(dataDirs[i]);
try {
DiskChecker.checkDir(data);
dirs.add(data);
} catch(DiskErrorException e) {
LOG.warn("Invalid directory in dfs.data.dir: " + e.getMessage());
}
}
if (dirs.size() > 0)
return new DataNode(conf, dirs);
LOG.error("All directories in dfs.data.dir are invalid.");
return null;
}
@Override
public String toString() {
return "DataNode{" +
"data=" + data +
", localName='" + dnRegistration.getName() + "'" +
", storageID='" + dnRegistration.getStorageID() + "'" +
", xmitsInProgress=" + xmitsInProgress +
"}";
}
private static void printUsage() {
System.err.println("Usage: java DataNode");
System.err.println(" [-rollback]");
}
/**
* Parse and verify command line arguments and set configuration parameters.
*
* @return false if passed argements are incorrect
*/
private static boolean parseArguments(String args[],
Configuration conf) {
int argsLen = (args == null) ? 0 : args.length;
StartupOption startOpt = StartupOption.REGULAR;
for(int i=0; i < argsLen; i++) {
String cmd = args[i];
if ("-r".equalsIgnoreCase(cmd) || "--rack".equalsIgnoreCase(cmd)) {
LOG.error("-r, --rack arguments are not supported anymore. RackID " +
"resolution is handled by the NameNode.");
System.exit(-1);
} else if ("-rollback".equalsIgnoreCase(cmd)) {
startOpt = StartupOption.ROLLBACK;
} else if ("-regular".equalsIgnoreCase(cmd)) {
startOpt = StartupOption.REGULAR;
} else
return false;
}
setStartupOption(conf, startOpt);
return true;
}
private static void setStartupOption(Configuration conf, StartupOption opt) {
conf.set("dfs.datanode.startup", opt.toString());
}
static StartupOption getStartupOption(Configuration conf) {
return StartupOption.valueOf(conf.get("dfs.datanode.startup",
StartupOption.REGULAR.toString()));
}
/**
* This methods arranges for the data node to send the block report at the next heartbeat.
*/
public void scheduleBlockReport(long delay) {
if (delay > 0) { // send BR after random delay
lastBlockReport = System.currentTimeMillis()
- ( blockReportInterval - R.nextInt((int)(delay)));
} else { // send at next heartbeat
lastBlockReport = lastHeartbeat - blockReportInterval;
}
resetBlockReportTime = true; // reset future BRs for randomness
}
/**
* This method is used for testing.
* Examples are adding and deleting blocks directly.
* The most common usage will be when the data node's storage is similated.
*
* @return the fsdataset that stores the blocks
*/
public FSDatasetInterface getFSDataset() {
return data;
}
/**
*/
public static void main(String args[]) {
try {
StringUtils.startupShutdownMessage(DataNode.class, args, LOG);
DataNode datanode = createDataNode(args, null);
if (datanode != null)
datanode.join();
} catch (Throwable e) {
LOG.error(StringUtils.stringifyException(e));
System.exit(-1);
}
}
// InterDataNodeProtocol implementation
/** {@inheritDoc} */
public BlockMetaDataInfo getBlockMetaDataInfo(Block block
) throws IOException {
if (LOG.isDebugEnabled()) {
LOG.debug("block=" + block);
}
Block stored = data.getStoredBlock(block.getBlockId());
if (stored == null) {
return null;
}
BlockMetaDataInfo info = new BlockMetaDataInfo(stored,
blockScanner.getLastScanTime(stored));
if (LOG.isDebugEnabled()) {
LOG.debug("getBlockMetaDataInfo successful block=" + stored +
" length " + stored.getNumBytes() +
" genstamp " + stored.getGenerationStamp());
}
// paranoia! verify that the contents of the stored block
// matches the block file on disk.
data.validateBlockMetadata(stored);
return info;
}
public Daemon recoverBlocks(final Block[] blocks, final DatanodeInfo[][] targets) {
Daemon d = new Daemon(threadGroup, new Runnable() {
/** Recover a list of blocks. It is run by the primary datanode. */
public void run() {
for(int i = 0; i < blocks.length; i++) {
try {
logRecoverBlock("NameNode", blocks[i], targets[i]);
recoverBlock(blocks[i], false, targets[i], true);
} catch (IOException e) {
LOG.warn("recoverBlocks FAILED, blocks[" + i + "]=" + blocks[i], e);
}
}
}
});
d.start();
return d;
}
/** {@inheritDoc} */
public void updateBlock(Block oldblock, Block newblock, boolean finalize) throws IOException {
LOG.info("oldblock=" + oldblock + "(length=" + oldblock.getNumBytes()
+ "), newblock=" + newblock + "(length=" + newblock.getNumBytes()
+ "), datanode=" + dnRegistration.getName());
data.updateBlock(oldblock, newblock);
if (finalize) {
data.finalizeBlock(newblock);
myMetrics.blocksWritten.inc();
notifyNamenodeReceivedBlock(newblock, EMPTY_DEL_HINT);
LOG.info("Received block " + newblock +
" of size " + newblock.getNumBytes() +
" as part of lease recovery.");
}
}
/** {@inheritDoc} */
public long getProtocolVersion(String protocol, long clientVersion
) throws IOException {
if (protocol.equals(InterDatanodeProtocol.class.getName())) {
return InterDatanodeProtocol.versionID;
} else if (protocol.equals(ClientDatanodeProtocol.class.getName())) {
return ClientDatanodeProtocol.versionID;
}
throw new IOException("Unknown protocol to " + getClass().getSimpleName()
+ ": " + protocol);
}
/** A convenient class used in lease recovery */
private static class BlockRecord {
final DatanodeID id;
final InterDatanodeProtocol datanode;
final Block block;
BlockRecord(DatanodeID id, InterDatanodeProtocol datanode, Block block) {
this.id = id;
this.datanode = datanode;
this.block = block;
}
/** {@inheritDoc} */
public String toString() {
return "block:" + block + " node:" + id;
}
}
/** Recover a block */
private LocatedBlock recoverBlock(Block block, boolean keepLength,
DatanodeID[] datanodeids, boolean closeFile) throws IOException {
// If the block is already being recovered, then skip recovering it.
// This can happen if the namenode and client start recovering the same
// file at the same time.
synchronized (ongoingRecovery) {
Block tmp = new Block();
tmp.set(block.getBlockId(), block.getNumBytes(), GenerationStamp.WILDCARD_STAMP);
if (ongoingRecovery.get(tmp) != null) {
String msg = "Block " + block + " is already being recovered, " +
" ignoring this request to recover it.";
LOG.info(msg);
throw new IOException(msg);
}
ongoingRecovery.put(block, block);
}
try {
List<BlockRecord> syncList = new ArrayList<BlockRecord>();
long minlength = Long.MAX_VALUE;
int errorCount = 0;
//check generation stamps
for(DatanodeID id : datanodeids) {
try {
InterDatanodeProtocol datanode = dnRegistration.equals(id)?
this: DataNode.createInterDataNodeProtocolProxy(id, getConf());
BlockMetaDataInfo info = datanode.getBlockMetaDataInfo(block);
if (info != null && info.getGenerationStamp() >= block.getGenerationStamp()) {
if (keepLength) {
if (info.getNumBytes() == block.getNumBytes()) {
syncList.add(new BlockRecord(id, datanode, new Block(info)));
}
}
else {
syncList.add(new BlockRecord(id, datanode, new Block(info)));
if (info.getNumBytes() < minlength) {
minlength = info.getNumBytes();
}
}
}
} catch (IOException e) {
++errorCount;
InterDatanodeProtocol.LOG.warn(
"Failed to getBlockMetaDataInfo for block (=" + block
+ ") from datanode (=" + id + ")", e);
}
}
if (syncList.isEmpty() && errorCount > 0) {
throw new IOException("All datanodes failed: block=" + block
+ ", datanodeids=" + Arrays.asList(datanodeids));
}
if (!keepLength) {
block.setNumBytes(minlength);
}
return syncBlock(block, syncList, closeFile);
} finally {
synchronized (ongoingRecovery) {
ongoingRecovery.remove(block);
}
}
}
/** Block synchronization */
private LocatedBlock syncBlock(Block block, List<BlockRecord> syncList,
boolean closeFile) throws IOException {
if (LOG.isDebugEnabled()) {
LOG.debug("block=" + block + ", (length=" + block.getNumBytes()
+ "), syncList=" + syncList + ", closeFile=" + closeFile);
}
//syncList.isEmpty() that all datanodes do not have the block
//so the block can be deleted.
if (syncList.isEmpty()) {
namenode.commitBlockSynchronization(block, 0, 0, closeFile, true,
DatanodeID.EMPTY_ARRAY);
return null;
}
List<DatanodeID> successList = new ArrayList<DatanodeID>();
long generationstamp = namenode.nextGenerationStamp(block);
Block newblock = new Block(block.getBlockId(), block.getNumBytes(), generationstamp);
for(BlockRecord r : syncList) {
try {
r.datanode.updateBlock(r.block, newblock, closeFile);
successList.add(r.id);
} catch (IOException e) {
InterDatanodeProtocol.LOG.warn("Failed to updateBlock (newblock="
+ newblock + ", datanode=" + r.id + ")", e);
}
}
if (!successList.isEmpty()) {
DatanodeID[] nlist = successList.toArray(new DatanodeID[successList.size()]);
namenode.commitBlockSynchronization(block,
newblock.getGenerationStamp(), newblock.getNumBytes(), closeFile, false,
nlist);
DatanodeInfo[] info = new DatanodeInfo[nlist.length];
for (int i = 0; i < nlist.length; i++) {
info[i] = new DatanodeInfo(nlist[i]);
}
return new LocatedBlock(newblock, info); // success
}
//failed
StringBuilder b = new StringBuilder();
for(BlockRecord r : syncList) {
b.append("\n " + r.id);
}
throw new IOException("Cannot recover " + block + ", none of these "
+ syncList.size() + " datanodes success {" + b + "\n}");
}
// ClientDataNodeProtocol implementation
/** {@inheritDoc} */
public LocatedBlock recoverBlock(Block block, boolean keepLength, DatanodeInfo[] targets
) throws IOException {
logRecoverBlock("Client", block, targets);
return recoverBlock(block, keepLength, targets, false);
}
private static void logRecoverBlock(String who,
Block block, DatanodeID[] targets) {
StringBuilder msg = new StringBuilder(targets[0].getName());
for (int i = 1; i < targets.length; i++) {
msg.append(", " + targets[i].getName());
}
LOG.info(who + " calls recoverBlock(block=" + block
+ ", targets=[" + msg + "])");
}
}
| true | true |
void startDataNode(Configuration conf,
AbstractList<File> dataDirs
) throws IOException {
// use configured nameserver & interface to get local hostname
if (conf.get("slave.host.name") != null) {
machineName = conf.get("slave.host.name");
}
if (machineName == null) {
machineName = DNS.getDefaultHost(
conf.get("dfs.datanode.dns.interface","default"),
conf.get("dfs.datanode.dns.nameserver","default"));
}
InetSocketAddress nameNodeAddr = NameNode.getAddress(conf);
this.socketTimeout = conf.getInt("dfs.socket.timeout",
HdfsConstants.READ_TIMEOUT);
this.socketWriteTimeout = conf.getInt("dfs.datanode.socket.write.timeout",
HdfsConstants.WRITE_TIMEOUT);
/* Based on results on different platforms, we might need set the default
* to false on some of them. */
this.transferToAllowed = conf.getBoolean("dfs.datanode.transferTo.allowed",
true);
this.writePacketSize = conf.getInt("dfs.write.packet.size", 64*1024);
String address =
NetUtils.getServerAddress(conf,
"dfs.datanode.bindAddress",
"dfs.datanode.port",
"dfs.datanode.address");
InetSocketAddress socAddr = NetUtils.createSocketAddr(address);
int tmpPort = socAddr.getPort();
storage = new DataStorage();
// construct registration
this.dnRegistration = new DatanodeRegistration(machineName + ":" + tmpPort);
// connect to name node
this.namenode = (DatanodeProtocol)
RPC.waitForProxy(DatanodeProtocol.class,
DatanodeProtocol.versionID,
nameNodeAddr,
conf);
// get version and id info from the name-node
NamespaceInfo nsInfo = handshake();
StartupOption startOpt = getStartupOption(conf);
assert startOpt != null : "Startup option must be set.";
boolean simulatedFSDataset =
conf.getBoolean("dfs.datanode.simulateddatastorage", false);
if (simulatedFSDataset) {
setNewStorageID(dnRegistration);
dnRegistration.storageInfo.layoutVersion = FSConstants.LAYOUT_VERSION;
dnRegistration.storageInfo.namespaceID = nsInfo.namespaceID;
// it would have been better to pass storage as a parameter to
// constructor below - need to augment ReflectionUtils used below.
conf.set("StorageId", dnRegistration.getStorageID());
try {
//Equivalent of following (can't do because Simulated is in test dir)
// this.data = new SimulatedFSDataset(conf);
this.data = (FSDatasetInterface) ReflectionUtils.newInstance(
Class.forName("org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset"), conf);
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.stringifyException(e));
}
} else { // real storage
// read storage info, lock data dirs and transition fs state if necessary
storage.recoverTransitionRead(nsInfo, dataDirs, startOpt);
// adjust
this.dnRegistration.setStorageInfo(storage);
// initialize data node internal structure
this.data = new FSDataset(storage, conf);
}
// find free port
ServerSocket ss = (socketWriteTimeout > 0) ?
ServerSocketChannel.open().socket() : new ServerSocket();
Server.bind(ss, socAddr, 0);
ss.setReceiveBufferSize(DEFAULT_DATA_SOCKET_SIZE);
// adjust machine name with the actual port
tmpPort = ss.getLocalPort();
selfAddr = new InetSocketAddress(ss.getInetAddress().getHostAddress(),
tmpPort);
this.dnRegistration.setName(machineName + ":" + tmpPort);
LOG.info("Opened info server at " + tmpPort);
this.threadGroup = new ThreadGroup("dataXceiverServer");
this.dataXceiverServer = new Daemon(threadGroup,
new DataXceiverServer(ss, conf, this));
this.threadGroup.setDaemon(true); // auto destroy when empty
this.blockReportInterval =
conf.getLong("dfs.blockreport.intervalMsec", BLOCKREPORT_INTERVAL);
this.initialBlockReportDelay = conf.getLong("dfs.blockreport.initialDelay",
BLOCKREPORT_INITIAL_DELAY)* 1000L;
if (this.initialBlockReportDelay >= blockReportInterval) {
this.initialBlockReportDelay = 0;
LOG.info("dfs.blockreport.initialDelay is greater than " +
"dfs.blockreport.intervalMsec." + " Setting initial delay to 0 msec:");
}
this.heartBeatInterval = conf.getLong("dfs.heartbeat.interval", HEARTBEAT_INTERVAL) * 1000L;
DataNode.nameNodeAddr = nameNodeAddr;
//initialize periodic block scanner
String reason = null;
if (conf.getInt("dfs.datanode.scan.period.hours", 0) < 0) {
reason = "verification is turned off by configuration";
} else if ( !(data instanceof FSDataset) ) {
reason = "verifcation is supported only with FSDataset";
}
if ( reason == null ) {
blockScanner = new DataBlockScanner(this, (FSDataset)data, conf);
} else {
LOG.info("Periodic Block Verification is disabled because " +
reason + ".");
}
//create a servlet to serve full-file content
String infoAddr =
NetUtils.getServerAddress(conf,
"dfs.datanode.info.bindAddress",
"dfs.datanode.info.port",
"dfs.datanode.http.address");
InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
String infoHost = infoSocAddr.getHostName();
int tmpInfoPort = infoSocAddr.getPort();
this.infoServer = new HttpServer("datanode", infoHost, tmpInfoPort,
tmpInfoPort == 0, conf);
InetSocketAddress secInfoSocAddr = NetUtils.createSocketAddr(
conf.get("dfs.datanode.https.address", infoHost + ":" + 0));
Configuration sslConf = new Configuration(conf);
sslConf.addResource(conf.get("https.keystore.info.rsrc", "sslinfo.xml"));
String keyloc = sslConf.get("https.keystore.location");
if (null != keyloc) {
this.infoServer.addSslListener(secInfoSocAddr, keyloc,
sslConf.get("https.keystore.password", ""),
sslConf.get("https.keystore.keypassword", ""));
}
this.infoServer.addInternalServlet(null, "/streamFile/*", StreamFile.class);
this.infoServer.addInternalServlet(null, "/getFileChecksum/*",
FileChecksumServlets.GetServlet.class);
this.infoServer.setAttribute("datanode.blockScanner", blockScanner);
this.infoServer.addServlet(null, "/blockScannerReport",
DataBlockScanner.Servlet.class);
this.infoServer.start();
// adjust info port
this.dnRegistration.setInfoPort(this.infoServer.getPort());
myMetrics = new DataNodeMetrics(conf, dnRegistration.getName());
//init ipc server
InetSocketAddress ipcAddr = NetUtils.createSocketAddr(
conf.get("dfs.datanode.ipc.address"));
ipcServer = RPC.getServer(this, ipcAddr.getHostName(), ipcAddr.getPort(),
conf.getInt("dfs.datanode.handler.count", 3), false, conf);
ipcServer.start();
dnRegistration.setIpcPort(ipcServer.getListenerAddress().getPort());
LOG.info("dnRegistration = " + dnRegistration);
}
|
void startDataNode(Configuration conf,
AbstractList<File> dataDirs
) throws IOException {
// use configured nameserver & interface to get local hostname
if (conf.get("slave.host.name") != null) {
machineName = conf.get("slave.host.name");
}
if (machineName == null) {
machineName = DNS.getDefaultHost(
conf.get("dfs.datanode.dns.interface","default"),
conf.get("dfs.datanode.dns.nameserver","default"));
}
InetSocketAddress nameNodeAddr = NameNode.getAddress(conf);
this.socketTimeout = conf.getInt("dfs.socket.timeout",
HdfsConstants.READ_TIMEOUT);
this.socketWriteTimeout = conf.getInt("dfs.datanode.socket.write.timeout",
HdfsConstants.WRITE_TIMEOUT);
/* Based on results on different platforms, we might need set the default
* to false on some of them. */
this.transferToAllowed = conf.getBoolean("dfs.datanode.transferTo.allowed",
true);
this.writePacketSize = conf.getInt("dfs.write.packet.size", 64*1024);
String address =
NetUtils.getServerAddress(conf,
"dfs.datanode.bindAddress",
"dfs.datanode.port",
"dfs.datanode.address");
InetSocketAddress socAddr = NetUtils.createSocketAddr(address);
int tmpPort = socAddr.getPort();
storage = new DataStorage();
// construct registration
this.dnRegistration = new DatanodeRegistration(machineName + ":" + tmpPort);
// connect to name node
this.namenode = (DatanodeProtocol)
RPC.waitForProxy(DatanodeProtocol.class,
DatanodeProtocol.versionID,
nameNodeAddr,
conf);
// get version and id info from the name-node
NamespaceInfo nsInfo = handshake();
StartupOption startOpt = getStartupOption(conf);
assert startOpt != null : "Startup option must be set.";
boolean simulatedFSDataset =
conf.getBoolean("dfs.datanode.simulateddatastorage", false);
if (simulatedFSDataset) {
setNewStorageID(dnRegistration);
dnRegistration.storageInfo.layoutVersion = FSConstants.LAYOUT_VERSION;
dnRegistration.storageInfo.namespaceID = nsInfo.namespaceID;
// it would have been better to pass storage as a parameter to
// constructor below - need to augment ReflectionUtils used below.
conf.set("StorageId", dnRegistration.getStorageID());
try {
//Equivalent of following (can't do because Simulated is in test dir)
// this.data = new SimulatedFSDataset(conf);
this.data = (FSDatasetInterface) ReflectionUtils.newInstance(
Class.forName("org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset"), conf);
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.stringifyException(e));
}
} else { // real storage
// read storage info, lock data dirs and transition fs state if necessary
storage.recoverTransitionRead(nsInfo, dataDirs, startOpt);
// adjust
this.dnRegistration.setStorageInfo(storage);
// initialize data node internal structure
this.data = new FSDataset(storage, conf);
}
// find free port
ServerSocket ss = (socketWriteTimeout > 0) ?
ServerSocketChannel.open().socket() : new ServerSocket();
Server.bind(ss, socAddr, 0);
ss.setReceiveBufferSize(DEFAULT_DATA_SOCKET_SIZE);
// adjust machine name with the actual port
tmpPort = ss.getLocalPort();
selfAddr = new InetSocketAddress(ss.getInetAddress().getHostAddress(),
tmpPort);
this.dnRegistration.setName(machineName + ":" + tmpPort);
LOG.info("Opened info server at " + tmpPort);
this.threadGroup = new ThreadGroup("dataXceiverServer");
this.dataXceiverServer = new Daemon(threadGroup,
new DataXceiverServer(ss, conf, this));
this.threadGroup.setDaemon(true); // auto destroy when empty
this.blockReportInterval =
conf.getLong("dfs.blockreport.intervalMsec", BLOCKREPORT_INTERVAL);
this.initialBlockReportDelay = conf.getLong("dfs.blockreport.initialDelay",
BLOCKREPORT_INITIAL_DELAY)* 1000L;
if (this.initialBlockReportDelay >= blockReportInterval) {
this.initialBlockReportDelay = 0;
LOG.info("dfs.blockreport.initialDelay is greater than " +
"dfs.blockreport.intervalMsec." + " Setting initial delay to 0 msec:");
}
this.heartBeatInterval = conf.getLong("dfs.heartbeat.interval", HEARTBEAT_INTERVAL) * 1000L;
DataNode.nameNodeAddr = nameNodeAddr;
//initialize periodic block scanner
String reason = null;
if (conf.getInt("dfs.datanode.scan.period.hours", 0) < 0) {
reason = "verification is turned off by configuration";
} else if ( !(data instanceof FSDataset) ) {
reason = "verifcation is supported only with FSDataset";
}
if ( reason == null ) {
blockScanner = new DataBlockScanner(this, (FSDataset)data, conf);
} else {
LOG.info("Periodic Block Verification is disabled because " +
reason + ".");
}
//create a servlet to serve full-file content
String infoAddr =
NetUtils.getServerAddress(conf,
"dfs.datanode.info.bindAddress",
"dfs.datanode.info.port",
"dfs.datanode.http.address");
InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
String infoHost = infoSocAddr.getHostName();
int tmpInfoPort = infoSocAddr.getPort();
this.infoServer = new HttpServer("datanode", infoHost, tmpInfoPort,
tmpInfoPort == 0, conf);
InetSocketAddress secInfoSocAddr = NetUtils.createSocketAddr(
conf.get("dfs.datanode.https.address", infoHost + ":" + 0));
Configuration sslConf = new Configuration(conf);
sslConf.addResource(conf.get("https.keystore.info.rsrc", "sslinfo.xml"));
String keyloc = sslConf.get("https.keystore.location");
if (null != keyloc) {
this.infoServer.addSslListener(secInfoSocAddr, keyloc,
sslConf.get("https.keystore.password", ""),
sslConf.get("https.keystore.keypassword", ""));
}
this.infoServer.addInternalServlet(null, "/streamFile/*", StreamFile.class);
this.infoServer.addInternalServlet(null, "/getFileChecksum/*",
FileChecksumServlets.GetServlet.class);
this.infoServer.setAttribute("datanode.blockScanner", blockScanner);
this.infoServer.addServlet(null, "/blockScannerReport",
DataBlockScanner.Servlet.class);
this.infoServer.start();
// adjust info port
this.dnRegistration.setInfoPort(this.infoServer.getPort());
myMetrics = new DataNodeMetrics(conf, dnRegistration.getStorageID());
//init ipc server
InetSocketAddress ipcAddr = NetUtils.createSocketAddr(
conf.get("dfs.datanode.ipc.address"));
ipcServer = RPC.getServer(this, ipcAddr.getHostName(), ipcAddr.getPort(),
conf.getInt("dfs.datanode.handler.count", 3), false, conf);
ipcServer.start();
dnRegistration.setIpcPort(ipcServer.getListenerAddress().getPort());
LOG.info("dnRegistration = " + dnRegistration);
}
|
diff --git a/src/common/basiccomponents/BCLoader.java b/src/common/basiccomponents/BCLoader.java
index 3c7f0f9..85edbc9 100644
--- a/src/common/basiccomponents/BCLoader.java
+++ b/src/common/basiccomponents/BCLoader.java
@@ -1,290 +1,290 @@
package basiccomponents;
import net.minecraft.src.Block;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.FurnaceRecipes;
import net.minecraft.src.IInventory;
import net.minecraft.src.Item;
import net.minecraft.src.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.liquids.LiquidContainerData;
import net.minecraftforge.liquids.LiquidContainerRegistry;
import net.minecraftforge.liquids.LiquidStack;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import universalelectricity.core.UEConfig;
import universalelectricity.core.UniversalElectricity;
import universalelectricity.prefab.RecipeHelper;
import universalelectricity.prefab.UETab;
import universalelectricity.prefab.network.ConnectionHandler;
import universalelectricity.prefab.network.PacketManager;
import universalelectricity.prefab.ore.OreGenReplaceStone;
import universalelectricity.prefab.ore.OreGenerator;
import basiccomponents.block.BlockBCOre;
import basiccomponents.block.BlockBasicMachine;
import basiccomponents.block.BlockCopperWire;
import basiccomponents.block.BlockOilFlowing;
import basiccomponents.block.BlockOilStill;
import basiccomponents.item.ItemBasic;
import basiccomponents.item.ItemBasicMachine;
import basiccomponents.item.ItemBattery;
import basiccomponents.item.ItemBlockCopperWire;
import basiccomponents.item.ItemBlockOre;
import basiccomponents.item.ItemCircuit;
import basiccomponents.item.ItemOilBucket;
import basiccomponents.item.ItemWrench;
import basiccomponents.tile.TileEntityBatteryBox;
import basiccomponents.tile.TileEntityCoalGenerator;
import basiccomponents.tile.TileEntityElectricFurnace;
import cpw.mods.fml.common.ICraftingHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
@Mod(modid = "BasicComponents", name = "Basic Components", version = UniversalElectricity.VERSION)
@NetworkMod(channels = BCLoader.CHANNEL, clientSideRequired = true, serverSideRequired = false, connectionHandler = ConnectionHandler.class, packetHandler = PacketManager.class)
public class BCLoader implements ICraftingHandler
{
public static final String CHANNEL = "BasicComponents";
public static final String FILE_PATH = "/basiccomponents/textures/";
public static final String BLOCK_TEXTURE_FILE = FILE_PATH + "blocks.png";
public static final String ITEM_TEXTURE_FILE = FILE_PATH + "items.png";
@Instance("BasicComponents")
public static BCLoader instance;
@SidedProxy(clientSide = "basiccomponents.BCClientProxy", serverSide = "basiccomponents.BCCommonProxy")
public static BCCommonProxy proxy;
@PreInit
public void preInit(FMLPreInitializationEvent event)
{
UniversalElectricity.register(this, UniversalElectricity.MAJOR_VERSION, UniversalElectricity.MINOR_VERSION, UniversalElectricity.REVISION_VERSION, false);
NetworkRegistry.instance().registerGuiHandler(this, this.proxy);
/**
* Define the items and blocks.
*/
BasicComponents.blockBasicOre = new BlockBCOre(UEConfig.getBlockConfigID(UniversalElectricity.CONFIGURATION, "Copper and Tin Ores", BasicComponents.BLOCK_ID_PREFIX));
BasicComponents.blockCopperWire = new BlockCopperWire(UEConfig.getBlockConfigID(UniversalElectricity.CONFIGURATION, "Copper_Wire", BasicComponents.BLOCK_ID_PREFIX + 1));
BasicComponents.oilMoving = new BlockOilFlowing(UEConfig.getBlockConfigID(UniversalElectricity.CONFIGURATION, "Oil_Flowing", BasicComponents.BLOCK_ID_PREFIX + 2));
BasicComponents.oilStill = new BlockOilStill(UEConfig.getBlockConfigID(UniversalElectricity.CONFIGURATION, "Oil_Still", BasicComponents.BLOCK_ID_PREFIX + 3));
BasicComponents.blockMachine = new BlockBasicMachine(UEConfig.getBlockConfigID(UniversalElectricity.CONFIGURATION, "Basic Machine", BasicComponents.BLOCK_ID_PREFIX + 4), 0);
BasicComponents.itemBattery = new ItemBattery(UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Battery", BasicComponents.ITEM_ID_PREFIX + 1), 0);
BasicComponents.itemWrench = new ItemWrench(UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Universal Wrench", BasicComponents.ITEM_ID_PREFIX + 2), 20);
BasicComponents.itemCircuit = new ItemCircuit(UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Circuit", BasicComponents.ITEM_ID_PREFIX + 7), 16);
BasicComponents.itemTinIngot = new ItemBasic("Tin Ingot", UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Tin Ingot", BasicComponents.ITEM_ID_PREFIX + 4), 2);
BasicComponents.itemCopperIngot = new ItemBasic("Copper Ingot", UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Copper Ingot", BasicComponents.ITEM_ID_PREFIX + 3), 1);
BasicComponents.itemSteelIngot = new ItemBasic("Steel Ingot", UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Steel Ingot", BasicComponents.ITEM_ID_PREFIX + 5), 3);
BasicComponents.itemBronzeIngot = new ItemBasic("Bronze Ingot", UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Bronze Ingot", BasicComponents.ITEM_ID_PREFIX + 8), 7);
BasicComponents.itemBronzeDust = new ItemBasic("Bronze Dust", UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Bronze Dust", BasicComponents.ITEM_ID_PREFIX + 9), 6);
BasicComponents.itemSteelDust = new ItemBasic("Steel Dust", UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Steel Dust", BasicComponents.ITEM_ID_PREFIX + 6), 5);
BasicComponents.itemMotor = new ItemBasic("Motor", UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Motor", BasicComponents.ITEM_ID_PREFIX + 12), 12);
BasicComponents.itemOilBucket = new ItemOilBucket("Oil Bucket", UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Oil Bucket", BasicComponents.ITEM_ID_PREFIX + 13), 4);
BasicComponents.itemCopperPlate = new ItemBasic("Copper Plate", UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Copper Plate", BasicComponents.ITEM_ID_PREFIX + 14), 10);
BasicComponents.itemSteelPlate = new ItemBasic("Steel Plate", UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Steel Plate", BasicComponents.ITEM_ID_PREFIX + 10), 9);
BasicComponents.itemBronzePlate = new ItemBasic("Bronze Plate", UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Bronze Plate", BasicComponents.ITEM_ID_PREFIX + 11), 8);
BasicComponents.itemTinPlate = new ItemBasic("Tin Plate", UEConfig.getItemConfigID(UniversalElectricity.CONFIGURATION, "Tin Plate", BasicComponents.ITEM_ID_PREFIX + 15), 11);
BasicComponents.coalGenerator = ((BlockBasicMachine) BasicComponents.blockMachine).getCoalGenerator();
BasicComponents.batteryBox = ((BlockBasicMachine) BasicComponents.blockMachine).getBatteryBox();
BasicComponents.electricFurnace = ((BlockBasicMachine) BasicComponents.blockMachine).getElectricFurnace();
BasicComponents.copperOreGeneration = new OreGenReplaceStone("Copper Ore", "oreCopper", new ItemStack(BasicComponents.blockBasicOre, 1, 0), 0, 50, 33, 4).enable();
BasicComponents.tinOreGeneration = new OreGenReplaceStone("Tin Ore", "oreTin", new ItemStack(BasicComponents.blockBasicOre, 1, 1), 0, 50, 28, 3).enable();
/**
* @author Cammygames
*/
LiquidContainerRegistry.registerLiquid(new LiquidContainerData(new LiquidStack(BasicComponents.oilStill, LiquidContainerRegistry.BUCKET_VOLUME), new ItemStack(BasicComponents.itemOilBucket), new ItemStack(Item.bucketEmpty)));
MinecraftForge.EVENT_BUS.register(BasicComponents.itemOilBucket);
// Register Blocks
GameRegistry.registerBlock(BasicComponents.blockBasicOre, ItemBlockOre.class);
GameRegistry.registerBlock(BasicComponents.blockMachine, ItemBasicMachine.class);
GameRegistry.registerBlock(BasicComponents.blockCopperWire, ItemBlockCopperWire.class);
GameRegistry.registerBlock(BasicComponents.oilMoving);
GameRegistry.registerBlock(BasicComponents.oilStill);
GameRegistry.registerCraftingHandler(this);
/**
* Registering all Basic Component items into the Forge Ore Dictionary.
*/
OreDictionary.registerOre("oreCopper", new ItemStack(BasicComponents.blockBasicOre, 0));
OreDictionary.registerOre("oreTin", new ItemStack(BasicComponents.blockBasicOre, 0));
OreDictionary.registerOre("copperWire", BasicComponents.blockCopperWire);
OreDictionary.registerOre("coalGenerator", BasicComponents.coalGenerator);
OreDictionary.registerOre("batteryBox", BasicComponents.batteryBox);
OreDictionary.registerOre("electricFurnace", BasicComponents.electricFurnace);
OreDictionary.registerOre("battery", BasicComponents.itemBattery);
OreDictionary.registerOre("wrench", BasicComponents.itemWrench);
OreDictionary.registerOre("motor", BasicComponents.itemMotor);
OreDictionary.registerOre("basicCircuit", new ItemStack(BasicComponents.itemCircuit, 1, 0));
OreDictionary.registerOre("advancedCircuit", new ItemStack(BasicComponents.itemCircuit, 1, 1));
OreDictionary.registerOre("eliteCircuit", new ItemStack(BasicComponents.itemCircuit, 1, 2));
OreDictionary.registerOre("oilMoving", BasicComponents.oilMoving);
OreDictionary.registerOre("oilStill", BasicComponents.oilStill);
OreDictionary.registerOre("oilBucket", BasicComponents.itemOilBucket);
OreDictionary.registerOre("ingotCopper", BasicComponents.itemCopperIngot);
OreDictionary.registerOre("ingotTin", BasicComponents.itemTinIngot);
OreDictionary.registerOre("ingotBronze", BasicComponents.itemBronzeIngot);
OreDictionary.registerOre("ingotSteel", BasicComponents.itemSteelIngot);
OreDictionary.registerOre("dustBronze", BasicComponents.itemBronzeDust);
OreDictionary.registerOre("dustSteel", BasicComponents.itemSteelDust);
OreDictionary.registerOre("plateCopper", BasicComponents.itemCopperPlate);
OreDictionary.registerOre("plateTin", BasicComponents.itemTinPlate);
OreDictionary.registerOre("plateBronze", BasicComponents.itemBronzePlate);
OreDictionary.registerOre("plateSteel", BasicComponents.itemSteelPlate);
UETab.setItemStack(BasicComponents.batteryBox);
proxy.preInit();
}
@Init
public void load(FMLInitializationEvent evt)
{
proxy.init();
/**
* Adding names
*/
LanguageRegistry.addName(new ItemStack(BasicComponents.blockBasicOre, 1, 0), "Copper Ore");
LanguageRegistry.addName(new ItemStack(BasicComponents.blockBasicOre, 1, 1), "Tin Ore");
LanguageRegistry.addName(BasicComponents.oilMoving, "Oil Moving");
LanguageRegistry.addName(BasicComponents.oilStill, "Oil Still");
LanguageRegistry.addName(BasicComponents.itemBattery, "Basic Battery");
LanguageRegistry.addName(new ItemStack(BasicComponents.blockCopperWire, 1, 0), "Copper Wire");
LanguageRegistry.addName(new ItemStack(BasicComponents.itemCircuit, 1, 0), "Basic Circuit");
LanguageRegistry.addName(new ItemStack(BasicComponents.itemCircuit, 1, 1), "Advanced Circuit");
LanguageRegistry.addName(new ItemStack(BasicComponents.itemCircuit, 1, 2), "Elite Circuit");
LanguageRegistry.addName(BasicComponents.itemOilBucket, "Oil Bucket");
LanguageRegistry.addName(BasicComponents.itemWrench, "Universal Wrench");
LanguageRegistry.addName(BasicComponents.coalGenerator, "Coal Generator");
LanguageRegistry.addName(BasicComponents.batteryBox, "Battery Box");
LanguageRegistry.addName(BasicComponents.electricFurnace, "Electric Furnace");
/**
* Registering Tile Entities
*/
GameRegistry.registerTileEntity(TileEntityBatteryBox.class, "UEBatteryBox");
GameRegistry.registerTileEntity(TileEntityCoalGenerator.class, "UECoalGenerator");
GameRegistry.registerTileEntity(TileEntityElectricFurnace.class, "UEElectricFurnace");
OreGenerator.addOre(BasicComponents.copperOreGeneration);
OreGenerator.addOre(BasicComponents.tinOreGeneration);
// Recipes
// Oil Bucket
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemOilBucket), new Object[]
{ "CCC", "CBC", "CCC", 'B', Item.bucketWater, 'C', Item.coal }));
// Motor
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemMotor), new Object[]
{ "@!@", "!#!", "@!@", '!', "ingotSteel", '#', Item.ingotIron, '@', BasicComponents.blockCopperWire }));
// Wrench
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemWrench), new Object[]
{ " S ", " DS", "S ", 'S', "ingotSteel", 'D', Item.diamond }));
// Battery Box
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.batteryBox, new Object[]
{ "?!?", "###", "?!?", '#', BasicComponents.blockCopperWire, '!', BasicComponents.itemSteelPlate, '?', BasicComponents.itemBattery.getUncharged() }));
GameRegistry.addSmelting(BasicComponents.batteryBox.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Coal Generator
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.coalGenerator, new Object[]
{ "SCS", "FMF", "BBB", 'B', "ingotBronze", 'S', BasicComponents.itemSteelPlate, 'C', BasicComponents.blockCopperWire, 'M', BasicComponents.itemMotor, 'F', Block.stoneOvenIdle }));
GameRegistry.addSmelting(BasicComponents.coalGenerator.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Electric Furnace
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.electricFurnace, new Object[]
{ "SSS", "SCS", "SMS", 'S', "ingotSteel", 'C', BasicComponents.itemCircuit, 'M', BasicComponents.itemMotor }));
GameRegistry.addSmelting(BasicComponents.electricFurnace.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Copper
- FurnaceRecipes.smelting().addSmelting(BasicComponents.blockBasicOre.blockID, 0, new ItemStack(BasicComponents.itemCopperIngot));
+ FurnaceRecipes.smelting().addSmelting(BasicComponents.blockBasicOre.blockID, 0, new ItemStack(BasicComponents.itemCopperIngot), 0.7f);
// Copper Wire
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.blockCopperWire, 6), new Object[]
{ "!!!", "@@@", "!!!", '!', Item.leather, '@', "ingotCopper" }));
// Tin
- FurnaceRecipes.smelting().addSmelting(BasicComponents.blockBasicOre.blockID, 1, new ItemStack(BasicComponents.itemTinIngot));
+ FurnaceRecipes.smelting().addSmelting(BasicComponents.blockBasicOre.blockID, 1, new ItemStack(BasicComponents.itemTinIngot), 0.7f);
// Battery
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBattery), new Object[]
{ " T ", "TRT", "TCT", 'T', "ingotTin", 'R', Item.redstone, 'C', Item.coal }));
// Steel
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelDust), new Object[]
{ " C ", "CIC", " C ", 'C', new ItemStack(Item.coal, 1, 1), 'I', Item.ingotIron }), "Steel Dust", UniversalElectricity.CONFIGURATION, true);
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelDust), new Object[]
{ " C ", "CIC", " C ", 'C', new ItemStack(Item.coal, 1, 0), 'I', Item.ingotIron }), "Steel Dust", UniversalElectricity.CONFIGURATION, true);
GameRegistry.addSmelting(BasicComponents.itemSteelDust.shiftedIndex, new ItemStack(BasicComponents.itemSteelIngot), 0.8f);
GameRegistry.addSmelting(BasicComponents.itemSteelPlate.shiftedIndex, new ItemStack(BasicComponents.itemSteelDust, 3), 0f);
// Bronze
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBronzeDust), new Object[]
{ "!#!", '!', "ingotCopper", '#', "ingotTin" }), "Bronze Dust", UniversalElectricity.CONFIGURATION, true);
GameRegistry.addSmelting(BasicComponents.itemBronzeDust.shiftedIndex, new ItemStack(BasicComponents.itemBronzeIngot), 0.6f);
GameRegistry.addSmelting(BasicComponents.itemBronzePlate.shiftedIndex, new ItemStack(BasicComponents.itemBronzeDust, 3), 0f);
// Plates
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCopperPlate), new Object[]
{ "!!", "!!", '!', "ingotCopper" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemTinPlate), new Object[]
{ "!!", "!!", '!', "ingotTin" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelPlate), new Object[]
{ "!!", "!!", '!', "ingotSteel" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBronzePlate), new Object[]
{ "!!", "!!", '!', "ingotBronze" }));
// Circuit
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 0), new Object[]
{ "!#!", "#@#", "!#!", '@', BasicComponents.itemBronzePlate, '#', Item.redstone, '!', BasicComponents.blockCopperWire }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 0), new Object[]
{ "!#!", "#@#", "!#!", '@', BasicComponents.itemSteelPlate, '#', Item.redstone, '!', BasicComponents.blockCopperWire }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 1), new Object[]
{ "@@@", "#?#", "@@@", '@', Item.redstone, '?', Item.diamond, '#', BasicComponents.itemCircuit }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 2), new Object[]
{ "@@@", "?#?", "@@@", '@', Item.ingotGold, '?', new ItemStack(BasicComponents.itemCircuit, 1, 1), '#', Block.blockLapis }));
}
@Override
public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix)
{
if (item.itemID == BasicComponents.itemOilBucket.shiftedIndex)
{
for (int i = 0; i < craftMatrix.getSizeInventory(); i++)
{
if (craftMatrix.getStackInSlot(i) != null)
{
if (craftMatrix.getStackInSlot(i).itemID == Item.bucketWater.shiftedIndex)
{
craftMatrix.setInventorySlotContents(i, null);
return;
}
}
}
}
}
@Override
public void onSmelting(EntityPlayer player, ItemStack item)
{
}
}
| false | true |
public void load(FMLInitializationEvent evt)
{
proxy.init();
/**
* Adding names
*/
LanguageRegistry.addName(new ItemStack(BasicComponents.blockBasicOre, 1, 0), "Copper Ore");
LanguageRegistry.addName(new ItemStack(BasicComponents.blockBasicOre, 1, 1), "Tin Ore");
LanguageRegistry.addName(BasicComponents.oilMoving, "Oil Moving");
LanguageRegistry.addName(BasicComponents.oilStill, "Oil Still");
LanguageRegistry.addName(BasicComponents.itemBattery, "Basic Battery");
LanguageRegistry.addName(new ItemStack(BasicComponents.blockCopperWire, 1, 0), "Copper Wire");
LanguageRegistry.addName(new ItemStack(BasicComponents.itemCircuit, 1, 0), "Basic Circuit");
LanguageRegistry.addName(new ItemStack(BasicComponents.itemCircuit, 1, 1), "Advanced Circuit");
LanguageRegistry.addName(new ItemStack(BasicComponents.itemCircuit, 1, 2), "Elite Circuit");
LanguageRegistry.addName(BasicComponents.itemOilBucket, "Oil Bucket");
LanguageRegistry.addName(BasicComponents.itemWrench, "Universal Wrench");
LanguageRegistry.addName(BasicComponents.coalGenerator, "Coal Generator");
LanguageRegistry.addName(BasicComponents.batteryBox, "Battery Box");
LanguageRegistry.addName(BasicComponents.electricFurnace, "Electric Furnace");
/**
* Registering Tile Entities
*/
GameRegistry.registerTileEntity(TileEntityBatteryBox.class, "UEBatteryBox");
GameRegistry.registerTileEntity(TileEntityCoalGenerator.class, "UECoalGenerator");
GameRegistry.registerTileEntity(TileEntityElectricFurnace.class, "UEElectricFurnace");
OreGenerator.addOre(BasicComponents.copperOreGeneration);
OreGenerator.addOre(BasicComponents.tinOreGeneration);
// Recipes
// Oil Bucket
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemOilBucket), new Object[]
{ "CCC", "CBC", "CCC", 'B', Item.bucketWater, 'C', Item.coal }));
// Motor
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemMotor), new Object[]
{ "@!@", "!#!", "@!@", '!', "ingotSteel", '#', Item.ingotIron, '@', BasicComponents.blockCopperWire }));
// Wrench
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemWrench), new Object[]
{ " S ", " DS", "S ", 'S', "ingotSteel", 'D', Item.diamond }));
// Battery Box
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.batteryBox, new Object[]
{ "?!?", "###", "?!?", '#', BasicComponents.blockCopperWire, '!', BasicComponents.itemSteelPlate, '?', BasicComponents.itemBattery.getUncharged() }));
GameRegistry.addSmelting(BasicComponents.batteryBox.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Coal Generator
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.coalGenerator, new Object[]
{ "SCS", "FMF", "BBB", 'B', "ingotBronze", 'S', BasicComponents.itemSteelPlate, 'C', BasicComponents.blockCopperWire, 'M', BasicComponents.itemMotor, 'F', Block.stoneOvenIdle }));
GameRegistry.addSmelting(BasicComponents.coalGenerator.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Electric Furnace
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.electricFurnace, new Object[]
{ "SSS", "SCS", "SMS", 'S', "ingotSteel", 'C', BasicComponents.itemCircuit, 'M', BasicComponents.itemMotor }));
GameRegistry.addSmelting(BasicComponents.electricFurnace.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Copper
FurnaceRecipes.smelting().addSmelting(BasicComponents.blockBasicOre.blockID, 0, new ItemStack(BasicComponents.itemCopperIngot));
// Copper Wire
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.blockCopperWire, 6), new Object[]
{ "!!!", "@@@", "!!!", '!', Item.leather, '@', "ingotCopper" }));
// Tin
FurnaceRecipes.smelting().addSmelting(BasicComponents.blockBasicOre.blockID, 1, new ItemStack(BasicComponents.itemTinIngot));
// Battery
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBattery), new Object[]
{ " T ", "TRT", "TCT", 'T', "ingotTin", 'R', Item.redstone, 'C', Item.coal }));
// Steel
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelDust), new Object[]
{ " C ", "CIC", " C ", 'C', new ItemStack(Item.coal, 1, 1), 'I', Item.ingotIron }), "Steel Dust", UniversalElectricity.CONFIGURATION, true);
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelDust), new Object[]
{ " C ", "CIC", " C ", 'C', new ItemStack(Item.coal, 1, 0), 'I', Item.ingotIron }), "Steel Dust", UniversalElectricity.CONFIGURATION, true);
GameRegistry.addSmelting(BasicComponents.itemSteelDust.shiftedIndex, new ItemStack(BasicComponents.itemSteelIngot), 0.8f);
GameRegistry.addSmelting(BasicComponents.itemSteelPlate.shiftedIndex, new ItemStack(BasicComponents.itemSteelDust, 3), 0f);
// Bronze
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBronzeDust), new Object[]
{ "!#!", '!', "ingotCopper", '#', "ingotTin" }), "Bronze Dust", UniversalElectricity.CONFIGURATION, true);
GameRegistry.addSmelting(BasicComponents.itemBronzeDust.shiftedIndex, new ItemStack(BasicComponents.itemBronzeIngot), 0.6f);
GameRegistry.addSmelting(BasicComponents.itemBronzePlate.shiftedIndex, new ItemStack(BasicComponents.itemBronzeDust, 3), 0f);
// Plates
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCopperPlate), new Object[]
{ "!!", "!!", '!', "ingotCopper" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemTinPlate), new Object[]
{ "!!", "!!", '!', "ingotTin" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelPlate), new Object[]
{ "!!", "!!", '!', "ingotSteel" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBronzePlate), new Object[]
{ "!!", "!!", '!', "ingotBronze" }));
// Circuit
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 0), new Object[]
{ "!#!", "#@#", "!#!", '@', BasicComponents.itemBronzePlate, '#', Item.redstone, '!', BasicComponents.blockCopperWire }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 0), new Object[]
{ "!#!", "#@#", "!#!", '@', BasicComponents.itemSteelPlate, '#', Item.redstone, '!', BasicComponents.blockCopperWire }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 1), new Object[]
{ "@@@", "#?#", "@@@", '@', Item.redstone, '?', Item.diamond, '#', BasicComponents.itemCircuit }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 2), new Object[]
{ "@@@", "?#?", "@@@", '@', Item.ingotGold, '?', new ItemStack(BasicComponents.itemCircuit, 1, 1), '#', Block.blockLapis }));
}
@Override
public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix)
{
if (item.itemID == BasicComponents.itemOilBucket.shiftedIndex)
{
for (int i = 0; i < craftMatrix.getSizeInventory(); i++)
{
if (craftMatrix.getStackInSlot(i) != null)
{
if (craftMatrix.getStackInSlot(i).itemID == Item.bucketWater.shiftedIndex)
{
craftMatrix.setInventorySlotContents(i, null);
return;
}
}
}
}
}
@Override
public void onSmelting(EntityPlayer player, ItemStack item)
{
}
}
|
public void load(FMLInitializationEvent evt)
{
proxy.init();
/**
* Adding names
*/
LanguageRegistry.addName(new ItemStack(BasicComponents.blockBasicOre, 1, 0), "Copper Ore");
LanguageRegistry.addName(new ItemStack(BasicComponents.blockBasicOre, 1, 1), "Tin Ore");
LanguageRegistry.addName(BasicComponents.oilMoving, "Oil Moving");
LanguageRegistry.addName(BasicComponents.oilStill, "Oil Still");
LanguageRegistry.addName(BasicComponents.itemBattery, "Basic Battery");
LanguageRegistry.addName(new ItemStack(BasicComponents.blockCopperWire, 1, 0), "Copper Wire");
LanguageRegistry.addName(new ItemStack(BasicComponents.itemCircuit, 1, 0), "Basic Circuit");
LanguageRegistry.addName(new ItemStack(BasicComponents.itemCircuit, 1, 1), "Advanced Circuit");
LanguageRegistry.addName(new ItemStack(BasicComponents.itemCircuit, 1, 2), "Elite Circuit");
LanguageRegistry.addName(BasicComponents.itemOilBucket, "Oil Bucket");
LanguageRegistry.addName(BasicComponents.itemWrench, "Universal Wrench");
LanguageRegistry.addName(BasicComponents.coalGenerator, "Coal Generator");
LanguageRegistry.addName(BasicComponents.batteryBox, "Battery Box");
LanguageRegistry.addName(BasicComponents.electricFurnace, "Electric Furnace");
/**
* Registering Tile Entities
*/
GameRegistry.registerTileEntity(TileEntityBatteryBox.class, "UEBatteryBox");
GameRegistry.registerTileEntity(TileEntityCoalGenerator.class, "UECoalGenerator");
GameRegistry.registerTileEntity(TileEntityElectricFurnace.class, "UEElectricFurnace");
OreGenerator.addOre(BasicComponents.copperOreGeneration);
OreGenerator.addOre(BasicComponents.tinOreGeneration);
// Recipes
// Oil Bucket
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemOilBucket), new Object[]
{ "CCC", "CBC", "CCC", 'B', Item.bucketWater, 'C', Item.coal }));
// Motor
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemMotor), new Object[]
{ "@!@", "!#!", "@!@", '!', "ingotSteel", '#', Item.ingotIron, '@', BasicComponents.blockCopperWire }));
// Wrench
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemWrench), new Object[]
{ " S ", " DS", "S ", 'S', "ingotSteel", 'D', Item.diamond }));
// Battery Box
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.batteryBox, new Object[]
{ "?!?", "###", "?!?", '#', BasicComponents.blockCopperWire, '!', BasicComponents.itemSteelPlate, '?', BasicComponents.itemBattery.getUncharged() }));
GameRegistry.addSmelting(BasicComponents.batteryBox.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Coal Generator
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.coalGenerator, new Object[]
{ "SCS", "FMF", "BBB", 'B', "ingotBronze", 'S', BasicComponents.itemSteelPlate, 'C', BasicComponents.blockCopperWire, 'M', BasicComponents.itemMotor, 'F', Block.stoneOvenIdle }));
GameRegistry.addSmelting(BasicComponents.coalGenerator.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Electric Furnace
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.electricFurnace, new Object[]
{ "SSS", "SCS", "SMS", 'S', "ingotSteel", 'C', BasicComponents.itemCircuit, 'M', BasicComponents.itemMotor }));
GameRegistry.addSmelting(BasicComponents.electricFurnace.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Copper
FurnaceRecipes.smelting().addSmelting(BasicComponents.blockBasicOre.blockID, 0, new ItemStack(BasicComponents.itemCopperIngot), 0.7f);
// Copper Wire
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.blockCopperWire, 6), new Object[]
{ "!!!", "@@@", "!!!", '!', Item.leather, '@', "ingotCopper" }));
// Tin
FurnaceRecipes.smelting().addSmelting(BasicComponents.blockBasicOre.blockID, 1, new ItemStack(BasicComponents.itemTinIngot), 0.7f);
// Battery
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBattery), new Object[]
{ " T ", "TRT", "TCT", 'T', "ingotTin", 'R', Item.redstone, 'C', Item.coal }));
// Steel
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelDust), new Object[]
{ " C ", "CIC", " C ", 'C', new ItemStack(Item.coal, 1, 1), 'I', Item.ingotIron }), "Steel Dust", UniversalElectricity.CONFIGURATION, true);
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelDust), new Object[]
{ " C ", "CIC", " C ", 'C', new ItemStack(Item.coal, 1, 0), 'I', Item.ingotIron }), "Steel Dust", UniversalElectricity.CONFIGURATION, true);
GameRegistry.addSmelting(BasicComponents.itemSteelDust.shiftedIndex, new ItemStack(BasicComponents.itemSteelIngot), 0.8f);
GameRegistry.addSmelting(BasicComponents.itemSteelPlate.shiftedIndex, new ItemStack(BasicComponents.itemSteelDust, 3), 0f);
// Bronze
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBronzeDust), new Object[]
{ "!#!", '!', "ingotCopper", '#', "ingotTin" }), "Bronze Dust", UniversalElectricity.CONFIGURATION, true);
GameRegistry.addSmelting(BasicComponents.itemBronzeDust.shiftedIndex, new ItemStack(BasicComponents.itemBronzeIngot), 0.6f);
GameRegistry.addSmelting(BasicComponents.itemBronzePlate.shiftedIndex, new ItemStack(BasicComponents.itemBronzeDust, 3), 0f);
// Plates
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCopperPlate), new Object[]
{ "!!", "!!", '!', "ingotCopper" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemTinPlate), new Object[]
{ "!!", "!!", '!', "ingotTin" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelPlate), new Object[]
{ "!!", "!!", '!', "ingotSteel" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBronzePlate), new Object[]
{ "!!", "!!", '!', "ingotBronze" }));
// Circuit
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 0), new Object[]
{ "!#!", "#@#", "!#!", '@', BasicComponents.itemBronzePlate, '#', Item.redstone, '!', BasicComponents.blockCopperWire }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 0), new Object[]
{ "!#!", "#@#", "!#!", '@', BasicComponents.itemSteelPlate, '#', Item.redstone, '!', BasicComponents.blockCopperWire }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 1), new Object[]
{ "@@@", "#?#", "@@@", '@', Item.redstone, '?', Item.diamond, '#', BasicComponents.itemCircuit }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 2), new Object[]
{ "@@@", "?#?", "@@@", '@', Item.ingotGold, '?', new ItemStack(BasicComponents.itemCircuit, 1, 1), '#', Block.blockLapis }));
}
@Override
public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix)
{
if (item.itemID == BasicComponents.itemOilBucket.shiftedIndex)
{
for (int i = 0; i < craftMatrix.getSizeInventory(); i++)
{
if (craftMatrix.getStackInSlot(i) != null)
{
if (craftMatrix.getStackInSlot(i).itemID == Item.bucketWater.shiftedIndex)
{
craftMatrix.setInventorySlotContents(i, null);
return;
}
}
}
}
}
@Override
public void onSmelting(EntityPlayer player, ItemStack item)
{
}
}
|
diff --git a/library/src/org/onepf/oms/OpenIabHelper.java b/library/src/org/onepf/oms/OpenIabHelper.java
index aa9bb97..472b070 100644
--- a/library/src/org/onepf/oms/OpenIabHelper.java
+++ b/library/src/org/onepf/oms/OpenIabHelper.java
@@ -1,812 +1,813 @@
/*******************************************************************************
* Copyright 2013 One Platform Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.onepf.oms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.onepf.oms.appstore.AmazonAppstore;
import org.onepf.oms.appstore.GooglePlay;
import org.onepf.oms.appstore.OpenAppstore;
import org.onepf.oms.appstore.SamsungApps;
import org.onepf.oms.appstore.TStore;
import org.onepf.oms.appstore.googleUtils.IabException;
import org.onepf.oms.appstore.googleUtils.IabHelper;
import org.onepf.oms.appstore.googleUtils.IabHelper.OnIabPurchaseFinishedListener;
import org.onepf.oms.appstore.googleUtils.IabHelper.OnIabSetupFinishedListener;
import org.onepf.oms.appstore.googleUtils.IabResult;
import org.onepf.oms.appstore.googleUtils.Inventory;
import org.onepf.oms.appstore.googleUtils.Purchase;
import org.onepf.oms.appstore.googleUtils.Security;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
/**
*
*
* @author Boris Minaev, Oleg Orlov
* @since 16.04.13
*/
public class OpenIabHelper {
private static final String TAG = OpenIabHelper.class.getSimpleName();
// Is debug logging enabled?
private static final boolean mDebugLog = false;
private static final String BIND_INTENT = "org.onepf.oms.openappstore.BIND";
/** */
private static final int DISCOVER_TIMEOUT_MS = 5000;
/** */
private static final int INVENTORY_CHECK_TIMEOUT_MS = 5000;
private final Context context;
private Handler notifyHandler = null;
/** selected appstore */
private Appstore mAppstore;
/** selected appstore billing service */
private AppstoreInAppBillingService mAppstoreBillingService;
private final Options options;
// Is setup done?
private boolean mSetupDone = false;
// Is an asynchronous operation in progress?
// (only one at a time can be in progress)
private boolean mAsyncInProgress = false;
// (for logging/debugging)
// if mAsyncInProgress == true, what asynchronous operation is in progress?
private String mAsyncOperation = "";
// The request code used to launch purchase flow
int mRequestCode;
// The item type of the current purchase flow
String mPurchasingItemType;
// Item types
public static final String ITEM_TYPE_INAPP = "inapp";
public static final String ITEM_TYPE_SUBS = "subs";
// Billing response codes
public static final int BILLING_RESPONSE_RESULT_OK = 0;
public static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3;
public static final int BILLING_RESPONSE_RESULT_ERROR = 6;
public static final String NAME_GOOGLE = "com.google.play";
public static final String NAME_AMAZON = "com.amazon.apps";
public static final String NAME_TSTORE = "com.tmobile.store";
public static final String NAME_SAMSUNG = "com.samsung.apps";
/**
* NOTE: used as sync object in related methods<br>
*
* storeName -> [ ... {app_sku1 -> store_sku1}, ... ]
*/
private static final Map <String, Map<String, String>> sku2storeSkuMappings = new HashMap<String, Map <String, String>>();
/**
* storeName -> [ ... {store_sku1 -> app_sku1}, ... ]
*/
private static final Map <String, Map<String, String>> storeSku2skuMappings = new HashMap<String, Map <String, String>>();
/**
* Map sku and storeSku for particular store.
*
* TODO: returns smth with nice API like:
* <pre>
* mapSku(sku).store(GOOGLE_PLAY).to(SKU_MY1_GOOGLE).and(AMAZON_APPS).to(SKU_MY1_AMAZON)
* or
* mapStore(AMAZON_APPS).sku(SKU_MY2).to(SKU_MY2_AMAZON).sku(SKU_MY3).to(SKU_MY3_AMAZON)
* </pre>
*
* @param sku - and
* @param storeSku - shouldn't duplicate already mapped values
* @param storeName - @see {@link IOpenAppstore#getAppstoreName()} or {@link #NAME_AMAZON} {@link #NAME_GOOGLE} {@link #NAME_TSTORE}
*/
public static void mapSku(String sku, String storeName, String storeSku) {
synchronized (sku2storeSkuMappings) {
Map<String, String> skuMap = sku2storeSkuMappings.get(storeName);
if (skuMap == null) {
skuMap = new HashMap<String, String>();
sku2storeSkuMappings.put(storeName, skuMap);
}
if (skuMap.get(sku) != null) {
throw new IllegalArgumentException("Already specified SKU. sku: " + sku + " -> storeSku: " + skuMap.get(sku));
}
;
Map<String, String> storeSkuMap = storeSku2skuMappings.get(storeName);
if (storeSkuMap == null) {
storeSkuMap = new HashMap<String, String>();
storeSku2skuMappings.put(storeName, storeSkuMap);
}
if (storeSkuMap.get(storeSku) != null) {
throw new IllegalArgumentException("Ambigous SKU mapping. You try to map sku: " + sku + " -> storeSku: " + storeSku + ", that is already mapped to sku: " + storeSkuMap.get(storeSku));
}
skuMap.put(sku, storeSku);
storeSkuMap.put(storeSku, sku);
}
}
public static String getStoreSku(final String appstoreName, String sku) {
synchronized (sku2storeSkuMappings) {
String currentStoreSku = sku;
Map<String, String> skuMap = sku2storeSkuMappings.get(appstoreName);
if (skuMap != null && skuMap.get(sku) != null) {
currentStoreSku = skuMap.get(sku);
if (mDebugLog) Log.d(TAG, "getStoreSku() using mapping for sku: " + sku + " -> " + currentStoreSku);
}
return currentStoreSku;
}
}
public static String getSku(final String appstoreName, String storeSku) {
synchronized (sku2storeSkuMappings) {
String sku = storeSku;
Map<String, String> skuMap = storeSku2skuMappings.get(appstoreName);
if (skuMap != null && skuMap.get(sku) != null) {
sku = skuMap.get(sku);
if (mDebugLog) Log.d(TAG, "getSku() restore sku from storeSku: " + storeSku + " -> " + sku);
}
return sku;
}
}
/**
* @param appstoreName for example {@link OpenIabHelper#NAME_AMAZON}
* @return list of skus those have mappings for specified appstore
*/
public static List<String> getAllStoreSkus(final String appstoreName) {
Map<String, String> skuMap = sku2storeSkuMappings.get(appstoreName);
List<String> result = new ArrayList<String>();
if (skuMap != null) {
result.addAll(skuMap.values());
}
return result;
}
public OpenIabHelper(Context context, Map<String, String> storeKeys) {
this(context, storeKeys, null);
}
/**
* @param storeKeys - map [ storeName -> publicKey ]
* @param prefferedStoreNames - will be used if package installer cannot be found
*/
public OpenIabHelper(Context context, Map<String, String> storeKeys, String[] prefferedStores) {
this(context, storeKeys, prefferedStores, null);
}
/**
* @param storeKeys - map [ storeName -> publicKey ]
* @param prefferedStoreNames - will be used if package installer cannot be found
* @param availableStores - exact list of stores to participate in store election
*/
public OpenIabHelper(Context context, Map<String, String> storeKeys, String[] prefferedStores, Appstore[] availableStores) {
this.context = context;
this.options = new Options();
options.storeKeys = storeKeys;
options.prefferedStoreNames = prefferedStores != null ? prefferedStores : options.prefferedStoreNames;
options.availableStores = availableStores != null ? new ArrayList<Appstore>(Arrays.asList(availableStores)) : null;
}
/**
* @param options - specify all neccessary options
*/
public OpenIabHelper(Context context, Options options) {
this.context = context;
this.options = options;
}
/**
* Discover available stores and select the best billing service.
* Calls listener when service is found.
*
* Should be called from UI thread
*/
public void startSetup(final IabHelper.OnIabSetupFinishedListener listener) {
this.notifyHandler = new Handler();
checkOptions(options);
new Thread(new Runnable() {
public void run() {
List<Appstore> stores2check = new ArrayList<Appstore>();
if (options.availableStores != null) {
stores2check.addAll(options.availableStores);
} else { // if appstores are not specified by user - lookup for all available stores
final List<Appstore> openStores = discoverOpenStores(context, null, options);
if (mDebugLog) Log.d(TAG, "startSetup() discovered openstores: " + openStores.toString());
stores2check.addAll(openStores);
if (options.verifyMode == Options.VERIFY_EVERYTHING && !options.storeKeys.containsKey(NAME_GOOGLE)) {
// don't work with GooglePlay if verifyMode is strict and no publicKey provided
} else {
final String publicKey = options.verifyMode == Options.VERIFY_SKIP ? null
: options.storeKeys.get(OpenIabHelper.NAME_GOOGLE);
stores2check.add(new GooglePlay(context, publicKey));
}
stores2check.add(new AmazonAppstore(context));
stores2check.add(new TStore(context, options.storeKeys.get(OpenIabHelper.NAME_TSTORE)));
if (getAllStoreSkus(NAME_SAMSUNG).size() > 0) {
// SamsungApps shows lot of UI stuff during init
// try it only if samsung SKUs are specified
stores2check.add(new SamsungApps(context));
}
}
if (options.checkInventory) {
if (mDebugLog) Log.d(TAG, "startSetup() check inventory. stores: " + stores2check);
final List<Appstore> equippedStores = inventoryCheck(stores2check);
if (mDebugLog) Log.d(TAG, "startSetup() equipped stores: " + equippedStores);
if (equippedStores.size() > 0) {
mAppstore = selectBillingService(equippedStores);
if (mDebugLog) Log.d(TAG, "startSetup() selected store: " + mAppstore);
}
if (mAppstore != null) {
mAppstoreBillingService = mAppstore.getInAppBillingService();
final IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK
, "Successfully initialized with existing inventory: " + mAppstore.getAppstoreName());
fireSetupFinished(listener, result);
if (mDebugLog) Log.d(TAG, "startSetup() selected store: " + mAppstore);
return;
}
// found no equipped stores. Select store based on store parameters
if (mDebugLog) Log.d(TAG, "startSetup() equipped elections: " + mAppstore);
IabResult result = new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "Billing isn't supported");
if (mAppstore == null) {
mAppstore = selectBillingService(stores2check);
}
if (mAppstore != null) {
mAppstoreBillingService = mAppstore.getInAppBillingService();
result = new IabResult(BILLING_RESPONSE_RESULT_OK
, "Successfully initialized: " + mAppstore.getAppstoreName());
if (mDebugLog) Log.d(TAG, "startSetup() selected store: " + mAppstore);
} else {
result = new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE
, "Billing isn't supported");
if (mDebugLog) Log.d(TAG, "startSetup() billing is not available");
}
fireSetupFinished(listener, result);
} else { // no inventory check. Select store based on store parameters
if (mDebugLog) Log.d(TAG, "startSetup() No inventory check. stores: " + stores2check);
mAppstore = selectBillingService(stores2check);
if (mDebugLog) Log.d(TAG, "startSetup() selected store: " + mAppstore);
if (mAppstore == null) {
IabResult iabResult = new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "Billing isn't supported");
fireSetupFinished(listener, iabResult);
+ return;
}
mAppstoreBillingService = mAppstore.getInAppBillingService();
mAppstoreBillingService.startSetup(new OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
fireSetupFinished(listener, result);
}
});
}
}
}, "openiab-setup").start();
}
/** Check options are valid */
public static void checkOptions(Options options) {
if (options.verifyMode != Options.VERIFY_SKIP && options.storeKeys != null) { // check publicKeys. Must be not null and valid
for (Entry<String, String> entry : options.storeKeys.entrySet()) {
if (entry.getValue() == null) {
throw new IllegalArgumentException("Null publicKey for store: " + entry.getKey() + ", key: " + entry.getValue());
}
try {
Security.generatePublicKey(entry.getValue());
} catch (Exception e) {
throw new IllegalArgumentException("Invalid publicKey for store: " + entry.getKey() + ", key: " + entry.getValue(), e);
}
}
}
}
protected void fireSetupFinished(final IabHelper.OnIabSetupFinishedListener listener, final IabResult result) {
mSetupDone = true;
notifyHandler.post(new Runnable() {
public void run() {
listener.onIabSetupFinished(result);
}
});
}
/**
* Discover all OpenStore services, checks them and build {@link #availableStores} list<br>.
* Time is limited by 5 seconds
*
* @param appstores - discovered OpenStores will be added here. Must be not null
* @param listener - called back when all OpenStores collected and analyzed
*/
public static List<Appstore> discoverOpenStores(final Context context, final List<Appstore> dest, final Options options) {
PackageManager packageManager = context.getPackageManager();
final Intent intentAppstoreServices = new Intent(BIND_INTENT);
List<ResolveInfo> infoList = packageManager.queryIntentServices(intentAppstoreServices, 0);
final List<Appstore> result = dest != null ? dest : new ArrayList<Appstore>(infoList.size());
final CountDownLatch storesToCheck = new CountDownLatch(infoList.size());
for (ResolveInfo info : infoList) {
String packageName = info.serviceInfo.packageName;
String name = info.serviceInfo.name;
Intent intentAppstore = new Intent(intentAppstoreServices);
intentAppstore.setClassName(packageName, name);
context.bindService(intentAppstore, new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (mDebugLog) Log.d(TAG, "discoverOpenStores() appstoresService connected for component: " + name.flattenToShortString());
IOpenAppstore openAppstoreService = IOpenAppstore.Stub.asInterface(service);
try {
String appstoreName = openAppstoreService.getAppstoreName();
Intent billingIntent = openAppstoreService.getBillingServiceIntent();
if (appstoreName == null) { // no name - no service
Log.e(TAG, "discoverOpenStores() Appstore doesn't have name. Skipped. ComponentName: " + name);
} else if (billingIntent == null) { // don't handle stores without billing support
if (mDebugLog) Log.d(TAG, "discoverOpenStores(): billing is not supported by store: " + name);
} else if ((options.verifyMode == Options.VERIFY_EVERYTHING) && !options.storeKeys.containsKey(appstoreName)) {
// don't connect to OpenStore if no key provided and verification is strict
Log.e(TAG, "discoverOpenStores(): verification is required but publicKey is not provided: " + name);
} else {
String publicKey = options.storeKeys.get(appstoreName);
if (options.verifyMode == Options.VERIFY_SKIP) publicKey = null;
final OpenAppstore openAppstore = new OpenAppstore(context, appstoreName, openAppstoreService, billingIntent, publicKey);
openAppstore.componentName = name;
Log.d(TAG, "discoverOpenStores() add new OpenStore: " + openAppstore);
synchronized (result) {
if (result.contains(openAppstore) == false) {
result.add(openAppstore);
}
}
}
} catch (RemoteException e) {
Log.e(TAG, "discoverOpenStores() ComponentName: " + name, e);
}
storesToCheck.countDown();
}
@Override
public void onServiceDisconnected(ComponentName name) {
if (mDebugLog) Log.d(TAG, "onServiceDisconnected() appstoresService disconnected for component: " + name.flattenToShortString());
//Nothing to do here
}
}, Context.BIND_AUTO_CREATE);
}
try {
storesToCheck.await(options.discoveryTimeoutMs, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Log.e(TAG, "Interrupted: discovering OpenStores. ", e);
}
return result;
}
/**
* Connects to Billing Service of each store. Request list of user purchases (inventory)
*
* @see {@link OpenIabHelper#INVENTORY_CHECK_TIMEOUT_MS} to set timout value
*
* @param availableStores - list of stores to check
* @return list of stores with non-empty inventory
*/
protected List<Appstore> inventoryCheck(final List<Appstore> availableStores) {
String packageName = context.getPackageName();
// candidates:
Map<String, Appstore> candidates = new HashMap<String, Appstore>();
for (Appstore appstore : availableStores) {
if (appstore.isBillingAvailable(packageName)) {
candidates.put(appstore.getAppstoreName(), appstore);
}
}
final List<Appstore> equippedStores = Collections.synchronizedList(new ArrayList<Appstore>());
final CountDownLatch storeRemains = new CountDownLatch(candidates.size());
// for every appstore: connect to billing service and check inventory
for (Map.Entry<String, Appstore> entry : candidates.entrySet()) {
final Appstore appstore = entry.getValue();
final AppstoreInAppBillingService billingService = entry.getValue().getInAppBillingService();
billingService.startSetup(new OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
new Thread(new Runnable() {
public void run() {
try {
Inventory inventory = billingService.queryInventory(false, null, null);
if (inventory.getAllPurchases().size() > 0) {
equippedStores.add(appstore);
}
if (mDebugLog) Log.d(TAG, "inventoryCheck() found: " + inventory.getAllPurchases().size() + " purchases in " + appstore.getAppstoreName());
} catch (IabException e) {
Log.e(TAG, "inventoryCheck() failed for " + appstore.getAppstoreName());
}
storeRemains.countDown();
}
}, "inv-check-" + appstore.getAppstoreName()).start();;
}
});
}
try {
storeRemains.await(options.checkInventoryTimeoutMs, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Log.e(TAG, "selectBillingService() inventory check is failed. candidates: " + candidates.size()
+ ", inventory remains: " + storeRemains.getCount() , e);
}
return equippedStores;
}
/**
* Lookup for requested service in store based on isPackageInstaller() & isBillingAvailable()
* <p>
* Scenario:
* <li>
* - look for installer: if exists and supports billing service - we done <li>
* - rest of stores who support billing considered as candidates<p><li>
*
* - find candidate according to [prefferedStoreNames]. if found - we done<p><li>
*
* - select candidate randomly from 3 groups based on published package version<li>
* - published version == app.versionCode<li>
* - published version > app.versionCode<li>
* - published version < app.versionCode
*
*/
protected Appstore selectBillingService(final List<Appstore> availableStores) {
String packageName = context.getPackageName();
// candidates:
Map<String, Appstore> candidates = new HashMap<String, Appstore>();
//
for (Appstore appstore : availableStores) {
if (appstore.isBillingAvailable(packageName)) {
candidates.put(appstore.getAppstoreName(), appstore);
} else {
continue; // for billing we cannot select store without billing
}
if (appstore.isPackageInstaller(packageName)) {
return appstore;
}
}
if (candidates.size() == 0) return null;
// lookup for developer preffered stores
for (int i = 0; i < options.prefferedStoreNames.length; i++) {
Appstore candidate = candidates.get(options.prefferedStoreNames[i]);
if (candidate != null) {
return candidate;
}
}
// nothing found. select something that matches package version
int versionCode = Appstore.PACKAGE_VERSION_UNDEFINED;
try {
versionCode = context.getPackageManager().getPackageInfo(packageName, 0).versionCode;
} catch (NameNotFoundException e) {
Log.e(TAG, "Are we installed?", e);
}
List<Appstore> sameVersion = new ArrayList<Appstore>();
List<Appstore> higherVersion = new ArrayList<Appstore>();
for (Appstore candidate : candidates.values()) {
final int storeVersion = candidate.getPackageVersion(packageName);
if (storeVersion == versionCode) {
sameVersion.add(candidate);
} else if (storeVersion > versionCode) {
higherVersion.add(candidate);
}
}
// use random if found stores with same version of package
if (sameVersion.size() > 0) {
return sameVersion.get(new Random().nextInt(sameVersion.size()));
} else if (higherVersion.size() > 0) { // or one of higher version
return higherVersion.get(new Random().nextInt(higherVersion.size()));
} else { // ok, return no matter what
return new ArrayList<Appstore>(candidates.values()).get(new Random().nextInt(candidates.size()));
}
}
public void dispose() {
logDebug("Disposing.");
checkSetupDone("dispose");
mAppstoreBillingService.dispose();
}
public boolean subscriptionsSupported() {
// TODO: implement this
return true;
}
public void launchPurchaseFlow(Activity act, String sku, int requestCode, IabHelper.OnIabPurchaseFinishedListener listener) {
launchPurchaseFlow(act, sku, requestCode, listener, "");
}
public void launchPurchaseFlow(Activity act, String sku, int requestCode,
IabHelper.OnIabPurchaseFinishedListener listener, String extraData) {
launchPurchaseFlow(act, sku, ITEM_TYPE_INAPP, requestCode, listener, extraData);
}
public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode,
IabHelper.OnIabPurchaseFinishedListener listener) {
launchSubscriptionPurchaseFlow(act, sku, requestCode, listener, "");
}
public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode,
IabHelper.OnIabPurchaseFinishedListener listener, String extraData) {
launchPurchaseFlow(act, sku, ITEM_TYPE_SUBS, requestCode, listener, extraData);
}
public void launchPurchaseFlow(Activity act, String sku, String itemType, int requestCode,
IabHelper.OnIabPurchaseFinishedListener listener, String extraData) {
checkSetupDone("launchPurchaseFlow");
String storeSku = getStoreSku(mAppstore.getAppstoreName(), sku);
mAppstoreBillingService.launchPurchaseFlow(act, storeSku, itemType, requestCode, listener, extraData);
}
public boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
return mAppstoreBillingService.handleActivityResult(requestCode, resultCode, data);
}
/**
* See {@link #queryInventory(boolean, List, List)} for details
*/
public Inventory queryInventory(boolean querySkuDetails, List<String> moreSkus) throws IabException {
return queryInventory(querySkuDetails, moreSkus, null);
}
/**
* Queries the inventory. This will query all owned items from the server, as well as
* information on additional skus, if specified. This method may block or take long to execute.
* Do not call from a UI thread. For that, use the non-blocking version {@link #refreshInventoryAsync}.
*
* @param querySkuDetails if true, SKU details (price, description, etc) will be queried as well
* as purchase information.
* @param moreItemSkus additional PRODUCT skus to query information on, regardless of ownership.
* Ignored if null or if querySkuDetails is false.
* @param moreSubsSkus additional SUBSCRIPTIONS skus to query information on, regardless of ownership.
* Ignored if null or if querySkuDetails is false.
* @throws IabException if a problem occurs while refreshing the inventory.
*/
public Inventory queryInventory(boolean querySkuDetails, List<String> moreItemSkus, List<String> moreSubsSkus) throws IabException {
checkSetupDone("queryInventory");
List<String> moreItemStoreSkus = null;
if (moreItemSkus != null) {
moreItemStoreSkus = new ArrayList<String>();
for (String sku : moreItemSkus) {
String storeSku = getStoreSku(mAppstore.getAppstoreName(), sku);
moreItemStoreSkus.add(storeSku);
}
}
List<String> moreSubsStoreSkus = null;
if (moreSubsSkus != null) {
moreSubsStoreSkus = new ArrayList<String>();
for (String sku : moreSubsSkus) {
String storeSku = getStoreSku(mAppstore.getAppstoreName(), sku);
moreSubsStoreSkus.add(storeSku);
}
}
return mAppstoreBillingService.queryInventory(querySkuDetails, moreItemStoreSkus, moreSubsStoreSkus);
}
public void queryInventoryAsync(final boolean querySkuDetails, final List<String> moreSkus, final IabHelper.QueryInventoryFinishedListener listener) {
checkSetupDone("queryInventory");
flagStartAsync("refresh inventory");
(new Thread(new Runnable() {
public void run() {
IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful.");
Inventory inv = null;
try {
inv = queryInventory(querySkuDetails, moreSkus);
} catch (IabException ex) {
result = ex.getResult();
}
flagEndAsync();
final IabResult result_f = result;
final Inventory inv_f = inv;
notifyHandler.post(new Runnable() {
public void run() {
listener.onQueryInventoryFinished(result_f, inv_f);
}
});
}
})).start();
}
public void queryInventoryAsync(IabHelper.QueryInventoryFinishedListener listener) {
queryInventoryAsync(true, null, listener);
}
public void queryInventoryAsync(boolean querySkuDetails, IabHelper.QueryInventoryFinishedListener listener) {
queryInventoryAsync(querySkuDetails, null, listener);
}
public void consume(Purchase itemInfo) throws IabException {
checkSetupDone("consume");
Purchase purchaseStoreSku = (Purchase) itemInfo.clone(); // TODO: use Purchase.getStoreSku()
purchaseStoreSku.setSku(getStoreSku(mAppstore.getAppstoreName(), itemInfo.getSku()));
mAppstoreBillingService.consume(purchaseStoreSku);
}
public void consumeAsync(Purchase purchase, IabHelper.OnConsumeFinishedListener listener) {
List<Purchase> purchases = new ArrayList<Purchase>();
purchases.add(purchase);
consumeAsyncInternal(purchases, listener, null);
}
public void consumeAsync(List<Purchase> purchases, IabHelper.OnConsumeMultiFinishedListener listener) {
consumeAsyncInternal(purchases, null, listener);
}
void consumeAsyncInternal(final List<Purchase> purchases,
final IabHelper.OnConsumeFinishedListener singleListener,
final IabHelper.OnConsumeMultiFinishedListener multiListener) {
flagStartAsync("consume");
(new Thread(new Runnable() {
public void run() {
final List<IabResult> results = new ArrayList<IabResult>();
for (Purchase purchase : purchases) {
try {
consume(purchase);
results.add(new IabResult(BILLING_RESPONSE_RESULT_OK, "Successful consume of sku " + purchase.getSku()));
} catch (IabException ex) {
results.add(ex.getResult());
}
}
flagEndAsync();
if (singleListener != null) {
notifyHandler.post(new Runnable() {
public void run() {
singleListener.onConsumeFinished(purchases.get(0), results.get(0));
}
});
}
if (multiListener != null) {
notifyHandler.post(new Runnable() {
public void run() {
multiListener.onConsumeMultiFinished(purchases, results);
}
});
}
}
})).start();
}
// Checks that setup was done; if not, throws an exception.
void checkSetupDone(String operation) {
if (!mSetupDone) {
logError("Illegal state for operation (" + operation + "): IAB helper is not set up.");
throw new IllegalStateException("IAB helper is not set up. Can't perform operation: " + operation);
}
}
void flagStartAsync(String operation) {
// TODO: why can't be called consume and queryInventory at the same time?
// if (mAsyncInProgress) {
// throw new IllegalStateException("Can't start async operation (" +
// operation + ") because another async operation(" + mAsyncOperation + ") is in progress.");
// }
mAsyncOperation = operation;
mAsyncInProgress = true;
logDebug("Starting async operation: " + operation);
}
void flagEndAsync() {
logDebug("Ending async operation: " + mAsyncOperation);
mAsyncOperation = "";
mAsyncInProgress = false;
}
void logDebug(String msg) {
if (mDebugLog) Log.d(TAG, msg);
}
void logError(String msg) {
Log.e(TAG, "In-app billing error: " + msg);
}
void logWarn(String msg) {
if (mDebugLog) Log.w(TAG, "In-app billing warning: " + msg);
}
public interface OnInitListener {
public void onInitFinished();
}
public interface OnOpenIabHelperInitFinished {
public void onOpenIabHelperInitFinished();
}
/**
* All options of OpenIAB can be found here
*
* TODO: consider to use cloned instance of Options in OpenIABHelper
*/
public static class Options {
/**
* Candidates for billing. If not provided by user than discovered OpenStores + GP/Amazon/Samsung
* {@link #discoverOpenStores(Context, List, Map, OnInitListener)}
*/
public List<Appstore> availableStores;
/**
* Wait specified amount of ms to find all OpenStores on device
*/
public int discoveryTimeoutMs = DISCOVER_TIMEOUT_MS;
/**
* Check user inventory in every store to select proper store
* <p>
* Will try to connect to each billingService and extract user's purchases.
* If purchases have been found in the only store that store will be used for further purchases.
* If purchases have been found in multiple stores only such stores will be used for further elections
*/
public boolean checkInventory = false;
/**
* Wait specified amount of ms to check inventory in all stores
*/
public int checkInventoryTimeoutMs = INVENTORY_CHECK_TIMEOUT_MS;
/**
* OpenIAB could skip receipt verification by publicKey for GooglePlay and OpenStores
* <p>
* Receipt could be verified in {@link OnIabPurchaseFinishedListener#onIabPurchaseFinished()}
* using {@link Purchase#getOriginalJson()} and {@link Purchase#getSignature()}
*/
public int verifyMode = VERIFY_EVERYTHING;
/**
* Verify signatures in any store.
* <p>
* By default in Google's IabHelper. Throws exception if key is not available or invalid.
* To prevent crashes OpenIAB wouldn't connect to OpenStore if no publicKey provided
*/
public static final int VERIFY_EVERYTHING = 0;
/**
* Don't verify signatires. To perform verification on server-side
*/
public static final int VERIFY_SKIP = 1;
/**
* Verify signatures only if publicKey is available. Otherwise skip verification.
* <p>
* Developer is responsible for verify
*/
public static final int VERIFY_ONLY_KNOWN = 2;
/** <b>publicKey</b> should be specified for GooglePlay and OpenStores to verify reciept signature */
public Map<String, String> storeKeys;
/** Developer preferred store names */
public String[] prefferedStoreNames = new String[] {};
}
}
| true | true |
public void startSetup(final IabHelper.OnIabSetupFinishedListener listener) {
this.notifyHandler = new Handler();
checkOptions(options);
new Thread(new Runnable() {
public void run() {
List<Appstore> stores2check = new ArrayList<Appstore>();
if (options.availableStores != null) {
stores2check.addAll(options.availableStores);
} else { // if appstores are not specified by user - lookup for all available stores
final List<Appstore> openStores = discoverOpenStores(context, null, options);
if (mDebugLog) Log.d(TAG, "startSetup() discovered openstores: " + openStores.toString());
stores2check.addAll(openStores);
if (options.verifyMode == Options.VERIFY_EVERYTHING && !options.storeKeys.containsKey(NAME_GOOGLE)) {
// don't work with GooglePlay if verifyMode is strict and no publicKey provided
} else {
final String publicKey = options.verifyMode == Options.VERIFY_SKIP ? null
: options.storeKeys.get(OpenIabHelper.NAME_GOOGLE);
stores2check.add(new GooglePlay(context, publicKey));
}
stores2check.add(new AmazonAppstore(context));
stores2check.add(new TStore(context, options.storeKeys.get(OpenIabHelper.NAME_TSTORE)));
if (getAllStoreSkus(NAME_SAMSUNG).size() > 0) {
// SamsungApps shows lot of UI stuff during init
// try it only if samsung SKUs are specified
stores2check.add(new SamsungApps(context));
}
}
if (options.checkInventory) {
if (mDebugLog) Log.d(TAG, "startSetup() check inventory. stores: " + stores2check);
final List<Appstore> equippedStores = inventoryCheck(stores2check);
if (mDebugLog) Log.d(TAG, "startSetup() equipped stores: " + equippedStores);
if (equippedStores.size() > 0) {
mAppstore = selectBillingService(equippedStores);
if (mDebugLog) Log.d(TAG, "startSetup() selected store: " + mAppstore);
}
if (mAppstore != null) {
mAppstoreBillingService = mAppstore.getInAppBillingService();
final IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK
, "Successfully initialized with existing inventory: " + mAppstore.getAppstoreName());
fireSetupFinished(listener, result);
if (mDebugLog) Log.d(TAG, "startSetup() selected store: " + mAppstore);
return;
}
// found no equipped stores. Select store based on store parameters
if (mDebugLog) Log.d(TAG, "startSetup() equipped elections: " + mAppstore);
IabResult result = new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "Billing isn't supported");
if (mAppstore == null) {
mAppstore = selectBillingService(stores2check);
}
if (mAppstore != null) {
mAppstoreBillingService = mAppstore.getInAppBillingService();
result = new IabResult(BILLING_RESPONSE_RESULT_OK
, "Successfully initialized: " + mAppstore.getAppstoreName());
if (mDebugLog) Log.d(TAG, "startSetup() selected store: " + mAppstore);
} else {
result = new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE
, "Billing isn't supported");
if (mDebugLog) Log.d(TAG, "startSetup() billing is not available");
}
fireSetupFinished(listener, result);
} else { // no inventory check. Select store based on store parameters
if (mDebugLog) Log.d(TAG, "startSetup() No inventory check. stores: " + stores2check);
mAppstore = selectBillingService(stores2check);
if (mDebugLog) Log.d(TAG, "startSetup() selected store: " + mAppstore);
if (mAppstore == null) {
IabResult iabResult = new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "Billing isn't supported");
fireSetupFinished(listener, iabResult);
}
mAppstoreBillingService = mAppstore.getInAppBillingService();
mAppstoreBillingService.startSetup(new OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
fireSetupFinished(listener, result);
}
});
}
}
}, "openiab-setup").start();
}
|
public void startSetup(final IabHelper.OnIabSetupFinishedListener listener) {
this.notifyHandler = new Handler();
checkOptions(options);
new Thread(new Runnable() {
public void run() {
List<Appstore> stores2check = new ArrayList<Appstore>();
if (options.availableStores != null) {
stores2check.addAll(options.availableStores);
} else { // if appstores are not specified by user - lookup for all available stores
final List<Appstore> openStores = discoverOpenStores(context, null, options);
if (mDebugLog) Log.d(TAG, "startSetup() discovered openstores: " + openStores.toString());
stores2check.addAll(openStores);
if (options.verifyMode == Options.VERIFY_EVERYTHING && !options.storeKeys.containsKey(NAME_GOOGLE)) {
// don't work with GooglePlay if verifyMode is strict and no publicKey provided
} else {
final String publicKey = options.verifyMode == Options.VERIFY_SKIP ? null
: options.storeKeys.get(OpenIabHelper.NAME_GOOGLE);
stores2check.add(new GooglePlay(context, publicKey));
}
stores2check.add(new AmazonAppstore(context));
stores2check.add(new TStore(context, options.storeKeys.get(OpenIabHelper.NAME_TSTORE)));
if (getAllStoreSkus(NAME_SAMSUNG).size() > 0) {
// SamsungApps shows lot of UI stuff during init
// try it only if samsung SKUs are specified
stores2check.add(new SamsungApps(context));
}
}
if (options.checkInventory) {
if (mDebugLog) Log.d(TAG, "startSetup() check inventory. stores: " + stores2check);
final List<Appstore> equippedStores = inventoryCheck(stores2check);
if (mDebugLog) Log.d(TAG, "startSetup() equipped stores: " + equippedStores);
if (equippedStores.size() > 0) {
mAppstore = selectBillingService(equippedStores);
if (mDebugLog) Log.d(TAG, "startSetup() selected store: " + mAppstore);
}
if (mAppstore != null) {
mAppstoreBillingService = mAppstore.getInAppBillingService();
final IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK
, "Successfully initialized with existing inventory: " + mAppstore.getAppstoreName());
fireSetupFinished(listener, result);
if (mDebugLog) Log.d(TAG, "startSetup() selected store: " + mAppstore);
return;
}
// found no equipped stores. Select store based on store parameters
if (mDebugLog) Log.d(TAG, "startSetup() equipped elections: " + mAppstore);
IabResult result = new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "Billing isn't supported");
if (mAppstore == null) {
mAppstore = selectBillingService(stores2check);
}
if (mAppstore != null) {
mAppstoreBillingService = mAppstore.getInAppBillingService();
result = new IabResult(BILLING_RESPONSE_RESULT_OK
, "Successfully initialized: " + mAppstore.getAppstoreName());
if (mDebugLog) Log.d(TAG, "startSetup() selected store: " + mAppstore);
} else {
result = new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE
, "Billing isn't supported");
if (mDebugLog) Log.d(TAG, "startSetup() billing is not available");
}
fireSetupFinished(listener, result);
} else { // no inventory check. Select store based on store parameters
if (mDebugLog) Log.d(TAG, "startSetup() No inventory check. stores: " + stores2check);
mAppstore = selectBillingService(stores2check);
if (mDebugLog) Log.d(TAG, "startSetup() selected store: " + mAppstore);
if (mAppstore == null) {
IabResult iabResult = new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "Billing isn't supported");
fireSetupFinished(listener, iabResult);
return;
}
mAppstoreBillingService = mAppstore.getInAppBillingService();
mAppstoreBillingService.startSetup(new OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
fireSetupFinished(listener, result);
}
});
}
}
}, "openiab-setup").start();
}
|
diff --git a/src/com/readytalk/olive/logic/OliveLogic.java b/src/com/readytalk/olive/logic/OliveLogic.java
index 4317f77..fcf89f1 100644
--- a/src/com/readytalk/olive/logic/OliveLogic.java
+++ b/src/com/readytalk/olive/logic/OliveLogic.java
@@ -1,192 +1,192 @@
package com.readytalk.olive.logic;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import com.readytalk.olive.model.User;
/**
* This is a nice, normal type of class. I call it logic because it is the type
* of place where you would want to write some "business logic". The sorts of
* things that a servlet would kick off. In this case, it's a ridiculous example
* that mocks me (and other older folks). Not that old, of course...
*
* All that said, this is a good sort of class to make to do things. I made the
* methods static because this will only be used in the HttpRequest/HttpResponse
* cycle that a user will initiate.
*
* I hope that makes sense, read on!
*
* @author mweaver
*/
public class OliveLogic {
/**
* I don't use this method in my example, but this would be an excellent
* place to put some logic that:
*
* 1) Connects to a database. 2) Validates a username and password. 3)
* returns some value.
*
* I use a boolean here, but an enum that you write would be heaps better!
*
* @param username
* @param password
* @return
*/
public static Boolean isAuthorized(User user) {
try{
Connection conn = getDBConnection();
Statement st = conn.createStatement();
String s = "USE OliveData;";
st.executeUpdate(s);
s = "SELECT Username FROM Accounts WHERE Username = '"
+user.getUsername()+"' AND Password = '"+user.getPassword()+"';";
ResultSet r = st.executeQuery(s);
if(r.first()){
closeConnection(conn);
- return "Welcome!";
+ return true;
}
else{
closeConnection(conn);
- return "Incorrect username and/or password.";
+ return false;
}
}catch (Exception e) { e.printStackTrace(); }
/*if (user.getUsername().equals("olive")
&& user.getPassword().equals("evilo")) {
return true;
} else {
return false;
}*/
/*
* try { Statement stmt = null;
*
* // Register the JDBC driver for MySQL.
* Class.forName("com.mysql.jdbc.Driver");
*
* // Define URL of database server for // database named mysql on the
* localhost // with the default port number 3306. String url =
* "jdbc:mysql://localhost:3306/testDB";
*
* // Get a connection to the database for a // user named root with a
* blank password. // This user is the default administrator // having
* full privileges to do anything. Connection con =
* DriverManager.getConnection(url, "root", "olive");
*
* // Display URL and connection information System.out.println("URL: "
* + url); System.out.println("Connection: " + con); stmt =
* con.createStatement();
*
* stmt.executeUpdate("CREATE TABLE myTable(test_id int," +
* "test_val char(15) not null)");
* stmt.executeUpdate("INSERT INTO myTable(test_id, " +
* "test_val) VALUES(2,'Two')");
* stmt.executeUpdate("INSERT INTO myTable(test_id, " +
* "test_val) VALUES(3,'Three')");
* stmt.executeUpdate("INSERT INTO myTable(test_id, " +
* "test_val) VALUES(4,'Four')");
* stmt.executeUpdate("INSERT INTO myTable(test_id, " +
* "test_val) VALUES(5,'Five')");
*
* try { stmt.executeUpdate("DROP TABLE myTable"); } catch (Exception e)
* { System.out.print(e);
* System.out.println("No existing table to delete"); }
*
* } catch (Exception e) { e.printStackTrace(); }
*/
- return "error!";
+ return false; // Error!
}
public static Connection getDBConnection(){
try{
Context initCtx = new InitialContext();
DataSource ds = (DataSource)initCtx.lookup("java:comp/env/jdbc/OliveData");
return ds.getConnection();
}catch (Exception e) { e.printStackTrace(); }
return null;
}
public static void closeConnection(Connection c){
try{
c.close();
}catch (Exception e) { e.printStackTrace(); }
}
public static void AddAccount(String username, String password, String name, String email){
try{
Connection conn = getDBConnection();
Statement st = conn.createStatement();
String s = "USE OliveData;";
st.executeUpdate(s);
s = "INSERT INTO Accounts (Username, Password, Name, Email)" +
"VALUES ('"+username+"', '"+password+"' , '"+name+"', '"+email+"');";
st.executeUpdate(s);
closeConnection(conn);
}catch (Exception e) { e.printStackTrace(); }
}
public static void AddProject(String name, int AccountID, String icon){
try{
Connection conn = getDBConnection();
Statement st = conn.createStatement();
String s = "USE OliveData;";
st.executeUpdate(s);
s = "INSERT INTO Projects (Name, AccountID, Icon)" +
"VALUES ('"+name+"', '"+AccountID+"' , '"+icon+"');";
st.executeUpdate(s);
closeConnection(conn);
}catch (Exception e) { e.printStackTrace(); }
}
public static void AddVideo(String name,String URL,int ProjectID,String icon){
try{
Connection conn = getDBConnection();
Statement st = conn.createStatement();
String s = "USE OliveData;";
st.executeUpdate(s);
s = "INSERT INTO Videos (Name, URL, ProjectID, Icon)" +
"VALUES ('"+name+"', '"+URL+"', '"+ProjectID+"' , '"+icon+"');";
st.executeUpdate(s);
closeConnection(conn);
}catch (Exception e) { e.printStackTrace(); }
}
public static void deleteAccount(User user){
try{
Connection conn = getDBConnection();
Statement st = conn.createStatement();
String s = "USE OliveData;";
st.executeUpdate(s);
s = "DELETE FROM Accounts WHERE" +
"username = '"+user.getUsername()+"';"; //Need to add error checking
st.executeUpdate(s);
closeConnection(conn);
}catch (Exception e) { e.printStackTrace(); }
}
public static void deleteProject(String name, int AccountID){
try{
Connection conn = getDBConnection();
Statement st = conn.createStatement();
String s = "USE OliveData;";
st.executeUpdate(s);
s = "DELETE FROM Projects WHERE" +
"Name = '"+name+"' AND AccountID = '"+AccountID+"';"; //Need to add error checking
st.executeUpdate(s);
closeConnection(conn);
}catch (Exception e) { e.printStackTrace(); }
}
public static void deleteVideo(String URL){
try{
Connection conn = getDBConnection();
Statement st = conn.createStatement();
String s = "USE OliveData;";
st.executeUpdate(s);
s = "DELETE FROM Videos WHERE" +
"URL = '"+URL+"';"; //Need to add error checking
st.executeUpdate(s);
closeConnection(conn);
}catch (Exception e) { e.printStackTrace(); }
}
}
| false | true |
public static Boolean isAuthorized(User user) {
try{
Connection conn = getDBConnection();
Statement st = conn.createStatement();
String s = "USE OliveData;";
st.executeUpdate(s);
s = "SELECT Username FROM Accounts WHERE Username = '"
+user.getUsername()+"' AND Password = '"+user.getPassword()+"';";
ResultSet r = st.executeQuery(s);
if(r.first()){
closeConnection(conn);
return "Welcome!";
}
else{
closeConnection(conn);
return "Incorrect username and/or password.";
}
}catch (Exception e) { e.printStackTrace(); }
/*if (user.getUsername().equals("olive")
&& user.getPassword().equals("evilo")) {
return true;
} else {
return false;
}*/
/*
* try { Statement stmt = null;
*
* // Register the JDBC driver for MySQL.
* Class.forName("com.mysql.jdbc.Driver");
*
* // Define URL of database server for // database named mysql on the
* localhost // with the default port number 3306. String url =
* "jdbc:mysql://localhost:3306/testDB";
*
* // Get a connection to the database for a // user named root with a
* blank password. // This user is the default administrator // having
* full privileges to do anything. Connection con =
* DriverManager.getConnection(url, "root", "olive");
*
* // Display URL and connection information System.out.println("URL: "
* + url); System.out.println("Connection: " + con); stmt =
* con.createStatement();
*
* stmt.executeUpdate("CREATE TABLE myTable(test_id int," +
* "test_val char(15) not null)");
* stmt.executeUpdate("INSERT INTO myTable(test_id, " +
* "test_val) VALUES(2,'Two')");
* stmt.executeUpdate("INSERT INTO myTable(test_id, " +
* "test_val) VALUES(3,'Three')");
* stmt.executeUpdate("INSERT INTO myTable(test_id, " +
* "test_val) VALUES(4,'Four')");
* stmt.executeUpdate("INSERT INTO myTable(test_id, " +
* "test_val) VALUES(5,'Five')");
*
* try { stmt.executeUpdate("DROP TABLE myTable"); } catch (Exception e)
* { System.out.print(e);
* System.out.println("No existing table to delete"); }
*
* } catch (Exception e) { e.printStackTrace(); }
*/
return "error!";
}
|
public static Boolean isAuthorized(User user) {
try{
Connection conn = getDBConnection();
Statement st = conn.createStatement();
String s = "USE OliveData;";
st.executeUpdate(s);
s = "SELECT Username FROM Accounts WHERE Username = '"
+user.getUsername()+"' AND Password = '"+user.getPassword()+"';";
ResultSet r = st.executeQuery(s);
if(r.first()){
closeConnection(conn);
return true;
}
else{
closeConnection(conn);
return false;
}
}catch (Exception e) { e.printStackTrace(); }
/*if (user.getUsername().equals("olive")
&& user.getPassword().equals("evilo")) {
return true;
} else {
return false;
}*/
/*
* try { Statement stmt = null;
*
* // Register the JDBC driver for MySQL.
* Class.forName("com.mysql.jdbc.Driver");
*
* // Define URL of database server for // database named mysql on the
* localhost // with the default port number 3306. String url =
* "jdbc:mysql://localhost:3306/testDB";
*
* // Get a connection to the database for a // user named root with a
* blank password. // This user is the default administrator // having
* full privileges to do anything. Connection con =
* DriverManager.getConnection(url, "root", "olive");
*
* // Display URL and connection information System.out.println("URL: "
* + url); System.out.println("Connection: " + con); stmt =
* con.createStatement();
*
* stmt.executeUpdate("CREATE TABLE myTable(test_id int," +
* "test_val char(15) not null)");
* stmt.executeUpdate("INSERT INTO myTable(test_id, " +
* "test_val) VALUES(2,'Two')");
* stmt.executeUpdate("INSERT INTO myTable(test_id, " +
* "test_val) VALUES(3,'Three')");
* stmt.executeUpdate("INSERT INTO myTable(test_id, " +
* "test_val) VALUES(4,'Four')");
* stmt.executeUpdate("INSERT INTO myTable(test_id, " +
* "test_val) VALUES(5,'Five')");
*
* try { stmt.executeUpdate("DROP TABLE myTable"); } catch (Exception e)
* { System.out.print(e);
* System.out.println("No existing table to delete"); }
*
* } catch (Exception e) { e.printStackTrace(); }
*/
return false; // Error!
}
|
diff --git a/codegen/src/main/java/org/exolab/castor/builder/JClassRegistry.java b/codegen/src/main/java/org/exolab/castor/builder/JClassRegistry.java
index 55981092..a06c89e5 100644
--- a/codegen/src/main/java/org/exolab/castor/builder/JClassRegistry.java
+++ b/codegen/src/main/java/org/exolab/castor/builder/JClassRegistry.java
@@ -1,489 +1,490 @@
/*
* Copyright 2007 Werner Guttmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.exolab.castor.builder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.exolab.castor.builder.binding.ExtendedBinding;
import org.exolab.castor.builder.binding.XMLBindingComponent;
import org.exolab.castor.builder.binding.XPathHelper;
import org.exolab.castor.builder.binding.xml.Exclude;
import org.exolab.castor.builder.conflict.strategy.ClassNameConflictResolver;
import org.exolab.castor.builder.conflict.strategy.XPATHClassNameConflictResolver;
import org.exolab.castor.xml.JavaNaming;
import org.exolab.castor.xml.schema.Annotated;
import org.exolab.castor.xml.schema.ElementDecl;
import org.exolab.castor.xml.schema.Group;
import org.exolab.castor.xml.schema.ModelGroup;
import org.exolab.castor.xml.schema.Order;
import org.exolab.castor.xml.schema.XMLType;
import org.exolab.javasource.JClass;
/**
* A registry for maintaing information about {@link JClass} instances already
* processed.
*
* @author <a href="mailto:werner DOT guttmann AT gmx DOT net">Werner Guttmann</a>
* @since 1.1
*/
public class JClassRegistry {
/**
* Logger instance used for all logging functionality.
*/
private static final Log LOG = LogFactory.getLog(JClassRegistry.class);
/**
* Registry for holding a set of global element definitions.
*/
private Set _globalElements = new HashSet();
/**
* Registry for mapping an XPATH location to a {@link JClass} instance
* generated for the XML artefact uniquely identified by the XPATH.
*/
private Map _xpathToJClass = new HashMap();
/**
* Registry for recording naming collisions, keyed by the local part of an
* otherwise rooted XPATH.
*/
private Map _localNames = new HashMap();
/**
* Registry for recording naming collisions, keyed by the typed local part of an
* otherwise rooted XPATH.
*/
private Map _typedLocalNames = new HashMap();
/**
* Class name conflict resolver.
*/
private ClassNameConflictResolver _classNameConflictResolver =
new XPATHClassNameConflictResolver();
/**
* Registers the XPATH identifier for a global element definition for
* further use.
*
* @param xpath
* The XPATH identifier of a global element.
*/
public void prebindGlobalElement(final String xpath) {
_globalElements.add(xpath);
}
/**
* Creates an instance of this class, providing the class anme conflict
* resolver to be used during automatic class name conflict resolution
* (for local element conflicts).
* @param resolver {@link ClassNameConflictResolver} instance to be used
*/
public JClassRegistry(final ClassNameConflictResolver resolver) {
_classNameConflictResolver = resolver;
}
/**
* Registers a {@link JClass} instance for a given XPATH.
*
* @param jClass
* The {@link JClass} instance to register.
* @param component
* Container for the {@link Annotated} instance referred to by the XPATH.
* @param mode Whether we register JClass instances in 'field' or 'class'mode.
*/
public void bind(final JClass jClass, final XMLBindingComponent component,
final String mode) {
Annotated annotated = component.getAnnotated();
// String xPath = XPathHelper.getSchemaLocation(annotated);
String xPath = XPathHelper.getSchemaLocation(annotated, true);
String localXPath = getLocalXPath(xPath);
String untypedXPath = xPath;
//TODO: it could happen that we silently ignore a custom package as defined in a binding - FIX !
// get local name
String localName = getLocalName(xPath);
String typedLocalName = localName;
if (annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
String typexPath = XPathHelper.getSchemaLocation(element.getType());
xPath += "[" + typexPath + "]";
typedLocalName += "[" + typexPath + "]";
} else if (annotated instanceof Group) {
Group group = (Group) annotated;
if (group.getOrder().getType() == Order.CHOICE
&& !_globalElements.contains("/" + localXPath)) {
xPath += "/#choice";
}
}
ExtendedBinding binding = component.getBinding();
if (binding != null) {
// deal with explicit exclusions
if (binding.existsExclusion(typedLocalName)) {
Exclude exclusion = binding.getExclusion(typedLocalName);
if (exclusion.getClassName() != null) {
LOG.info("Dealing with exclusion for local element " + xPath
+ " as per binding file.");
jClass.changeLocalName(exclusion.getClassName());
}
return;
}
// deal with explicit forces
if (binding.existsForce(localName)) {
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
LOG.info("Changing class name for local element " + xPath
+ " as per binding file (force).");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
return;
}
}
String jClassLocalName = jClass.getLocalName();
String expectedClassNameDerivedFromXPath = JavaNaming.toJavaClassName(localName);
if (!jClassLocalName.equals(expectedClassNameDerivedFromXPath)) {
if (component.createGroupItem()) {
xPath += "/#item";
}
_xpathToJClass.put(xPath, jClass);
return;
}
if (mode.equals("field")) {
if (annotated instanceof ModelGroup) {
ModelGroup group = (ModelGroup) annotated;
final boolean isReference = group.isReference();
if (isReference) {
return;
}
}
if (annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
final boolean isReference = element.isReference();
if (isReference) {
ElementDecl referredElement = element.getReference();
// if that global element definition is a substitution head,
// we now
// need to do work out the global element's type, and use
// its
// JClass instance to defer the type of the member currently
// processed
Enumeration possibleSubstitutes = referredElement
.getSubstitutionGroupMembers();
if (possibleSubstitutes.hasMoreElements()) {
XMLType referredType = referredElement.getType();
String xPathType = XPathHelper.getSchemaLocation(referredType);
JClass typeJClass = (JClass) _xpathToJClass
.get(xPathType);
if (typeJClass != null) {
jClass.changeLocalName(typeJClass.getLocalName());
} else {
// manually deriving class name for referenced type
XMLBindingComponent temp = component;
temp.setView(referredType);
jClass.changeLocalName(temp.getJavaClassName());
+ component.setView(annotated);
}
// String typeXPath = XPathHelper
// .getSchemaLocation(referredElement);
// JClass referredJClass = (JClass) _xpathToJClass
// .get(typeXPath + "_class");
// jClass.changeLocalName(referredJClass.getSuperClass()
// .getLocalName());
}
return;
}
}
}
final boolean alreadyProcessed = _xpathToJClass.containsKey(xPath);
// if already processed, change the JClass instance accordingly
if (alreadyProcessed) {
JClass jClassAlreadyProcessed = (JClass) _xpathToJClass.get(xPath);
jClass.changeLocalName(jClassAlreadyProcessed.getLocalName());
return;
}
// register JClass instance for XPATH
_xpathToJClass.put(xPath, jClass);
LOG.debug("Binding JClass[" + jClass.getName() + "] for XML schema structure " + xPath);
// global elements don't need to change
final boolean isGlobalElement = _globalElements.contains(untypedXPath);
if (isGlobalElement) {
return;
}
// resolve references to global elements
if (mode.equals("field") && annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
final boolean isReference = element.isReference();
if (isReference) {
ElementDecl referredElement = element.getReference();
// if that global element definition is a substitution head, we
// now
// need to do work out the global element's type, and use its
// JClass instance to defer the type of the member currently
// processed
Enumeration possibleSubstitutes = referredElement
.getSubstitutionGroupMembers();
if (possibleSubstitutes.hasMoreElements()) {
String typeXPath = XPathHelper
.getSchemaLocation(referredElement);
JClass referredJClass = (JClass) _xpathToJClass
.get(typeXPath + "_class");
jClass.changeLocalName(referredJClass.getSuperClass()
.getLocalName());
}
return;
}
}
// resolve conflict with a global element
final boolean conflictExistsWithGlobalElement = _globalElements
.contains("/" + localXPath);
if (conflictExistsWithGlobalElement) {
LOG.info("Resolving conflict for local element " + xPath + " against global element.");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
// remember that we had a collision for this local element
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
return;
}
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
if (localNamesList == null) {
String typedJClassName = (String) _typedLocalNames.get(typedLocalName);
if (typedJClassName == null) {
_typedLocalNames.put(typedLocalName, jClass.getName());
}
} else {
LOG.info("Resolving conflict for local element " + xPath
+ " against another local element of the same name.");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
}
}
/**
* Memorize that we have a collision for the 'local name' given.
* @param xPath Full (typed) XPATH identifier for the local element definition.
* @param localName Local element name
* @param localNamesList Collection store for collisions for that 'local name'.
*/
private void memorizeCollision(final String xPath, final String localName,
final List localNamesList) {
// resolve conflict with another element
if (localNamesList == null) {
// this name never occured before
ArrayList arrayList = new ArrayList();
arrayList.add(xPath);
_localNames.put(localName, arrayList);
} else {
// this entry should be renamed
if (!localNamesList.contains(xPath)) {
localNamesList.add(xPath);
}
}
}
/**
* Check and change (suggested) class name.
* @param jClass {@link JClass} instance
* @param annotated {@link Annotated} instance
* @param untypedXPath blah
* @param typedLocalName blah
*/
private void checkAndChange(final JClass jClass, final Annotated annotated,
final String untypedXPath, final String typedLocalName) {
// check whether we have seen that typed local name already
String typedJClassName = (String) _typedLocalNames.get(typedLocalName);
if (typedJClassName != null) {
// if so, simple re-use it by changing the local class name
String localClassName =
typedJClassName.substring(typedJClassName.lastIndexOf(".") + 1);
jClass.changeLocalName(localClassName);
} else {
// 'calculate' a new class name
changeClassInfoAsResultOfConflict(jClass, untypedXPath, typedLocalName, annotated);
// store it for further use
_typedLocalNames.put(typedLocalName, jClass.getName());
}
}
/**
* Returns the local name of rooted XPATH expression.
*
* @param xPath
* An (rooted) XPATH expression
* @return the local name
*/
private String getLocalName(final String xPath) {
String localName = xPath.substring(xPath.lastIndexOf("/") + 1);
if (localName.startsWith(ExtendedBinding.COMPLEXTYPE_ID)
|| localName.startsWith(ExtendedBinding.SIMPLETYPE_ID)
|| localName.startsWith(ExtendedBinding.ENUMTYPE_ID)
|| localName.startsWith(ExtendedBinding.GROUP_ID)) {
localName = localName.substring(localName.indexOf(":") + 1);
}
return localName;
}
/**
* Returns the local part of rooted XPATH expression.
*
* @param xPath
* An (rooted) XPATH expression
* @return the local part
*/
private String getLocalXPath(final String xPath) {
return xPath.substring(xPath.lastIndexOf("/") + 1);
}
/**
* Changes the JClass' internal class name, as a result of an XPATH
* expression uniquely identifying an XML artefact within an XML schema.
*
* @param jClass
* The {@link JClass} instance whose local name should be
* changed.
* @param xpath
* XPATH expression used to defer the new local class name
* @param typedXPath
* Typed XPATH expression used to defer the new local class name
* @param annotated {@link Annotated} instance
*/
private void changeClassInfoAsResultOfConflict(final JClass jClass,
final String xpath, final String typedXPath, final Annotated annotated) {
_classNameConflictResolver.changeClassInfoAsResultOfConflict(jClass, xpath,
typedXPath, annotated);
}
/**
* Sets the {@link ClassNameConflictResolver} insatnce to be used.
* @param conflictResolver {@link ClassNameConflictResolver} insatnce to be used.
*/
public void setClassNameConflictResolver(final ClassNameConflictResolver conflictResolver) {
_classNameConflictResolver = conflictResolver;
}
/**
* Utility method to hgather and output statistical information about naming
* collisions occured during source code generation.
* @param binding {@link XMLBindingComponent} instance
*/
public void printStatistics(final XMLBindingComponent binding) {
Iterator keyIterator = _localNames.keySet().iterator();
LOG.info("*** Summary ***");
if (binding.getBinding() != null
&& binding.getBinding().getForces() != null
&& binding.getBinding().getForces().size() > 0) {
Iterator forceIterator = binding.getBinding().getForces().iterator();
LOG.info("The following 'forces' have been enabled:");
while (forceIterator.hasNext()) {
String forceValue = (String) forceIterator.next();
LOG.info(forceValue);
}
}
if (keyIterator.hasNext()) {
LOG.info("Local name conflicts encountered for the following element definitions");
while (keyIterator.hasNext()) {
String localName = (String) keyIterator.next();
List collisions = (List) _localNames.get(localName);
if (collisions.size() > 1 && !ofTheSameType(collisions)) {
LOG.info(localName
+ ", with the following (element) definitions being involved:");
for (Iterator iter = collisions.iterator(); iter.hasNext(); ) {
String xPath = (String) iter.next();
LOG.info(xPath);
}
}
}
}
keyIterator = _localNames.keySet().iterator();
if (keyIterator.hasNext()) {
StringBuffer xmlFragment = new StringBuffer();
xmlFragment.append("<forces>\n");
while (keyIterator.hasNext()) {
String localName = (String) keyIterator.next();
List collisions = (List) _localNames.get(localName);
if (collisions.size() > 1 && !ofTheSameType(collisions)) {
xmlFragment.append(" <force>");
xmlFragment.append(localName);
xmlFragment.append("</force>\n");
}
}
xmlFragment.append("</forces>");
LOG.info(xmlFragment.toString());
}
}
/**
* Indicates whether all XPATH entries within the list of collisions are of the same type.
* @param collisions The list of XPATH (collidings) for a local element name
* @return True if all are of the same type.
*/
private boolean ofTheSameType(final List collisions) {
boolean allSame = true;
Iterator iterator = collisions.iterator();
String typeString = null;
while (iterator.hasNext()) {
String xPath = (String) iterator.next();
String newTypeString = xPath.substring(xPath.indexOf("[") + 1,
xPath.indexOf("]"));
if (typeString != null) {
if (!typeString.equals(newTypeString)) {
allSame = false;
break;
}
} else {
typeString = newTypeString;
}
}
return allSame;
}
}
| true | true |
public void bind(final JClass jClass, final XMLBindingComponent component,
final String mode) {
Annotated annotated = component.getAnnotated();
// String xPath = XPathHelper.getSchemaLocation(annotated);
String xPath = XPathHelper.getSchemaLocation(annotated, true);
String localXPath = getLocalXPath(xPath);
String untypedXPath = xPath;
//TODO: it could happen that we silently ignore a custom package as defined in a binding - FIX !
// get local name
String localName = getLocalName(xPath);
String typedLocalName = localName;
if (annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
String typexPath = XPathHelper.getSchemaLocation(element.getType());
xPath += "[" + typexPath + "]";
typedLocalName += "[" + typexPath + "]";
} else if (annotated instanceof Group) {
Group group = (Group) annotated;
if (group.getOrder().getType() == Order.CHOICE
&& !_globalElements.contains("/" + localXPath)) {
xPath += "/#choice";
}
}
ExtendedBinding binding = component.getBinding();
if (binding != null) {
// deal with explicit exclusions
if (binding.existsExclusion(typedLocalName)) {
Exclude exclusion = binding.getExclusion(typedLocalName);
if (exclusion.getClassName() != null) {
LOG.info("Dealing with exclusion for local element " + xPath
+ " as per binding file.");
jClass.changeLocalName(exclusion.getClassName());
}
return;
}
// deal with explicit forces
if (binding.existsForce(localName)) {
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
LOG.info("Changing class name for local element " + xPath
+ " as per binding file (force).");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
return;
}
}
String jClassLocalName = jClass.getLocalName();
String expectedClassNameDerivedFromXPath = JavaNaming.toJavaClassName(localName);
if (!jClassLocalName.equals(expectedClassNameDerivedFromXPath)) {
if (component.createGroupItem()) {
xPath += "/#item";
}
_xpathToJClass.put(xPath, jClass);
return;
}
if (mode.equals("field")) {
if (annotated instanceof ModelGroup) {
ModelGroup group = (ModelGroup) annotated;
final boolean isReference = group.isReference();
if (isReference) {
return;
}
}
if (annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
final boolean isReference = element.isReference();
if (isReference) {
ElementDecl referredElement = element.getReference();
// if that global element definition is a substitution head,
// we now
// need to do work out the global element's type, and use
// its
// JClass instance to defer the type of the member currently
// processed
Enumeration possibleSubstitutes = referredElement
.getSubstitutionGroupMembers();
if (possibleSubstitutes.hasMoreElements()) {
XMLType referredType = referredElement.getType();
String xPathType = XPathHelper.getSchemaLocation(referredType);
JClass typeJClass = (JClass) _xpathToJClass
.get(xPathType);
if (typeJClass != null) {
jClass.changeLocalName(typeJClass.getLocalName());
} else {
// manually deriving class name for referenced type
XMLBindingComponent temp = component;
temp.setView(referredType);
jClass.changeLocalName(temp.getJavaClassName());
}
// String typeXPath = XPathHelper
// .getSchemaLocation(referredElement);
// JClass referredJClass = (JClass) _xpathToJClass
// .get(typeXPath + "_class");
// jClass.changeLocalName(referredJClass.getSuperClass()
// .getLocalName());
}
return;
}
}
}
final boolean alreadyProcessed = _xpathToJClass.containsKey(xPath);
// if already processed, change the JClass instance accordingly
if (alreadyProcessed) {
JClass jClassAlreadyProcessed = (JClass) _xpathToJClass.get(xPath);
jClass.changeLocalName(jClassAlreadyProcessed.getLocalName());
return;
}
// register JClass instance for XPATH
_xpathToJClass.put(xPath, jClass);
LOG.debug("Binding JClass[" + jClass.getName() + "] for XML schema structure " + xPath);
// global elements don't need to change
final boolean isGlobalElement = _globalElements.contains(untypedXPath);
if (isGlobalElement) {
return;
}
// resolve references to global elements
if (mode.equals("field") && annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
final boolean isReference = element.isReference();
if (isReference) {
ElementDecl referredElement = element.getReference();
// if that global element definition is a substitution head, we
// now
// need to do work out the global element's type, and use its
// JClass instance to defer the type of the member currently
// processed
Enumeration possibleSubstitutes = referredElement
.getSubstitutionGroupMembers();
if (possibleSubstitutes.hasMoreElements()) {
String typeXPath = XPathHelper
.getSchemaLocation(referredElement);
JClass referredJClass = (JClass) _xpathToJClass
.get(typeXPath + "_class");
jClass.changeLocalName(referredJClass.getSuperClass()
.getLocalName());
}
return;
}
}
// resolve conflict with a global element
final boolean conflictExistsWithGlobalElement = _globalElements
.contains("/" + localXPath);
if (conflictExistsWithGlobalElement) {
LOG.info("Resolving conflict for local element " + xPath + " against global element.");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
// remember that we had a collision for this local element
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
return;
}
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
if (localNamesList == null) {
String typedJClassName = (String) _typedLocalNames.get(typedLocalName);
if (typedJClassName == null) {
_typedLocalNames.put(typedLocalName, jClass.getName());
}
} else {
LOG.info("Resolving conflict for local element " + xPath
+ " against another local element of the same name.");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
}
}
|
public void bind(final JClass jClass, final XMLBindingComponent component,
final String mode) {
Annotated annotated = component.getAnnotated();
// String xPath = XPathHelper.getSchemaLocation(annotated);
String xPath = XPathHelper.getSchemaLocation(annotated, true);
String localXPath = getLocalXPath(xPath);
String untypedXPath = xPath;
//TODO: it could happen that we silently ignore a custom package as defined in a binding - FIX !
// get local name
String localName = getLocalName(xPath);
String typedLocalName = localName;
if (annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
String typexPath = XPathHelper.getSchemaLocation(element.getType());
xPath += "[" + typexPath + "]";
typedLocalName += "[" + typexPath + "]";
} else if (annotated instanceof Group) {
Group group = (Group) annotated;
if (group.getOrder().getType() == Order.CHOICE
&& !_globalElements.contains("/" + localXPath)) {
xPath += "/#choice";
}
}
ExtendedBinding binding = component.getBinding();
if (binding != null) {
// deal with explicit exclusions
if (binding.existsExclusion(typedLocalName)) {
Exclude exclusion = binding.getExclusion(typedLocalName);
if (exclusion.getClassName() != null) {
LOG.info("Dealing with exclusion for local element " + xPath
+ " as per binding file.");
jClass.changeLocalName(exclusion.getClassName());
}
return;
}
// deal with explicit forces
if (binding.existsForce(localName)) {
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
LOG.info("Changing class name for local element " + xPath
+ " as per binding file (force).");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
return;
}
}
String jClassLocalName = jClass.getLocalName();
String expectedClassNameDerivedFromXPath = JavaNaming.toJavaClassName(localName);
if (!jClassLocalName.equals(expectedClassNameDerivedFromXPath)) {
if (component.createGroupItem()) {
xPath += "/#item";
}
_xpathToJClass.put(xPath, jClass);
return;
}
if (mode.equals("field")) {
if (annotated instanceof ModelGroup) {
ModelGroup group = (ModelGroup) annotated;
final boolean isReference = group.isReference();
if (isReference) {
return;
}
}
if (annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
final boolean isReference = element.isReference();
if (isReference) {
ElementDecl referredElement = element.getReference();
// if that global element definition is a substitution head,
// we now
// need to do work out the global element's type, and use
// its
// JClass instance to defer the type of the member currently
// processed
Enumeration possibleSubstitutes = referredElement
.getSubstitutionGroupMembers();
if (possibleSubstitutes.hasMoreElements()) {
XMLType referredType = referredElement.getType();
String xPathType = XPathHelper.getSchemaLocation(referredType);
JClass typeJClass = (JClass) _xpathToJClass
.get(xPathType);
if (typeJClass != null) {
jClass.changeLocalName(typeJClass.getLocalName());
} else {
// manually deriving class name for referenced type
XMLBindingComponent temp = component;
temp.setView(referredType);
jClass.changeLocalName(temp.getJavaClassName());
component.setView(annotated);
}
// String typeXPath = XPathHelper
// .getSchemaLocation(referredElement);
// JClass referredJClass = (JClass) _xpathToJClass
// .get(typeXPath + "_class");
// jClass.changeLocalName(referredJClass.getSuperClass()
// .getLocalName());
}
return;
}
}
}
final boolean alreadyProcessed = _xpathToJClass.containsKey(xPath);
// if already processed, change the JClass instance accordingly
if (alreadyProcessed) {
JClass jClassAlreadyProcessed = (JClass) _xpathToJClass.get(xPath);
jClass.changeLocalName(jClassAlreadyProcessed.getLocalName());
return;
}
// register JClass instance for XPATH
_xpathToJClass.put(xPath, jClass);
LOG.debug("Binding JClass[" + jClass.getName() + "] for XML schema structure " + xPath);
// global elements don't need to change
final boolean isGlobalElement = _globalElements.contains(untypedXPath);
if (isGlobalElement) {
return;
}
// resolve references to global elements
if (mode.equals("field") && annotated instanceof ElementDecl) {
ElementDecl element = (ElementDecl) annotated;
final boolean isReference = element.isReference();
if (isReference) {
ElementDecl referredElement = element.getReference();
// if that global element definition is a substitution head, we
// now
// need to do work out the global element's type, and use its
// JClass instance to defer the type of the member currently
// processed
Enumeration possibleSubstitutes = referredElement
.getSubstitutionGroupMembers();
if (possibleSubstitutes.hasMoreElements()) {
String typeXPath = XPathHelper
.getSchemaLocation(referredElement);
JClass referredJClass = (JClass) _xpathToJClass
.get(typeXPath + "_class");
jClass.changeLocalName(referredJClass.getSuperClass()
.getLocalName());
}
return;
}
}
// resolve conflict with a global element
final boolean conflictExistsWithGlobalElement = _globalElements
.contains("/" + localXPath);
if (conflictExistsWithGlobalElement) {
LOG.info("Resolving conflict for local element " + xPath + " against global element.");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
// remember that we had a collision for this local element
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
return;
}
List localNamesList = (List) _localNames.get(localName);
memorizeCollision(xPath, localName, localNamesList);
if (localNamesList == null) {
String typedJClassName = (String) _typedLocalNames.get(typedLocalName);
if (typedJClassName == null) {
_typedLocalNames.put(typedLocalName, jClass.getName());
}
} else {
LOG.info("Resolving conflict for local element " + xPath
+ " against another local element of the same name.");
checkAndChange(jClass, annotated, untypedXPath, typedLocalName);
}
}
|
diff --git a/src/xtremweb/role/examples/akratos/Akratos.java b/src/xtremweb/role/examples/akratos/Akratos.java
index 11f91ff..c73bd83 100644
--- a/src/xtremweb/role/examples/akratos/Akratos.java
+++ b/src/xtremweb/role/examples/akratos/Akratos.java
@@ -1,728 +1,735 @@
package xtremweb.role.examples.akratos;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.Hashtable;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.xml.sax.SAXException;
import xtremweb.role.examples.akratos.exception.AkratosException;
import xtremweb.role.examples.akratos.pojo.Contact;
import xtremweb.role.examples.akratos.pojo.Contacts;
import xtremweb.role.examples.akratos.pojo.PersonalInfo;
import xtremweb.role.examples.akratos.pojo.User;
import xtremweb.role.examples.akratos.util.AkratosUtil;
import xtremweb.api.activedata.ActiveData;
import xtremweb.api.activedata.ActiveDataCallback;
import xtremweb.api.activedata.ActiveDataException;
import xtremweb.api.bitdew.BitDew;
import xtremweb.api.bitdew.BitDewException;
import xtremweb.api.transman.TransferManager;
import xtremweb.api.transman.TransferManagerException;
import xtremweb.core.com.idl.ComWorld;
import xtremweb.core.com.idl.ModuleLoaderException;
import xtremweb.core.iface.Interfacedc;
import xtremweb.core.iface.Interfacedr;
import xtremweb.core.iface.Interfaceds;
import xtremweb.core.iface.Interfacedt;
import xtremweb.core.log.Logger;
import xtremweb.core.obj.dc.Data;
import xtremweb.core.obj.ds.Attribute;
import xtremweb.serv.dt.OOBTransfer;
import xtremweb.core.conf.ConfigurationProperties;
import xtremweb.core.conf.ConfigurationException;
public class Akratos {
/**
* Class logger
*/
Logger log = Logger.getLogger("akr.inria.fr.pojo");
/**
* Bootstrap node
*/
private String bootstrap;
/**
* How many replicas of your public info do you want in the system ?
*/
private int REPLICA_PUBLICINFO = 2;
/**
* How many replcias of your ciphered-priviledged info do you want in the system ?
*/
private int REPLICA_PRIVILEGED_INFO = 2;
/**
* Private info prefix
*/
public static final String PRIVATE_INFO_PREFIX = "privateinfo_";
/**
* Postfix to recognize the aes key from the ciphered plain text
*/
public static final String AES_CIPHERED_POSTFIX = "aeskey_ciphered";
/**
* Your public info file path
*/
public static final String PUBLICINFO_XML = "data/publicinfo.xml";
/**
* Your personal info file path
*/
public static final String PERSONAL_INFO_XML = "personalinfo.xml";
/**
* In this file are stored your friends public keys
*/
public static final String PUBLICKEYS_XML = "data/publickeys.xml";
/**
* Your public key name
*/
public static final String PUBLIC_KEY = "data/akratos.pub";
/**
* Your private key name
*/
public static final String PRIVATE_KEY = "akratos.rsa";
/**
* Ciphered file prefix, each friend feed will have a different number
*/
public static final String CIPHERED_PREFIX = "ciphered_file_";
/**
* Your contact XML file; here is stored your contacts
*/
public static final String CONTACTS_XML = "contacts.xml";
/**
* BitDew API component
*/
private BitDew bitdew;
/**
* ActiveData API component
*/
private ActiveData activeData;
/**
* TransferManager API component
*/
private TransferManager transferManager;
/**
* Akratos constructor, initialize dr and dt in localhost, dc and ds in bootstrap node (we are using a DHT).
*/
public Akratos() {
try {
bootstrap = ConfigurationProperties.getProperties().getProperty("xtremweb.core.http.bootstrapNode");
String localhost = InetAddress.getLocalHost().getHostAddress();
Interfacedr dr = (Interfacedr) ComWorld.getComm(localhost, "rmi", 4325, "dr");
Interfaceds ds = (Interfaceds) ComWorld.getComm(bootstrap, "rmi", 4325, "ds");
Interfacedt dt = (Interfacedt) ComWorld.getComm(localhost, "rmi", 4325, "dt");
Interfacedc dc = (Interfacedc) ComWorld.getComm(bootstrap, "rmi", 4325, "dc");
bitdew = new BitDew(dc, dr, ds, true);
transferManager = new TransferManager(dt);
} catch (ModuleLoaderException e) {
e.printStackTrace();
} catch (ConfigurationException e) {
e.printStackTrace();
} catch (UnknownHostException e){
e.printStackTrace();
}
}
/**
* This constructor adds two handlers to each client of BitDew.
* @param mock
*/
public Akratos(String mock) {
Vector comms;
try {
bootstrap = ConfigurationProperties.getProperties().getProperty("xtremweb.core.http.bootstrapNode");
String localhost = InetAddress.getLocalHost().getHostAddress();
comms = ComWorld.getMultipleComms(localhost,"rmi",4325,"dr","dc","dt","ds");
Interfacedr dr = (Interfacedr) ComWorld.getComm(localhost, "rmi", 4325, "dr");
Interfacedt dt = (Interfacedt) ComWorld.getComm(localhost, "rmi", 4325, "dt");
Interfaceds ds = (Interfaceds) ComWorld.getComm(bootstrap, "rmi", 4325, "ds");
Interfacedc ddc = (Interfacedc) ComWorld.getComm(bootstrap, "rmi", 4325, "dc");
bitdew = new BitDew(ddc, dr, ds, true);
transferManager = new TransferManager(dt);
System.out.println(" In constructor boot is " + bootstrap);
activeData = new ActiveData(ddc, ds);
activeData.registerActiveDataCallback(new PublicInfoCallback());
activeData.registerActiveDataCallback(new PriviledgedInfoCallback(bootstrap));
} catch (ModuleLoaderException e) {
e.printStackTrace();
} catch (ConfigurationException e) {
e.printStackTrace();
}catch (UnknownHostException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
System.setProperty("PROPERTIES_FILE", "properties_peer.json");
if (args[0].equals("subscribe")){
Akratos akr = new Akratos("");
akr.subscribe(args[1]);
}
if (args[0].equals("fill"))
Akratos.fillFile(args[1]);
if (args[0].equals("drop")){
Akratos akr = new Akratos("");
akr.dropNews(args[1]);
}
if (args[0].equals("get")){
Akratos akr = new Akratos("");
akr.getNews(args[1]);
}
} catch (JAXBException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
/**
* This method generates a user public key and an user uid in Akratos
* @throws JAXBException if an exception occurs while parsing the XML document.
* @throws IOException if a IO exception appears
* @throws NoSuchAlgorithmException if an exception related to Checksum algorithm appears
*/
public static void fillFile(String file_name) throws JAXBException,IOException, NoSuchAlgorithmException {
User us = (User) AkratosUtil.unmarshall(User.class, file_name);
SecureRandom sr = new SecureRandom();
FileOutputStream fos = new FileOutputStream(new File(PRIVATE_KEY));
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024, sr);
KeyPair myPair = kpg.generateKeyPair();
PublicKey pukey = myPair.getPublic();
PrivateKey prkey = myPair.getPrivate();
byte[] bencPrivate = prkey.getEncoded();
byte[] pukeyblob = pukey.getEncoded();
String pukeystr = Base64.encodeBase64String(pukeyblob);
String prkeystr = Base64.encodeBase64String(bencPrivate);
IOUtils.write(prkeystr, fos);
us.setPublickey(pukeystr);
AkratosUtil.marshall(User.class, us, file_name);
}
/**
* This method subscribes you to the network, this means that a user POJO is
* generated from your publicinfo.xml and is published in the DHT.
* @param fileName the file name where you store your personal public information
*/
public void subscribe(String fileName) {
File f;
if (fileName == null || fileName.equals(""))
f = new File(PUBLICINFO_XML);
else
f = new File(fileName);
log.setLevel("debug");
File privatef = new File(Akratos.PERSONAL_INFO_XML);
User us;
try {
String localhost = InetAddress.getLocalHost().getHostAddress();
Data data_public_info = bitdew.createData(f);
Data data_private_info = bitdew.createData(privatef);
System.out.println("Bootstrap node is " + bootstrap);
data_public_info.setname("public_info");
us = (User) AkratosUtil.unmarshall(User.class, fileName);
us.setUid(data_public_info.getuid());
us.setPrivateuid(data_private_info.getuid());
AkratosUtil.marshall(User.class, us, fileName);
OOBTransfer oobt = bitdew.put(f, data_public_info, "http");
transferManager.start();
transferManager.registerTransfer(oobt);
transferManager.waitFor(data_public_info);
transferManager.stop();
bitdew.ddcPublish(us.getUid(), us);
bitdew.ddcPublish(us.getPublicname(), us);
bitdew.ddcPublish(us.getTag(), us);
log.info("information published ");
Attribute attr_public_info = activeData.createAttribute("{name: 'publicinfo', ft: true, replicat: "
+ REPLICA_PUBLICINFO + " }");
activeData.schedule(data_public_info, attr_public_info);
activeData.start();
} catch (JAXBException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BitDewException e) {
e.printStackTrace();
} catch (TransferManagerException e) {
e.printStackTrace();
} catch (ActiveDataException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* This method find you a contact according either its tag name (like in twitter), or
* by its complete name.
* @param tag
* @param public_name
* @return a list of people registered in the Network whose tag or complete name is equal to the
* one that you inserted.
*/
public List findFriend(String tag, String public_name) {
List ret = null;
try {
String localhost = InetAddress.getLocalHost().getHostAddress();
String searchBy = null;
if (tag != null && !tag.equals(""))
searchBy = tag;
if (public_name != null && !public_name.equals(""))
searchBy = public_name;
ret = bitdew.ddcSearch(searchBy);
} catch (BitDewException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
/**
* Add a contact to your contacts.xml file
* @param uid contact uid
* @param privateuid contact private uid,
* @param publicname contact public complete name
* @param tag contact tag name (like in twitter)
* @param pu_key contact public key in base64
* @param city contact city
* @param country contact residence country
* @param profession contact profession
*/
public void addFriend(String uid, String privateuid, String publicname, String tag, String pu_key, String city,
String country, String profession) {
try {
Contact c = new Contact(uid, privateuid, pu_key);
Contacts pks;
pks = (Contacts) AkratosUtil.unmarshall(Contacts.class, PUBLICKEYS_XML);
pks.addContact(c);
AkratosUtil.marshall(Contacts.class, pks, PUBLICKEYS_XML);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
}
/**
* This method send the user newsletter as an AES-ciphered XML file in the network. To achieve this,
* a public key list is maintained in contacts.xml file, the current user ciphers its XML file using a generated AES key that is cipehred
* with each of the public keys in the file system.
* @param public_file_name The file where you have your public personal information.
*/
public void dropNews(String public_file_name) {
try {
Contacts contacts;
User user = (User) AkratosUtil.unmarshall(User.class, public_file_name);
String thisuserid = user.getUid();
contacts = (Contacts) AkratosUtil.unmarshall(Contacts.class, CONTACTS_XML);
FileInputStream file = new FileInputStream(new File(PERSONAL_INFO_XML));
File personalinfo = new File(PERSONAL_INFO_XML);
Data data_personal_info = bitdew.createData(personalinfo);
String localhost = "127.0.0.1";
transferManager.start();
Interfacedr dr = (Interfacedr) ComWorld.getComm(localhost, "rmi", 4325, "dr");
Interfaceds ds = (Interfaceds) ComWorld.getComm(localhost, "rmi", 4325, "ds");
Interfacedc dc = (Interfacedc) ComWorld.getComm(localhost, "rmi", 4325, "dc");
BitDew bitdewlocal = new BitDew(dc, dr, ds);
for (int i = 0; i < contacts.getSize(); i++) {
Contact c = contacts.getContact(i);
// The personal info ciphered
String file_complete_name = thisuserid + "_" + c.getPrivateuid();
File personalinfociphered = new File(file_complete_name);
AkratosUtil.cipherAndWriteFile(file_complete_name, c.getPublickey(), file);
Data data_personal_info_ciphered = bitdewlocal.createData(personalinfociphered);
data_personal_info_ciphered.setname(c.getPrivateuid());
bitdew.ddcPublish(c.getPrivateuid(), data_personal_info_ciphered);
bitdew.ddcPublish(data_personal_info_ciphered.getchecksum(), InetAddress.getLocalHost()
.getHostAddress());
System.out.println(" dropped checksum " + data_personal_info_ciphered.getchecksum());
// The AES key ciphered
File aeskeyciphered = new File(file_complete_name + Akratos.AES_CIPHERED_POSTFIX);
Data data_aeskeyciphered = bitdewlocal.createData(aeskeyciphered);
data_aeskeyciphered.setname(c.getPrivateuid() + Akratos.AES_CIPHERED_POSTFIX);
bitdew.ddcPublish(data_aeskeyciphered.getchecksum(), InetAddress.getLocalHost().getHostAddress());
System.out.println(" dropped checksum " + data_aeskeyciphered.getchecksum());
// Put of the personal info file
OOBTransfer oob = bitdewlocal.put(personalinfociphered, data_personal_info_ciphered, "http");
transferManager.registerTransfer(oob);
transferManager.waitFor(data_personal_info_ciphered);
// Put of the AES key RSA-ciphered
oob = bitdewlocal.put(aeskeyciphered, data_aeskeyciphered, "http");
transferManager.registerTransfer(oob);
transferManager.waitFor(data_aeskeyciphered);
// scheduling
Attribute attr_personal_info = activeData.createAttribute("{ft: true, replicat: "
+ REPLICA_PRIVILEGED_INFO + " }");
Attribute attr_aes_key = activeData.createAttribute("{ft: true , affinity: '"
+ data_personal_info_ciphered.getuid() + "' }");
activeData.schedule(data_personal_info_ciphered, attr_personal_info);
activeData.schedule(data_aeskeyciphered, attr_aes_key);
bitdew.ddcPublish(c.getPrivateuid() + Akratos.AES_CIPHERED_POSTFIX, data_aeskeyciphered);
}
transferManager.stop();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (BitDewException e) {
e.printStackTrace();
} catch (ActiveDataException e) {
e.printStackTrace();
} catch (TransferManagerException e) {
e.printStackTrace();
} catch (ModuleLoaderException e){
e.printStackTrace();
}
}
/**
* This method is called whenever you want to get news from your friends. To achieve this,
* you must insert your private uid in the system, to get the files that has been directed
* to you by your friends. Then by inserting your privateuid_<AES_CIPHERED_POSTFIX> you can get
* the AES key associated to this ciphered file. You decrypt the AES key with your private key.
* @param file_name
*/
public void getNews(String file_name) {
User u;
PersonalInfo personal;
String plaintext = "";
Hashtable ht = new Hashtable();
String dataaff;
String ip="";
try {
Contacts contacts = (Contacts) AkratosUtil.unmarshall(Contacts.class, "contacts.xml");
u = (User) AkratosUtil.unmarshall(User.class, file_name);
// datas contains feed and replicas of your friends, need depurate
// to take only unique values
List<Data> plaindatas = bitdew.ddcSearch(u.getPrivateuid());
List<Data> aeskeys = bitdew.ddcSearch(u.getPrivateuid() + Akratos.AES_CIPHERED_POSTFIX);
System.out.println(" Size of aes keys" + aeskeys.size());
System.out.println(" Size of response : " + plaindatas.size());
List<Data> uniqdatas = AkratosUtil.getUniques(plaindatas);
List<Data> uniqaes = AkratosUtil.getUniques(aeskeys);
System.out.println("Uniq aes " + uniqaes.size() + " Uniq datas " + uniqdatas.size());
Hashtable<String, Data> hashdata = AkratosUtil.getDataHashTable(uniqdatas);
Hashtable<String, Data> hashaes = AkratosUtil.getDataHashTable(uniqaes);
// for each data name in the hash
transferManager.start();
for (int i = 0; i < uniqaes.size(); i++) {
+ Interfacedr dr = (Interfacedr) ComWorld.getComm(InetAddress.getLocalHost().getHostAddress(), "rmi", 4325, "dr");
+ Interfaceds ds = (Interfaceds) ComWorld.getComm(bootstrap, "rmi", 4325, "ds");
+ Interfacedt dt = (Interfacedt) ComWorld.getComm(InetAddress.getLocalHost().getHostAddress(), "rmi", 4325, "dt");
+ Interfacedc dc = (Interfacedc) ComWorld.getComm(bootstrap, "rmi", 4325, "dc");
+ bitdew = new BitDew(dc, dr, ds, true);
System.out.println("entro al ciclo");
Data pre_aes_key = (Data) uniqaes.get(i);
System.out.println("data before is " + pre_aes_key + " data attrid " + pre_aes_key.getattruid());
Attribute attr = bitdew.getAttributeByUid(pre_aes_key.getattruid());
System.out.println("Attribute is " + attr);
dataaff = attr.getaffinity();
Data pre_ciphered_info = hashdata.get(dataaff);
String md5info = pre_ciphered_info.getchecksum();
String md5aes = pre_aes_key.getchecksum();
List<String> ips = bitdew.ddcSearch(md5info);
boolean done = false;
for (int ind_ips = 0 ; ind_ips < ips.size() && !done; ind_ips ++ ){
try{
ip = ips.get(0);
System.out.println("ip to connect with " + ip);
- Interfacedc dc = (Interfacedc) ComWorld.getComm(ip, "rmi", 4325, "dc");
- Interfacedr dr = (Interfacedr) ComWorld.getComm(ip, "rmi", 4325, "dr");
- Interfaceds ds = (Interfaceds) ComWorld.getComm(ip, "rmi", 4325, "ds");
+ dc = (Interfacedc) ComWorld.getComm(ip, "rmi", 4325, "dc");
+ dr = (Interfacedr) ComWorld.getComm(ip, "rmi", 4325, "dr");
+ ds = (Interfaceds) ComWorld.getComm(ip, "rmi", 4325, "ds");
bitdew = new BitDew(dc, dr, ds);
Data ciphered_info = bitdew.getDataFromMd5(md5info);
Data aes_key = bitdew.getDataFromMd5(md5aes);
System.out.println("Data to download " + ciphered_info.getuid());
System.out.println("AES Key to download " + aes_key.getuid());
File ciphered_file = new File("feed" + i);
// Get ciphered file
OOBTransfer oob = bitdew.get(ciphered_info, ciphered_file);
transferManager.registerTransfer(oob);
transferManager.waitFor(ciphered_info);
// Get AES Key
File aes = new File("feed"+i+Akratos.AES_CIPHERED_POSTFIX);
oob = bitdew.get(aes_key, aes);
transferManager.registerTransfer(oob);
transferManager.waitFor(aes_key);
done = true;
}catch (ModuleLoaderException e) {
e.printStackTrace();
}
catch(Exception e ){
System.out.println("The host " + ip + "seems to be down, trying with next one");
e.printStackTrace();
}
}
// At this point we have both files, we proceed to decryption
plaintext = AkratosUtil.uncipher("feed" + i );
System.out.println(" The plain Text is " + plaintext);
//String getFriendUid = AkratosUtil.getFriendUid(plaintext);
//System.out.println("Friend uid is " + getFriendUid);
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("plaintext"+i+".xml")));
bw.write(plaintext);
bw.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BitDewException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
+ }catch (ModuleLoaderException e) {
+ e.printStackTrace();
}
}
/**
* Callback to be called when public information is scheduled on a given machine.
* @author jsaray
*
*/
public class PublicInfoCallback implements ActiveDataCallback {
/**
* This method retrieves the data that has been inserted on the DHT and replicates it in the DHT.
*/
public void onDataScheduled(Data data, Attribute attribute) {
if (data.getname().equals("public_info")) {
System.out.println("on scheduled called on public! " + data.getuid() + " data name : "+ data.getname());
String uid = data.getuid();
List<User> users;
try {
users = bitdew.ddcSearch(uid);
User user = users.get(0);
AkratosUtil.marshall(User.class, user, uid);
bitdew.ddcPublish(user.getUid(), user);
bitdew.ddcPublish(user.getPublicname(), user);
bitdew.ddcPublish(user.getTag(), user);
} catch (BitDewException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
} catch (ClassCastException e) {
System.out.println("A controlled exception has occured, PublicInfoCallback was executed where another callback was needed (Private)");
e.printStackTrace();
}
}
}
/**
* For now, this method is empty
*/
public void onDataDeleted(Data data, Attribute attr) {
}
}
/**
* This callback is used to store a copy of ciphered XML file representing the personal information
* of a peer.
*
*
* @author jsaray
*/
public class PriviledgedInfoCallback implements ActiveDataCallback {
/**
* Bootstrap node
*/
private String bootstrap;
/**
* Localhost address
*/
private String localhost;
/**
* BitDew distributed data catalog.
*/
private BitDew ddcbitdew;
/**
* Bitdew local catalog
*/
private BitDew bitdewlocal;
/**
* Initialize fields in constructor
* @param bootstrap the bootstrap node running dc and ds.
*/
public PriviledgedInfoCallback(String bootstrap) {
this.bootstrap = bootstrap;
try{
String localhost = InetAddress.getLocalHost().getHostAddress();
Interfacedt dt = (Interfacedt )ComWorld.getComm(localhost, "rmi", 4325, "dt");
transferManager = new TransferManager(dt);
Interfacedr dr = (Interfacedr) ComWorld.getComm(localhost, "rmi", 4325, "dr");
Interfaceds ds = (Interfaceds) ComWorld.getComm(localhost, "rmi", 4325, "ds");
Interfacedc ddc = (Interfacedc) ComWorld.getComm(bootstrap, "rmi", 4325, "dc");
ddcbitdew = new BitDew(ddc,dr,ds,true);
Interfacedc dc = (Interfacedc) ComWorld.getComm(localhost, "rmi", 4325, "dc");
bitdewlocal = new BitDew(dc, dr, ds);
}catch(Exception e ){
e.printStackTrace();
}
}
/**
* Called when a private data is scheduled to this machine, the handler replicates the data.
*/
public void onDataScheduled(Data data, Attribute attribute) {
if (!data.getname().equals("public_info")) {
System.out.println("on scheduled called on private! " + data.getuid() + " data name : "+ data.getname() + " data checksum :" + data.getchecksum());
try {
List<String> ips;
ips = ddcbitdew.ddcSearch(data.getchecksum());
ddcbitdew.ddcPublish(data.getname(), data);
ddcbitdew.ddcPublish(data.getchecksum(), InetAddress.getLocalHost().getHostAddress());
System.out.println(" Machine to contact " + ips.get(0) + " checksum to search "+ data.getchecksum());
Interfacedr dr = (Interfacedr) ComWorld.getComm(ips.get(0), "rmi", 4325, "dr");
Interfaceds ds = (Interfaceds) ComWorld.getComm(ips.get(0), "rmi", 4325, "ds");
Interfacedc dc= (Interfacedc) ComWorld.getComm(ips.get(0), "rmi", 4325, "dc");
BitDew bitdewrepo = new BitDew(dc, dr, ds);
Data final_data = bitdewrepo.getDataFromMd5(data.getchecksum());
File file_to_get = new File(final_data.getuid());
// Get physically the file
OOBTransfer oob = bitdewrepo.get(final_data, file_to_get);
transferManager.start();
transferManager.registerTransfer(oob);
transferManager.waitFor(final_data);
// Put locally the file to make it visible to bitdew
File to_put_internally = new File(data.getuid());
oob = bitdewlocal.put(to_put_internally, final_data, "http");
transferManager.registerTransfer(oob);
transferManager.waitFor(data);
transferManager.stop();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (BitDewException e) {
e.printStackTrace();
} catch (TransferManagerException e) {
e.printStackTrace();
} catch (ModuleLoaderException e) {
e.printStackTrace();
} catch (ClassCastException e) {
System.out.println(" A controlled exception has occured, private callback was call but it was not its turn");
e.printStackTrace();
}
}
}
/**
* For now this method is not implemented
*/
public void onDataDeleted(Data data, Attribute attr) {
}
}
}
| false | true |
public void getNews(String file_name) {
User u;
PersonalInfo personal;
String plaintext = "";
Hashtable ht = new Hashtable();
String dataaff;
String ip="";
try {
Contacts contacts = (Contacts) AkratosUtil.unmarshall(Contacts.class, "contacts.xml");
u = (User) AkratosUtil.unmarshall(User.class, file_name);
// datas contains feed and replicas of your friends, need depurate
// to take only unique values
List<Data> plaindatas = bitdew.ddcSearch(u.getPrivateuid());
List<Data> aeskeys = bitdew.ddcSearch(u.getPrivateuid() + Akratos.AES_CIPHERED_POSTFIX);
System.out.println(" Size of aes keys" + aeskeys.size());
System.out.println(" Size of response : " + plaindatas.size());
List<Data> uniqdatas = AkratosUtil.getUniques(plaindatas);
List<Data> uniqaes = AkratosUtil.getUniques(aeskeys);
System.out.println("Uniq aes " + uniqaes.size() + " Uniq datas " + uniqdatas.size());
Hashtable<String, Data> hashdata = AkratosUtil.getDataHashTable(uniqdatas);
Hashtable<String, Data> hashaes = AkratosUtil.getDataHashTable(uniqaes);
// for each data name in the hash
transferManager.start();
for (int i = 0; i < uniqaes.size(); i++) {
System.out.println("entro al ciclo");
Data pre_aes_key = (Data) uniqaes.get(i);
System.out.println("data before is " + pre_aes_key + " data attrid " + pre_aes_key.getattruid());
Attribute attr = bitdew.getAttributeByUid(pre_aes_key.getattruid());
System.out.println("Attribute is " + attr);
dataaff = attr.getaffinity();
Data pre_ciphered_info = hashdata.get(dataaff);
String md5info = pre_ciphered_info.getchecksum();
String md5aes = pre_aes_key.getchecksum();
List<String> ips = bitdew.ddcSearch(md5info);
boolean done = false;
for (int ind_ips = 0 ; ind_ips < ips.size() && !done; ind_ips ++ ){
try{
ip = ips.get(0);
System.out.println("ip to connect with " + ip);
Interfacedc dc = (Interfacedc) ComWorld.getComm(ip, "rmi", 4325, "dc");
Interfacedr dr = (Interfacedr) ComWorld.getComm(ip, "rmi", 4325, "dr");
Interfaceds ds = (Interfaceds) ComWorld.getComm(ip, "rmi", 4325, "ds");
bitdew = new BitDew(dc, dr, ds);
Data ciphered_info = bitdew.getDataFromMd5(md5info);
Data aes_key = bitdew.getDataFromMd5(md5aes);
System.out.println("Data to download " + ciphered_info.getuid());
System.out.println("AES Key to download " + aes_key.getuid());
File ciphered_file = new File("feed" + i);
// Get ciphered file
OOBTransfer oob = bitdew.get(ciphered_info, ciphered_file);
transferManager.registerTransfer(oob);
transferManager.waitFor(ciphered_info);
// Get AES Key
File aes = new File("feed"+i+Akratos.AES_CIPHERED_POSTFIX);
oob = bitdew.get(aes_key, aes);
transferManager.registerTransfer(oob);
transferManager.waitFor(aes_key);
done = true;
}catch (ModuleLoaderException e) {
e.printStackTrace();
}
catch(Exception e ){
System.out.println("The host " + ip + "seems to be down, trying with next one");
e.printStackTrace();
}
}
// At this point we have both files, we proceed to decryption
plaintext = AkratosUtil.uncipher("feed" + i );
System.out.println(" The plain Text is " + plaintext);
//String getFriendUid = AkratosUtil.getFriendUid(plaintext);
//System.out.println("Friend uid is " + getFriendUid);
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("plaintext"+i+".xml")));
bw.write(plaintext);
bw.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BitDewException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
|
public void getNews(String file_name) {
User u;
PersonalInfo personal;
String plaintext = "";
Hashtable ht = new Hashtable();
String dataaff;
String ip="";
try {
Contacts contacts = (Contacts) AkratosUtil.unmarshall(Contacts.class, "contacts.xml");
u = (User) AkratosUtil.unmarshall(User.class, file_name);
// datas contains feed and replicas of your friends, need depurate
// to take only unique values
List<Data> plaindatas = bitdew.ddcSearch(u.getPrivateuid());
List<Data> aeskeys = bitdew.ddcSearch(u.getPrivateuid() + Akratos.AES_CIPHERED_POSTFIX);
System.out.println(" Size of aes keys" + aeskeys.size());
System.out.println(" Size of response : " + plaindatas.size());
List<Data> uniqdatas = AkratosUtil.getUniques(plaindatas);
List<Data> uniqaes = AkratosUtil.getUniques(aeskeys);
System.out.println("Uniq aes " + uniqaes.size() + " Uniq datas " + uniqdatas.size());
Hashtable<String, Data> hashdata = AkratosUtil.getDataHashTable(uniqdatas);
Hashtable<String, Data> hashaes = AkratosUtil.getDataHashTable(uniqaes);
// for each data name in the hash
transferManager.start();
for (int i = 0; i < uniqaes.size(); i++) {
Interfacedr dr = (Interfacedr) ComWorld.getComm(InetAddress.getLocalHost().getHostAddress(), "rmi", 4325, "dr");
Interfaceds ds = (Interfaceds) ComWorld.getComm(bootstrap, "rmi", 4325, "ds");
Interfacedt dt = (Interfacedt) ComWorld.getComm(InetAddress.getLocalHost().getHostAddress(), "rmi", 4325, "dt");
Interfacedc dc = (Interfacedc) ComWorld.getComm(bootstrap, "rmi", 4325, "dc");
bitdew = new BitDew(dc, dr, ds, true);
System.out.println("entro al ciclo");
Data pre_aes_key = (Data) uniqaes.get(i);
System.out.println("data before is " + pre_aes_key + " data attrid " + pre_aes_key.getattruid());
Attribute attr = bitdew.getAttributeByUid(pre_aes_key.getattruid());
System.out.println("Attribute is " + attr);
dataaff = attr.getaffinity();
Data pre_ciphered_info = hashdata.get(dataaff);
String md5info = pre_ciphered_info.getchecksum();
String md5aes = pre_aes_key.getchecksum();
List<String> ips = bitdew.ddcSearch(md5info);
boolean done = false;
for (int ind_ips = 0 ; ind_ips < ips.size() && !done; ind_ips ++ ){
try{
ip = ips.get(0);
System.out.println("ip to connect with " + ip);
dc = (Interfacedc) ComWorld.getComm(ip, "rmi", 4325, "dc");
dr = (Interfacedr) ComWorld.getComm(ip, "rmi", 4325, "dr");
ds = (Interfaceds) ComWorld.getComm(ip, "rmi", 4325, "ds");
bitdew = new BitDew(dc, dr, ds);
Data ciphered_info = bitdew.getDataFromMd5(md5info);
Data aes_key = bitdew.getDataFromMd5(md5aes);
System.out.println("Data to download " + ciphered_info.getuid());
System.out.println("AES Key to download " + aes_key.getuid());
File ciphered_file = new File("feed" + i);
// Get ciphered file
OOBTransfer oob = bitdew.get(ciphered_info, ciphered_file);
transferManager.registerTransfer(oob);
transferManager.waitFor(ciphered_info);
// Get AES Key
File aes = new File("feed"+i+Akratos.AES_CIPHERED_POSTFIX);
oob = bitdew.get(aes_key, aes);
transferManager.registerTransfer(oob);
transferManager.waitFor(aes_key);
done = true;
}catch (ModuleLoaderException e) {
e.printStackTrace();
}
catch(Exception e ){
System.out.println("The host " + ip + "seems to be down, trying with next one");
e.printStackTrace();
}
}
// At this point we have both files, we proceed to decryption
plaintext = AkratosUtil.uncipher("feed" + i );
System.out.println(" The plain Text is " + plaintext);
//String getFriendUid = AkratosUtil.getFriendUid(plaintext);
//System.out.println("Friend uid is " + getFriendUid);
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("plaintext"+i+".xml")));
bw.write(plaintext);
bw.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BitDewException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (ModuleLoaderException e) {
e.printStackTrace();
}
}
|
diff --git a/StaXParser.java b/StaXParser.java
index ceeff66..3d8e314 100644
--- a/StaXParser.java
+++ b/StaXParser.java
@@ -1,273 +1,274 @@
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
public class StaXParser {
static final String PART = "part";
static final String MEASURE = "measure";
static final String NOTE = "note";
static final String PITCH = "pitch";
static final String STEP = "step";
static final String ALTER = "alter";
static final String OCTAVE = "octave";
static final String CHORD = "chord";
static final String TIE = "tie";
static final String BACKUP = "backup";
static final String DURATION = "duration";
static final String VOICE = "voice";
static final String KEY = "key";
static final String ATTRIBUTES = "attributes";
static final String MODE = "mode";
static final String FIFTHS = "fifths";
public void readConfig(String configFile) {
try {
Converter c = new Converter();
//input a note and string key and measure
//method "what_key" given (fifths and mode) outputs string which is the key
// First create a new XMLInputFactory
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader
System.out.println(configFile);
InputStream in = new FileInputStream(configFile);
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
FileWriter fw = new FileWriter("newXML.xml");
BufferedWriter bw = new BufferedWriter(fw);
// Read the XML document
String mode = "";
int fifths = 0;
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement() &&
event.asStartElement().getName().toString().equals(PART)){
while(eventReader.hasNext()){
event = eventReader.nextEvent();
//System.out.println("GOES");
boolean endMeasure = false;
if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(MEASURE)){
//System.out.println("GOES INTO MEASURE");
bw.write(event.toString());
ArrayList<Note> measure = new ArrayList<Note>();
int counter = 0;
boolean endAttribute = false;
while(eventReader.hasNext() && !endMeasure){
event = eventReader.nextEvent();
if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(ATTRIBUTES)){
while(eventReader.hasNext() && !endAttribute){
if(event.isEndElement() &&
event.asEndElement().getName().toString().equals(ATTRIBUTES)){
bw.write(event.toString());
endAttribute = true;
}
else if(event.isStartElement()){
String currentTag = event.asStartElement().getName().toString();
bw.write(event.toString());
event = eventReader.nextEvent();
if(currentTag.equals(KEY)){
boolean endKey = false;
while(eventReader.hasNext() && !endKey){
if(event.isEndElement() &&
event.asEndElement().getName().toString().equals(KEY)){
endKey = true;
}
else if(event.isStartElement()){
currentTag = event.asStartElement().getName().toString();
bw.write(event.toString());
if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(FIFTHS)){
event = eventReader.nextEvent();
bw.write(event.toString());
if(event.isCharacters()){
String character = event.asCharacters().getData().toString();
int num = Integer.parseInt(character);
fifths = num;
}
}
else if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(MODE)){
event = eventReader.nextEvent();
bw.write(event.toString());
if(event.isCharacters()){
String character = event.asCharacters().getData().toString();
mode = character;
}
}
}
else
bw.write(event.toString());
if(eventReader.hasNext() && !endKey)
event = eventReader.nextEvent();
}
}
}
else{
bw.write(event.toString());
if(eventReader.hasNext() && !endAttribute)
event = eventReader.nextEvent();
}
}
}
else if(event.isEndElement() &&
event.asEndElement().getName().toString().equals(MEASURE)){
bw.write(event.toString());
endMeasure = true;
}
//New Note
else if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(NOTE)){
//System.out.println("Goes in here and mode = " + mode + "\n fifth = " + fifth);
Note current = new Note();
current.setMode(mode);
current.setFifth(fifths);
String key = c.whatKey(mode, fifths);
boolean endNote = false;
String currentTag = "";
Note newNote = new Note();
while(eventReader.hasNext() && !endNote){
if(event.isEndElement() &&
event.asEndElement().getName().toString().equals(NOTE)){
bw.write(event.toString());
endNote = true;
}
if(event.isStartElement()){
currentTag = event.asStartElement().getName().toString();
bw.write(event.toString());
if(currentTag.equals(CHORD))
current.setChord(true);
}
if(event.isEndElement() && !endNote){
String eventName = event.asEndElement().getName().toString();
if(eventName.equals(STEP))
bw.write(newNote.getStep() + event.toString());
else if(eventName.equals(ALTER))
bw.write(newNote.getAlter() + event.toString());
else if(eventName.equals(OCTAVE))
bw.write(newNote.getOctave() + event.toString());
else
bw.write(event.toString());
event = eventReader.nextEvent();
}
if(event.isCharacters()){
String character = event.asCharacters().getData().toString();
boolean pitch = false;
//System.out.println(currentTag + " : " + character);
if(currentTag.equals(STEP) && current.getStep().length()!=1){
current.setStep(character);
//putting hash but here is where you change it
pitch = true;
}
if(currentTag.equals(ALTER) && current.getAlter() == 0){
current.setAlter(Integer.parseInt(character));
//where you change alter
}
if(currentTag.equals(OCTAVE) && current.getOctave() == 0){
current.setOctave(Integer.parseInt(character));
//change octave code
}
if(pitch){
newNote = c.convert(current, key, "toMin", measure);
}
if(currentTag.equals(DURATION) && current.getDuration() == 0){
current.setPosition(counter);
current.setDuration(Integer.parseInt(character));
counter = counter + current.getDuration();
bw.write(event.toString());
}
if(currentTag.equals(VOICE) && current.getVoice() == 0){
current.setVoice(Integer.parseInt(character));
System.out.println(event.asCharacters().getData());
bw.write(character);
}
}
//System.out.println(event.asCharacters().getData());
event = eventReader.nextEvent();
}
System.out.println(current);
System.out.println("********");
measure.add(current);
//System.out.println(measure.size());
}
else if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(BACKUP)){
+ bw.write(event.toString());
event = eventReader.nextEvent();
if(event.isStartElement() && event.asStartElement().getName().toString().equals(DURATION)){
event = eventReader.nextEvent();
if(event.isCharacters()){
String character = event.asCharacters().getData().toString();
int num = Integer.parseInt(character);
counter = counter - num;
}
}
}
else
bw.write(event.toString());
}
}
else
bw.write(event.toString());
}
}
else
bw.write(event.toString());
}
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
| true | true |
public void readConfig(String configFile) {
try {
Converter c = new Converter();
//input a note and string key and measure
//method "what_key" given (fifths and mode) outputs string which is the key
// First create a new XMLInputFactory
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader
System.out.println(configFile);
InputStream in = new FileInputStream(configFile);
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
FileWriter fw = new FileWriter("newXML.xml");
BufferedWriter bw = new BufferedWriter(fw);
// Read the XML document
String mode = "";
int fifths = 0;
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement() &&
event.asStartElement().getName().toString().equals(PART)){
while(eventReader.hasNext()){
event = eventReader.nextEvent();
//System.out.println("GOES");
boolean endMeasure = false;
if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(MEASURE)){
//System.out.println("GOES INTO MEASURE");
bw.write(event.toString());
ArrayList<Note> measure = new ArrayList<Note>();
int counter = 0;
boolean endAttribute = false;
while(eventReader.hasNext() && !endMeasure){
event = eventReader.nextEvent();
if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(ATTRIBUTES)){
while(eventReader.hasNext() && !endAttribute){
if(event.isEndElement() &&
event.asEndElement().getName().toString().equals(ATTRIBUTES)){
bw.write(event.toString());
endAttribute = true;
}
else if(event.isStartElement()){
String currentTag = event.asStartElement().getName().toString();
bw.write(event.toString());
event = eventReader.nextEvent();
if(currentTag.equals(KEY)){
boolean endKey = false;
while(eventReader.hasNext() && !endKey){
if(event.isEndElement() &&
event.asEndElement().getName().toString().equals(KEY)){
endKey = true;
}
else if(event.isStartElement()){
currentTag = event.asStartElement().getName().toString();
bw.write(event.toString());
if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(FIFTHS)){
event = eventReader.nextEvent();
bw.write(event.toString());
if(event.isCharacters()){
String character = event.asCharacters().getData().toString();
int num = Integer.parseInt(character);
fifths = num;
}
}
else if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(MODE)){
event = eventReader.nextEvent();
bw.write(event.toString());
if(event.isCharacters()){
String character = event.asCharacters().getData().toString();
mode = character;
}
}
}
else
bw.write(event.toString());
if(eventReader.hasNext() && !endKey)
event = eventReader.nextEvent();
}
}
}
else{
bw.write(event.toString());
if(eventReader.hasNext() && !endAttribute)
event = eventReader.nextEvent();
}
}
}
else if(event.isEndElement() &&
event.asEndElement().getName().toString().equals(MEASURE)){
bw.write(event.toString());
endMeasure = true;
}
//New Note
else if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(NOTE)){
//System.out.println("Goes in here and mode = " + mode + "\n fifth = " + fifth);
Note current = new Note();
current.setMode(mode);
current.setFifth(fifths);
String key = c.whatKey(mode, fifths);
boolean endNote = false;
String currentTag = "";
Note newNote = new Note();
while(eventReader.hasNext() && !endNote){
if(event.isEndElement() &&
event.asEndElement().getName().toString().equals(NOTE)){
bw.write(event.toString());
endNote = true;
}
if(event.isStartElement()){
currentTag = event.asStartElement().getName().toString();
bw.write(event.toString());
if(currentTag.equals(CHORD))
current.setChord(true);
}
if(event.isEndElement() && !endNote){
String eventName = event.asEndElement().getName().toString();
if(eventName.equals(STEP))
bw.write(newNote.getStep() + event.toString());
else if(eventName.equals(ALTER))
bw.write(newNote.getAlter() + event.toString());
else if(eventName.equals(OCTAVE))
bw.write(newNote.getOctave() + event.toString());
else
bw.write(event.toString());
event = eventReader.nextEvent();
}
if(event.isCharacters()){
String character = event.asCharacters().getData().toString();
boolean pitch = false;
//System.out.println(currentTag + " : " + character);
if(currentTag.equals(STEP) && current.getStep().length()!=1){
current.setStep(character);
//putting hash but here is where you change it
pitch = true;
}
if(currentTag.equals(ALTER) && current.getAlter() == 0){
current.setAlter(Integer.parseInt(character));
//where you change alter
}
if(currentTag.equals(OCTAVE) && current.getOctave() == 0){
current.setOctave(Integer.parseInt(character));
//change octave code
}
if(pitch){
newNote = c.convert(current, key, "toMin", measure);
}
if(currentTag.equals(DURATION) && current.getDuration() == 0){
current.setPosition(counter);
current.setDuration(Integer.parseInt(character));
counter = counter + current.getDuration();
bw.write(event.toString());
}
if(currentTag.equals(VOICE) && current.getVoice() == 0){
current.setVoice(Integer.parseInt(character));
System.out.println(event.asCharacters().getData());
bw.write(character);
}
}
//System.out.println(event.asCharacters().getData());
event = eventReader.nextEvent();
}
System.out.println(current);
System.out.println("********");
measure.add(current);
//System.out.println(measure.size());
}
else if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(BACKUP)){
event = eventReader.nextEvent();
if(event.isStartElement() && event.asStartElement().getName().toString().equals(DURATION)){
event = eventReader.nextEvent();
if(event.isCharacters()){
String character = event.asCharacters().getData().toString();
int num = Integer.parseInt(character);
counter = counter - num;
}
}
}
else
bw.write(event.toString());
}
}
else
bw.write(event.toString());
}
}
else
bw.write(event.toString());
}
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
|
public void readConfig(String configFile) {
try {
Converter c = new Converter();
//input a note and string key and measure
//method "what_key" given (fifths and mode) outputs string which is the key
// First create a new XMLInputFactory
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader
System.out.println(configFile);
InputStream in = new FileInputStream(configFile);
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
FileWriter fw = new FileWriter("newXML.xml");
BufferedWriter bw = new BufferedWriter(fw);
// Read the XML document
String mode = "";
int fifths = 0;
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement() &&
event.asStartElement().getName().toString().equals(PART)){
while(eventReader.hasNext()){
event = eventReader.nextEvent();
//System.out.println("GOES");
boolean endMeasure = false;
if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(MEASURE)){
//System.out.println("GOES INTO MEASURE");
bw.write(event.toString());
ArrayList<Note> measure = new ArrayList<Note>();
int counter = 0;
boolean endAttribute = false;
while(eventReader.hasNext() && !endMeasure){
event = eventReader.nextEvent();
if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(ATTRIBUTES)){
while(eventReader.hasNext() && !endAttribute){
if(event.isEndElement() &&
event.asEndElement().getName().toString().equals(ATTRIBUTES)){
bw.write(event.toString());
endAttribute = true;
}
else if(event.isStartElement()){
String currentTag = event.asStartElement().getName().toString();
bw.write(event.toString());
event = eventReader.nextEvent();
if(currentTag.equals(KEY)){
boolean endKey = false;
while(eventReader.hasNext() && !endKey){
if(event.isEndElement() &&
event.asEndElement().getName().toString().equals(KEY)){
endKey = true;
}
else if(event.isStartElement()){
currentTag = event.asStartElement().getName().toString();
bw.write(event.toString());
if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(FIFTHS)){
event = eventReader.nextEvent();
bw.write(event.toString());
if(event.isCharacters()){
String character = event.asCharacters().getData().toString();
int num = Integer.parseInt(character);
fifths = num;
}
}
else if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(MODE)){
event = eventReader.nextEvent();
bw.write(event.toString());
if(event.isCharacters()){
String character = event.asCharacters().getData().toString();
mode = character;
}
}
}
else
bw.write(event.toString());
if(eventReader.hasNext() && !endKey)
event = eventReader.nextEvent();
}
}
}
else{
bw.write(event.toString());
if(eventReader.hasNext() && !endAttribute)
event = eventReader.nextEvent();
}
}
}
else if(event.isEndElement() &&
event.asEndElement().getName().toString().equals(MEASURE)){
bw.write(event.toString());
endMeasure = true;
}
//New Note
else if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(NOTE)){
//System.out.println("Goes in here and mode = " + mode + "\n fifth = " + fifth);
Note current = new Note();
current.setMode(mode);
current.setFifth(fifths);
String key = c.whatKey(mode, fifths);
boolean endNote = false;
String currentTag = "";
Note newNote = new Note();
while(eventReader.hasNext() && !endNote){
if(event.isEndElement() &&
event.asEndElement().getName().toString().equals(NOTE)){
bw.write(event.toString());
endNote = true;
}
if(event.isStartElement()){
currentTag = event.asStartElement().getName().toString();
bw.write(event.toString());
if(currentTag.equals(CHORD))
current.setChord(true);
}
if(event.isEndElement() && !endNote){
String eventName = event.asEndElement().getName().toString();
if(eventName.equals(STEP))
bw.write(newNote.getStep() + event.toString());
else if(eventName.equals(ALTER))
bw.write(newNote.getAlter() + event.toString());
else if(eventName.equals(OCTAVE))
bw.write(newNote.getOctave() + event.toString());
else
bw.write(event.toString());
event = eventReader.nextEvent();
}
if(event.isCharacters()){
String character = event.asCharacters().getData().toString();
boolean pitch = false;
//System.out.println(currentTag + " : " + character);
if(currentTag.equals(STEP) && current.getStep().length()!=1){
current.setStep(character);
//putting hash but here is where you change it
pitch = true;
}
if(currentTag.equals(ALTER) && current.getAlter() == 0){
current.setAlter(Integer.parseInt(character));
//where you change alter
}
if(currentTag.equals(OCTAVE) && current.getOctave() == 0){
current.setOctave(Integer.parseInt(character));
//change octave code
}
if(pitch){
newNote = c.convert(current, key, "toMin", measure);
}
if(currentTag.equals(DURATION) && current.getDuration() == 0){
current.setPosition(counter);
current.setDuration(Integer.parseInt(character));
counter = counter + current.getDuration();
bw.write(event.toString());
}
if(currentTag.equals(VOICE) && current.getVoice() == 0){
current.setVoice(Integer.parseInt(character));
System.out.println(event.asCharacters().getData());
bw.write(character);
}
}
//System.out.println(event.asCharacters().getData());
event = eventReader.nextEvent();
}
System.out.println(current);
System.out.println("********");
measure.add(current);
//System.out.println(measure.size());
}
else if(event.isStartElement() &&
event.asStartElement().getName().toString().equals(BACKUP)){
bw.write(event.toString());
event = eventReader.nextEvent();
if(event.isStartElement() && event.asStartElement().getName().toString().equals(DURATION)){
event = eventReader.nextEvent();
if(event.isCharacters()){
String character = event.asCharacters().getData().toString();
int num = Integer.parseInt(character);
counter = counter - num;
}
}
}
else
bw.write(event.toString());
}
}
else
bw.write(event.toString());
}
}
else
bw.write(event.toString());
}
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
|
diff --git a/srcj/com/sun/electric/tool/routing/InteractiveRouter.java b/srcj/com/sun/electric/tool/routing/InteractiveRouter.java
index 1a4eb5160..a0e6e80f6 100644
--- a/srcj/com/sun/electric/tool/routing/InteractiveRouter.java
+++ b/srcj/com/sun/electric/tool/routing/InteractiveRouter.java
@@ -1,791 +1,791 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: InteractiveRouter.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.routing;
import com.sun.electric.tool.user.ui.EditWindow;
import com.sun.electric.tool.user.Highlight;
import com.sun.electric.tool.user.User;
import com.sun.electric.tool.user.CircuitChanges;
import com.sun.electric.tool.user.Highlighter;
import com.sun.electric.tool.Job;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.prototype.ArcProto;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.geometry.Dimension2D;
import com.sun.electric.database.geometry.DBMath;
import com.sun.electric.database.variable.ElectricObject;
import com.sun.electric.technology.*;
import com.sun.electric.technology.technologies.Artwork;
import java.awt.geom.Point2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
/**
* An Interactive Router has several methods that build on Router
* methods to provide interactive control to user. It also
* provides methods for highlighting routes to provide visual
* feedback to the user. Finally, non-interactive routing is done only
* from PortInst to PortInst, whereas interactive routing can start and
* end on any arc, and can end in space.
* <p>
* Note: 'Interactive' is somewhat of a misnomer, as it would imply
* the route can be incremently built or changed by the user. In
* reality, it is expected that the route simply be rebuilt whenever
* the user input changes, until the user decides that the route is acceptable,
* at which point the route can be made.
* <p>
* User: gainsley
* Date: Feb 24, 2004
* Time: 4:58:24 PM
*/
public abstract class InteractiveRouter extends Router {
/** for highlighting the start of the route */ private List startRouteHighlights = new ArrayList();
/** if start has been called */ private boolean started;
/** EditWindow we are routing in */ private EditWindow wnd;
/** last bad object routed from: prevent too many error messages */ private ElectricObject badStartObject;
/** last bad object routing to: prevent too many error messages */ private ElectricObject badEndObject;
public InteractiveRouter() {
verbose = true;
started = false;
badStartObject = badEndObject = null;
wnd = null;
}
public String toString() { return "Interactive Router"; }
protected abstract boolean planRoute(Route route, Cell cell, RouteElementPort endRE,
Point2D startLoc, Point2D endLoc, Point2D clicked, VerticalRoute vroute,
boolean contactsOnEndObject);
// ----------------------- Interactive Route Control --------------------------
/**
* This stores the currently highlighted objects to highlight
* in addition to route highlighting. If routing it cancelled,
* it also restores the original highlighting.
*/
public void startInteractiveRoute(EditWindow wnd) {
this.wnd = wnd;
// copy current highlights
startRouteHighlights.clear();
for (Iterator it = wnd.getHighlighter().getHighlights().iterator(); it.hasNext(); ) {
Highlight h = (Highlight)it.next();
startRouteHighlights.add(h);
}
wnd.getHighlighter().clear();
started = true;
}
/**
* Cancels interative routing and restores original highlights
*/
public void cancelInteractiveRoute() {
// restore original highlights
Highlighter highlighter = wnd.getHighlighter();
highlighter.clear();
highlighter.setHighlightList(startRouteHighlights);
highlighter.finished();
wnd = null;
started = false;
}
/**
* Make a route between startObj and endObj in the EditWindow wnd.
* Uses the point where the user clicked as a parameter to set the route.
* @param wnd the EditWindow the user is editing
* @param cell the cell in which to create the route
* @param startObj a PortInst or ArcInst from which to start the route
* @param endObj a PortInst or ArcInst to end the route on. May be null
* if the user is drawing to empty space.
* @param clicked the point where the user clicked
*/
public void makeRoute(EditWindow wnd, Cell cell, ElectricObject startObj, ElectricObject endObj, Point2D clicked) {
if (!started) startInteractiveRoute(wnd);
// plan the route
Route route = planRoute(cell, startObj, endObj, clicked);
// restore highlights at start of planning, so that
// they will correctly show up if this job is undone.
wnd.getHighlighter().clear();
wnd.getHighlighter().setHighlightList(startRouteHighlights);
// create route
createRoute(route, cell);
started = false;
}
/**
* Make a vertical route. Will add in contacts in startPort's technology
* to be able to connect to endPort. The added contacts will be placed on
* top of startPort. The final contact will be able to connect to <i>arc</i>.
* @param wnd the EditWindow the user is editing
* @param startPort the start of the route
* @param arc the arc type that the last contact will be able to connect to
* @return true on sucess
*/
public boolean makeVerticalRoute(EditWindow wnd, PortInst startPort, ArcProto arc) {
// do nothing if startPort can already connect to arc
if (startPort.getPortProto().connectsTo(arc)) return true;
Cell cell = startPort.getNodeInst().getParent();
if (!started) startInteractiveRoute(wnd);
Point2D startLoc = new Point2D.Double(startPort.getPoly().getCenterX(), startPort.getPoly().getCenterY());
Poly poly = getConnectingSite(startPort, startLoc, -1);
RouteElementPort startRE = RouteElementPort.existingPortInst(startPort, poly);
Route route = new Route();
route.add(startRE); route.setStart(startRE);
//route.setEnd(startRE);
PrimitiveNode pn = ((PrimitiveArc)arc).findOverridablePinProto();
PortProto pp = pn.getPort(0);
VerticalRoute vroute = VerticalRoute.newRoute(startPort.getPortProto(), arc);
if (!vroute.isSpecificationSucceeded()) {
cancelInteractiveRoute();
return false;
}
vroute.buildRoute(route, startRE.getCell(), startRE, null, startLoc, startLoc, startLoc);
// restore highlights at start of planning, so that
// they will correctly show up if this job is undone.
wnd.getHighlighter().clear();
wnd.getHighlighter().setHighlightList(startRouteHighlights);
MakeVerticalRouteJob job = new MakeVerticalRouteJob(this, route, startPort.getNodeInst().getParent(), true);
started = false;
return true;
}
public static class MakeVerticalRouteJob extends Router.CreateRouteJob {
protected MakeVerticalRouteJob(Router router, Route route, Cell cell, boolean verbose) {
super(router, route, cell, false);
}
/** Implemented doIt() method to perform Job */
public boolean doIt() {
if (!super.doIt()) return false;
RouteElementPort startRE = route.getStart();
if (startRE.getAction() == RouteElement.RouteElementAction.existingPortInst) {
// if this is a pin, replace it with the first contact in vertical route
PortInst pi = startRE.getPortInst();
NodeInst ni = pi.getNodeInst();
if (ni.getProto().getFunction() == PrimitiveNode.Function.PIN) {
CircuitChanges.Reconnect re = CircuitChanges.Reconnect.erasePassThru(ni, false);
if (re != null) re.reconnectArcs();
ni.kill();
}
}
return true;
}
}
// -------------------------- Highlight Route Methods -------------------------
/**
* Make a route and highlight it in the window.
* @param cell the cell in which to create the route
* @param startObj a PortInst or ArcInst from which to start the route
* @param endObj a PortInst or ArcInst to end the route on. May be null
* if the user is drawing to empty space.
* @param clicked the point where the user clicked
*/
public void highlightRoute(EditWindow wnd, Cell cell, ElectricObject startObj, ElectricObject endObj, Point2D clicked) {
if (!started) startInteractiveRoute(wnd);
// highlight route
Route route = planRoute(cell, startObj, endObj, clicked);
highlightRoute(wnd, route, cell);
}
/**
* Highlight a route in the window
* @param route the route to be highlighted
*/
public void highlightRoute(EditWindow wnd, Route route, Cell cell) {
if (!started) startInteractiveRoute(wnd);
wnd.getHighlighter().clear();
//wnd.getHighlighter().setHighlightList(startRouteHighlights);
for (Iterator it = route.iterator(); it.hasNext(); ) {
RouteElement e = (RouteElement)it.next();
e.addHighlightArea(wnd.getHighlighter());
}
wnd.getHighlighter().finished();
}
// -------------------- Internal Router Wrapper of Router ---------------------
/**
* Plan a route from startObj to endObj, taking into account
* where the user clicked in the cell.
* @param cell the cell in which to create the arc
* @param startObj a PortInst or ArcInst from which to start the route
* @param endObj a PortInst or ArcInst to end the route on. May be null
* if the user is drawing to empty space.
* @param clicked the point where the user clicked
* @return a List of RouteElements denoting route
*/
protected Route planRoute(Cell cell, ElectricObject startObj, ElectricObject endObj, Point2D clicked) {
Route route = new Route(); // hold the route
if (cell == null) return route;
RouteElementPort startRE = null; // denote start of route
RouteElementPort endRE = null; // denote end of route
// first, convert NodeInsts to PortInsts, if it is one.
// Now we don't have to worry about NodeInsts.
startObj = filterRouteObject(startObj, clicked);
endObj = filterRouteObject(endObj, clicked);
// get the port types at each end so we can build electrical route
PortProto startPort = getRoutePort(startObj);
PortProto endPort;
if (endObj == null) {
// end object is null, we are routing to a pin. Figure out what arc to use
ArcProto useArc = getArcToUse(startPort, null);
if (useArc == null) return route;
PrimitiveNode pn = ((PrimitiveArc)useArc).findOverridablePinProto();
endPort = pn.getPort(0);
} else {
endPort = getRoutePort(endObj);
}
// now determine the electrical route. We need to know what
// arcs will be used (and their widths, eventually) to determine
// the Port Poly size for contacts
VerticalRoute vroute = VerticalRoute.newRoute(startPort, endPort);
if (!vroute.isSpecificationSucceeded()) return new Route();
// arc width of arcs that will connect to startObj, endObj will determine
// valid attachment points of arcs
ArcProto startArc = vroute.getStartArc();
ArcProto endArc = vroute.getEndArc();
double startArcWidth = getArcWidthToUse(startObj, startArc);
double endArcWidth = (endObj == null) ? startArcWidth : getArcWidthToUse(endObj, endArc);
// get valid connecting sites for start and end objects based on the objects
// themselves, the point the user clicked, and the width of the wire that will
// attach to each
- Poly startPoly = getConnectingSite(startObj, clicked, startArcWidth);
- Poly endPoly = getConnectingSite(endObj, clicked, endArcWidth);
+ Poly startPoly = getConnectingSite(startObj, clicked, startArcWidth - startArc.getWidthOffset());
+ Poly endPoly = getConnectingSite(endObj, clicked, endArcWidth - endArc.getWidthOffset());
//Poly startPoly = getConnectingSite(startObj, clicked, 3);
//Poly endPoly = getConnectingSite(endObj, clicked, 3);
// Now we can figure out where on the start and end objects the connecting
// arc(s) should connect
Point2D startPoint = new Point2D.Double(0, 0);
Point2D endPoint = new Point2D.Double(0,0);
getConnectingPoints(startObj, endObj, clicked, startPoint, endPoint, startPoly, endPoly, startArc, endArc);
PortInst existingStartPort = null;
PortInst existingEndPort = null;
// favor contact cuts on arcs
boolean contactsOnEndObject = true;
// plan start of route
if (startObj instanceof PortInst) {
// portinst: just wrap in RouteElement
existingStartPort = (PortInst)startObj;
startRE = RouteElementPort.existingPortInst(existingStartPort, startPoly);
}
if (startObj instanceof ArcInst) {
// arc: figure out where on arc to start
startRE = findArcConnectingPoint(route, (ArcInst)startObj, startPoint);
contactsOnEndObject = false;
}
if (startRE == null) {
if (startObj != badStartObject)
System.out.println(" Can't route from "+startObj+", no ports");
badStartObject = startObj;
return route;
}
// plan end of route
if (endObj != null) {
// we have somewhere to route to
if (endObj instanceof PortInst) {
// portinst: just wrap in RouteElement
existingEndPort = (PortInst)endObj;
endRE = RouteElementPort.existingPortInst(existingEndPort, endPoly);
}
if (endObj instanceof ArcInst) {
// arc: figure out where on arc to end
// use startRE location when possible if connecting to arc
endRE = findArcConnectingPoint(route, (ArcInst)endObj, endPoint);
contactsOnEndObject = true;
}
if (endRE == null) {
if (endObj != badEndObject)
System.out.println(" Can't route to "+endObj+", no ports");
badEndObject = endObj;
endObj = null;
}
}
if (endObj == null) {
// nowhere to route to, must make new pin to route to
// first we need to determine what pin to make based on
// start object
ArcProto useArc = null;
if (startObj instanceof PortInst) {
PortInst startPi = (PortInst)startObj;
useArc = getArcToUse(startPi.getPortProto(), null);
}
if (startObj instanceof ArcInst) {
ArcInst startAi = (ArcInst)startObj;
useArc = startAi.getProto();
}
if (!(useArc instanceof PrimitiveArc)) {
System.out.println(" Don't know how to determine pin for arc "+useArc);
return new Route();
}
// make new pin to route to
PrimitiveNode pn = ((PrimitiveArc)useArc).findOverridablePinProto();
SizeOffset so = pn.getProtoSizeOffset();
endRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), endPoint,
pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset(),
pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset());
}
// special check: if both are existing port insts and are same port, do nothing
if ((existingEndPort != null) && (existingEndPort == existingStartPort)) return new Route();
// add startRE and endRE to route
route.add(startRE);
route.setStart(startRE);
route.setEnd(startRE);
//route.add(endRE); route.setEnd(endRE);
// Tell Router to route between startRE and endRE
if (planRoute(route, cell, endRE, startPoint, endPoint, clicked, vroute, contactsOnEndObject)) {
return route;
} else
return new Route(); // error, return empty route
}
// -------------------- Internal Router Utility Methods --------------------
/**
* If routeObj is a NodeInst, first thing we do is get the nearest PortInst
* to where the user clicked, and use that instead.
* @param routeObj the route object (possibly a NodeInst).
* @param clicked where the user clicked
* @return the PortInst on the NodeInst closest to where the user clicked,
* or just the routeObj back if it is not a NodeInst.
*/
protected static ElectricObject filterRouteObject(ElectricObject routeObj, Point2D clicked) {
if (routeObj instanceof NodeInst) {
return ((NodeInst)routeObj).findClosestPortInst(clicked);
}
if (routeObj instanceof Export) {
Export exp = (Export)routeObj;
return exp.getOriginalPort();
}
return routeObj;
}
/**
* Get the PortProto associated with routeObj (it should be either
* a ArcInst or a PortInst, otherwise this will return null).
* @param routeObj the route object
* @return the PortProto for this route object
*/
protected static PortProto getRoutePort(ElectricObject routeObj) {
assert(!(routeObj instanceof NodeInst));
if (routeObj instanceof ArcInst) {
ArcInst ai = (ArcInst)routeObj;
PrimitiveNode pn = ((PrimitiveArc)ai.getProto()).findOverridablePinProto();
return (PortProto)pn.getPort(0);
}
if (routeObj instanceof PortInst) {
PortInst pi = (PortInst)routeObj;
return pi.getPortProto();
}
return null;
}
protected static double getArcWidthToUse(ElectricObject routeObj, ArcProto ap) {
double width = -1;
if (routeObj instanceof ArcInst) {
ArcInst ai = (ArcInst)routeObj;
if (ai.getProto() == ap)
return ai.getWidth();
}
if (routeObj instanceof PortInst) {
width = Router.getArcWidthToUse((PortInst)routeObj, ap);
}
return width;
}
/**
* Get the connecting points for the start and end objects of the route. This fills in
* the two Point2D's startPoint and endPoint. These will be the end points of an arc that
* connects to either startObj or endObj.
* @param startObj the start route object
* @param endObj the end route object
* @param clicked where the user clicked
* @param startPoint point inside startPoly on startObj to connect arc to
* @param endPoint point inside endPoly on endObj to connect arc to
* @param startPoly valid port site on startObj
* @param endPoly valid port site on endObj
*/
protected static void getConnectingPoints(ElectricObject startObj, ElectricObject endObj, Point2D clicked,
Point2D startPoint, Point2D endPoint, Poly startPoly, Poly endPoly,
ArcProto startArc, ArcProto endArc) {
// just go by bounds for now
Rectangle2D startBounds = startPoly.getBounds2D();
// default is center point
startPoint.setLocation(startBounds.getCenterX(), startBounds.getCenterY());
if (startObj instanceof ArcInst) {
double x, y;
// if nothing to connect to, clicked will determine connecting point on startPoly
// endPoint will be location of new pin
x = getClosestValue(startBounds.getMinX(), startBounds.getMaxX(), clicked.getX());
y = getClosestValue(startBounds.getMinY(), startBounds.getMaxY(), clicked.getY());
startPoint.setLocation(x, y);
}
if (endPoly == null) {
// if arc, find place to connect to. Otherwise use the center point (default)
endPoint.setLocation(getClosestOrthogonalPoint(startPoint, clicked));
// however, if this is an Artwork technology, just put end point at mouse
if (startArc.getTechnology() == Artwork.tech)
endPoint.setLocation(clicked);
return;
}
Rectangle2D endBounds = endPoly.getBounds2D();
endPoint.setLocation(endBounds.getCenterX(), endBounds.getCenterY());
if (endObj instanceof ArcInst) {
double x, y;
// if nothing to connect to, clicked will determine connecting point on startPoly
// endPoint will be location of new pin
x = getClosestValue(endBounds.getMinX(), endBounds.getMaxX(), clicked.getX());
y = getClosestValue(endBounds.getMinY(), endBounds.getMaxY(), clicked.getY());
endPoint.setLocation(x, y);
}
// if bounds share x-space, use closest x within that space to clicked point
double lowerBoundX = Math.max(startBounds.getMinX(), endBounds.getMinX());
double upperBoundX = Math.min(startBounds.getMaxX(), endBounds.getMaxX());
if (lowerBoundX <= upperBoundX) {
double x = getClosestValue(lowerBoundX, upperBoundX, clicked.getX());
startPoint.setLocation(x, startPoint.getY());
endPoint.setLocation(x, endPoint.getY());
} else {
// otherwise, use closest point in bounds to the other port
// see which one is higher in X...they don't overlap, so any X coord in bounds is comparable
if (startBounds.getMinX() > endBounds.getMaxX()) {
startPoint.setLocation(startBounds.getMinX(), startPoint.getY());
endPoint.setLocation(endBounds.getMaxX(), endPoint.getY());
} else {
startPoint.setLocation(startBounds.getMaxX(), startPoint.getY());
endPoint.setLocation(endBounds.getMinX(), endPoint.getY());
}
}
// if bounds share y-space, use closest y within that space to clicked point
double lowerBoundY = Math.max(startBounds.getMinY(), endBounds.getMinY());
double upperBoundY = Math.min(startBounds.getMaxY(), endBounds.getMaxY());
if (lowerBoundY <= upperBoundY) {
double y = getClosestValue(lowerBoundY, upperBoundY, clicked.getY());
startPoint.setLocation(startPoint.getX(), y);
endPoint.setLocation(endPoint.getX(), y);
} else {
// otherwise, use closest point in bounds to the other port
// see which one is higher in Y...they don't overlap, so any Y coord in bounds is comparable
if (startBounds.getMinY() > endBounds.getMaxY()) {
startPoint.setLocation(startPoint.getX(), startBounds.getMinY());
endPoint.setLocation(endPoint.getX(), endBounds.getMaxY());
} else {
startPoint.setLocation(startPoint.getX(), startBounds.getMaxY());
endPoint.setLocation(endPoint.getX(), endBounds.getMinY());
}
}
}
/**
* Get the connecting site of the electric object.
* <ul>
* <li>For NodeInsts, this is the nearest portinst to "clicked", which is then subject to:
* <li>For PortInsts, this is the nearest site of a multisite port, or just the entire port
* <li>For ArcInsts, this is a poly composed of the head location and the tail location
* </ul>
* See NodeInst.getShapeOfPort() for more details.
* @param obj the object to get a connection site for
* @param clicked used to find the nearest portinst on a nodeinst, and nearest
* site on a multisite port
* @param arcWidth contacts port sites are restricted by the size of arcs connecting
* to them, such that the arc width does extend beyond the contact edges.
* @return a poly describing where something can connect to
*/
protected static Poly getConnectingSite(ElectricObject obj, Point2D clicked, double arcWidth) {
assert(clicked != null);
if (obj instanceof NodeInst) {
PortInst pi = ((NodeInst)obj).findClosestPortInst(clicked);
if (pi == null) return null;
obj = pi;
}
if (obj instanceof PortInst) {
PortInst pi = (PortInst)obj;
NodeInst ni = pi.getNodeInst();
PortProto pp = pi.getPortProto();
boolean compressPort = false;
if (ni.getProto() instanceof PrimitiveNode) compressPort = true;
Poly poly = ni.getShapeOfPort(pp, clicked, compressPort, arcWidth); // this is for multi-site ports
return poly;
}
if (obj instanceof ArcInst) {
// make poly out of possible connecting points on arc
ArcInst arc = (ArcInst)obj;
Point2D [] points = new Point2D[2];
points[0] = arc.getHead().getLocation();
points[1] = arc.getTail().getLocation();
Poly poly = new Poly(points);
return poly;
}
return null;
}
/**
* If drawing to/from an ArcInst, we may connect to some
* point along the arc. This may bisect the arc, in which case
* we delete the current arc, add in a pin at the appropriate
* place, and create 2 new arcs to the old arc head/tail points.
* The bisection point depends on where the user point, but it
* is always a point on the arc.
* <p>
* Note that this method adds the returned RouteElement to the
* route, and updates the route if the arc is bisected.
* This method should NOT add the returned RouteElement to the route.
* @param route the route so far
* @param arc the arc to draw from/to
* @param point point on or near arc
* @return a RouteElement holding the new pin at the bisection
* point, or a RouteElement holding an existingPortInst if
* drawing from either end of the ArcInst.
*/
protected RouteElementPort findArcConnectingPoint(Route route, ArcInst arc, Point2D point) {
Point2D head = arc.getHead().getLocation();
Point2D tail = arc.getTail().getLocation();
RouteElementPort headRE = RouteElementPort.existingPortInst(arc.getHead().getPortInst(), head);
RouteElementPort tailRE = RouteElementPort.existingPortInst(arc.getTail().getPortInst(), tail);
RouteElementPort startRE = null;
// find extents of wire
double minX, minY, maxX, maxY;
Point2D minXpin = null, minYpin = null;
if (head.getX() < tail.getX()) {
minX = head.getX(); maxX = tail.getX(); minXpin = head;
} else {
minX = tail.getX(); maxX = head.getX(); minXpin = tail;
}
if (head.getY() < tail.getY()) {
minY = head.getY(); maxY = tail.getY(); minYpin = head;
} else {
minY = tail.getY(); maxY = head.getY(); minYpin = tail;
}
// for efficiency purposes, we are going to assume the arc is
// either vertical or horizontal for bisecting the arc
if (head.getX() == tail.getX()) {
// line is vertical, see if point point bisects
if (point.getY() > minY && point.getY() < maxY) {
Point2D location = new Point2D.Double(head.getX(), point.getY());
startRE = bisectArc(route, arc, location);
}
// not within Y bounds, choose closest pin
else if (point.getY() <= minY) {
if (minYpin == head) startRE = headRE; else startRE = tailRE;
} else {
if (minYpin == head) startRE = tailRE; else startRE = headRE;
}
}
// check if arc is horizontal
else if (head.getY() == tail.getY()) {
// line is horizontal, see if point bisects
if (point.getX() > minX && point.getX() < maxX) {
Point2D location = new Point2D.Double(point.getX(), head.getY());
startRE = bisectArc(route, arc, location);
}
// not within X bounds, choose closest pin
else if (point.getX() <= minX) {
if (minXpin == head) startRE = headRE; else startRE = tailRE;
} else {
if (minXpin == head) startRE = tailRE; else startRE = headRE;
}
}
// arc is not horizontal or vertical, draw from closest pin
else {
double headDist = point.distance(head);
double tailDist = point.distance(tail);
if (headDist < tailDist)
startRE = headRE;
else
startRE = tailRE;
}
//route.add(startRE); // DON'T ADD!!
return startRE;
}
/**
* Splits an arc at bisectPoint and updates the route to reflect the change.
* This method should NOT add the returned RouteElement to the route.
*
* @param route the current route
* @param arc the arc to split
* @param bisectPoint point on arc from which to split it
* @return the RouteElement from which to continue the route
*/
protected RouteElementPort bisectArc(Route route, ArcInst arc, Point2D bisectPoint) {
Cell cell = arc.getParent();
Point2D head = arc.getHead().getLocation();
Point2D tail = arc.getTail().getLocation();
// determine pin type to use if bisecting arc
PrimitiveNode pn = ((PrimitiveArc)arc.getProto()).findOverridablePinProto();
SizeOffset so = pn.getProtoSizeOffset();
double width = pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset();
double height = pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset();
// make new pin
RouteElementPort newPinRE = RouteElementPort.newNode(cell, pn, pn.getPort(0),
bisectPoint, width, height);
newPinRE.setBisectArcPin(true);
// make dummy end pins
RouteElementPort headRE = RouteElementPort.existingPortInst(arc.getHead().getPortInst(), head);
RouteElementPort tailRE = RouteElementPort.existingPortInst(arc.getTail().getPortInst(), tail);
headRE.setShowHighlight(false);
tailRE.setShowHighlight(false);
// put name on longer arc
String name1 = null;
String name2 = null;
if (head.distance(bisectPoint) > tail.distance(bisectPoint))
name1 = arc.getName();
else
name2 = arc.getName();
// add two arcs to rebuild old startArc
RouteElement newHeadArcRE = RouteElementArc.newArc(cell, arc.getProto(), arc.getWidth(), headRE, newPinRE,
head, bisectPoint, name1, arc.getNameTextDescriptor(), arc);
RouteElement newTailArcRE = RouteElementArc.newArc(cell, arc.getProto(), arc.getWidth(), newPinRE, tailRE,
bisectPoint, tail, name2, arc.getNameTextDescriptor(), arc);
newHeadArcRE.setShowHighlight(false);
newTailArcRE.setShowHighlight(false);
// delete old arc
RouteElement deleteArcRE = RouteElementArc.deleteArc(arc);
// add new stuff to route
route.add(deleteArcRE);
//route.add(newPinRE); // DON'T ADD!!
route.add(headRE);
route.add(tailRE);
route.add(newHeadArcRE);
route.add(newTailArcRE);
return newPinRE;
}
// ------------------------- Spatial Dimension Calculations -------------------------
/**
* Get closest value to clicked within a range from min to max
*/
protected static double getClosestValue(double min, double max, double clicked) {
if (clicked >= max) {
return max;
} else if (clicked <= min) {
return min;
} else {
return clicked;
}
}
/**
* Gets the closest orthogonal point from the startPoint to the clicked point.
* This is used when the user clicks in space and the router draws only a single
* arc towards the clicked point in one dimension.
* @param startPoint start point of the arc
* @param clicked where the user clicked
* @return an end point to draw to from start point to make a single arc segment.
*/
protected static Point2D getClosestOrthogonalPoint(Point2D startPoint, Point2D clicked) {
Point2D newPoint;
if (Math.abs(startPoint.getX() - clicked.getX()) < Math.abs(startPoint.getY() - clicked.getY())) {
// draw horizontally
newPoint = new Point2D.Double(startPoint.getX(), clicked.getY());
} else {
// draw vertically
newPoint = new Point2D.Double(clicked.getX(), startPoint.getY());
}
return newPoint;
}
protected boolean withinBounds(double point, double bound1, double bound2) {
double min, max;
if (bound1 < bound2) {
min = bound1; max = bound2;
} else {
min = bound2; max = bound1;
}
return ((point >= min) && (point <= max));
}
/**
* Returns true if point is on the line segment, false otherwise.
*/
protected boolean onSegment(Point2D point, Line2D line) {
double minX, minY, maxX, maxY;
Point2D head = line.getP1();
Point2D tail = line.getP2();
if (head.getX() < tail.getX()) {
minX = head.getX(); maxX = tail.getX();
} else {
minX = tail.getX(); maxX = head.getX();
}
if (head.getY() < tail.getY()) {
minY = head.getY(); maxY = tail.getY();
} else {
minY = tail.getY(); maxY = head.getY();
}
if ((point.getX() >= minX) && (point.getX() <= maxX) &&
(point.getY() >= minY) && (point.getY() <= maxY))
return true;
return false;
}
}
| true | true |
protected Route planRoute(Cell cell, ElectricObject startObj, ElectricObject endObj, Point2D clicked) {
Route route = new Route(); // hold the route
if (cell == null) return route;
RouteElementPort startRE = null; // denote start of route
RouteElementPort endRE = null; // denote end of route
// first, convert NodeInsts to PortInsts, if it is one.
// Now we don't have to worry about NodeInsts.
startObj = filterRouteObject(startObj, clicked);
endObj = filterRouteObject(endObj, clicked);
// get the port types at each end so we can build electrical route
PortProto startPort = getRoutePort(startObj);
PortProto endPort;
if (endObj == null) {
// end object is null, we are routing to a pin. Figure out what arc to use
ArcProto useArc = getArcToUse(startPort, null);
if (useArc == null) return route;
PrimitiveNode pn = ((PrimitiveArc)useArc).findOverridablePinProto();
endPort = pn.getPort(0);
} else {
endPort = getRoutePort(endObj);
}
// now determine the electrical route. We need to know what
// arcs will be used (and their widths, eventually) to determine
// the Port Poly size for contacts
VerticalRoute vroute = VerticalRoute.newRoute(startPort, endPort);
if (!vroute.isSpecificationSucceeded()) return new Route();
// arc width of arcs that will connect to startObj, endObj will determine
// valid attachment points of arcs
ArcProto startArc = vroute.getStartArc();
ArcProto endArc = vroute.getEndArc();
double startArcWidth = getArcWidthToUse(startObj, startArc);
double endArcWidth = (endObj == null) ? startArcWidth : getArcWidthToUse(endObj, endArc);
// get valid connecting sites for start and end objects based on the objects
// themselves, the point the user clicked, and the width of the wire that will
// attach to each
Poly startPoly = getConnectingSite(startObj, clicked, startArcWidth);
Poly endPoly = getConnectingSite(endObj, clicked, endArcWidth);
//Poly startPoly = getConnectingSite(startObj, clicked, 3);
//Poly endPoly = getConnectingSite(endObj, clicked, 3);
// Now we can figure out where on the start and end objects the connecting
// arc(s) should connect
Point2D startPoint = new Point2D.Double(0, 0);
Point2D endPoint = new Point2D.Double(0,0);
getConnectingPoints(startObj, endObj, clicked, startPoint, endPoint, startPoly, endPoly, startArc, endArc);
PortInst existingStartPort = null;
PortInst existingEndPort = null;
// favor contact cuts on arcs
boolean contactsOnEndObject = true;
// plan start of route
if (startObj instanceof PortInst) {
// portinst: just wrap in RouteElement
existingStartPort = (PortInst)startObj;
startRE = RouteElementPort.existingPortInst(existingStartPort, startPoly);
}
if (startObj instanceof ArcInst) {
// arc: figure out where on arc to start
startRE = findArcConnectingPoint(route, (ArcInst)startObj, startPoint);
contactsOnEndObject = false;
}
if (startRE == null) {
if (startObj != badStartObject)
System.out.println(" Can't route from "+startObj+", no ports");
badStartObject = startObj;
return route;
}
// plan end of route
if (endObj != null) {
// we have somewhere to route to
if (endObj instanceof PortInst) {
// portinst: just wrap in RouteElement
existingEndPort = (PortInst)endObj;
endRE = RouteElementPort.existingPortInst(existingEndPort, endPoly);
}
if (endObj instanceof ArcInst) {
// arc: figure out where on arc to end
// use startRE location when possible if connecting to arc
endRE = findArcConnectingPoint(route, (ArcInst)endObj, endPoint);
contactsOnEndObject = true;
}
if (endRE == null) {
if (endObj != badEndObject)
System.out.println(" Can't route to "+endObj+", no ports");
badEndObject = endObj;
endObj = null;
}
}
if (endObj == null) {
// nowhere to route to, must make new pin to route to
// first we need to determine what pin to make based on
// start object
ArcProto useArc = null;
if (startObj instanceof PortInst) {
PortInst startPi = (PortInst)startObj;
useArc = getArcToUse(startPi.getPortProto(), null);
}
if (startObj instanceof ArcInst) {
ArcInst startAi = (ArcInst)startObj;
useArc = startAi.getProto();
}
if (!(useArc instanceof PrimitiveArc)) {
System.out.println(" Don't know how to determine pin for arc "+useArc);
return new Route();
}
// make new pin to route to
PrimitiveNode pn = ((PrimitiveArc)useArc).findOverridablePinProto();
SizeOffset so = pn.getProtoSizeOffset();
endRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), endPoint,
pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset(),
pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset());
}
// special check: if both are existing port insts and are same port, do nothing
if ((existingEndPort != null) && (existingEndPort == existingStartPort)) return new Route();
// add startRE and endRE to route
route.add(startRE);
route.setStart(startRE);
route.setEnd(startRE);
//route.add(endRE); route.setEnd(endRE);
// Tell Router to route between startRE and endRE
if (planRoute(route, cell, endRE, startPoint, endPoint, clicked, vroute, contactsOnEndObject)) {
return route;
} else
return new Route(); // error, return empty route
}
|
protected Route planRoute(Cell cell, ElectricObject startObj, ElectricObject endObj, Point2D clicked) {
Route route = new Route(); // hold the route
if (cell == null) return route;
RouteElementPort startRE = null; // denote start of route
RouteElementPort endRE = null; // denote end of route
// first, convert NodeInsts to PortInsts, if it is one.
// Now we don't have to worry about NodeInsts.
startObj = filterRouteObject(startObj, clicked);
endObj = filterRouteObject(endObj, clicked);
// get the port types at each end so we can build electrical route
PortProto startPort = getRoutePort(startObj);
PortProto endPort;
if (endObj == null) {
// end object is null, we are routing to a pin. Figure out what arc to use
ArcProto useArc = getArcToUse(startPort, null);
if (useArc == null) return route;
PrimitiveNode pn = ((PrimitiveArc)useArc).findOverridablePinProto();
endPort = pn.getPort(0);
} else {
endPort = getRoutePort(endObj);
}
// now determine the electrical route. We need to know what
// arcs will be used (and their widths, eventually) to determine
// the Port Poly size for contacts
VerticalRoute vroute = VerticalRoute.newRoute(startPort, endPort);
if (!vroute.isSpecificationSucceeded()) return new Route();
// arc width of arcs that will connect to startObj, endObj will determine
// valid attachment points of arcs
ArcProto startArc = vroute.getStartArc();
ArcProto endArc = vroute.getEndArc();
double startArcWidth = getArcWidthToUse(startObj, startArc);
double endArcWidth = (endObj == null) ? startArcWidth : getArcWidthToUse(endObj, endArc);
// get valid connecting sites for start and end objects based on the objects
// themselves, the point the user clicked, and the width of the wire that will
// attach to each
Poly startPoly = getConnectingSite(startObj, clicked, startArcWidth - startArc.getWidthOffset());
Poly endPoly = getConnectingSite(endObj, clicked, endArcWidth - endArc.getWidthOffset());
//Poly startPoly = getConnectingSite(startObj, clicked, 3);
//Poly endPoly = getConnectingSite(endObj, clicked, 3);
// Now we can figure out where on the start and end objects the connecting
// arc(s) should connect
Point2D startPoint = new Point2D.Double(0, 0);
Point2D endPoint = new Point2D.Double(0,0);
getConnectingPoints(startObj, endObj, clicked, startPoint, endPoint, startPoly, endPoly, startArc, endArc);
PortInst existingStartPort = null;
PortInst existingEndPort = null;
// favor contact cuts on arcs
boolean contactsOnEndObject = true;
// plan start of route
if (startObj instanceof PortInst) {
// portinst: just wrap in RouteElement
existingStartPort = (PortInst)startObj;
startRE = RouteElementPort.existingPortInst(existingStartPort, startPoly);
}
if (startObj instanceof ArcInst) {
// arc: figure out where on arc to start
startRE = findArcConnectingPoint(route, (ArcInst)startObj, startPoint);
contactsOnEndObject = false;
}
if (startRE == null) {
if (startObj != badStartObject)
System.out.println(" Can't route from "+startObj+", no ports");
badStartObject = startObj;
return route;
}
// plan end of route
if (endObj != null) {
// we have somewhere to route to
if (endObj instanceof PortInst) {
// portinst: just wrap in RouteElement
existingEndPort = (PortInst)endObj;
endRE = RouteElementPort.existingPortInst(existingEndPort, endPoly);
}
if (endObj instanceof ArcInst) {
// arc: figure out where on arc to end
// use startRE location when possible if connecting to arc
endRE = findArcConnectingPoint(route, (ArcInst)endObj, endPoint);
contactsOnEndObject = true;
}
if (endRE == null) {
if (endObj != badEndObject)
System.out.println(" Can't route to "+endObj+", no ports");
badEndObject = endObj;
endObj = null;
}
}
if (endObj == null) {
// nowhere to route to, must make new pin to route to
// first we need to determine what pin to make based on
// start object
ArcProto useArc = null;
if (startObj instanceof PortInst) {
PortInst startPi = (PortInst)startObj;
useArc = getArcToUse(startPi.getPortProto(), null);
}
if (startObj instanceof ArcInst) {
ArcInst startAi = (ArcInst)startObj;
useArc = startAi.getProto();
}
if (!(useArc instanceof PrimitiveArc)) {
System.out.println(" Don't know how to determine pin for arc "+useArc);
return new Route();
}
// make new pin to route to
PrimitiveNode pn = ((PrimitiveArc)useArc).findOverridablePinProto();
SizeOffset so = pn.getProtoSizeOffset();
endRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), endPoint,
pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset(),
pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset());
}
// special check: if both are existing port insts and are same port, do nothing
if ((existingEndPort != null) && (existingEndPort == existingStartPort)) return new Route();
// add startRE and endRE to route
route.add(startRE);
route.setStart(startRE);
route.setEnd(startRE);
//route.add(endRE); route.setEnd(endRE);
// Tell Router to route between startRE and endRE
if (planRoute(route, cell, endRE, startPoint, endPoint, clicked, vroute, contactsOnEndObject)) {
return route;
} else
return new Route(); // error, return empty route
}
|
diff --git a/robocode.core/src/main/java/net/sf/robocode/version/VersionManager.java b/robocode.core/src/main/java/net/sf/robocode/version/VersionManager.java
index 48ad49ea5..4dcb63c5d 100644
--- a/robocode.core/src/main/java/net/sf/robocode/version/VersionManager.java
+++ b/robocode.core/src/main/java/net/sf/robocode/version/VersionManager.java
@@ -1,371 +1,371 @@
/*******************************************************************************
* Copyright (c) 2001, 2008 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://robocode.sourceforge.net/license/cpl-v10.html
*
* Contributors:
* Pavel Savara
* - Initial implementation
*******************************************************************************/
package net.sf.robocode.version;
import net.sf.robocode.io.FileUtil;
import static net.sf.robocode.io.Logger.logError;
import static net.sf.robocode.io.Logger.logMessage;
import net.sf.robocode.settings.ISettingsManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* @author Pavel Savara (original)
* @author Mathew A. Nelson (original)
* @author Flemming N. Larsen (contributor)
*/
public final class VersionManager implements IVersionManager {
private static final String UNKNOWN_VERSION = "unknown";
private static Version version;
final ISettingsManager settingsManager;
final boolean versionChanged;
public VersionManager(ISettingsManager settingsManager) {
this.settingsManager = settingsManager;
if (settingsManager != null) {
versionChanged = !settingsManager.getLastRunVersion().equals(getVersion());
if (versionChanged) {
settingsManager.setLastRunVersion(getVersion());
}
} else {
versionChanged = false;
}
}
public String checkForNewVersion() {
String newVersLine = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
try {
URL url = new URL("http://robocode.sourceforge.net/version/version.html");
URLConnection urlConnection = url.openConnection();
urlConnection.setConnectTimeout(5000);
if (urlConnection instanceof HttpURLConnection) {
net.sf.robocode.io.Logger.logMessage("Update checking with http.");
HttpURLConnection h = (HttpURLConnection) urlConnection;
if (h.usingProxy()) {
net.sf.robocode.io.Logger.logMessage("http using proxy.");
}
}
inputStream = urlConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
newVersLine = reader.readLine();
} catch (MalformedURLException e) {
logError("Unable to check for new version", e);
newVersLine = null;
} catch (IOException e) {
logError("Unable to check for new version", e);
newVersLine = null;
} finally {
FileUtil.cleanupStream(inputStream);
FileUtil.cleanupStream(inputStreamReader);
FileUtil.cleanupStream(reader);
}
return newVersLine;
}
public boolean isFinal(String version) {
return new Version(version).isFinal();
}
public String getVersion() {
return getVersionInstance().toString();
}
private static Version getVersionInstance() {
if (version == null) {
version = new Version(getVersionFromJar());
}
return version;
}
public boolean isLastRunVersionChanged() {
return versionChanged;
}
public int getVersionAsInt() {
Version v = getVersionInstance();
return (v.getMajor() << 24) + (v.getMinor() << 16) + (v.getRevision() << 8) + v.getBuild();
}
private static String getVersionFromJar() {
String versionString = null;
BufferedReader in = null;
try {
URL versionsUrl = VersionManager.class.getResource("/versions.txt");
if (versionsUrl == null) {
logMessage("The URL for the versions.txt was not found");
versionString = UNKNOWN_VERSION;
} else {
final URLConnection connection = versionsUrl.openConnection();
connection.setUseCaches(false);
final InputStream is = connection.getInputStream();
in = new BufferedReader(new InputStreamReader(is));
versionString = in.readLine();
while (versionString != null && !versionString.substring(0, 8).equalsIgnoreCase("Version ")) {
versionString = in.readLine();
}
}
} catch (FileNotFoundException e) {
logError("No versions.txt file in robocode.jar");
versionString = UNKNOWN_VERSION;
} catch (IOException e) {
logError("IO Exception reading versions.txt from robocode.jar" + e);
versionString = UNKNOWN_VERSION;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignored) {}
}
}
String version = UNKNOWN_VERSION;
if (versionString != null && !versionString.equals(UNKNOWN_VERSION)) {
try {
version = versionString.substring(7);
} catch (Exception ignore) {}
}
if (version.equals(UNKNOWN_VERSION)) {
logMessage("Warning: Getting version from file");
return getVersionFromFile();
}
return version;
}
private static String getVersionFromFile() {
String versionString = null;
FileReader fileReader = null;
BufferedReader in = null;
try {
File dir = FileUtil.getCwd();
if (System.getProperty("TESTING", "false").equals("true")) {
dir = dir.getParentFile().getParentFile().getParentFile();
}
fileReader = new FileReader(new File(dir, "versions.txt"));
in = new BufferedReader(fileReader);
versionString = in.readLine();
} catch (FileNotFoundException e) {
logError("No versions.txt file.");
versionString = UNKNOWN_VERSION;
} catch (IOException e) {
logError("IO Exception reading versions.txt" + e);
versionString = UNKNOWN_VERSION;
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException ignored) {}
}
if (in != null) {
try {
in.close();
} catch (IOException ignored) {}
}
}
String version = UNKNOWN_VERSION;
if (versionString != null && !versionString.equals(UNKNOWN_VERSION)) {
try {
version = versionString.substring(7);
} catch (Exception ignore) {}
}
return version;
}
public int compare(String a, String b) {
return new Version(a).compareTo(new Version(b));
}
static class Version implements Comparable<Object> {
private final String version;
// The allowed format is <major>.<minor>.<revision>.<build> where all of these are ints
private final int major;
private final int minor;
private final int revision;
private final int build;
// <maturity> <maturity version>, e.g. in "Beta 3" the maturity is 2, and maturity version is 3
public final int maturity; // Alpha is 1, Beta is 2, Final is 3
public final int maturity_version; // The number following e.g. "Alpha" or "Beta"
public Version(String version) {
// Validate version format
if (!version.matches(
- "\\s*[0-9]+\\.[0-9]+(\\.[0-9]+)?(\\.[0-9]+)?(\\s?(([aA]lpha)|([bB]eta))(\\s?[0-9])?)?\\s*")) {
+ "\\s*[0-9]+\\.[0-9]+(\\.[0-9]+)?(\\.[0-9]+)?(\\s?(([aA]lpha)|([bB]eta))(\\s?[0-9]+)?)?\\s*")) {
throw new IllegalArgumentException("The format of the version string is not a valid");
}
this.version = version;
// Split the version number into its integer numbers
final String[] numbers = version.trim().split("\\.");
// Parse the major version
int major = 0;
if (numbers.length >= 1) {
try {
major = Integer.parseInt(numbers[0]);
} catch (NumberFormatException ignore) {}
}
this.major = major;
// Parse the minor version
int minor = 0;
if (numbers.length >= 2) {
try {
String[] split = numbers[1].split("\\s++|([aA]lpha)|([bB]eta)");
minor = Integer.parseInt(split[0]);
} catch (NumberFormatException ignore) {}
}
this.minor = minor;
// Parse the revision
int revision = 0;
if (numbers.length >= 3) {
try {
String[] split = numbers[2].split("\\s++|([aA]lpha)|([bB]eta)");
revision = Integer.parseInt(split[0]);
} catch (NumberFormatException ignore) {}
}
this.revision = revision;
// Parse the build number
int build = 0;
if (numbers.length >= 4) {
try {
String[] split = numbers[3].split("\\s++|([aA]lpha)|([bB]eta)");
build = Integer.parseInt(split[0]);
} catch (NumberFormatException ignore) {}
}
this.build = build;
// Parse the maturity version, e.g. "Beta 1"
int maturity;
int maturity_version = 1;
if (isAlpha()) {
maturity = 1;
final String[] split = version.split("[aA]lpha");
if (split.length >= 2) {
maturity_version = Integer.parseInt(split[1].trim());
}
} else if (isBeta()) {
maturity = 2;
final String[] split = version.split("[bB]eta");
if (split.length >= 2) {
maturity_version = Integer.parseInt(split[1].trim());
}
} else {
maturity = 3;
}
this.maturity = maturity;
this.maturity_version = maturity_version;
}
public boolean isAlpha() {
return (version.matches(".*[aA]lpha.*"));
}
public boolean isBeta() {
return (version.matches(".*[bB]eta.*"));
}
public boolean isFinal() {
return !(isAlpha() || isBeta());
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getRevision() {
return revision;
}
public int getBuild() {
return build;
}
@Override
public String toString() {
return version;
}
public int compareTo(Object o) {
if (o == null) {
throw new IllegalArgumentException("The input object cannot be null");
}
if (o instanceof String) {
return compareTo(new Version((String) o));
}
if (o instanceof Version) {
Version v = (Version) o;
long delta = getVersionLong() - v.getVersionLong();
return (delta == 0) ? 0 : (delta < 0) ? -1 : 1;
}
throw new IllegalArgumentException("The input object must be a String or Version object");
}
private long getVersionLong() {
return ((long) major << 40) + ((long) minor << 32) + (revision << 24) + (build << 16) + (maturity << 8)
+ maturity_version;
}
}
}
| true | true |
public Version(String version) {
// Validate version format
if (!version.matches(
"\\s*[0-9]+\\.[0-9]+(\\.[0-9]+)?(\\.[0-9]+)?(\\s?(([aA]lpha)|([bB]eta))(\\s?[0-9])?)?\\s*")) {
throw new IllegalArgumentException("The format of the version string is not a valid");
}
this.version = version;
// Split the version number into its integer numbers
final String[] numbers = version.trim().split("\\.");
// Parse the major version
int major = 0;
if (numbers.length >= 1) {
try {
major = Integer.parseInt(numbers[0]);
} catch (NumberFormatException ignore) {}
}
this.major = major;
// Parse the minor version
int minor = 0;
if (numbers.length >= 2) {
try {
String[] split = numbers[1].split("\\s++|([aA]lpha)|([bB]eta)");
minor = Integer.parseInt(split[0]);
} catch (NumberFormatException ignore) {}
}
this.minor = minor;
// Parse the revision
int revision = 0;
if (numbers.length >= 3) {
try {
String[] split = numbers[2].split("\\s++|([aA]lpha)|([bB]eta)");
revision = Integer.parseInt(split[0]);
} catch (NumberFormatException ignore) {}
}
this.revision = revision;
// Parse the build number
int build = 0;
if (numbers.length >= 4) {
try {
String[] split = numbers[3].split("\\s++|([aA]lpha)|([bB]eta)");
build = Integer.parseInt(split[0]);
} catch (NumberFormatException ignore) {}
}
this.build = build;
// Parse the maturity version, e.g. "Beta 1"
int maturity;
int maturity_version = 1;
if (isAlpha()) {
maturity = 1;
final String[] split = version.split("[aA]lpha");
if (split.length >= 2) {
maturity_version = Integer.parseInt(split[1].trim());
}
} else if (isBeta()) {
maturity = 2;
final String[] split = version.split("[bB]eta");
if (split.length >= 2) {
maturity_version = Integer.parseInt(split[1].trim());
}
} else {
maturity = 3;
}
this.maturity = maturity;
this.maturity_version = maturity_version;
}
|
public Version(String version) {
// Validate version format
if (!version.matches(
"\\s*[0-9]+\\.[0-9]+(\\.[0-9]+)?(\\.[0-9]+)?(\\s?(([aA]lpha)|([bB]eta))(\\s?[0-9]+)?)?\\s*")) {
throw new IllegalArgumentException("The format of the version string is not a valid");
}
this.version = version;
// Split the version number into its integer numbers
final String[] numbers = version.trim().split("\\.");
// Parse the major version
int major = 0;
if (numbers.length >= 1) {
try {
major = Integer.parseInt(numbers[0]);
} catch (NumberFormatException ignore) {}
}
this.major = major;
// Parse the minor version
int minor = 0;
if (numbers.length >= 2) {
try {
String[] split = numbers[1].split("\\s++|([aA]lpha)|([bB]eta)");
minor = Integer.parseInt(split[0]);
} catch (NumberFormatException ignore) {}
}
this.minor = minor;
// Parse the revision
int revision = 0;
if (numbers.length >= 3) {
try {
String[] split = numbers[2].split("\\s++|([aA]lpha)|([bB]eta)");
revision = Integer.parseInt(split[0]);
} catch (NumberFormatException ignore) {}
}
this.revision = revision;
// Parse the build number
int build = 0;
if (numbers.length >= 4) {
try {
String[] split = numbers[3].split("\\s++|([aA]lpha)|([bB]eta)");
build = Integer.parseInt(split[0]);
} catch (NumberFormatException ignore) {}
}
this.build = build;
// Parse the maturity version, e.g. "Beta 1"
int maturity;
int maturity_version = 1;
if (isAlpha()) {
maturity = 1;
final String[] split = version.split("[aA]lpha");
if (split.length >= 2) {
maturity_version = Integer.parseInt(split[1].trim());
}
} else if (isBeta()) {
maturity = 2;
final String[] split = version.split("[bB]eta");
if (split.length >= 2) {
maturity_version = Integer.parseInt(split[1].trim());
}
} else {
maturity = 3;
}
this.maturity = maturity;
this.maturity_version = maturity_version;
}
|
diff --git a/src/main/java/tconstruct/library/tools/AbilityHelper.java b/src/main/java/tconstruct/library/tools/AbilityHelper.java
index 7e3df5588..a21abac08 100644
--- a/src/main/java/tconstruct/library/tools/AbilityHelper.java
+++ b/src/main/java/tconstruct/library/tools/AbilityHelper.java
@@ -1,788 +1,789 @@
package tconstruct.library.tools;
import cofh.api.energy.IEnergyContainerItem;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.eventhandler.Event.Result;
import java.util.*;
import net.minecraft.block.Block;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.*;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.monster.*;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.entity.player.*;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.stats.*;
import net.minecraft.util.*;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.event.entity.player.UseHoeEvent;
import tconstruct.TConstruct;
import tconstruct.library.*;
import tconstruct.library.util.PiercingEntityDamage;
public class AbilityHelper
{
public static Random random = new Random();
public static boolean necroticUHS;
/* Normal interactions */
public static boolean onBlockChanged (ItemStack stack, World world, Block block, int x, int y, int z, EntityLivingBase player, Random random)
{
if (!stack.hasTagCompound())
return false;
int reinforced = 0;
NBTTagCompound tags = stack.getTagCompound();
if (tags.getCompoundTag("InfiTool").hasKey("Unbreaking"))
reinforced = tags.getCompoundTag("InfiTool").getInteger("Unbreaking");
if (random.nextInt(10) < 10 - reinforced)
{
damageTool(stack, 1, tags, player, false);
}
return true;
}
public static boolean onLeftClickEntity (ItemStack stack, EntityLivingBase player, Entity entity, ToolCore tool)
{
return onLeftClickEntity(stack, player, entity, tool, 0);
}
public static boolean onLeftClickEntity (ItemStack stack, EntityLivingBase player, Entity entity, ToolCore tool, int baseDamage)
{
if (entity.canAttackWithItem() && stack.hasTagCompound())
{
if (!entity.hitByEntity(player)) // can't attack this entity
{
NBTTagCompound tags = stack.getTagCompound();
NBTTagCompound toolTags = stack.getTagCompound().getCompoundTag("InfiTool");
boolean broken = toolTags.getBoolean("Broken");
int durability = tags.getCompoundTag("InfiTool").getInteger("Damage");
float stonebound = tags.getCompoundTag("InfiTool").getFloat("Shoddy");
float stoneboundDamage = (float) Math.log(durability / 72f + 1) * -2 * stonebound;
int damage = calcDamage(player, entity, stack, tool, toolTags, baseDamage);
float knockback = calcKnockback(player, entity, stack, tool, toolTags, baseDamage);
float enchantDamage = 0;
// magic extra damage
if (entity instanceof EntityLivingBase)
{
enchantDamage = EnchantmentHelper.getEnchantmentModifierLiving(player, (EntityLivingBase) entity);
}
if (damage > 0 || enchantDamage > 0)
{
boolean criticalHit = player.fallDistance > 0.0F && !player.onGround && !player.isOnLadder() && !player.isInWater() && !player.isPotionActive(Potion.blindness) && player.ridingEntity == null && entity instanceof EntityLivingBase;
for (ActiveToolMod mod : TConstructRegistry.activeModifiers)
{
if (mod.doesCriticalHit(tool, tags, toolTags, stack, player, entity))
criticalHit = true;
}
if (criticalHit)
{
damage += random.nextInt(damage / 2 + 2);
}
damage += enchantDamage;
if (tool.getDamageModifier() != 1f)
{
damage *= tool.getDamageModifier();
}
if (broken)
{
if (baseDamage > 0)
damage = baseDamage;
else
damage = 1;
}
boolean causedDamage = false;
+ boolean isAlive = entity.isEntityAlive();
if (tool.pierceArmor() && !broken)
{
if (player instanceof EntityPlayer)
causedDamage = entity.attackEntityFrom(causePlayerPiercingDamage((EntityPlayer) player), damage);
else
causedDamage = entity.attackEntityFrom(causePiercingDamage(player), damage);
}
else
{
if (player instanceof EntityPlayer)
causedDamage = entity.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) player), damage);
else
causedDamage = entity.attackEntityFrom(DamageSource.causeMobDamage(player), damage);
}
if (causedDamage)
{
damageTool(stack, 1, tags, player, false);
// damageTool(stack, 1, player, false);
tool.onEntityDamaged(player.worldObj, player, entity);
if (!necroticUHS || (entity instanceof IMob && entity instanceof EntityLivingBase && ((EntityLivingBase) entity).getHealth() <= 0))
{
- if(entity.isEntityAlive()) {
+ if(isAlive) {
int drain = toolTags.getInteger("Necrotic") * 2;
if (drain > 0)
player.heal(random.nextInt(drain + 1));
}
}
if (knockback > 0)
{
entity.addVelocity((double) (-MathHelper.sin(player.rotationYaw * (float) Math.PI / 180.0F) * (float) knockback * 0.5F), 0.1D, (double) (MathHelper.cos(player.rotationYaw * (float) Math.PI / 180.0F) * (float) knockback * 0.5F));
player.motionX *= 0.6D;
player.motionZ *= 0.6D;
player.setSprinting(false);
}
if (player instanceof EntityPlayer)
{
if (criticalHit)
{
((EntityPlayer) player).onCriticalHit(entity);
}
if (enchantDamage > 0)
{
((EntityPlayer) player).onEnchantmentCritical(entity);
}
if (damage >= 18)
{
((EntityPlayer) player).triggerAchievement(AchievementList.overkill);
}
}
player.setLastAttacker(entity);
if (entity instanceof EntityLivingBase)
{
DamageSource.causeThornsDamage(entity);// (((EntityLivingBase)player,
// (EntityLivingBase)
// entity);
}
}
if (entity instanceof EntityLivingBase)
{
if (entity instanceof EntityPlayer)
{
stack.hitEntity((EntityLivingBase) entity, (EntityPlayer) player);
if (entity.isEntityAlive())
{
alertPlayerWolves((EntityPlayer) player, (EntityLivingBase) entity, true);
}
((EntityPlayer) player).addStat(StatList.damageDealtStat, damage);
}
else
{
stack.getItem().hitEntity(stack, (EntityLivingBase) entity, player);
}
if(causedDamage)
processFiery(player, entity, toolTags);
}
if (entity instanceof EntityPlayer)
((EntityPlayer) player).addExhaustion(0.3F);
if (causedDamage)
return true;
}
}
}
return false;
}
public static int calcDamage(Entity user, Entity entity, ItemStack stack, ToolCore tool, NBTTagCompound toolTags, int baseDamage)
{
EntityLivingBase living = user instanceof EntityLivingBase ? (EntityLivingBase)user : null;
int damage = toolTags.getInteger("Attack") + baseDamage;
int earlyModDamage = 0;
for (ActiveToolMod mod : TConstructRegistry.activeModifiers)
{
earlyModDamage = mod.baseAttackDamage(earlyModDamage, damage, tool, stack.getTagCompound(), toolTags, stack, living, entity);
}
damage += earlyModDamage;
if(living != null) {
if (living.isPotionActive(Potion.damageBoost)) {
damage += 3 << living.getActivePotionEffect(Potion.damageBoost).getAmplifier();
}
if (living.isPotionActive(Potion.weakness)) {
damage -= 2 << living.getActivePotionEffect(Potion.weakness).getAmplifier();
}
}
damage -= calcStoneboundBonus(tool, toolTags);
if (damage < 1)
damage = 1;
if (living != null && living.isSprinting())
{
float lunge = tool.chargeAttack();
if (lunge > 1f)
{
damage *= lunge;
}
}
int modDamage = 0;
for (ActiveToolMod mod : TConstructRegistry.activeModifiers)
{
modDamage = mod.attackDamage(modDamage, damage, tool, stack.getTagCompound(), toolTags, stack, living, entity);
}
damage += modDamage;
return damage;
}
public static float calcKnockback(Entity user, Entity entity, ItemStack stack, ToolCore tool, NBTTagCompound toolTags, int baseDamage)
{
float knockback = 0;
if (entity instanceof EntityLivingBase && user instanceof EntityLivingBase)
{
knockback += EnchantmentHelper.getKnockbackModifier((EntityLivingBase)user, (EntityLivingBase) entity);
}
if (user.isSprinting())
{
knockback++;
float lunge = tool.chargeAttack();
if (lunge > 1f)
{
knockback += lunge - 1.0f;
}
}
float modKnockback = 0f;
for (ActiveToolMod mod : TConstructRegistry.activeModifiers)
{
modKnockback = mod.knockback(modKnockback, knockback, tool, stack.getTagCompound(), toolTags, stack, user instanceof EntityLivingBase ? (EntityLivingBase)user : null, entity);
}
knockback += modKnockback;
return knockback;
}
public static void processFiery(Entity player, Entity target, NBTTagCompound toolTags)
{
// only living things burnnnn
if(!(target instanceof EntityLivingBase))
return;
int fireAspect = 0;
if(player instanceof EntityLivingBase)
fireAspect = EnchantmentHelper.getFireAspectModifier((EntityLivingBase)player);
if ((fireAspect > 0 || toolTags.hasKey("Fiery") || toolTags.hasKey("Lava")))
{
fireAspect *= 4;
if (toolTags.hasKey("Fiery"))
{
fireAspect += toolTags.getInteger("Fiery") / 5 + 1;
}
if (toolTags.getBoolean("Lava"))
{
fireAspect += 3;
}
target.setFire(fireAspect);
}
}
static void alertPlayerWolves (EntityPlayer player, EntityLivingBase living, boolean par2)
{
if (!(living instanceof EntityCreeper) && !(living instanceof EntityGhast))
{
if (living instanceof EntityWolf)
{
EntityWolf var3 = (EntityWolf) living;
if (var3.isTamed() && player.getDisplayName().equals(var3.func_152113_b()))
{
return;
}
}
if (!(living instanceof EntityPlayer) || player.canAttackPlayer((EntityPlayer) living))
{
List var6 = player.worldObj.getEntitiesWithinAABB(EntityWolf.class, AxisAlignedBB.getBoundingBox(player.posX, player.posY, player.posZ, player.posX + 1.0D, player.posY + 1.0D, player.posZ + 1.0D).expand(16.0D, 4.0D, 16.0D));
Iterator var4 = var6.iterator();
while (var4.hasNext())
{
EntityWolf var5 = (EntityWolf) var4.next();
if (var5.isTamed() && var5.getEntityToAttack() == null && player.getDisplayName().equals(var5.func_152113_b()) && (!par2 || !var5.isSitting()))
{
var5.setSitting(false);
var5.setTarget(living);
}
}
}
}
}
/* Tool specific */
public static void damageTool (ItemStack stack, int dam, EntityLivingBase entity, boolean ignoreCharge)
{
NBTTagCompound tags = stack.getTagCompound();
damageTool(stack, dam, tags, entity, ignoreCharge);
}
public static void healTool (ItemStack stack, int dam, EntityLivingBase entity, boolean ignoreCharge)
{
NBTTagCompound tags = stack.getTagCompound();
damageTool(stack, -dam, tags, entity, ignoreCharge);
}
public static void damageTool (ItemStack stack, int dam, NBTTagCompound tags, EntityLivingBase entity, boolean ignoreCharge)
{
if (entity instanceof EntityPlayer && ((EntityPlayer) entity).capabilities.isCreativeMode || tags == null)
return;
// calculate in reinforced/unbreaking
int reinforced = 0;
if(tags.hasKey("InfiTool") && dam > 0) // unbreaking only affects damage, not healing
{
NBTTagCompound toolTags = tags.getCompoundTag("InfiTool");
if(toolTags.hasKey("Unbreaking"))
{
reinforced = tags.getCompoundTag("InfiTool").getInteger("Unbreaking");
// for each point of damage we deal, we separately decide if reinforced takes effect
for(int i = dam; i > 0; i--)
if(random.nextInt(10) < reinforced)
dam--;
// we prevented all damage with reinforced
if(dam <= 0)
return;
}
}
if (ignoreCharge || !damageEnergyTool(stack, tags, entity))
{
boolean damagedTool = false;
for (ActiveToolMod mod : TConstructRegistry.activeModifiers)
{
if (mod.damageTool(stack, dam, entity))
damagedTool = true;
}
if (damagedTool)
return;
int damage = tags.getCompoundTag("InfiTool").getInteger("Damage");
int damageTrue = damage + dam;
int maxDamage = tags.getCompoundTag("InfiTool").getInteger("TotalDurability");
if (damageTrue <= 0)
{
tags.getCompoundTag("InfiTool").setInteger("Damage", 0);
//stack.setItemDamage(0);
tags.getCompoundTag("InfiTool").setBoolean("Broken", false);
}
else if (damageTrue > maxDamage)
{
breakTool(stack, tags, entity);
//stack.setItemDamage(0);
}
else
{
tags.getCompoundTag("InfiTool").setInteger("Damage", damage + dam);
int toolDamage = (damage * 100 / maxDamage) + 1;
int stackDamage = stack.getItemDamage();
if (toolDamage != stackDamage)
{
//stack.setItemDamage((damage * 100 / maxDamage) + 1);
}
}
}
}
public static boolean damageEnergyTool (ItemStack stack, NBTTagCompound tags, Entity entity)
{
if (!tags.hasKey("Energy"))
return false;
NBTTagCompound toolTag = stack.getTagCompound().getCompoundTag("InfiTool");
int energy = tags.getInteger("Energy");
int durability = toolTag.getInteger("Damage");
float shoddy = toolTag.getFloat("Shoddy");
float mineSpeed = toolTag.getInteger("MiningSpeed");
int heads = 1;
if (toolTag.hasKey("MiningSpeed2"))
{
mineSpeed += toolTag.getInteger("MiningSpeed2");
heads++;
}
if (toolTag.hasKey("MiningSpeedHandle"))
{
mineSpeed += toolTag.getInteger("MiningSpeedHandle");
heads++;
}
if (toolTag.hasKey("MiningSpeedExtra"))
{
mineSpeed += toolTag.getInteger("MiningSpeedExtra");
heads++;
}
float trueSpeed = mineSpeed / (heads * 100f);
float stonebound = toolTag.getFloat("Shoddy");
float bonusLog = (float) Math.log(durability / 72f + 1) * 2 * stonebound;
trueSpeed += bonusLog;
trueSpeed *= 6;
if (energy != -1)
{
int usage = (int)(trueSpeed * 2.8f);
// first try charging from the hotbar if we don't have CoFHs override
if (!equalityOverrideLoaded && entity instanceof EntityPlayer)
{
ToolCore tool = (ToolCore) stack.getItem();
// workaround for charging flux-capacitors making tools unusable
chargeEnergyFromHotbar(stack, (EntityPlayer) entity, tags);
energy = tool.getEnergyStored(stack);
}
if (energy < usage)
{
if (energy > 0)
tags.setInteger("Energy", 0);
return false;
}
energy -= usage;
tags.setInteger("Energy", energy);
//stack.setItemDamage(1 + (tool.getMaxEnergyStored(stack) - energy) * (stack.getMaxDamage() - 1) / tool.getMaxEnergyStored(stack));
}
return true;
}
protected static void chargeEnergyFromHotbar (ItemStack stack, EntityPlayer player, NBTTagCompound tags)
{
// cool kids only
if (!(stack.getItem() instanceof ToolCore))
return;
ToolCore tool = (ToolCore) stack.getItem();
// check if the tool can actually receive energy
if (tool.receiveEnergy(stack, 1, true) != 1)
// no you're not going to charge that potato battery on your tool
return;
int buffer = tool.getEnergyStored(stack);
int max = tool.getMaxEnergyStored(stack);
int missing = max - buffer;
// you're full. xbox go home.
if (missing <= 0)
return;
// iterate through hotbar
for (int iter = 0; iter < 9; ++iter)
{
ItemStack slot = player.inventory.mainInventory[iter];
// check if item is not another tool
if (slot == null || slot.getItem() instanceof ToolCore)
continue;
// check if item gives energy
if (!(slot.getItem() instanceof IEnergyContainerItem))
continue;
IEnergyContainerItem fluxItem = (IEnergyContainerItem) slot.getItem();
// mDiyo EATS your power
while (fluxItem.extractEnergy(slot, missing, true) > 0)
{
missing -= fluxItem.extractEnergy(slot, missing, false);
}
}
// update energy
tags.setInteger("Energy", max - missing);
}
private static boolean equalityOverrideLoaded = Loader.isModLoaded("CoFHCore"); // Mods should be loaded far enough before this is ever initialized
public static void breakTool (ItemStack stack, NBTTagCompound tags, Entity entity)
{
tags.getCompoundTag("InfiTool").setBoolean("Broken", true);
if (entity != null)
entity.worldObj.playSound(entity.posX, entity.posY, entity.posZ, "random.break", 1f, 1f, true);
}
public static void repairTool (ItemStack stack, NBTTagCompound tags)
{
tags.getCompoundTag("InfiTool").setBoolean("Broken", false);
tags.getCompoundTag("InfiTool").setInteger("Damage", 0);
}
public static DamageSource causePiercingDamage (EntityLivingBase mob)
{
return new PiercingEntityDamage("mob", mob);
}
public static DamageSource causePlayerPiercingDamage (EntityPlayer player)
{
return new PiercingEntityDamage("player", player);
}
public static void knockbackEntity (EntityLivingBase living, double boost)
{
living.motionX *= boost;
// living.motionY *= boost/2;
living.motionZ *= boost;
}
public static boolean hoeGround (ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, Random random)
{
if (!player.canPlayerEdit(x, y, z, side, stack))
{
return false;
}
else
{
UseHoeEvent event = new UseHoeEvent(player, stack, world, x, y, z);
if (MinecraftForge.EVENT_BUS.post(event))
{
return false;
}
if (event.getResult() == Result.ALLOW)
{
damageTool(stack, 1, player, false);
return true;
}
Block block = world.getBlock(x, y, z);
if (side != 0 && world.getBlock(x, y + 1, z).isAir(world, x, y + 1, z) && (block == Blocks.grass || block == Blocks.dirt))
{
Block block1 = Blocks.farmland;
world.playSoundEffect((double) ((float) x + 0.5F), (double) ((float) y + 0.5F), (double) ((float) z + 0.5F), block1.stepSound.getStepResourcePath(), (block1.stepSound.getVolume() + 1.0F) / 2.0F, block1.stepSound.getPitch() * 0.8F);
if (world.isRemote)
{
return true;
}
else
{
world.setBlock(x, y, z, block1);
damageTool(stack, 1, player, false);
return true;
}
}
else
{
return false;
}
}
}
public static void spawnItemAtEntity (Entity entity, ItemStack stack, int delay)
{
if (!entity.worldObj.isRemote)
{
EntityItem entityitem = new EntityItem(entity.worldObj, entity.posX + 0.5D, entity.posY + 0.5D, entity.posZ + 0.5D, stack);
entityitem.delayBeforeCanPickup = delay;
entity.worldObj.spawnEntityInWorld(entityitem);
}
}
public static void spawnItemAtPlayer (EntityPlayer player, ItemStack stack)
{
if (!player.worldObj.isRemote)
{
// try to put it into the players inventory
if(player instanceof FakePlayer || !player.inventory.addItemStackToInventory(stack)) // note that the addItemStackToInventory is not called for fake players
{
// drop the rest as an entity
EntityItem entityitem = new EntityItem(player.worldObj, player.posX + 0.5D, player.posY + 0.5D, player.posZ + 0.5D, stack);
player.worldObj.spawnEntityInWorld(entityitem);
if (!(player instanceof FakePlayer))
entityitem.onCollideWithPlayer(player);
}
// if it got picked up, we're playing the sound
else {
if(player instanceof EntityPlayerMP) {
player.worldObj.playSoundAtEntity(player, "random.pop", 0.2F, ((TConstruct.random.nextFloat() - TConstruct.random.nextFloat()) * 0.7F + 1.0F) * 2.0F);
player.inventoryContainer.detectAndSendChanges();
}
}
}
}
/* Ranged weapons */
public static void forceAddToInv (EntityPlayer entityplayer, ItemStack itemstack, int i, boolean flag)
{
ItemStack itemstack1 = entityplayer.inventory.getStackInSlot(i);
entityplayer.inventory.setInventorySlotContents(i, itemstack);
if (itemstack1 != null)
{
addToInv(entityplayer, itemstack1, flag);
}
}
public static boolean addToInv (EntityPlayer entityplayer, ItemStack itemstack, boolean flag)
{
return addToInv(entityplayer, itemstack, entityplayer.inventory.currentItem, flag);
}
public static boolean addToInv (EntityPlayer entityplayer, ItemStack itemstack, int i, boolean flag)
{
ItemStack itemstack1 = entityplayer.inventory.getStackInSlot(i);
boolean flag1;
if (itemstack1 == null)
{
entityplayer.inventory.setInventorySlotContents(i, itemstack);
flag1 = true;
}
else
{
flag1 = entityplayer.inventory.addItemStackToInventory(itemstack);
}
if (flag && !flag1)
{
addItemStackToWorld(entityplayer.worldObj, (float) Math.floor(entityplayer.posX), (float) Math.floor(entityplayer.posY), (float) Math.floor(entityplayer.posZ), itemstack);
return true;
}
else
{
return flag1;
}
}
public static EntityItem addItemStackToWorld (World world, float f, float f1, float f2, ItemStack itemstack)
{
return addItemStackToWorld(world, f, f1, f2, itemstack, false);
}
public static EntityItem addItemStackToWorld (World world, float f, float f1, float f2, ItemStack itemstack, boolean flag)
{
EntityItem entityitem;
if (flag)
{
entityitem = new EntityItem(world, f, f1, f2, itemstack);
}
else
{
float f3 = 0.7F;
float f4 = random.nextFloat() * f3 + (1.0F - f3) * 0.5F;
float f5 = 1.2F;
float f6 = random.nextFloat() * f3 + (1.0F - f3) * 0.5F;
entityitem = new EntityItem(world, f + f4, f1 + f5, f2 + f6, itemstack);
}
entityitem.delayBeforeCanPickup = 10;
world.spawnEntityInWorld(entityitem);
return entityitem;
}
public static MovingObjectPosition raytraceFromEntity (World world, Entity player, boolean par3, double range)
{
float f = 1.0F;
float f1 = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * f;
float f2 = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * f;
double d0 = player.prevPosX + (player.posX - player.prevPosX) * (double) f;
double d1 = player.prevPosY + (player.posY - player.prevPosY) * (double) f;
if (!world.isRemote && player instanceof EntityPlayer)
d1 += 1.62D;
double d2 = player.prevPosZ + (player.posZ - player.prevPosZ) * (double) f;
Vec3 vec3 = Vec3.createVectorHelper(d0, d1, d2);
float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI);
float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI);
float f5 = -MathHelper.cos(-f1 * 0.017453292F);
float f6 = MathHelper.sin(-f1 * 0.017453292F);
float f7 = f4 * f5;
float f8 = f3 * f5;
double d3 = range;
if (player instanceof EntityPlayerMP)
{
d3 = ((EntityPlayerMP) player).theItemInWorldManager.getBlockReachDistance();
}
Vec3 vec31 = vec3.addVector((double) f7 * d3, (double) f6 * d3, (double) f8 * d3);
return world.func_147447_a(vec3, vec31, par3, !par3, par3);
}
public static float calcToolSpeed (ToolCore tool, NBTTagCompound tags)
{
float mineSpeed = tags.getInteger("MiningSpeed");
int heads = 1;
if (tags.hasKey("MiningSpeed2"))
{
mineSpeed += tags.getInteger("MiningSpeed2");
heads++;
}
if (tags.hasKey("MiningSpeedHandle"))
{
mineSpeed += tags.getInteger("MiningSpeedHandle");
heads++;
}
if (tags.hasKey("MiningSpeedExtra"))
{
mineSpeed += tags.getInteger("MiningSpeedExtra");
heads++;
}
float speedMod = 1f;
if (tool instanceof HarvestTool)
speedMod = ((HarvestTool) tool).breakSpeedModifier();
float trueSpeed = mineSpeed / (heads * 100f) * speedMod;
trueSpeed += calcStoneboundBonus(tool, tags);
return trueSpeed;
}
public static float calcDualToolSpeed (ToolCore tool, NBTTagCompound tags, boolean secondary)
{
String tag = "MiningSpeed";
if(secondary) tag += "2";
float mineSpeed = tags.getInteger(tag);
float speedMod = 1f;
if (tool instanceof HarvestTool)
speedMod = ((HarvestTool) tool).breakSpeedModifier();
float trueSpeed = mineSpeed / 100f * speedMod;
trueSpeed += calcStoneboundBonus(tool, tags);
return trueSpeed;
}
public static float calcStoneboundBonus (ToolCore tool, NBTTagCompound tags)
{
int durability = tags.getInteger("Damage");
float stonebound = tags.getFloat("Shoddy");
float stoneboundMod = 72f;
if (tool instanceof HarvestTool)
stoneboundMod = ((HarvestTool) tool).stoneboundModifier();
return (float) Math.log(durability / stoneboundMod + 1) * 2 * stonebound;
}
}
| false | true |
public static boolean onLeftClickEntity (ItemStack stack, EntityLivingBase player, Entity entity, ToolCore tool, int baseDamage)
{
if (entity.canAttackWithItem() && stack.hasTagCompound())
{
if (!entity.hitByEntity(player)) // can't attack this entity
{
NBTTagCompound tags = stack.getTagCompound();
NBTTagCompound toolTags = stack.getTagCompound().getCompoundTag("InfiTool");
boolean broken = toolTags.getBoolean("Broken");
int durability = tags.getCompoundTag("InfiTool").getInteger("Damage");
float stonebound = tags.getCompoundTag("InfiTool").getFloat("Shoddy");
float stoneboundDamage = (float) Math.log(durability / 72f + 1) * -2 * stonebound;
int damage = calcDamage(player, entity, stack, tool, toolTags, baseDamage);
float knockback = calcKnockback(player, entity, stack, tool, toolTags, baseDamage);
float enchantDamage = 0;
// magic extra damage
if (entity instanceof EntityLivingBase)
{
enchantDamage = EnchantmentHelper.getEnchantmentModifierLiving(player, (EntityLivingBase) entity);
}
if (damage > 0 || enchantDamage > 0)
{
boolean criticalHit = player.fallDistance > 0.0F && !player.onGround && !player.isOnLadder() && !player.isInWater() && !player.isPotionActive(Potion.blindness) && player.ridingEntity == null && entity instanceof EntityLivingBase;
for (ActiveToolMod mod : TConstructRegistry.activeModifiers)
{
if (mod.doesCriticalHit(tool, tags, toolTags, stack, player, entity))
criticalHit = true;
}
if (criticalHit)
{
damage += random.nextInt(damage / 2 + 2);
}
damage += enchantDamage;
if (tool.getDamageModifier() != 1f)
{
damage *= tool.getDamageModifier();
}
if (broken)
{
if (baseDamage > 0)
damage = baseDamage;
else
damage = 1;
}
boolean causedDamage = false;
if (tool.pierceArmor() && !broken)
{
if (player instanceof EntityPlayer)
causedDamage = entity.attackEntityFrom(causePlayerPiercingDamage((EntityPlayer) player), damage);
else
causedDamage = entity.attackEntityFrom(causePiercingDamage(player), damage);
}
else
{
if (player instanceof EntityPlayer)
causedDamage = entity.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) player), damage);
else
causedDamage = entity.attackEntityFrom(DamageSource.causeMobDamage(player), damage);
}
if (causedDamage)
{
damageTool(stack, 1, tags, player, false);
// damageTool(stack, 1, player, false);
tool.onEntityDamaged(player.worldObj, player, entity);
if (!necroticUHS || (entity instanceof IMob && entity instanceof EntityLivingBase && ((EntityLivingBase) entity).getHealth() <= 0))
{
if(entity.isEntityAlive()) {
int drain = toolTags.getInteger("Necrotic") * 2;
if (drain > 0)
player.heal(random.nextInt(drain + 1));
}
}
if (knockback > 0)
{
entity.addVelocity((double) (-MathHelper.sin(player.rotationYaw * (float) Math.PI / 180.0F) * (float) knockback * 0.5F), 0.1D, (double) (MathHelper.cos(player.rotationYaw * (float) Math.PI / 180.0F) * (float) knockback * 0.5F));
player.motionX *= 0.6D;
player.motionZ *= 0.6D;
player.setSprinting(false);
}
if (player instanceof EntityPlayer)
{
if (criticalHit)
{
((EntityPlayer) player).onCriticalHit(entity);
}
if (enchantDamage > 0)
{
((EntityPlayer) player).onEnchantmentCritical(entity);
}
if (damage >= 18)
{
((EntityPlayer) player).triggerAchievement(AchievementList.overkill);
}
}
player.setLastAttacker(entity);
if (entity instanceof EntityLivingBase)
{
DamageSource.causeThornsDamage(entity);// (((EntityLivingBase)player,
// (EntityLivingBase)
// entity);
}
}
if (entity instanceof EntityLivingBase)
{
if (entity instanceof EntityPlayer)
{
stack.hitEntity((EntityLivingBase) entity, (EntityPlayer) player);
if (entity.isEntityAlive())
{
alertPlayerWolves((EntityPlayer) player, (EntityLivingBase) entity, true);
}
((EntityPlayer) player).addStat(StatList.damageDealtStat, damage);
}
else
{
stack.getItem().hitEntity(stack, (EntityLivingBase) entity, player);
}
if(causedDamage)
processFiery(player, entity, toolTags);
}
if (entity instanceof EntityPlayer)
((EntityPlayer) player).addExhaustion(0.3F);
if (causedDamage)
return true;
}
}
}
return false;
}
|
public static boolean onLeftClickEntity (ItemStack stack, EntityLivingBase player, Entity entity, ToolCore tool, int baseDamage)
{
if (entity.canAttackWithItem() && stack.hasTagCompound())
{
if (!entity.hitByEntity(player)) // can't attack this entity
{
NBTTagCompound tags = stack.getTagCompound();
NBTTagCompound toolTags = stack.getTagCompound().getCompoundTag("InfiTool");
boolean broken = toolTags.getBoolean("Broken");
int durability = tags.getCompoundTag("InfiTool").getInteger("Damage");
float stonebound = tags.getCompoundTag("InfiTool").getFloat("Shoddy");
float stoneboundDamage = (float) Math.log(durability / 72f + 1) * -2 * stonebound;
int damage = calcDamage(player, entity, stack, tool, toolTags, baseDamage);
float knockback = calcKnockback(player, entity, stack, tool, toolTags, baseDamage);
float enchantDamage = 0;
// magic extra damage
if (entity instanceof EntityLivingBase)
{
enchantDamage = EnchantmentHelper.getEnchantmentModifierLiving(player, (EntityLivingBase) entity);
}
if (damage > 0 || enchantDamage > 0)
{
boolean criticalHit = player.fallDistance > 0.0F && !player.onGround && !player.isOnLadder() && !player.isInWater() && !player.isPotionActive(Potion.blindness) && player.ridingEntity == null && entity instanceof EntityLivingBase;
for (ActiveToolMod mod : TConstructRegistry.activeModifiers)
{
if (mod.doesCriticalHit(tool, tags, toolTags, stack, player, entity))
criticalHit = true;
}
if (criticalHit)
{
damage += random.nextInt(damage / 2 + 2);
}
damage += enchantDamage;
if (tool.getDamageModifier() != 1f)
{
damage *= tool.getDamageModifier();
}
if (broken)
{
if (baseDamage > 0)
damage = baseDamage;
else
damage = 1;
}
boolean causedDamage = false;
boolean isAlive = entity.isEntityAlive();
if (tool.pierceArmor() && !broken)
{
if (player instanceof EntityPlayer)
causedDamage = entity.attackEntityFrom(causePlayerPiercingDamage((EntityPlayer) player), damage);
else
causedDamage = entity.attackEntityFrom(causePiercingDamage(player), damage);
}
else
{
if (player instanceof EntityPlayer)
causedDamage = entity.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) player), damage);
else
causedDamage = entity.attackEntityFrom(DamageSource.causeMobDamage(player), damage);
}
if (causedDamage)
{
damageTool(stack, 1, tags, player, false);
// damageTool(stack, 1, player, false);
tool.onEntityDamaged(player.worldObj, player, entity);
if (!necroticUHS || (entity instanceof IMob && entity instanceof EntityLivingBase && ((EntityLivingBase) entity).getHealth() <= 0))
{
if(isAlive) {
int drain = toolTags.getInteger("Necrotic") * 2;
if (drain > 0)
player.heal(random.nextInt(drain + 1));
}
}
if (knockback > 0)
{
entity.addVelocity((double) (-MathHelper.sin(player.rotationYaw * (float) Math.PI / 180.0F) * (float) knockback * 0.5F), 0.1D, (double) (MathHelper.cos(player.rotationYaw * (float) Math.PI / 180.0F) * (float) knockback * 0.5F));
player.motionX *= 0.6D;
player.motionZ *= 0.6D;
player.setSprinting(false);
}
if (player instanceof EntityPlayer)
{
if (criticalHit)
{
((EntityPlayer) player).onCriticalHit(entity);
}
if (enchantDamage > 0)
{
((EntityPlayer) player).onEnchantmentCritical(entity);
}
if (damage >= 18)
{
((EntityPlayer) player).triggerAchievement(AchievementList.overkill);
}
}
player.setLastAttacker(entity);
if (entity instanceof EntityLivingBase)
{
DamageSource.causeThornsDamage(entity);// (((EntityLivingBase)player,
// (EntityLivingBase)
// entity);
}
}
if (entity instanceof EntityLivingBase)
{
if (entity instanceof EntityPlayer)
{
stack.hitEntity((EntityLivingBase) entity, (EntityPlayer) player);
if (entity.isEntityAlive())
{
alertPlayerWolves((EntityPlayer) player, (EntityLivingBase) entity, true);
}
((EntityPlayer) player).addStat(StatList.damageDealtStat, damage);
}
else
{
stack.getItem().hitEntity(stack, (EntityLivingBase) entity, player);
}
if(causedDamage)
processFiery(player, entity, toolTags);
}
if (entity instanceof EntityPlayer)
((EntityPlayer) player).addExhaustion(0.3F);
if (causedDamage)
return true;
}
}
}
return false;
}
|
diff --git a/src/xmlvm/org/xmlvm/main/Arguments.java b/src/xmlvm/org/xmlvm/main/Arguments.java
index 0b791945..37b44bfb 100644
--- a/src/xmlvm/org/xmlvm/main/Arguments.java
+++ b/src/xmlvm/org/xmlvm/main/Arguments.java
@@ -1,566 +1,568 @@
/* Copyright (c) 2002-2011 by XMLVM.org
*
* Project Info: http://www.xmlvm.org
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
package org.xmlvm.main;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.xmlvm.Log;
import org.xmlvm.proc.lib.Libraries;
/**
* This class parses the arguments given in a string array and makes them easily
* accessible for the application to use.
*/
public class Arguments {
// The arguments that are given by the user on the command line.
public static final String ARG_IN = "--in=";
public static final String ARG_OUT = "--out=";
public static final String ARG_TARGET = "--target=";
public static final String ARG_RESOURCE = "--resource=";
public static final String ARG_LIB = "--lib=";
public static final String ARG_LIBRARIES = "--libraries=";
public static final String ARG_APP_NAME = "--app-name=";
public static final String ARG_QX_MAIN = "--qx-main=";
public static final String ARG_QX_DEBUG = "--qx-debug";
public static final String ARG_DEBUG = "--debug=";
public static final String ARG_VERSION = "--version";
public static final String ARG_GEN_NATIVE_SKELETONS = "--gen-native-skeletons";
public static final String ARG_HELP = "--help";
public static final String ARG_SKELETON = "--skeleton=";
// These are obsolete arguments, being here for compatibility reasons
public static final String ARG_IPHONE_APP = "--iphone-app=";
public static final String ARG_QX_APP = "--qx-app=";
public static final String ARG_QUIET = "--quiet";
// This is just temporary for activating the new DEX processing.
public static final String ARG_USE_JVM = "--use-jvm";
// Enables/disables the dependency resolution feature.
public static final String ARG_LOAD_DEPENDENCIES = "--load-dependencies";
public static final String ARG_DISABLE_LOAD_DEPENDENCIES = "--disable-load-dependencies";
// Enables reference counting for DEX input.
public static final String ARG_ENABLE_REF_COUNTING = "--enable-ref-counting";
// Enables a debug counter for measuring execution time.
public static final String ARG_ENABLE_TIMER = "--enable-timer";
public static final String ARG_C_SOURCE_EXTENSION = "--c-source-extension=";
public static final String ARG_NO_CACHE = "--no-cache";
// This argument will store various properties to XMLVM
// An example of these values can be found in the long help
public static final String ARG_PROPERTY = "-D";
public static final String ARG_XMLVM_NEW_IOS_API = "--xmlvm-new-ios-api";
// The parsed values will be stored here.
private List<String> option_in = new ArrayList<String>();
private String option_out = null;
private Targets option_target = Targets.NONE;
private boolean option_gen_native_skeletons = false;
private Set<String> option_resource = new HashSet<String>();
private Set<String> option_lib = new HashSet<String>();
private Set<String> option_libraries = new HashSet<String>();
private String option_app_name = null;
private String option_qx_main = null;
private boolean option_qx_debug = false;
private Log.Level option_debug = Log.Level.WARNING;
private String option_skeleton = null;
private boolean option_use_jvm = false;
private boolean option_load_dependencies = false;
private boolean option_disable_load_dependencies = false;
private boolean option_enable_ref_counting = false;
private boolean option_enable_timer = false;
private String option_c_source_extension = "c";
private boolean option_no_cache = true;
private Map<String, String> option_property = new HashMap<String, String>();
private boolean option_xmlvm_new_ios_api = false;
private static final String[] shortUsage = {
"Usage: ",
"xmlvm [--in=<path> [--out=<dir>]]",
" [--target=[xmlvm|dexmlvm|jvm|clr|dfa|class|exe|dex|js|java|c|python|objc|iphone|qooxdoo|vtable|webos]]",
" [--skeleton=<type>]", " [--lib=<name>", " [--app-name=<app-name>]",
" [--resource=<path>]", " [--qx-main=<main-class> [--qx-debug]]",
" [--debug=[none|error|warning|all]]", " [--version] [--help]" };
private static final String[] longUsage = {
"Detailed usage:",
"===============",
"",
" --in=<path> Pathname of input files. Can be *.class *.exe and *.xmlvm",
"",
" --out=<dir> Directory of output files (defaults to \".\")",
"",
" --target=<target> Desired target, could be one of the following:",
" xmlvm XMLVM output, depending on the input (default)",
" dexmlvm XMLVM_dex output",
" jvm XMLVM_jvm output",
" clr XMLVM_clr output",
" dfa Data Flow Analysis on input files",
" class Java class bytecode",
" exe .NET executable",
" dex DEX bytecode",
" js JavaScript",
" java Java source code",
" c C source code",
" gen-c-wrappers Generates C wrappers while preserving hand-written code from overridden files in the 'out' directory.",
" python Python",
" objc Objective C source code",
" iphone iPhone Objective-C",
" qooxdoo JavaScript Qooxdoo web application",
" vtable Vtable calculation (pre-step for e.g. C generation)",
" webos WebOS JavaScript Project",
"",
"--gen-native-skeletons Generates skeletons for Java native methods in the target",
" language (currently only available for --target=c",
"",
" --skeleton=<type> Skeleton to create a new template project:",
" iphone iPhone project skeleton",
" android Android/iPhone project skeleton",
" android:migrate Migrate an existing Android project to XMLVM (needs project created by 'android create project' command)",
" iphone:update Update an existing XMLVM/iPhone project to latest build scripts",
" android:update Update an existing XMLVM/Android project to latest build scripts",
"",
" --lib=<libraries> Comma separated list of extra libraries required for the specified target. Use a tilde at the and of the library name, to mark it as 'Weak'.",
" android Support of android applications",
" <LIB>.dylib iPhone dynamic library <LIB>",
" <LIB>.Framework iPhone framework <LIB>",
"",
" --app-name=<name> Application name, required for iphone, android-based and qooxdoo targets",
"",
" --resource=<path> "
+ (File.pathSeparatorChar == ':' ? "Colon" : "Semicolon")
+ " separated list of external non parsable files and directories. Used in iphone-based templates to register auxilliary files. If this argument ends with '/', then the contents of this directory will be copied. If it is a directory and does not end with '/', then a verbatim copy of the directory will be performed. This argument can also be used to add extra C/C++/Obj-C source files in the produced Xcode project.",
"",
" --qx-main=<class> Entry point of Qooxdoo application",
"",
" --qx-debug Create debug information of Qooxdoo target",
"",
" -Dkey=value Set an Xcode property",
" XcodeProject Template to use for Xcode project:",
" iphone iPhone project skeleton",
" ipad iPad project skeleton",
" ios iPhone and iPad project skeleton",
" iphone3 Legacy iPhone 3.1 project skeleton",
" BundleIdentifier The value of CFBundleIdentifier in Info.plist",
" BundleVersion The value of CFBundleVersion in Info.plist",
" BundleDisplayName The value of CFBundleDisplayName in Info.plist",
" PrerenderedIcon The iPhone application icon is already pre-rendered",
" FileSharingEnabled If iTunes file sharing should be enabled (value is 'true') or not (value is 'false')",
" StatusBarHidden Hide (value is 'true') or display (value is 'false' status bar",
" ApplicationExits Application does not run in background on suspend",
" InterfaceOrientation Initial interface orientation. Should be one of: UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight",
" SupportedInterfaceOrientations Colon seperated list of supported interface orientations. See property InterfaceOrientation.",
" AppFonts Colon separated list of custom fonts",
" InjectedInfoPlist Raw XML that will be injected into Info.plist", "",
" --debug=<level> Debug information level",
" none Be completely quiet, no information is printed",
" error Only errors will be printed",
" warning Warning and errors will be printed",
" all All debug information (including errors and warnings)", "",
" --version Display version information", "",
" --help This message", "" };
private static final String[] Version = { "XMLVM 2",
"Note: Not all command line arguments activated yet." };
private boolean performSanityChecks = true;
public static void printVersion() {
printText(Version, System.out);
System.exit(0);
}
private static void longUsage() {
System.out.println("XMLVM: a flexible and extensible cross-compiler toolchain");
printText(Version, System.out);
System.out.println();
printText(shortUsage, System.out);
System.out.println();
printText(longUsage, System.out);
System.exit(0);
}
private static void parseError(String error) {
System.err.println("Error: " + error);
printText(shortUsage, System.err);
System.err.println("Give --help parameter to see more detailed command line instructions.");
System.exit(-1);
}
/**
* Creates a new instance that will parse the arguments of the given array.
*/
public Arguments(String[] argv) {
this(argv, true);
}
/**
* Creates a new instance that will parse the arguments of the given array.
*/
public Arguments(String[] argv, boolean performSanityChecks) {
// Add default properties
option_property.put("xcodeproject", "iphone");
option_property.put("bundleidentifier", "org.xmlvm.iphone.XMLVM_APP");
option_property.put("bundleversion", "1.0");
option_property.put("bundledisplayname", "XMLVM_APP");
option_property.put("statusbarhidden", "false");
option_property.put("prerenderedicon", "false");
option_property.put("applicationexits", "true");
option_property.put("interfaceorientation", "UIInterfaceOrientationPortrait");
+ option_property.put("filesharingenabled", "false");
+ option_property.put("injectedinfoplist", "");
// Add default libraries
option_lib.add("Foundation.framework");
option_lib.add("UIKit.framework");
option_lib.add("CoreGraphics.framework");
option_lib.add("AVFoundation.framework~");
option_lib.add("OpenGLES.framework~");
option_lib.add("QuartzCore.framework~");
option_lib.add("MessageUI.framework~");
option_lib.add("MediaPlayer.framework~");
option_lib.add("StoreKit.framework~");
option_lib.add("CoreLocation.framework~");
option_lib.add("MapKit.framework~");
option_lib.add("GameKit.framework~");
option_lib.add("iAd.framework~");
option_lib.add("AudioToolbox.framework~");
option_lib.add("CoreMotion.framework");
option_lib.add("QuickLook.framework~");
// Read command line arguments
for (int i = 0; i < argv.length; i++) {
String arg = argv[i];
if (arg.startsWith(ARG_IN)) {
option_in.add(arg.substring(ARG_IN.length()));
} else if (arg.startsWith(ARG_OUT)) {
if (option_out != null)
parseError("--out can only be used once");
option_out = arg.substring(ARG_OUT.length());
} else if (arg.startsWith(ARG_TARGET)) {
if (option_target != Targets.NONE)
parseError("--target can only be specified once");
String target = arg.substring(ARG_TARGET.length());
option_target = Targets.getTarget(target);
if (option_target == null)
parseError("Unkown target: " + target);
if (option_target.affinity != Targets.Affinity.TARGET)
parseError("Not valid target: " + target
+ ". Consider using --skeleton argument.");
} else if (arg.startsWith(ARG_RESOURCE)) {
parseListArgument(arg.substring(ARG_RESOURCE.length()), option_resource,
File.pathSeparator);
} else if (arg.equals(ARG_GEN_NATIVE_SKELETONS)) {
option_gen_native_skeletons = true;
} else if (arg.startsWith(ARG_LIB)) {
parseListArgument(arg.substring(ARG_LIB.length()), option_lib, ",");
} else if (arg.startsWith(ARG_LIBRARIES)) {
parseListArgument(arg.substring(ARG_LIBRARIES.length()), option_libraries, ",");
} else if (arg.startsWith(ARG_APP_NAME)) {
option_app_name = arg.substring(ARG_APP_NAME.length());
} else if (arg.startsWith(ARG_QX_MAIN)) {
option_qx_main = arg.substring(ARG_QX_MAIN.length());
} else if (arg.equals(ARG_QX_DEBUG)) {
option_qx_debug = true;
} else if (arg.equals(ARG_VERSION)) {
printVersion();
} else if (arg.startsWith(ARG_DEBUG)) {
option_debug = Log.Level.getLevel(arg.substring(ARG_DEBUG.length()));
} else if (arg.equals(ARG_HELP)) {
longUsage();
} else if (arg.startsWith(ARG_SKELETON)) {
if (option_skeleton != null)
parseError("--skeleton can only be specified once");
option_skeleton = arg.substring(ARG_SKELETON.length()).toLowerCase();
// Obsolete arguments
} else if (arg.startsWith(ARG_IPHONE_APP)) {
option_app_name = arg.substring(ARG_IPHONE_APP.length());
} else if (arg.startsWith(ARG_QX_APP)) {
option_app_name = arg.substring(ARG_QX_APP.length());
} else if (arg.equals(ARG_QUIET)) {
option_debug = Log.Level.ERROR;
} else if (arg.equals(ARG_USE_JVM)) {
option_use_jvm = true;
} else if (arg.equals(ARG_LOAD_DEPENDENCIES)) {
option_load_dependencies = true;
} else if (arg.equals(ARG_DISABLE_LOAD_DEPENDENCIES)) {
option_disable_load_dependencies = true;
} else if (arg.equals(ARG_ENABLE_TIMER)) {
option_enable_timer = true;
} else if (arg.equals(ARG_ENABLE_REF_COUNTING)) {
option_enable_ref_counting = true;
} else if (arg.startsWith(ARG_C_SOURCE_EXTENSION)) {
option_c_source_extension = arg.substring(ARG_C_SOURCE_EXTENSION.length());
} else if (arg.equals(ARG_NO_CACHE)) {
option_no_cache = true;
} else if (arg.startsWith(ARG_PROPERTY)) {
String value = arg.substring(ARG_PROPERTY.length());
int equal = value.indexOf("=");
if (equal < 1) {
parseError("Unable to parse kay/value: " + value);
}
option_property.put(value.substring(0, equal).toLowerCase(),
value.substring(equal + 1));
} else if (arg.equals(ARG_XMLVM_NEW_IOS_API)) {
option_xmlvm_new_ios_api = true;
} else if (arg.length() == 0) {
// Ignore empty arguments
} else {
parseError("Unknown parameter: " + arg);
}
}
this.performSanityChecks = performSanityChecks;
if (performSanityChecks) {
// Sanity check command line arguments
performSanityChecks();
}
// Add additional libraries.
for (String library : option_libraries) {
if (!Libraries.addLibrary(library)) {
System.exit(-1);
}
}
}
private void performSanityChecks() {
if (option_skeleton != null && option_target != Targets.NONE) {
parseError("Only one argument of '--target' or '--skeleton' is allowed");
}
if (option_gen_native_skeletons
&& (option_target != Targets.C && option_target != Targets.GENCWRAPPERS)) {
parseError("--gen-native-skeletons only available for targets 'c' and 'gen-c-wrappers'.");
}
if ((option_target == Targets.POSIX || option_target == Targets.IPHONE
|| option_target == Targets.IPHONEC || option_target == Targets.IPHONEANDROID
|| option_target == Targets.WEBOS || option_skeleton != null)
&& option_app_name == null) {
option_app_name = guessAppName();
if (option_app_name == null)
parseError("Required parameter: --app-name");
}
if ("".equals(option_skeleton)) // empty existing skeleton definition
parseError("--skeleton option is empty");
if (option_skeleton != null) {
option_target = Targets.getTarget(option_skeleton + "template");
if (option_target == null)
parseError("Unknown skeleton: " + option_skeleton);
// Clearing all inputs will force EmptyInputProcess to be used.
option_in.clear();
}
if (option_target == Targets.NONE)
option_target = Targets.XMLVM;
if (option_lib.contains("android")) {
option_lib.remove("android");
if (option_target == Targets.IPHONE)
option_target = Targets.IPHONEANDROID;
else if (option_target == Targets.IPHONEC)
option_target = Targets.IPHONECANDROID;
else if (option_target == Targets.WEBOS) {
} else {
parseError("--lib=android is meaningless when not --target=[iphone|iphonec|webos]");
}
}
// // Due to default libraries provided, this check can not be performed
// if (option_lib.size() > 0 && option_target != Targets.IPHONE)
// parseError("--lib=" + option_lib.iterator().next() +
// " is not supported for this target");
// Only skeleton creation mode supports empty inputs.
if ((option_skeleton == null || option_skeleton.equals("")) && option_in.isEmpty())
parseError("Need at least one --in argument");
if (option_target == Targets.QOOXDOO && option_app_name != null && option_qx_main == null)
parseError("--target=qooxdoo with --qx-app requires --qx-main");
if (option_debug == null)
parseError("Unknown --debug level");
// We need to enforce reference counting for these targets.
if (option_target == Targets.OBJC || option_target == Targets.IPHONE
|| option_target == Targets.IPHONEANDROID) {
if (!option_enable_ref_counting) {
option_enable_ref_counting = true;
Log.debug("Forcing " + ARG_ENABLE_REF_COUNTING + " for target " + option_target);
}
}
if (option_target == Targets.IPHONE || option_target == Targets.IPHONEC
|| option_target == Targets.IPHONECANDROID
|| option_target == Targets.IPHONEANDROID) {
option_c_source_extension = "m";
}
// Enables the dependency loading for the specified targets.
if (option_target == Targets.POSIX || option_target == Targets.IPHONEC
|| option_target == Targets.IPHONECANDROID) {
if (!option_disable_load_dependencies) {
option_load_dependencies = true;
}
}
}
private static void parseListArgument(String argument, Set<String> option, String separator) {
if (argument == null || option == null || separator == null) {
return;
}
StringTokenizer tk = new StringTokenizer(argument, separator);
while (tk.hasMoreTokens()) {
String entry = tk.nextToken().trim();
if (!entry.equals("")) {
boolean status = true;
if (entry.startsWith("+")) {
entry = entry.substring(1);
} else if (entry.startsWith("-")) {
status = false;
entry = entry.substring(1);
}
if (!entry.equals("")) {
if (status) {
option.add(entry);
} else {
option.remove(entry);
}
}
}
}
}
public List<String> option_in() {
return option_in;
}
public String option_out() {
// Lazy definition of "smart" option_out parameter, so the warning will
// appear only when needed
if (option_out == null) {
if (option_app_name == null)
option_out = ".";
else {
option_out = option_app_name;
}
if (performSanityChecks) {
Log.warn("Using '" + option_out + "' as output directory");
}
}
return option_out;
}
public Set<String> option_resource() {
return option_resource;
}
public Targets option_target() {
return option_target;
}
public boolean option_gen_native_skeletons() {
return option_gen_native_skeletons;
}
public String option_app_name() {
return option_app_name;
}
public String option_qx_main() {
return option_qx_main;
}
public boolean option_qx_debug() {
return option_qx_debug;
}
public Log.Level option_debug() {
return option_debug;
}
public boolean option_use_jvm() {
return option_use_jvm;
}
public boolean option_load_dependencies() {
return option_load_dependencies;
}
public boolean option_disable_load_dependencies() {
return option_disable_load_dependencies;
}
public boolean option_enable_ref_counting() {
return option_enable_ref_counting;
}
public boolean option_enable_timer() {
return option_enable_timer;
}
public String option_c_source_extension() {
return option_c_source_extension;
}
public boolean option_no_cache() {
return option_no_cache;
}
public Set<String> option_lib() {
return option_lib;
}
public Set<String> option_library() {
return option_libraries;
}
public String option_property(String key) {
return option_property.get(key);
}
public boolean option_xmlvm_new_ios_api() {
return option_xmlvm_new_ios_api;
}
private static void printText(String[] txt, PrintStream out) {
for (int i = 0; i < txt.length; i++)
out.println(txt[i]);
}
private String guessAppName() {
if (option_out == null)
return null;
File outfile = new File(option_out).getAbsoluteFile();
if (outfile.exists() && outfile.isFile())
outfile = outfile.getParentFile();
while (outfile != null
&& (outfile.getName().equals("..") || outfile.getName().equals(".") || outfile
.getName().equals("/")))
outfile = outfile.getParentFile();
if (outfile == null)
return null;
String guess = outfile.getName();
if (guess.isEmpty())
return null;
Log.warn("Using " + guess + " as application name");
return guess;
}
}
| true | true |
public Arguments(String[] argv, boolean performSanityChecks) {
// Add default properties
option_property.put("xcodeproject", "iphone");
option_property.put("bundleidentifier", "org.xmlvm.iphone.XMLVM_APP");
option_property.put("bundleversion", "1.0");
option_property.put("bundledisplayname", "XMLVM_APP");
option_property.put("statusbarhidden", "false");
option_property.put("prerenderedicon", "false");
option_property.put("applicationexits", "true");
option_property.put("interfaceorientation", "UIInterfaceOrientationPortrait");
// Add default libraries
option_lib.add("Foundation.framework");
option_lib.add("UIKit.framework");
option_lib.add("CoreGraphics.framework");
option_lib.add("AVFoundation.framework~");
option_lib.add("OpenGLES.framework~");
option_lib.add("QuartzCore.framework~");
option_lib.add("MessageUI.framework~");
option_lib.add("MediaPlayer.framework~");
option_lib.add("StoreKit.framework~");
option_lib.add("CoreLocation.framework~");
option_lib.add("MapKit.framework~");
option_lib.add("GameKit.framework~");
option_lib.add("iAd.framework~");
option_lib.add("AudioToolbox.framework~");
option_lib.add("CoreMotion.framework");
option_lib.add("QuickLook.framework~");
// Read command line arguments
for (int i = 0; i < argv.length; i++) {
String arg = argv[i];
if (arg.startsWith(ARG_IN)) {
option_in.add(arg.substring(ARG_IN.length()));
} else if (arg.startsWith(ARG_OUT)) {
if (option_out != null)
parseError("--out can only be used once");
option_out = arg.substring(ARG_OUT.length());
} else if (arg.startsWith(ARG_TARGET)) {
if (option_target != Targets.NONE)
parseError("--target can only be specified once");
String target = arg.substring(ARG_TARGET.length());
option_target = Targets.getTarget(target);
if (option_target == null)
parseError("Unkown target: " + target);
if (option_target.affinity != Targets.Affinity.TARGET)
parseError("Not valid target: " + target
+ ". Consider using --skeleton argument.");
} else if (arg.startsWith(ARG_RESOURCE)) {
parseListArgument(arg.substring(ARG_RESOURCE.length()), option_resource,
File.pathSeparator);
} else if (arg.equals(ARG_GEN_NATIVE_SKELETONS)) {
option_gen_native_skeletons = true;
} else if (arg.startsWith(ARG_LIB)) {
parseListArgument(arg.substring(ARG_LIB.length()), option_lib, ",");
} else if (arg.startsWith(ARG_LIBRARIES)) {
parseListArgument(arg.substring(ARG_LIBRARIES.length()), option_libraries, ",");
} else if (arg.startsWith(ARG_APP_NAME)) {
option_app_name = arg.substring(ARG_APP_NAME.length());
} else if (arg.startsWith(ARG_QX_MAIN)) {
option_qx_main = arg.substring(ARG_QX_MAIN.length());
} else if (arg.equals(ARG_QX_DEBUG)) {
option_qx_debug = true;
} else if (arg.equals(ARG_VERSION)) {
printVersion();
} else if (arg.startsWith(ARG_DEBUG)) {
option_debug = Log.Level.getLevel(arg.substring(ARG_DEBUG.length()));
} else if (arg.equals(ARG_HELP)) {
longUsage();
} else if (arg.startsWith(ARG_SKELETON)) {
if (option_skeleton != null)
parseError("--skeleton can only be specified once");
option_skeleton = arg.substring(ARG_SKELETON.length()).toLowerCase();
// Obsolete arguments
} else if (arg.startsWith(ARG_IPHONE_APP)) {
option_app_name = arg.substring(ARG_IPHONE_APP.length());
} else if (arg.startsWith(ARG_QX_APP)) {
option_app_name = arg.substring(ARG_QX_APP.length());
} else if (arg.equals(ARG_QUIET)) {
option_debug = Log.Level.ERROR;
} else if (arg.equals(ARG_USE_JVM)) {
option_use_jvm = true;
} else if (arg.equals(ARG_LOAD_DEPENDENCIES)) {
option_load_dependencies = true;
} else if (arg.equals(ARG_DISABLE_LOAD_DEPENDENCIES)) {
option_disable_load_dependencies = true;
} else if (arg.equals(ARG_ENABLE_TIMER)) {
option_enable_timer = true;
} else if (arg.equals(ARG_ENABLE_REF_COUNTING)) {
option_enable_ref_counting = true;
} else if (arg.startsWith(ARG_C_SOURCE_EXTENSION)) {
option_c_source_extension = arg.substring(ARG_C_SOURCE_EXTENSION.length());
} else if (arg.equals(ARG_NO_CACHE)) {
option_no_cache = true;
} else if (arg.startsWith(ARG_PROPERTY)) {
String value = arg.substring(ARG_PROPERTY.length());
int equal = value.indexOf("=");
if (equal < 1) {
parseError("Unable to parse kay/value: " + value);
}
option_property.put(value.substring(0, equal).toLowerCase(),
value.substring(equal + 1));
} else if (arg.equals(ARG_XMLVM_NEW_IOS_API)) {
option_xmlvm_new_ios_api = true;
} else if (arg.length() == 0) {
// Ignore empty arguments
} else {
parseError("Unknown parameter: " + arg);
}
}
this.performSanityChecks = performSanityChecks;
if (performSanityChecks) {
// Sanity check command line arguments
performSanityChecks();
}
// Add additional libraries.
for (String library : option_libraries) {
if (!Libraries.addLibrary(library)) {
System.exit(-1);
}
}
}
|
public Arguments(String[] argv, boolean performSanityChecks) {
// Add default properties
option_property.put("xcodeproject", "iphone");
option_property.put("bundleidentifier", "org.xmlvm.iphone.XMLVM_APP");
option_property.put("bundleversion", "1.0");
option_property.put("bundledisplayname", "XMLVM_APP");
option_property.put("statusbarhidden", "false");
option_property.put("prerenderedicon", "false");
option_property.put("applicationexits", "true");
option_property.put("interfaceorientation", "UIInterfaceOrientationPortrait");
option_property.put("filesharingenabled", "false");
option_property.put("injectedinfoplist", "");
// Add default libraries
option_lib.add("Foundation.framework");
option_lib.add("UIKit.framework");
option_lib.add("CoreGraphics.framework");
option_lib.add("AVFoundation.framework~");
option_lib.add("OpenGLES.framework~");
option_lib.add("QuartzCore.framework~");
option_lib.add("MessageUI.framework~");
option_lib.add("MediaPlayer.framework~");
option_lib.add("StoreKit.framework~");
option_lib.add("CoreLocation.framework~");
option_lib.add("MapKit.framework~");
option_lib.add("GameKit.framework~");
option_lib.add("iAd.framework~");
option_lib.add("AudioToolbox.framework~");
option_lib.add("CoreMotion.framework");
option_lib.add("QuickLook.framework~");
// Read command line arguments
for (int i = 0; i < argv.length; i++) {
String arg = argv[i];
if (arg.startsWith(ARG_IN)) {
option_in.add(arg.substring(ARG_IN.length()));
} else if (arg.startsWith(ARG_OUT)) {
if (option_out != null)
parseError("--out can only be used once");
option_out = arg.substring(ARG_OUT.length());
} else if (arg.startsWith(ARG_TARGET)) {
if (option_target != Targets.NONE)
parseError("--target can only be specified once");
String target = arg.substring(ARG_TARGET.length());
option_target = Targets.getTarget(target);
if (option_target == null)
parseError("Unkown target: " + target);
if (option_target.affinity != Targets.Affinity.TARGET)
parseError("Not valid target: " + target
+ ". Consider using --skeleton argument.");
} else if (arg.startsWith(ARG_RESOURCE)) {
parseListArgument(arg.substring(ARG_RESOURCE.length()), option_resource,
File.pathSeparator);
} else if (arg.equals(ARG_GEN_NATIVE_SKELETONS)) {
option_gen_native_skeletons = true;
} else if (arg.startsWith(ARG_LIB)) {
parseListArgument(arg.substring(ARG_LIB.length()), option_lib, ",");
} else if (arg.startsWith(ARG_LIBRARIES)) {
parseListArgument(arg.substring(ARG_LIBRARIES.length()), option_libraries, ",");
} else if (arg.startsWith(ARG_APP_NAME)) {
option_app_name = arg.substring(ARG_APP_NAME.length());
} else if (arg.startsWith(ARG_QX_MAIN)) {
option_qx_main = arg.substring(ARG_QX_MAIN.length());
} else if (arg.equals(ARG_QX_DEBUG)) {
option_qx_debug = true;
} else if (arg.equals(ARG_VERSION)) {
printVersion();
} else if (arg.startsWith(ARG_DEBUG)) {
option_debug = Log.Level.getLevel(arg.substring(ARG_DEBUG.length()));
} else if (arg.equals(ARG_HELP)) {
longUsage();
} else if (arg.startsWith(ARG_SKELETON)) {
if (option_skeleton != null)
parseError("--skeleton can only be specified once");
option_skeleton = arg.substring(ARG_SKELETON.length()).toLowerCase();
// Obsolete arguments
} else if (arg.startsWith(ARG_IPHONE_APP)) {
option_app_name = arg.substring(ARG_IPHONE_APP.length());
} else if (arg.startsWith(ARG_QX_APP)) {
option_app_name = arg.substring(ARG_QX_APP.length());
} else if (arg.equals(ARG_QUIET)) {
option_debug = Log.Level.ERROR;
} else if (arg.equals(ARG_USE_JVM)) {
option_use_jvm = true;
} else if (arg.equals(ARG_LOAD_DEPENDENCIES)) {
option_load_dependencies = true;
} else if (arg.equals(ARG_DISABLE_LOAD_DEPENDENCIES)) {
option_disable_load_dependencies = true;
} else if (arg.equals(ARG_ENABLE_TIMER)) {
option_enable_timer = true;
} else if (arg.equals(ARG_ENABLE_REF_COUNTING)) {
option_enable_ref_counting = true;
} else if (arg.startsWith(ARG_C_SOURCE_EXTENSION)) {
option_c_source_extension = arg.substring(ARG_C_SOURCE_EXTENSION.length());
} else if (arg.equals(ARG_NO_CACHE)) {
option_no_cache = true;
} else if (arg.startsWith(ARG_PROPERTY)) {
String value = arg.substring(ARG_PROPERTY.length());
int equal = value.indexOf("=");
if (equal < 1) {
parseError("Unable to parse kay/value: " + value);
}
option_property.put(value.substring(0, equal).toLowerCase(),
value.substring(equal + 1));
} else if (arg.equals(ARG_XMLVM_NEW_IOS_API)) {
option_xmlvm_new_ios_api = true;
} else if (arg.length() == 0) {
// Ignore empty arguments
} else {
parseError("Unknown parameter: " + arg);
}
}
this.performSanityChecks = performSanityChecks;
if (performSanityChecks) {
// Sanity check command line arguments
performSanityChecks();
}
// Add additional libraries.
for (String library : option_libraries) {
if (!Libraries.addLibrary(library)) {
System.exit(-1);
}
}
}
|
diff --git a/src/java/com/eviware/soapui/impl/wsdl/support/http/HttpClientSupport.java b/src/java/com/eviware/soapui/impl/wsdl/support/http/HttpClientSupport.java
index 119c8687a..917d9b433 100644
--- a/src/java/com/eviware/soapui/impl/wsdl/support/http/HttpClientSupport.java
+++ b/src/java/com/eviware/soapui/impl/wsdl/support/http/HttpClientSupport.java
@@ -1,342 +1,344 @@
/*
* soapUI, copyright (C) 2004-2011 smartbear.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details at gnu.org.
*/
package com.eviware.soapui.impl.wsdl.support.http;
import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import org.apache.commons.ssl.KeyMaterial;
import org.apache.http.Header;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.auth.NTLMSchemeFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.RequestWrapper;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.log4j.Logger;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.impl.wsdl.submit.transports.http.ExtendedHttpMethod;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.metrics.SoapUIMetrics;
import com.eviware.soapui.impl.wsdl.support.CompressionSupport;
import com.eviware.soapui.model.settings.Settings;
import com.eviware.soapui.model.settings.SettingsListener;
import com.eviware.soapui.settings.HttpSettings;
import com.eviware.soapui.settings.SSLSettings;
import com.eviware.soapui.support.StringUtils;
/**
* HttpClient related tools
*
* @author Ole.Matzura
*/
public class HttpClientSupport
{
private final static Helper helper = new Helper();
/**
* Internal helper to ensure synchronized access..
*/
public static class SoapUIHttpClient extends DefaultHttpClient
{
public SoapUIHttpClient( final ClientConnectionManager conman )
{
super( conman, null );
}
@Override
protected HttpRequestExecutor createRequestExecutor()
{
return new SoapUIHttpRequestExecutor();
}
}
public static class SoapUIHttpRequestExecutor extends HttpRequestExecutor
{
protected HttpResponse doSendRequest( HttpRequest request, HttpClientConnection conn, HttpContext context )
throws IOException, HttpException
{
HttpResponse response = super.doSendRequest( request, conn, context );
RequestWrapper w = ( RequestWrapper )request;
if( w.getOriginal() instanceof ExtendedHttpMethod )
( ( ExtendedHttpMethod )w.getOriginal() ).getMetrics().getTimeToFirstByteTimer().start();
return response;
}
@Override
protected HttpResponse doReceiveResponse( final HttpRequest request, final HttpClientConnection conn,
final HttpContext context ) throws HttpException, IOException
{
if( request == null )
{
throw new IllegalArgumentException( "HTTP request may not be null" );
}
if( conn == null )
{
throw new IllegalArgumentException( "HTTP connection may not be null" );
}
if( context == null )
{
throw new IllegalArgumentException( "HTTP context may not be null" );
}
HttpResponse response = null;
int statuscode = 0;
while( response == null || statuscode < HttpStatus.SC_OK )
{
response = conn.receiveResponseHeader();
RequestWrapper w = ( RequestWrapper )request;
SoapUIMetrics metrics = null;
if( w.getOriginal() instanceof ExtendedHttpMethod )
{
metrics = ( ( ExtendedHttpMethod )w.getOriginal() ).getMetrics();
metrics.getTimeToFirstByteTimer().stop();
metrics.getReadTimer().start();
}
if( canResponseHaveBody( request, response ) )
{
conn.receiveResponseEntity( response );
if( metrics != null )
metrics.getReadTimer().stop();
}
statuscode = response.getStatusLine().getStatusCode();
SoapUIMetrics connectionMetrics = ( SoapUIMetrics )conn.getMetrics();
metrics.getConnectTimer().set( connectionMetrics.getConnectTimer().getStart(),
connectionMetrics.getConnectTimer().getStop() );
metrics.getDNSTimer().set( connectionMetrics.getDNSTimer().getStart(),
connectionMetrics.getDNSTimer().getStop() );
+ // reset connection-level metrics
+ connectionMetrics.reset();
} // while intermediate response
return response;
}
}
private static class Helper
{
private SoapUIHttpClient httpClient;
private final static Logger log = Logger.getLogger( HttpClientSupport.Helper.class );
private SoapUIMultiThreadedHttpConnectionManager connectionManager;
private SoapUISSLSocketFactory socketFactory;
public Helper()
{
Settings settings = SoapUI.getSettings();
SchemeRegistry registry = new SchemeRegistry();
registry.register( new Scheme( "http", 80, PlainSocketFactory.getSocketFactory() ) );
try
{
socketFactory = initSocketFactory();
registry.register( new Scheme( "https", 443, socketFactory ) );
}
catch( Throwable e )
{
SoapUI.logError( e );
}
connectionManager = new SoapUIMultiThreadedHttpConnectionManager( registry );
// connectionManager.setMaxConnectionsPerHost( ( int )settings.getLong( HttpSettings.MAX_CONNECTIONS_PER_HOST,
// 500 ) );
// connectionManager.setMaxTotalConnections( ( int )settings.getLong( HttpSettings.MAX_TOTAL_CONNECTIONS, 2000 ) );
httpClient = new SoapUIHttpClient( connectionManager );
httpClient.getAuthSchemes().register( AuthPolicy.NTLM, new NTLMSchemeFactory() );
httpClient.getAuthSchemes().register( AuthPolicy.SPNEGO, new NTLMSchemeFactory() );
settings.addSettingsListener( new SSLSettingsListener() );
}
public SoapUIHttpClient getHttpClient()
{
return httpClient;
}
public HttpResponse execute( ExtendedHttpMethod method, HttpContext httpContext ) throws ClientProtocolException,
IOException
{
method.afterWriteRequest();
HttpResponse httpResponse = httpClient.execute( ( HttpUriRequest )method, httpContext );
method.setHttpResponse( httpResponse );
return httpResponse;
}
public HttpResponse execute( ExtendedHttpMethod method ) throws ClientProtocolException, IOException
{
method.afterWriteRequest();
HttpResponse httpResponse = httpClient.execute( ( HttpUriRequest )method );
method.setHttpResponse( httpResponse );
return httpResponse;
}
public final class SSLSettingsListener implements SettingsListener
{
public void settingChanged( String name, String newValue, String oldValue )
{
if( !StringUtils.hasContent( newValue ) )
return;
if( name.equals( SSLSettings.KEYSTORE ) || name.equals( SSLSettings.KEYSTORE_PASSWORD ) )
{
try
{
log.info( "Updating keyStore.." );
initSocketFactory();
}
catch( Throwable e )
{
SoapUI.logError( e );
}
}
else if( name.equals( HttpSettings.MAX_CONNECTIONS_PER_HOST ) )
{
log.info( "Updating max connections per host to " + newValue );
// connectionManager.setMaxConnectionsPerHost( Integer.parseInt( newValue ) );
}
else if( name.equals( HttpSettings.MAX_TOTAL_CONNECTIONS ) )
{
log.info( "Updating max total connections host to " + newValue );
// connectionManager.setMaxTotalConnections( Integer.parseInt( newValue ) );
}
}
@Override
public void settingsReloaded()
{
try
{
log.info( "Updating keyStore.." );
initSocketFactory();
}
catch( Throwable e )
{
SoapUI.logError( e );
}
}
}
public SoapUISSLSocketFactory initSocketFactory() throws KeyStoreException, NoSuchAlgorithmException,
CertificateException, IOException, UnrecoverableKeyException, KeyManagementException
{
KeyStore keyStore = null;
Settings settings = SoapUI.getSettings();
String keyStoreUrl = settings.getString( SSLSettings.KEYSTORE, null );
keyStoreUrl = keyStoreUrl != null ? keyStoreUrl.trim() : "";
String pass = settings.getString( SSLSettings.KEYSTORE_PASSWORD, "" );
char[] pwd = pass.toCharArray();
if( keyStoreUrl.trim().length() > 0 )
{
File f = new File( keyStoreUrl );
if( f.exists() )
{
log.info( "Initializing KeyStore" );
try
{
KeyMaterial km = new KeyMaterial( f, pwd );
keyStore = km.getKeyStore();
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
}
return new SoapUISSLSocketFactory( keyStore, pass );
}
}
public static SoapUIHttpClient getHttpClient()
{
return helper.getHttpClient();
}
public static HttpResponse execute( ExtendedHttpMethod method, HttpContext httpContext )
throws ClientProtocolException, IOException
{
return helper.execute( method, httpContext );
}
public static HttpResponse execute( ExtendedHttpMethod method ) throws ClientProtocolException, IOException
{
return helper.execute( method );
}
public static void applyHttpSettings( HttpRequest httpMethod, Settings settings )
{
// user agent?
String userAgent = settings.getString( HttpSettings.USER_AGENT, null );
if( userAgent != null && userAgent.length() > 0 )
httpMethod.setHeader( "User-Agent", userAgent );
// timeout?
long timeout = settings.getLong( HttpSettings.SOCKET_TIMEOUT, HttpSettings.DEFAULT_SOCKET_TIMEOUT );
httpMethod.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, ( int )timeout );
}
public static String getResponseCompressionType( HttpResponse httpResponse )
{
Header contentType = httpResponse.getEntity().getContentType();
Header contentEncoding = httpResponse.getEntity().getContentEncoding();
return getCompressionType( contentType == null ? null : contentType.getValue(), contentEncoding == null ? null
: contentEncoding.getValue() );
}
public static String getCompressionType( String contentType, String contentEncoding )
{
String compressionAlg = contentType == null ? null : CompressionSupport.getAvailableAlgorithm( contentType );
if( compressionAlg != null )
return compressionAlg;
if( contentEncoding == null )
return null;
else
return CompressionSupport.getAvailableAlgorithm( contentEncoding );
}
public static void addSSLListener( Settings settings )
{
settings.addSettingsListener( helper.new SSLSettingsListener() );
}
}
| true | true |
protected HttpResponse doReceiveResponse( final HttpRequest request, final HttpClientConnection conn,
final HttpContext context ) throws HttpException, IOException
{
if( request == null )
{
throw new IllegalArgumentException( "HTTP request may not be null" );
}
if( conn == null )
{
throw new IllegalArgumentException( "HTTP connection may not be null" );
}
if( context == null )
{
throw new IllegalArgumentException( "HTTP context may not be null" );
}
HttpResponse response = null;
int statuscode = 0;
while( response == null || statuscode < HttpStatus.SC_OK )
{
response = conn.receiveResponseHeader();
RequestWrapper w = ( RequestWrapper )request;
SoapUIMetrics metrics = null;
if( w.getOriginal() instanceof ExtendedHttpMethod )
{
metrics = ( ( ExtendedHttpMethod )w.getOriginal() ).getMetrics();
metrics.getTimeToFirstByteTimer().stop();
metrics.getReadTimer().start();
}
if( canResponseHaveBody( request, response ) )
{
conn.receiveResponseEntity( response );
if( metrics != null )
metrics.getReadTimer().stop();
}
statuscode = response.getStatusLine().getStatusCode();
SoapUIMetrics connectionMetrics = ( SoapUIMetrics )conn.getMetrics();
metrics.getConnectTimer().set( connectionMetrics.getConnectTimer().getStart(),
connectionMetrics.getConnectTimer().getStop() );
metrics.getDNSTimer().set( connectionMetrics.getDNSTimer().getStart(),
connectionMetrics.getDNSTimer().getStop() );
} // while intermediate response
return response;
}
|
protected HttpResponse doReceiveResponse( final HttpRequest request, final HttpClientConnection conn,
final HttpContext context ) throws HttpException, IOException
{
if( request == null )
{
throw new IllegalArgumentException( "HTTP request may not be null" );
}
if( conn == null )
{
throw new IllegalArgumentException( "HTTP connection may not be null" );
}
if( context == null )
{
throw new IllegalArgumentException( "HTTP context may not be null" );
}
HttpResponse response = null;
int statuscode = 0;
while( response == null || statuscode < HttpStatus.SC_OK )
{
response = conn.receiveResponseHeader();
RequestWrapper w = ( RequestWrapper )request;
SoapUIMetrics metrics = null;
if( w.getOriginal() instanceof ExtendedHttpMethod )
{
metrics = ( ( ExtendedHttpMethod )w.getOriginal() ).getMetrics();
metrics.getTimeToFirstByteTimer().stop();
metrics.getReadTimer().start();
}
if( canResponseHaveBody( request, response ) )
{
conn.receiveResponseEntity( response );
if( metrics != null )
metrics.getReadTimer().stop();
}
statuscode = response.getStatusLine().getStatusCode();
SoapUIMetrics connectionMetrics = ( SoapUIMetrics )conn.getMetrics();
metrics.getConnectTimer().set( connectionMetrics.getConnectTimer().getStart(),
connectionMetrics.getConnectTimer().getStop() );
metrics.getDNSTimer().set( connectionMetrics.getDNSTimer().getStart(),
connectionMetrics.getDNSTimer().getStop() );
// reset connection-level metrics
connectionMetrics.reset();
} // while intermediate response
return response;
}
|
diff --git a/activiti-webapp-rest2/src/main/java/org/activiti/rest/api/task/TaskOperationResource.java b/activiti-webapp-rest2/src/main/java/org/activiti/rest/api/task/TaskOperationResource.java
index f66d9cf0e..1c864eb60 100644
--- a/activiti-webapp-rest2/src/main/java/org/activiti/rest/api/task/TaskOperationResource.java
+++ b/activiti-webapp-rest2/src/main/java/org/activiti/rest/api/task/TaskOperationResource.java
@@ -1,85 +1,85 @@
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.rest.api.task;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.activiti.engine.ActivitiException;
import org.activiti.rest.api.ActivitiUtil;
import org.activiti.rest.api.SecuredResource;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
import org.restlet.representation.Representation;
import org.restlet.resource.Put;
/**
* @author Tijs Rademakers
*/
public class TaskOperationResource extends SecuredResource {
@Put
public ObjectNode executeTaskOperation(Representation entity) {
if(authenticate() == false) return null;
String taskId = (String) getRequest().getAttributes().get("taskId");
String operation = (String) getRequest().getAttributes().get("operation");
try {
Map<String, Object> variables = new HashMap<String, Object>();
- if (entity != null && StringUtils.isNotEmpty(entity.getText())) {
- String startParams = entity.getText();
+ String startParams = entity.getText();
+ if (StringUtils.isNotEmpty(startParams)) {
JsonNode startJSON = new ObjectMapper().readTree(startParams);
Iterator<String> itName = startJSON.getFieldNames();
while(itName.hasNext()) {
String name = itName.next();
JsonNode valueNode = startJSON.path(name);
if (valueNode.isBoolean()) {
variables.put(name, valueNode.getBooleanValue());
} else if (valueNode.isLong()) {
variables.put(name, valueNode.getLongValue());
} else if (valueNode.isDouble()) {
variables.put(name, valueNode.getDoubleValue());
} else if (valueNode.isTextual()) {
variables.put(name, valueNode.getTextValue());
} else if("true".equals(valueNode.getTextValue()) || "false".equals(valueNode.getTextValue())) {
variables.put(name, Boolean.valueOf(valueNode.getTextValue()));
} else {
variables.put(name, valueNode.getValueAsText());
}
}
}
if ("claim".equals(operation)) {
ActivitiUtil.getTaskService().claim(taskId, loggedInUser);
} else if ("unclaim".equals(operation)) {
ActivitiUtil.getTaskService().claim(taskId, null);
} else if ("complete".equals(operation)) {
variables.remove("taskId");
ActivitiUtil.getTaskService().complete(taskId, variables);
} else {
throw new ActivitiException("'" + operation + "' is not a valid operation");
}
} catch(Exception e) {
throw new ActivitiException("Did not receive the operation parameters", e);
}
ObjectNode successNode = new ObjectMapper().createObjectNode();
successNode.put("success", true);
return successNode;
}
}
| true | true |
public ObjectNode executeTaskOperation(Representation entity) {
if(authenticate() == false) return null;
String taskId = (String) getRequest().getAttributes().get("taskId");
String operation = (String) getRequest().getAttributes().get("operation");
try {
Map<String, Object> variables = new HashMap<String, Object>();
if (entity != null && StringUtils.isNotEmpty(entity.getText())) {
String startParams = entity.getText();
JsonNode startJSON = new ObjectMapper().readTree(startParams);
Iterator<String> itName = startJSON.getFieldNames();
while(itName.hasNext()) {
String name = itName.next();
JsonNode valueNode = startJSON.path(name);
if (valueNode.isBoolean()) {
variables.put(name, valueNode.getBooleanValue());
} else if (valueNode.isLong()) {
variables.put(name, valueNode.getLongValue());
} else if (valueNode.isDouble()) {
variables.put(name, valueNode.getDoubleValue());
} else if (valueNode.isTextual()) {
variables.put(name, valueNode.getTextValue());
} else if("true".equals(valueNode.getTextValue()) || "false".equals(valueNode.getTextValue())) {
variables.put(name, Boolean.valueOf(valueNode.getTextValue()));
} else {
variables.put(name, valueNode.getValueAsText());
}
}
}
if ("claim".equals(operation)) {
ActivitiUtil.getTaskService().claim(taskId, loggedInUser);
} else if ("unclaim".equals(operation)) {
ActivitiUtil.getTaskService().claim(taskId, null);
} else if ("complete".equals(operation)) {
variables.remove("taskId");
ActivitiUtil.getTaskService().complete(taskId, variables);
} else {
throw new ActivitiException("'" + operation + "' is not a valid operation");
}
} catch(Exception e) {
throw new ActivitiException("Did not receive the operation parameters", e);
}
ObjectNode successNode = new ObjectMapper().createObjectNode();
successNode.put("success", true);
return successNode;
}
|
public ObjectNode executeTaskOperation(Representation entity) {
if(authenticate() == false) return null;
String taskId = (String) getRequest().getAttributes().get("taskId");
String operation = (String) getRequest().getAttributes().get("operation");
try {
Map<String, Object> variables = new HashMap<String, Object>();
String startParams = entity.getText();
if (StringUtils.isNotEmpty(startParams)) {
JsonNode startJSON = new ObjectMapper().readTree(startParams);
Iterator<String> itName = startJSON.getFieldNames();
while(itName.hasNext()) {
String name = itName.next();
JsonNode valueNode = startJSON.path(name);
if (valueNode.isBoolean()) {
variables.put(name, valueNode.getBooleanValue());
} else if (valueNode.isLong()) {
variables.put(name, valueNode.getLongValue());
} else if (valueNode.isDouble()) {
variables.put(name, valueNode.getDoubleValue());
} else if (valueNode.isTextual()) {
variables.put(name, valueNode.getTextValue());
} else if("true".equals(valueNode.getTextValue()) || "false".equals(valueNode.getTextValue())) {
variables.put(name, Boolean.valueOf(valueNode.getTextValue()));
} else {
variables.put(name, valueNode.getValueAsText());
}
}
}
if ("claim".equals(operation)) {
ActivitiUtil.getTaskService().claim(taskId, loggedInUser);
} else if ("unclaim".equals(operation)) {
ActivitiUtil.getTaskService().claim(taskId, null);
} else if ("complete".equals(operation)) {
variables.remove("taskId");
ActivitiUtil.getTaskService().complete(taskId, variables);
} else {
throw new ActivitiException("'" + operation + "' is not a valid operation");
}
} catch(Exception e) {
throw new ActivitiException("Did not receive the operation parameters", e);
}
ObjectNode successNode = new ObjectMapper().createObjectNode();
successNode.put("success", true);
return successNode;
}
|
diff --git a/src/org/pentaho/di/trans/steps/avroinput/AvroInput.java b/src/org/pentaho/di/trans/steps/avroinput/AvroInput.java
index 7486fbaf..3ef5532d 100644
--- a/src/org/pentaho/di/trans/steps/avroinput/AvroInput.java
+++ b/src/org/pentaho/di/trans/steps/avroinput/AvroInput.java
@@ -1,236 +1,237 @@
/*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.avroinput;
import java.io.IOException;
import org.apache.commons.vfs.FileObject;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
/**
* Class providing an input step for reading data from an Avro serialized file.
* Handles both container files (where the schema is serialized into the file)
* and schemaless files. In the case of the later, the user must supply a schema
* in order to read objects from the file. In the case of the former, a schema
* can be optionally supplied.
*
* Currently supports Avro records, arrays, maps and primitive types. Paths use
* the "dot" notation and "$" indicates the root of the object. Arrays and maps
* are accessed via "[]" and differ only in that array elements are accessed via
* zero-based integer indexes and map values are accessed by string keys.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class AvroInput extends BaseStep implements StepInterface {
protected AvroInputMeta m_meta;
protected AvroInputData m_data;
public AvroInput(StepMeta stepMeta, StepDataInterface stepDataInterface,
int copyNr, TransMeta transMeta, Trans trans) {
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
/*
* (non-Javadoc)
*
* @see
* org.pentaho.di.trans.step.BaseStep#processRow(org.pentaho.di.trans.step
* .StepMetaInterface, org.pentaho.di.trans.step.StepDataInterface)
*/
@Override
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi)
throws KettleException {
Object[] currentInputRow = getRow();
if (first) {
first = false;
m_data = (AvroInputData) sdi;
m_meta = (AvroInputMeta) smi;
if (Const.isEmpty(m_meta.getFilename()) && !m_meta.getAvroInField()) {
throw new KettleException(BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Error.NoAvroFileSpecified"));
}
String readerSchema = m_meta.getSchemaFilename();
readerSchema = environmentSubstitute(readerSchema);
String avroFieldName = m_meta.getAvroFieldName();
avroFieldName = environmentSubstitute(avroFieldName);
// setup the output row meta
RowMetaInterface outRowMeta = null;
outRowMeta = getInputRowMeta();
if (outRowMeta != null) {
outRowMeta = outRowMeta.clone();
} else {
outRowMeta = new RowMeta();
}
int newFieldOffset = outRowMeta.size();
m_data.setOutputRowMeta(outRowMeta);
m_meta.getFields(m_data.getOutputRowMeta(), getStepname(), null, null,
this);
// initialize substitution fields
if (m_meta.getLookupFields() != null
- && m_meta.getLookupFields().size() > 0) {
+ && m_meta.getLookupFields().size() > 0 && getInputRowMeta() != null
+ && currentInputRow != null) {
for (AvroInputMeta.LookupField f : m_meta.getLookupFields()) {
f.init(getInputRowMeta(), this);
}
}
if (m_meta.getAvroInField()) {
// initialize for reading from a field
m_data.initializeFromFieldDecoding(avroFieldName, readerSchema,
m_meta.getAvroFields(), m_meta.getAvroIsJsonEncoded(),
newFieldOffset);
} else {
// initialize for reading from a file
FileObject fileObject = KettleVFS.getFileObject(m_meta.getFilename(),
getTransMeta());
m_data.establishFileType(fileObject, readerSchema,
m_meta.getAvroFields(), m_meta.getAvroIsJsonEncoded(),
newFieldOffset);
}
}
if (!m_meta.getAvroInField()) {
currentInputRow = null;
} else {
if (currentInputRow != null) {
// set variables lookup values
if (m_meta.getLookupFields() != null
&& m_meta.getLookupFields().size() > 0) {
for (AvroInputMeta.LookupField f : m_meta.getLookupFields()) {
f.setVariable(this, currentInputRow);
}
}
}
}
Object[][] outputRow = null;
try {
outputRow = m_data.avroObjectToKettle(currentInputRow, this);
} catch (Exception ex) {
if (getStepMeta().isDoingErrorHandling()) {
String errorDescriptions = BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Error.ProblemDecodingAvroObject", ex.getMessage());
String errorFields = "";
RowMetaInterface rowMeta = null;
Object[] currentRow = new Object[0];
if (m_meta.getAvroInField()) {
errorFields += m_meta.getAvroFieldName();
rowMeta = getInputRowMeta();
currentRow = currentInputRow;
} else {
errorFields = "Data read from file";
rowMeta = m_data.getOutputRowMeta();
}
putError(rowMeta, currentRow, 1, errorDescriptions, errorFields,
"AvroInput001");
if (checkFeedback(getProcessed())) {
logBasic(BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Message.CheckFeedback", getProcessed()));
}
return true;
} else {
throw new KettleException(ex.getMessage(), ex);
}
}
if (outputRow != null) {
// there may be more than one row if the paths contain an array/map
// expansion
for (int i = 0; i < outputRow.length; i++) {
putRow(m_data.getOutputRowMeta(), outputRow[i]);
if (log.isRowLevel()) {
log.logRowlevel(toString(), "Outputted row #" + getProcessed()
+ " : " + outputRow);
}
}
} else {
if (!m_meta.getAvroInField()) {
try {
logBasic(BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Message.ClosingFile"));
m_data.close();
} catch (IOException ex) {
throw new KettleException(ex.getMessage(), ex);
}
}
setOutputDone();
return false;
}
if (checkFeedback(getProcessed())) {
logBasic(BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Message.CheckFeedback", getProcessed()));
}
return true;
}
/*
* (non-Javadoc)
*
* @see org.pentaho.di.trans.step.BaseStep#setStopped(boolean)
*/
@Override
public void setStopped(boolean stopped) {
if (isStopped() && stopped == true) {
return;
}
super.setStopped(stopped);
if (stopped && !m_meta.getAvroInField()) {
try {
logBasic(BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Message.ClosingFile"));
m_data.close();
} catch (IOException ex) {
logError(ex.getMessage(), ex);
}
}
}
}
| true | true |
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi)
throws KettleException {
Object[] currentInputRow = getRow();
if (first) {
first = false;
m_data = (AvroInputData) sdi;
m_meta = (AvroInputMeta) smi;
if (Const.isEmpty(m_meta.getFilename()) && !m_meta.getAvroInField()) {
throw new KettleException(BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Error.NoAvroFileSpecified"));
}
String readerSchema = m_meta.getSchemaFilename();
readerSchema = environmentSubstitute(readerSchema);
String avroFieldName = m_meta.getAvroFieldName();
avroFieldName = environmentSubstitute(avroFieldName);
// setup the output row meta
RowMetaInterface outRowMeta = null;
outRowMeta = getInputRowMeta();
if (outRowMeta != null) {
outRowMeta = outRowMeta.clone();
} else {
outRowMeta = new RowMeta();
}
int newFieldOffset = outRowMeta.size();
m_data.setOutputRowMeta(outRowMeta);
m_meta.getFields(m_data.getOutputRowMeta(), getStepname(), null, null,
this);
// initialize substitution fields
if (m_meta.getLookupFields() != null
&& m_meta.getLookupFields().size() > 0) {
for (AvroInputMeta.LookupField f : m_meta.getLookupFields()) {
f.init(getInputRowMeta(), this);
}
}
if (m_meta.getAvroInField()) {
// initialize for reading from a field
m_data.initializeFromFieldDecoding(avroFieldName, readerSchema,
m_meta.getAvroFields(), m_meta.getAvroIsJsonEncoded(),
newFieldOffset);
} else {
// initialize for reading from a file
FileObject fileObject = KettleVFS.getFileObject(m_meta.getFilename(),
getTransMeta());
m_data.establishFileType(fileObject, readerSchema,
m_meta.getAvroFields(), m_meta.getAvroIsJsonEncoded(),
newFieldOffset);
}
}
if (!m_meta.getAvroInField()) {
currentInputRow = null;
} else {
if (currentInputRow != null) {
// set variables lookup values
if (m_meta.getLookupFields() != null
&& m_meta.getLookupFields().size() > 0) {
for (AvroInputMeta.LookupField f : m_meta.getLookupFields()) {
f.setVariable(this, currentInputRow);
}
}
}
}
Object[][] outputRow = null;
try {
outputRow = m_data.avroObjectToKettle(currentInputRow, this);
} catch (Exception ex) {
if (getStepMeta().isDoingErrorHandling()) {
String errorDescriptions = BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Error.ProblemDecodingAvroObject", ex.getMessage());
String errorFields = "";
RowMetaInterface rowMeta = null;
Object[] currentRow = new Object[0];
if (m_meta.getAvroInField()) {
errorFields += m_meta.getAvroFieldName();
rowMeta = getInputRowMeta();
currentRow = currentInputRow;
} else {
errorFields = "Data read from file";
rowMeta = m_data.getOutputRowMeta();
}
putError(rowMeta, currentRow, 1, errorDescriptions, errorFields,
"AvroInput001");
if (checkFeedback(getProcessed())) {
logBasic(BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Message.CheckFeedback", getProcessed()));
}
return true;
} else {
throw new KettleException(ex.getMessage(), ex);
}
}
if (outputRow != null) {
// there may be more than one row if the paths contain an array/map
// expansion
for (int i = 0; i < outputRow.length; i++) {
putRow(m_data.getOutputRowMeta(), outputRow[i]);
if (log.isRowLevel()) {
log.logRowlevel(toString(), "Outputted row #" + getProcessed()
+ " : " + outputRow);
}
}
} else {
if (!m_meta.getAvroInField()) {
try {
logBasic(BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Message.ClosingFile"));
m_data.close();
} catch (IOException ex) {
throw new KettleException(ex.getMessage(), ex);
}
}
setOutputDone();
return false;
}
if (checkFeedback(getProcessed())) {
logBasic(BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Message.CheckFeedback", getProcessed()));
}
return true;
}
|
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi)
throws KettleException {
Object[] currentInputRow = getRow();
if (first) {
first = false;
m_data = (AvroInputData) sdi;
m_meta = (AvroInputMeta) smi;
if (Const.isEmpty(m_meta.getFilename()) && !m_meta.getAvroInField()) {
throw new KettleException(BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Error.NoAvroFileSpecified"));
}
String readerSchema = m_meta.getSchemaFilename();
readerSchema = environmentSubstitute(readerSchema);
String avroFieldName = m_meta.getAvroFieldName();
avroFieldName = environmentSubstitute(avroFieldName);
// setup the output row meta
RowMetaInterface outRowMeta = null;
outRowMeta = getInputRowMeta();
if (outRowMeta != null) {
outRowMeta = outRowMeta.clone();
} else {
outRowMeta = new RowMeta();
}
int newFieldOffset = outRowMeta.size();
m_data.setOutputRowMeta(outRowMeta);
m_meta.getFields(m_data.getOutputRowMeta(), getStepname(), null, null,
this);
// initialize substitution fields
if (m_meta.getLookupFields() != null
&& m_meta.getLookupFields().size() > 0 && getInputRowMeta() != null
&& currentInputRow != null) {
for (AvroInputMeta.LookupField f : m_meta.getLookupFields()) {
f.init(getInputRowMeta(), this);
}
}
if (m_meta.getAvroInField()) {
// initialize for reading from a field
m_data.initializeFromFieldDecoding(avroFieldName, readerSchema,
m_meta.getAvroFields(), m_meta.getAvroIsJsonEncoded(),
newFieldOffset);
} else {
// initialize for reading from a file
FileObject fileObject = KettleVFS.getFileObject(m_meta.getFilename(),
getTransMeta());
m_data.establishFileType(fileObject, readerSchema,
m_meta.getAvroFields(), m_meta.getAvroIsJsonEncoded(),
newFieldOffset);
}
}
if (!m_meta.getAvroInField()) {
currentInputRow = null;
} else {
if (currentInputRow != null) {
// set variables lookup values
if (m_meta.getLookupFields() != null
&& m_meta.getLookupFields().size() > 0) {
for (AvroInputMeta.LookupField f : m_meta.getLookupFields()) {
f.setVariable(this, currentInputRow);
}
}
}
}
Object[][] outputRow = null;
try {
outputRow = m_data.avroObjectToKettle(currentInputRow, this);
} catch (Exception ex) {
if (getStepMeta().isDoingErrorHandling()) {
String errorDescriptions = BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Error.ProblemDecodingAvroObject", ex.getMessage());
String errorFields = "";
RowMetaInterface rowMeta = null;
Object[] currentRow = new Object[0];
if (m_meta.getAvroInField()) {
errorFields += m_meta.getAvroFieldName();
rowMeta = getInputRowMeta();
currentRow = currentInputRow;
} else {
errorFields = "Data read from file";
rowMeta = m_data.getOutputRowMeta();
}
putError(rowMeta, currentRow, 1, errorDescriptions, errorFields,
"AvroInput001");
if (checkFeedback(getProcessed())) {
logBasic(BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Message.CheckFeedback", getProcessed()));
}
return true;
} else {
throw new KettleException(ex.getMessage(), ex);
}
}
if (outputRow != null) {
// there may be more than one row if the paths contain an array/map
// expansion
for (int i = 0; i < outputRow.length; i++) {
putRow(m_data.getOutputRowMeta(), outputRow[i]);
if (log.isRowLevel()) {
log.logRowlevel(toString(), "Outputted row #" + getProcessed()
+ " : " + outputRow);
}
}
} else {
if (!m_meta.getAvroInField()) {
try {
logBasic(BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Message.ClosingFile"));
m_data.close();
} catch (IOException ex) {
throw new KettleException(ex.getMessage(), ex);
}
}
setOutputDone();
return false;
}
if (checkFeedback(getProcessed())) {
logBasic(BaseMessages.getString(AvroInputMeta.PKG,
"AvroInput.Message.CheckFeedback", getProcessed()));
}
return true;
}
|
diff --git a/cotrix/cotrix-web-publish/src/main/java/org/cotrix/web/publish/client/wizard/PublishWizardPresenterImpl.java b/cotrix/cotrix-web-publish/src/main/java/org/cotrix/web/publish/client/wizard/PublishWizardPresenterImpl.java
index 0cc71a1a..95dfcf42 100644
--- a/cotrix/cotrix-web-publish/src/main/java/org/cotrix/web/publish/client/wizard/PublishWizardPresenterImpl.java
+++ b/cotrix/cotrix-web-publish/src/main/java/org/cotrix/web/publish/client/wizard/PublishWizardPresenterImpl.java
@@ -1,155 +1,155 @@
package org.cotrix.web.publish.client.wizard;
import java.util.Arrays;
import java.util.List;
import org.cotrix.web.publish.client.event.PublishBus;
import org.cotrix.web.publish.client.wizard.step.DestinationNodeSelector;
import org.cotrix.web.publish.client.wizard.step.DetailsNodeSelector;
import org.cotrix.web.publish.client.wizard.step.TypeNodeSelector;
import org.cotrix.web.publish.client.wizard.step.codelistdetails.CodelistDetailsStepPresenter;
import org.cotrix.web.publish.client.wizard.step.codelistselection.CodelistSelectionStepPresenter;
import org.cotrix.web.publish.client.wizard.step.csvconfiguration.CsvConfigurationStepPresenter;
import org.cotrix.web.publish.client.wizard.step.csvmapping.CsvMappingStepPresenter;
import org.cotrix.web.publish.client.wizard.step.destinationselection.DestinationSelectionStepPresenter;
import org.cotrix.web.publish.client.wizard.step.done.DoneStepPresenter;
import org.cotrix.web.publish.client.wizard.step.repositoryselection.RepositorySelectionStepPresenter;
import org.cotrix.web.publish.client.wizard.step.sdmxmapping.SdmxMappingStepPresenter;
import org.cotrix.web.publish.client.wizard.step.summary.SummaryStepPresenter;
import org.cotrix.web.publish.client.wizard.step.typeselection.TypeSelectionStepPresenter;
import org.cotrix.web.publish.client.wizard.task.PublishTask;
import org.cotrix.web.publish.client.wizard.task.RetrieveCSVConfigurationTask;
import org.cotrix.web.publish.client.wizard.task.RetrieveMappingsTask;
import org.cotrix.web.publish.client.wizard.task.RetrieveMetadataTask;
import org.cotrix.web.share.client.wizard.DefaultWizardActionHandler;
import org.cotrix.web.share.client.wizard.WizardController;
import org.cotrix.web.share.client.wizard.flow.FlowManager;
import org.cotrix.web.share.client.wizard.flow.FlowManager.LabelProvider;
import org.cotrix.web.share.client.wizard.flow.builder.FlowManagerBuilder;
import org.cotrix.web.share.client.wizard.flow.builder.NodeBuilder.RootNodeBuilder;
import org.cotrix.web.share.client.wizard.flow.builder.NodeBuilder.SingleNodeBuilder;
import org.cotrix.web.share.client.wizard.flow.builder.NodeBuilder.SwitchNodeBuilder;
import org.cotrix.web.share.client.wizard.step.WizardStep;
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
/**
* @author "Federico De Faveri [email protected]"
*
*/
public class PublishWizardPresenterImpl implements PublishWizardPresenter {
protected WizardController wizardController;
protected FlowManager<WizardStep> flow;
protected PublishWizardView view;
protected EventBus publishEventBus;
@Inject
public PublishWizardPresenterImpl(@PublishBus EventBus publishEventBus, PublishWizardView view,
CodelistSelectionStepPresenter codelistSelectionStep,
DetailsNodeSelector detailsNodeSelector,
RetrieveMetadataTask retrieveMetadataTask,
CodelistDetailsStepPresenter codelistDetailsStep,
DestinationSelectionStepPresenter destinationSelectionStep,
DestinationNodeSelector destinationSelector,
RepositorySelectionStepPresenter repositorySelectionStep,
TypeSelectionStepPresenter typeSelectionStep,
RetrieveCSVConfigurationTask retrieveCSVConfigurationTask,
CsvConfigurationStepPresenter csvConfigurationStep,
RetrieveMappingsTask retrieveMappingsTask,
CsvMappingStepPresenter csvMappingStep,
SdmxMappingStepPresenter sdmxMappingStep,
SummaryStepPresenter summaryStep,
PublishTask publishTask,
DoneStepPresenter doneStep,
PublishWizardActionHandler wizardActionHandler
) {
this.publishEventBus = publishEventBus;
this.view = view;
System.out.println("retrieveMetadataTask "+retrieveMetadataTask);
RootNodeBuilder<WizardStep> root = FlowManagerBuilder.<WizardStep>startFlow(codelistSelectionStep);
SwitchNodeBuilder<WizardStep> selectionStep = root.hasAlternatives(detailsNodeSelector);
selectionStep.alternative(retrieveMetadataTask).next(codelistDetailsStep);
SwitchNodeBuilder<WizardStep> destination = selectionStep.alternative(destinationSelectionStep).hasAlternatives(destinationSelector);
- TypeNodeSelector fileTypeSelector = new TypeNodeSelector(publishEventBus, retrieveCSVConfigurationTask, sdmxMappingStep);
+ TypeNodeSelector fileTypeSelector = new TypeNodeSelector(publishEventBus, retrieveMappingsTask, sdmxMappingStep);
SwitchNodeBuilder<WizardStep> type = destination.alternative(typeSelectionStep).hasAlternatives(fileTypeSelector);
- SingleNodeBuilder<WizardStep> csvMapping = type.alternative(retrieveCSVConfigurationTask).next(csvConfigurationStep).next(retrieveMappingsTask).next(csvMappingStep);
+ SingleNodeBuilder<WizardStep> csvMapping = type.alternative(retrieveMappingsTask).next(csvMappingStep).next(retrieveCSVConfigurationTask).next(csvConfigurationStep);
SingleNodeBuilder<WizardStep> sdmxMapping = type.alternative(sdmxMappingStep);
TypeNodeSelector repositoryTypeSelector = new TypeNodeSelector(publishEventBus, csvMappingStep, sdmxMappingStep);
SwitchNodeBuilder<WizardStep> repository = destination.alternative(repositorySelectionStep).hasAlternatives(repositoryTypeSelector);
repository.alternative(csvMapping);
repository.alternative(sdmxMapping);
SingleNodeBuilder<WizardStep> summary = csvMapping.next(summaryStep);
sdmxMapping.next(summary);
summary.next(publishTask).next(doneStep);
/*SwitchNodeBuilder<WizardStep> upload = source.alternative(uploadStep).hasAlternatives(new TypeNodeSelector(importEventBus, csvPreviewStep, sdmxMappingStep));
SingleNodeBuilder<WizardStep> csvPreview = upload.alternative(csvPreviewStep);
SingleNodeBuilder<WizardStep> csvMapping = csvPreview.next(csvMappingStep);
SingleNodeBuilder<WizardStep> sdmxMapping = upload.alternative(sdmxMappingStep);*/
/* SwitchNodeBuilder<WizardStep> selection = *//*.hasAlternatives(detailsNodeSelector);
/*SingleNodeBuilder<WizardStep> codelistDetails = selection.alternative(codelistDetailsStep);
SingleNodeBuilder<WizardStep> repositoryDetails = selection.alternative(repositoryDetailsStep);
codelistDetails.next(repositoryDetails);
SwitchNodeBuilder<WizardStep> retrieveAsset = selection.alternative(retrieveAssetTask).hasAlternatives(mappingNodeSelector);
retrieveAsset.alternative(sdmxMapping);
retrieveAsset.alternative(csvMapping);
SingleNodeBuilder<WizardStep> summary = csvMapping.next(summaryStep);
sdmxMapping.next(summary);
summary.next(importTask).next(doneStep);*/
flow = root.build();
//only for debug
if (Log.isTraceEnabled()) {
String dot = flow.toDot(new LabelProvider<WizardStep>() {
@Override
public String getLabel(WizardStep item) {
return item.getId();
}
});
Log.trace("dot: "+dot);
}
List<WizardStep> visualSteps = Arrays.<WizardStep>asList(
codelistSelectionStep, codelistDetailsStep, destinationSelectionStep, repositorySelectionStep, typeSelectionStep, csvConfigurationStep,
sdmxMappingStep, csvMappingStep, summaryStep, doneStep);
wizardController = new WizardController(visualSteps, flow, view, publishEventBus);
wizardController.addActionHandler(new DefaultWizardActionHandler());
wizardController.addActionHandler(wizardActionHandler);
}
public void go(HasWidgets container) {
container.add(view.asWidget());
wizardController.init();
}
}
| false | true |
public PublishWizardPresenterImpl(@PublishBus EventBus publishEventBus, PublishWizardView view,
CodelistSelectionStepPresenter codelistSelectionStep,
DetailsNodeSelector detailsNodeSelector,
RetrieveMetadataTask retrieveMetadataTask,
CodelistDetailsStepPresenter codelistDetailsStep,
DestinationSelectionStepPresenter destinationSelectionStep,
DestinationNodeSelector destinationSelector,
RepositorySelectionStepPresenter repositorySelectionStep,
TypeSelectionStepPresenter typeSelectionStep,
RetrieveCSVConfigurationTask retrieveCSVConfigurationTask,
CsvConfigurationStepPresenter csvConfigurationStep,
RetrieveMappingsTask retrieveMappingsTask,
CsvMappingStepPresenter csvMappingStep,
SdmxMappingStepPresenter sdmxMappingStep,
SummaryStepPresenter summaryStep,
PublishTask publishTask,
DoneStepPresenter doneStep,
PublishWizardActionHandler wizardActionHandler
) {
this.publishEventBus = publishEventBus;
this.view = view;
System.out.println("retrieveMetadataTask "+retrieveMetadataTask);
RootNodeBuilder<WizardStep> root = FlowManagerBuilder.<WizardStep>startFlow(codelistSelectionStep);
SwitchNodeBuilder<WizardStep> selectionStep = root.hasAlternatives(detailsNodeSelector);
selectionStep.alternative(retrieveMetadataTask).next(codelistDetailsStep);
SwitchNodeBuilder<WizardStep> destination = selectionStep.alternative(destinationSelectionStep).hasAlternatives(destinationSelector);
TypeNodeSelector fileTypeSelector = new TypeNodeSelector(publishEventBus, retrieveCSVConfigurationTask, sdmxMappingStep);
SwitchNodeBuilder<WizardStep> type = destination.alternative(typeSelectionStep).hasAlternatives(fileTypeSelector);
SingleNodeBuilder<WizardStep> csvMapping = type.alternative(retrieveCSVConfigurationTask).next(csvConfigurationStep).next(retrieveMappingsTask).next(csvMappingStep);
SingleNodeBuilder<WizardStep> sdmxMapping = type.alternative(sdmxMappingStep);
TypeNodeSelector repositoryTypeSelector = new TypeNodeSelector(publishEventBus, csvMappingStep, sdmxMappingStep);
SwitchNodeBuilder<WizardStep> repository = destination.alternative(repositorySelectionStep).hasAlternatives(repositoryTypeSelector);
repository.alternative(csvMapping);
repository.alternative(sdmxMapping);
SingleNodeBuilder<WizardStep> summary = csvMapping.next(summaryStep);
sdmxMapping.next(summary);
summary.next(publishTask).next(doneStep);
/*SwitchNodeBuilder<WizardStep> upload = source.alternative(uploadStep).hasAlternatives(new TypeNodeSelector(importEventBus, csvPreviewStep, sdmxMappingStep));
SingleNodeBuilder<WizardStep> csvPreview = upload.alternative(csvPreviewStep);
SingleNodeBuilder<WizardStep> csvMapping = csvPreview.next(csvMappingStep);
SingleNodeBuilder<WizardStep> sdmxMapping = upload.alternative(sdmxMappingStep);*/
/* SwitchNodeBuilder<WizardStep> selection = *//*.hasAlternatives(detailsNodeSelector);
/*SingleNodeBuilder<WizardStep> codelistDetails = selection.alternative(codelistDetailsStep);
SingleNodeBuilder<WizardStep> repositoryDetails = selection.alternative(repositoryDetailsStep);
codelistDetails.next(repositoryDetails);
SwitchNodeBuilder<WizardStep> retrieveAsset = selection.alternative(retrieveAssetTask).hasAlternatives(mappingNodeSelector);
retrieveAsset.alternative(sdmxMapping);
retrieveAsset.alternative(csvMapping);
SingleNodeBuilder<WizardStep> summary = csvMapping.next(summaryStep);
sdmxMapping.next(summary);
summary.next(importTask).next(doneStep);*/
flow = root.build();
//only for debug
if (Log.isTraceEnabled()) {
String dot = flow.toDot(new LabelProvider<WizardStep>() {
@Override
public String getLabel(WizardStep item) {
return item.getId();
}
});
Log.trace("dot: "+dot);
}
List<WizardStep> visualSteps = Arrays.<WizardStep>asList(
codelistSelectionStep, codelistDetailsStep, destinationSelectionStep, repositorySelectionStep, typeSelectionStep, csvConfigurationStep,
sdmxMappingStep, csvMappingStep, summaryStep, doneStep);
wizardController = new WizardController(visualSteps, flow, view, publishEventBus);
wizardController.addActionHandler(new DefaultWizardActionHandler());
wizardController.addActionHandler(wizardActionHandler);
}
|
public PublishWizardPresenterImpl(@PublishBus EventBus publishEventBus, PublishWizardView view,
CodelistSelectionStepPresenter codelistSelectionStep,
DetailsNodeSelector detailsNodeSelector,
RetrieveMetadataTask retrieveMetadataTask,
CodelistDetailsStepPresenter codelistDetailsStep,
DestinationSelectionStepPresenter destinationSelectionStep,
DestinationNodeSelector destinationSelector,
RepositorySelectionStepPresenter repositorySelectionStep,
TypeSelectionStepPresenter typeSelectionStep,
RetrieveCSVConfigurationTask retrieveCSVConfigurationTask,
CsvConfigurationStepPresenter csvConfigurationStep,
RetrieveMappingsTask retrieveMappingsTask,
CsvMappingStepPresenter csvMappingStep,
SdmxMappingStepPresenter sdmxMappingStep,
SummaryStepPresenter summaryStep,
PublishTask publishTask,
DoneStepPresenter doneStep,
PublishWizardActionHandler wizardActionHandler
) {
this.publishEventBus = publishEventBus;
this.view = view;
System.out.println("retrieveMetadataTask "+retrieveMetadataTask);
RootNodeBuilder<WizardStep> root = FlowManagerBuilder.<WizardStep>startFlow(codelistSelectionStep);
SwitchNodeBuilder<WizardStep> selectionStep = root.hasAlternatives(detailsNodeSelector);
selectionStep.alternative(retrieveMetadataTask).next(codelistDetailsStep);
SwitchNodeBuilder<WizardStep> destination = selectionStep.alternative(destinationSelectionStep).hasAlternatives(destinationSelector);
TypeNodeSelector fileTypeSelector = new TypeNodeSelector(publishEventBus, retrieveMappingsTask, sdmxMappingStep);
SwitchNodeBuilder<WizardStep> type = destination.alternative(typeSelectionStep).hasAlternatives(fileTypeSelector);
SingleNodeBuilder<WizardStep> csvMapping = type.alternative(retrieveMappingsTask).next(csvMappingStep).next(retrieveCSVConfigurationTask).next(csvConfigurationStep);
SingleNodeBuilder<WizardStep> sdmxMapping = type.alternative(sdmxMappingStep);
TypeNodeSelector repositoryTypeSelector = new TypeNodeSelector(publishEventBus, csvMappingStep, sdmxMappingStep);
SwitchNodeBuilder<WizardStep> repository = destination.alternative(repositorySelectionStep).hasAlternatives(repositoryTypeSelector);
repository.alternative(csvMapping);
repository.alternative(sdmxMapping);
SingleNodeBuilder<WizardStep> summary = csvMapping.next(summaryStep);
sdmxMapping.next(summary);
summary.next(publishTask).next(doneStep);
/*SwitchNodeBuilder<WizardStep> upload = source.alternative(uploadStep).hasAlternatives(new TypeNodeSelector(importEventBus, csvPreviewStep, sdmxMappingStep));
SingleNodeBuilder<WizardStep> csvPreview = upload.alternative(csvPreviewStep);
SingleNodeBuilder<WizardStep> csvMapping = csvPreview.next(csvMappingStep);
SingleNodeBuilder<WizardStep> sdmxMapping = upload.alternative(sdmxMappingStep);*/
/* SwitchNodeBuilder<WizardStep> selection = *//*.hasAlternatives(detailsNodeSelector);
/*SingleNodeBuilder<WizardStep> codelistDetails = selection.alternative(codelistDetailsStep);
SingleNodeBuilder<WizardStep> repositoryDetails = selection.alternative(repositoryDetailsStep);
codelistDetails.next(repositoryDetails);
SwitchNodeBuilder<WizardStep> retrieveAsset = selection.alternative(retrieveAssetTask).hasAlternatives(mappingNodeSelector);
retrieveAsset.alternative(sdmxMapping);
retrieveAsset.alternative(csvMapping);
SingleNodeBuilder<WizardStep> summary = csvMapping.next(summaryStep);
sdmxMapping.next(summary);
summary.next(importTask).next(doneStep);*/
flow = root.build();
//only for debug
if (Log.isTraceEnabled()) {
String dot = flow.toDot(new LabelProvider<WizardStep>() {
@Override
public String getLabel(WizardStep item) {
return item.getId();
}
});
Log.trace("dot: "+dot);
}
List<WizardStep> visualSteps = Arrays.<WizardStep>asList(
codelistSelectionStep, codelistDetailsStep, destinationSelectionStep, repositorySelectionStep, typeSelectionStep, csvConfigurationStep,
sdmxMappingStep, csvMappingStep, summaryStep, doneStep);
wizardController = new WizardController(visualSteps, flow, view, publishEventBus);
wizardController.addActionHandler(new DefaultWizardActionHandler());
wizardController.addActionHandler(wizardActionHandler);
}
|
diff --git a/doxia-linkcheck/src/test/java/org/apache/maven/doxia/linkcheck/LinkCheckTest.java b/doxia-linkcheck/src/test/java/org/apache/maven/doxia/linkcheck/LinkCheckTest.java
index f40df32..f7eefab 100644
--- a/doxia-linkcheck/src/test/java/org/apache/maven/doxia/linkcheck/LinkCheckTest.java
+++ b/doxia-linkcheck/src/test/java/org/apache/maven/doxia/linkcheck/LinkCheckTest.java
@@ -1,106 +1,106 @@
package org.apache.maven.doxia.linkcheck;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.maven.doxia.linkcheck.model.LinkcheckFile;
import org.apache.maven.doxia.linkcheck.model.LinkcheckModel;
import org.codehaus.plexus.PlexusTestCase;
/**
* @author Ben Walding
* @author <a href="mailto:[email protected]">Carlos Sanchez</a>
* @version $Id$
*/
public class LinkCheckTest
extends PlexusTestCase
{
/**
* @throws Exception
*/
public void testScan()
throws Exception
{
LinkCheck lc = (LinkCheck) lookup( LinkCheck.ROLE );
assertNotNull( lc );
lc.setOnline( true ); // TODO: check if online
- lc.setBasedir( new File( "src/test/resources" ) ); // TODO
+ lc.setBasedir( new File( getBasedir(), "src/test/resources" ) ); // TODO
- lc.setReportOutput( new File( "target/linkcheck/linkcheck.xml" ) );
+ lc.setReportOutput( new File( getBasedir(), "target/linkcheck/linkcheck.xml" ) );
lc.setReportOutputEncoding( "UTF-8" );
- lc.setLinkCheckCache( new File( "target/linkcheck/linkcheck.cache" ) ); // TODO
+ lc.setLinkCheckCache( new File( getBasedir(), "target/linkcheck/linkcheck.cache" ) ); // TODO
String[] excludes = new String[] {
"http://cvs.apache.org/viewcvs.cgi/maven-pluginszz/",
"http://cvs.apache.org/viewcvs.cgi/mavenzz/" };
lc.setExcludedLinks( excludes );
LinkcheckModel result = lc.execute();
Iterator iter = result.getFiles().iterator();
Map map = new HashMap();
while ( iter.hasNext() )
{
LinkcheckFile ftc = (LinkcheckFile) iter.next();
map.put( ftc.getRelativePath(), ftc );
}
assertEquals( "files.size()", 8, result.getFiles().size() );
check( map, "nolink.html", 0 );
check( map, "test-resources/nolink.html", 0 );
check( map, "test-resources/test1/test1.html", 2 );
check( map, "test-resources/test1/test2.html", 0 );
check( map, "test1/test1.html", 1 );
check( map, "testA.html", 3 );
/* test excludes */
String fileName = "testExcludes.html";
check( map, fileName, 2 );
LinkcheckFile ftc = (LinkcheckFile) map.get( fileName );
assertEquals( "Excluded links", 2, ftc.getSuccessful() );
// index-all.html should get parsed, but is currently having problems.
// There are 805 distinct links in this page
check( map, "index-all.html", 805 );
}
private void check( Map map, String name, int linkCount )
{
LinkcheckFile ftc = (LinkcheckFile) map.get( name );
assertNotNull( name + " = null!", ftc );
assertEquals( name + ".getResults().size()", linkCount, ftc.getResults().size() );
}
}
| false | true |
public void testScan()
throws Exception
{
LinkCheck lc = (LinkCheck) lookup( LinkCheck.ROLE );
assertNotNull( lc );
lc.setOnline( true ); // TODO: check if online
lc.setBasedir( new File( "src/test/resources" ) ); // TODO
lc.setReportOutput( new File( "target/linkcheck/linkcheck.xml" ) );
lc.setReportOutputEncoding( "UTF-8" );
lc.setLinkCheckCache( new File( "target/linkcheck/linkcheck.cache" ) ); // TODO
String[] excludes = new String[] {
"http://cvs.apache.org/viewcvs.cgi/maven-pluginszz/",
"http://cvs.apache.org/viewcvs.cgi/mavenzz/" };
lc.setExcludedLinks( excludes );
LinkcheckModel result = lc.execute();
Iterator iter = result.getFiles().iterator();
Map map = new HashMap();
while ( iter.hasNext() )
{
LinkcheckFile ftc = (LinkcheckFile) iter.next();
map.put( ftc.getRelativePath(), ftc );
}
assertEquals( "files.size()", 8, result.getFiles().size() );
check( map, "nolink.html", 0 );
check( map, "test-resources/nolink.html", 0 );
check( map, "test-resources/test1/test1.html", 2 );
check( map, "test-resources/test1/test2.html", 0 );
check( map, "test1/test1.html", 1 );
check( map, "testA.html", 3 );
/* test excludes */
String fileName = "testExcludes.html";
check( map, fileName, 2 );
LinkcheckFile ftc = (LinkcheckFile) map.get( fileName );
assertEquals( "Excluded links", 2, ftc.getSuccessful() );
// index-all.html should get parsed, but is currently having problems.
// There are 805 distinct links in this page
check( map, "index-all.html", 805 );
}
|
public void testScan()
throws Exception
{
LinkCheck lc = (LinkCheck) lookup( LinkCheck.ROLE );
assertNotNull( lc );
lc.setOnline( true ); // TODO: check if online
lc.setBasedir( new File( getBasedir(), "src/test/resources" ) ); // TODO
lc.setReportOutput( new File( getBasedir(), "target/linkcheck/linkcheck.xml" ) );
lc.setReportOutputEncoding( "UTF-8" );
lc.setLinkCheckCache( new File( getBasedir(), "target/linkcheck/linkcheck.cache" ) ); // TODO
String[] excludes = new String[] {
"http://cvs.apache.org/viewcvs.cgi/maven-pluginszz/",
"http://cvs.apache.org/viewcvs.cgi/mavenzz/" };
lc.setExcludedLinks( excludes );
LinkcheckModel result = lc.execute();
Iterator iter = result.getFiles().iterator();
Map map = new HashMap();
while ( iter.hasNext() )
{
LinkcheckFile ftc = (LinkcheckFile) iter.next();
map.put( ftc.getRelativePath(), ftc );
}
assertEquals( "files.size()", 8, result.getFiles().size() );
check( map, "nolink.html", 0 );
check( map, "test-resources/nolink.html", 0 );
check( map, "test-resources/test1/test1.html", 2 );
check( map, "test-resources/test1/test2.html", 0 );
check( map, "test1/test1.html", 1 );
check( map, "testA.html", 3 );
/* test excludes */
String fileName = "testExcludes.html";
check( map, fileName, 2 );
LinkcheckFile ftc = (LinkcheckFile) map.get( fileName );
assertEquals( "Excluded links", 2, ftc.getSuccessful() );
// index-all.html should get parsed, but is currently having problems.
// There are 805 distinct links in this page
check( map, "index-all.html", 805 );
}
|
diff --git a/FruitStandTracker/src/edu/upenn/cis350/project/Inventory2Activity.java b/FruitStandTracker/src/edu/upenn/cis350/project/Inventory2Activity.java
index 43e41f7..ad6fecf 100644
--- a/FruitStandTracker/src/edu/upenn/cis350/project/Inventory2Activity.java
+++ b/FruitStandTracker/src/edu/upenn/cis350/project/Inventory2Activity.java
@@ -1,166 +1,166 @@
package edu.upenn.cis350.project;
import java.util.HashMap;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Inventory2Activity extends Activity {
Bundle data;
int[] inventory; // pre-processing inventory
int[] fruitQtys; // post-processing changes
/* table to store quantity of each item
* 0 - apple
* 1 - banana
* 2 - grapes
* 3 - kiwi
* 4 - orange
* 5 - pear
* 6 - granola
* 7 - frozen fruit
* 8 - mixed bags
* 9 - smoothie
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory2);
data = getIntent().getExtras();
}
public void qtyClicked2(View view) {
switch(view.getId()) {
case R.id.apple2Plus:
- changeQty(true, 0, R.id.appleQty);
+ changeQty(true, 0, R.id.apple2Qty);
break;
case R.id.apple2Minus:
- changeQty(false, 0, R.id.appleQty);
+ changeQty(false, 0, R.id.apple2Qty);
break;
case R.id.banana2Plus:
- changeQty(true, 1, R.id.bananaQty);
+ changeQty(true, 1, R.id.banana2Qty);
break;
case R.id.banana2Minus:
- changeQty(false, 1, R.id.bananaQty);
+ changeQty(false, 1, R.id.banana2Qty);
break;
case R.id.grapes2Plus:
- changeQty(true, 2, R.id.grapesQty);
+ changeQty(true, 2, R.id.grapes2Qty);
break;
case R.id.grapes2Minus:
- changeQty(false, 2, R.id.grapesQty);
+ changeQty(false, 2, R.id.grapes2Qty);
break;
case R.id.kiwi2Plus:
- changeQty(true, 3, R.id.kiwiQty);
+ changeQty(true, 3, R.id.kiwi2Qty);
break;
case R.id.kiwi2Minus:
- changeQty(false, 3, R.id.kiwiQty);
+ changeQty(false, 3, R.id.kiwi2Qty);
break;
case R.id.orange2Plus:
- changeQty(true, 4, R.id.orangeQty);
+ changeQty(true, 4, R.id.orange2Qty);
break;
case R.id.orange2Minus:
- changeQty(false, 4, R.id.orangeQty);
+ changeQty(false, 4, R.id.orange2Qty);
break;
case R.id.pear2Plus:
- changeQty(true, 5, R.id.pearQty);
+ changeQty(true, 5, R.id.pear2Qty);
break;
case R.id.pear2Minus:
- changeQty(false, 5, R.id.pearQty);
+ changeQty(false, 5, R.id.pear2Qty);
break;
case R.id.mixedPlus:
changeQty(true, 8, R.id.mixedQty);
break;
case R.id.mixedMinus:
changeQty(false, 8, R.id.mixedQty);
break;
case R.id.smoothiePlus:
changeQty(true, 9, R.id.smoothieQty);
break;
case R.id.smoothieMinus:
changeQty(false, 9, R.id.smoothieQty);
break;
default:
throw new RuntimeException("Unknown Button!");
}
}
// method that modifies fruit quantity depending on which button was pressed
private void changeQty(boolean pm, int fruit, int cid ) {
int qtyTemp = getQty(cid);
if (pm) { // increment fruit qty
qtyTemp++;
} else if (qtyTemp > 0) { // decrement fruit qty
qtyTemp--;
}
fruitQtys[fruit] = qtyTemp;
EditText qtyEdit = (EditText) findViewById(cid);
qtyEdit.setText(""+qtyTemp);
}
private int getQty (int cid){
EditText qtyEdit = (EditText) findViewById(cid);
Editable qtyE = qtyEdit.getText();
try {
return Integer.parseInt(qtyE.toString());
} catch (Exception e) {
return 0;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_inventory2, menu);
return true;
}
public void continueToTransactionBase(View v) {
// calculate new inventory based on post-processing
inventory = (int[]) data.get("fruit_quantities");
// subtract fruits used to make mixed bags
for (int i=0; i<6; i++) {
inventory[i] -= fruitQtys[i];
}
// add on mixed fruit and smoothies that were made
inventory[8] = fruitQtys[8];
inventory[9] = fruitQtys[9];
//Launch to transaction base
Intent i = new Intent(this, TransactionBaseActivity.class);
//TODO Use savePostInventory to save info
HashMap<String, Integer> postinv = new HashMap<String, Integer>();
postinv.put("apples", inventory[0]);
postinv.put("bananas", inventory[1]);
postinv.put("grapes", inventory[2]);
postinv.put("kiwis", inventory[3]);
postinv.put("oranges", inventory[4]);
postinv.put("pears", inventory[5]);
postinv.put("granolas", inventory[6]);
postinv.put("mixed", inventory[8]);
postinv.put("smoothie", inventory[9]);
DataBaser.getInstance().savePostInventory(postinv);
i.putExtras(this.getIntent().getExtras());
this.startActivity(i);
}
}
| false | true |
public void qtyClicked2(View view) {
switch(view.getId()) {
case R.id.apple2Plus:
changeQty(true, 0, R.id.appleQty);
break;
case R.id.apple2Minus:
changeQty(false, 0, R.id.appleQty);
break;
case R.id.banana2Plus:
changeQty(true, 1, R.id.bananaQty);
break;
case R.id.banana2Minus:
changeQty(false, 1, R.id.bananaQty);
break;
case R.id.grapes2Plus:
changeQty(true, 2, R.id.grapesQty);
break;
case R.id.grapes2Minus:
changeQty(false, 2, R.id.grapesQty);
break;
case R.id.kiwi2Plus:
changeQty(true, 3, R.id.kiwiQty);
break;
case R.id.kiwi2Minus:
changeQty(false, 3, R.id.kiwiQty);
break;
case R.id.orange2Plus:
changeQty(true, 4, R.id.orangeQty);
break;
case R.id.orange2Minus:
changeQty(false, 4, R.id.orangeQty);
break;
case R.id.pear2Plus:
changeQty(true, 5, R.id.pearQty);
break;
case R.id.pear2Minus:
changeQty(false, 5, R.id.pearQty);
break;
case R.id.mixedPlus:
changeQty(true, 8, R.id.mixedQty);
break;
case R.id.mixedMinus:
changeQty(false, 8, R.id.mixedQty);
break;
case R.id.smoothiePlus:
changeQty(true, 9, R.id.smoothieQty);
break;
case R.id.smoothieMinus:
changeQty(false, 9, R.id.smoothieQty);
break;
default:
throw new RuntimeException("Unknown Button!");
}
}
|
public void qtyClicked2(View view) {
switch(view.getId()) {
case R.id.apple2Plus:
changeQty(true, 0, R.id.apple2Qty);
break;
case R.id.apple2Minus:
changeQty(false, 0, R.id.apple2Qty);
break;
case R.id.banana2Plus:
changeQty(true, 1, R.id.banana2Qty);
break;
case R.id.banana2Minus:
changeQty(false, 1, R.id.banana2Qty);
break;
case R.id.grapes2Plus:
changeQty(true, 2, R.id.grapes2Qty);
break;
case R.id.grapes2Minus:
changeQty(false, 2, R.id.grapes2Qty);
break;
case R.id.kiwi2Plus:
changeQty(true, 3, R.id.kiwi2Qty);
break;
case R.id.kiwi2Minus:
changeQty(false, 3, R.id.kiwi2Qty);
break;
case R.id.orange2Plus:
changeQty(true, 4, R.id.orange2Qty);
break;
case R.id.orange2Minus:
changeQty(false, 4, R.id.orange2Qty);
break;
case R.id.pear2Plus:
changeQty(true, 5, R.id.pear2Qty);
break;
case R.id.pear2Minus:
changeQty(false, 5, R.id.pear2Qty);
break;
case R.id.mixedPlus:
changeQty(true, 8, R.id.mixedQty);
break;
case R.id.mixedMinus:
changeQty(false, 8, R.id.mixedQty);
break;
case R.id.smoothiePlus:
changeQty(true, 9, R.id.smoothieQty);
break;
case R.id.smoothieMinus:
changeQty(false, 9, R.id.smoothieQty);
break;
default:
throw new RuntimeException("Unknown Button!");
}
}
|
diff --git a/src/main/java/org/kndl/util/classloader/KndlClassLoader.java b/src/main/java/org/kndl/util/classloader/KndlClassLoader.java
index 5cbf68b..d2db2c0 100644
--- a/src/main/java/org/kndl/util/classloader/KndlClassLoader.java
+++ b/src/main/java/org/kndl/util/classloader/KndlClassLoader.java
@@ -1,64 +1,65 @@
package org.kndl.util.classloader;
import org.apache.log4j.Logger;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.LinkedList;
import java.util.List;
/**
* Loads a class from any selection of remote jars.
*
*
*/
public class KndlClassLoader extends ClassLoader {
private static final Logger logger = Logger.getLogger(KndlClassLoader.class);
private List<URLClassLoader> jarLocations;
public KndlClassLoader() {
this.jarLocations = new LinkedList<URLClassLoader>();
}
public void addLocation(URL url) {
URLClassLoader ucl = new URLClassLoader(new URL[] {url},this.getClass().getClassLoader());
jarLocations.add(ucl);
}
public Class load(String className) {
Class c = null;
for(URLClassLoader loader : jarLocations) {
+ System.out.println("Loading " + loader.getURLs().toString());
try {
c = Class.forName(className,true,loader);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return c;
}
public Class get(String className) {
try {
return Class.forName(className,true,this);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static void main(String args[]) {
KndlClassLoader ncl = new KndlClassLoader();
try {
ncl.addLocation(new URL("http://pants.spacerobots.org/test.jar"));
} catch (MalformedURLException e) {
e.printStackTrace();
}
ncl.load("Test");
Class c = ncl.get("Test");
System.out.println(c.getSimpleName());
}
}
| true | true |
public Class load(String className) {
Class c = null;
for(URLClassLoader loader : jarLocations) {
try {
c = Class.forName(className,true,loader);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return c;
}
|
public Class load(String className) {
Class c = null;
for(URLClassLoader loader : jarLocations) {
System.out.println("Loading " + loader.getURLs().toString());
try {
c = Class.forName(className,true,loader);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return c;
}
|
diff --git a/neuro4j-nms-server/src/main/console/org/neuro4j/web/console/controller/vd/DefaultDecorator.java b/neuro4j-nms-server/src/main/console/org/neuro4j/web/console/controller/vd/DefaultDecorator.java
index abbe49c..fcb0896 100644
--- a/neuro4j-nms-server/src/main/console/org/neuro4j/web/console/controller/vd/DefaultDecorator.java
+++ b/neuro4j-nms-server/src/main/console/org/neuro4j/web/console/controller/vd/DefaultDecorator.java
@@ -1,35 +1,35 @@
package org.neuro4j.web.console.controller.vd;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.neuro4j.core.Entity;
import org.neuro4j.core.Relation;
public class DefaultDecorator implements ViewDecorator {
public String render(Entity displayedEntity, String groupName, List<Relation> relations, HttpServletRequest request) {
StringBuffer sb = new StringBuffer();
for (Relation r : relations)
{
- sb.append("<b><a href='/n4j-nms/relation-details?storage=" + request.getParameter("storage") + "&vt=graph&uuid=" + r.getUuid() +"'>" + r.getName() + "</a></b><br/>");
+ sb.append("<b><a href='relation-details?storage=" + request.getParameter("storage") + "&vt=graph&uuid=" + r.getUuid() +"'>" + r.getName() + "</a></b><br/>");
sb.append("<br/>");
for (Entity rp : r.getParticipants()) {
- sb.append("<a href='/n4j-nms/entity-details?storage=" + request.getParameter("storage") + "&vt=graph&eid=" + rp.getUuid() +"'>" + rp.getName() + "</a><br/>");
+ sb.append("<a href='entity-details?storage=" + request.getParameter("storage") + "&vt=graph&eid=" + rp.getUuid() +"'>" + rp.getName() + "</a><br/>");
sb.append("");
sb.append("");
sb.append("");
}
sb.append("<br/>");
}
return sb.toString();
}
}
| false | true |
public String render(Entity displayedEntity, String groupName, List<Relation> relations, HttpServletRequest request) {
StringBuffer sb = new StringBuffer();
for (Relation r : relations)
{
sb.append("<b><a href='/n4j-nms/relation-details?storage=" + request.getParameter("storage") + "&vt=graph&uuid=" + r.getUuid() +"'>" + r.getName() + "</a></b><br/>");
sb.append("<br/>");
for (Entity rp : r.getParticipants()) {
sb.append("<a href='/n4j-nms/entity-details?storage=" + request.getParameter("storage") + "&vt=graph&eid=" + rp.getUuid() +"'>" + rp.getName() + "</a><br/>");
sb.append("");
sb.append("");
sb.append("");
}
sb.append("<br/>");
}
return sb.toString();
}
|
public String render(Entity displayedEntity, String groupName, List<Relation> relations, HttpServletRequest request) {
StringBuffer sb = new StringBuffer();
for (Relation r : relations)
{
sb.append("<b><a href='relation-details?storage=" + request.getParameter("storage") + "&vt=graph&uuid=" + r.getUuid() +"'>" + r.getName() + "</a></b><br/>");
sb.append("<br/>");
for (Entity rp : r.getParticipants()) {
sb.append("<a href='entity-details?storage=" + request.getParameter("storage") + "&vt=graph&eid=" + rp.getUuid() +"'>" + rp.getName() + "</a><br/>");
sb.append("");
sb.append("");
sb.append("");
}
sb.append("<br/>");
}
return sb.toString();
}
|
diff --git a/src/org/rascalmpl/interpreter/result/NumberResult.java b/src/org/rascalmpl/interpreter/result/NumberResult.java
index 9cf6fe1d42..baf3d74a6c 100644
--- a/src/org/rascalmpl/interpreter/result/NumberResult.java
+++ b/src/org/rascalmpl/interpreter/result/NumberResult.java
@@ -1,325 +1,328 @@
package org.rascalmpl.interpreter.result;
import static org.rascalmpl.interpreter.result.IntegerResult.makeStepRangeFromToWithSecond;
import static org.rascalmpl.interpreter.result.ResultFactory.bool;
import static org.rascalmpl.interpreter.result.ResultFactory.makeResult;
import org.eclipse.imp.pdb.facts.IInteger;
import org.eclipse.imp.pdb.facts.IListWriter;
import org.eclipse.imp.pdb.facts.INumber;
import org.eclipse.imp.pdb.facts.IReal;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.type.Type;
import org.rascalmpl.interpreter.IEvaluatorContext;
import org.rascalmpl.interpreter.asserts.ImplementationError;
public class NumberResult extends ElementResult<INumber> {
public NumberResult(Type type, INumber value, IEvaluatorContext ctx) {
super(type, value, ctx);
}
@Override
public <U extends IValue, V extends IValue> Result<U> add(Result<V> result) {
return result.addNumber(this);
}
@Override
public <U extends IValue, V extends IValue> Result<U> multiply(Result<V> result) {
return result.multiplyNumber(this);
}
@Override
public <U extends IValue, V extends IValue> Result<U> divide(Result<V> result) {
return result.divideNumber(this);
}
@Override
public <U extends IValue, V extends IValue> Result<U> makeRange(Result<V> that) {
return that.makeRangeFromNumber(this);
}
@Override
public <U extends IValue, V extends IValue, W extends IValue> Result<U> makeStepRange(Result<V> to, Result<W> step) {
return to.makeStepRangeFromNumber(this, step);
}
@Override
public <U extends IValue, V extends IValue> Result<U> subtract(Result<V> result) {
return result.subtractNumber(this);
}
@Override
public <U extends IValue, V extends IValue> Result<U> equals(Result<V> that) {
return that.equalToNumber(this);
}
@Override
public <U extends IValue, V extends IValue> Result<U> nonEquals(Result<V> that) {
return that.nonEqualToNumber(this);
}
@Override
public <U extends IValue, V extends IValue> Result<U> lessThan(Result<V> result) {
return result.lessThanNumber(this);
}
@Override
public <U extends IValue, V extends IValue> Result<U> lessThanOrEqual(Result<V> result) {
return result.lessThanOrEqualNumber(this);
}
@Override
public <U extends IValue, V extends IValue> Result<U> greaterThan(Result<V> result) {
return result.greaterThanNumber(this);
}
@Override
public <U extends IValue, V extends IValue> Result<U> greaterThanOrEqual(Result<V> result) {
return result.greaterThanOrEqualNumber(this);
}
@Override
public <U extends IValue, V extends IValue> Result<U> compare(Result<V> result) {
return result.compareNumber(this);
}
/// real impls start here
@Override
public <U extends IValue> Result<U> negative() {
return makeResult(type, getValue().negate(), ctx);
}
@Override
protected <U extends IValue> Result<U> addInteger(IntegerResult n) {
return makeResult(type, getValue().add(n.getValue()), ctx);
}
@Override
protected <U extends IValue> Result<U> subtractInteger(IntegerResult n) {
// Note reversed args: we need n - this
return makeResult(type, n.getValue().subtract(getValue()), ctx);
}
@Override
protected <U extends IValue> Result<U> multiplyInteger(IntegerResult n) {
return makeResult(type, getValue().multiply(n.getValue()), ctx);
}
@Override
protected <U extends IValue> Result<U> divideInteger(IntegerResult n) {
// Note reversed args: we need n / this
return makeResult(type, n.getValue().divide(getValue(), RealResult.PRECISION), ctx);
}
@Override
protected <U extends IValue> Result<U> addReal(RealResult n) {
return makeResult(type, getValue().add(n.getValue()), ctx);
}
@Override
protected <U extends IValue> Result<U> subtractReal(RealResult n) {
// note the reverse subtraction.
return makeResult(type, n.getValue().subtract(getValue()), ctx);
}
@Override
protected <U extends IValue> Result<U> multiplyReal(RealResult n) {
return makeResult(type, getValue().multiply(n.getValue()), ctx);
}
@Override
protected <U extends IValue> Result<U> divideReal(RealResult n) {
// note the reverse division
return makeResult(type, n.getValue().divide(getValue(), RealResult.PRECISION), ctx);
}
@Override
protected <U extends IValue> Result<U> equalToReal(RealResult that) {
return that.equalityBoolean(this);
}
@Override
protected <U extends IValue> Result<U> nonEqualToReal(RealResult that) {
return that.nonEqualityBoolean(this);
}
@Override
protected <U extends IValue> Result<U> lessThanReal(RealResult that) {
// note reversed args: we need that < this
return bool((that.comparisonInts(this) < 0), ctx);
}
@Override
protected <U extends IValue> Result<U> lessThanOrEqualReal(RealResult that) {
// note reversed args: we need that <= this
return bool((that.comparisonInts(this) <= 0), ctx);
}
@Override
protected <U extends IValue> Result<U> greaterThanReal(RealResult that) {
// note reversed args: we need that > this
return bool((that.comparisonInts(this) > 0), ctx);
}
@Override
protected <U extends IValue> Result<U> greaterThanOrEqualReal(RealResult that) {
// note reversed args: we need that >= this
return bool((that.comparisonInts(this) >= 0), ctx);
}
@Override
protected <U extends IValue> Result<U> compareReal(RealResult that) {
// note reverse arguments
IReal left = that.getValue();
INumber right = this.getValue();
int result = left.compare(right);
return makeIntegerResult(result);
}
@Override
protected <U extends IValue> Result<U> compareInteger(IntegerResult that) {
return that.widenToReal().compare(this);
}
@Override
protected <U extends IValue> Result<U> addNumber(NumberResult n) {
return makeResult(type, getValue().add(n.getValue()), ctx);
}
@Override
protected <U extends IValue> Result<U> subtractNumber(NumberResult n) {
// note the reverse subtraction.
return makeResult(type, n.getValue().subtract(getValue()), ctx);
}
@Override
protected <U extends IValue> Result<U> multiplyNumber(NumberResult n) {
return makeResult(type, getValue().multiply(n.getValue()), ctx);
}
@Override
protected <U extends IValue> Result<U> divideNumber(NumberResult n) {
// note the reverse division
return makeResult(type, n.getValue().divide(getValue(), RealResult.PRECISION), ctx);
}
@Override
protected <U extends IValue> Result<U> equalToNumber(NumberResult that) {
return that.equalityBoolean(this);
}
@Override
protected <U extends IValue> Result<U> nonEqualToNumber(NumberResult that) {
return that.nonEqualityBoolean(this);
}
@Override
protected <U extends IValue> Result<U> lessThanNumber(NumberResult that) {
// note reversed args: we need that < this
return bool((that.comparisonInts(this) < 0), ctx);
}
@Override
protected <U extends IValue> Result<U> lessThanOrEqualNumber(NumberResult that) {
// note reversed args: we need that <= this
return bool((that.comparisonInts(this) <= 0), ctx);
}
@Override
protected <U extends IValue> Result<U> greaterThanNumber(NumberResult that) {
// note reversed args: we need that > this
return bool((that.comparisonInts(this) > 0), ctx);
}
@Override
protected <U extends IValue> Result<U> greaterThanOrEqualNumber(NumberResult that) {
// note reversed args: we need that >= this
return bool((that.comparisonInts(this) >= 0), ctx);
}
@Override
protected <U extends IValue> Result<U> equalToInteger(IntegerResult that) {
return that.equalityBoolean(this);
}
@Override
protected <U extends IValue> Result<U> nonEqualToInteger(IntegerResult that) {
return that.nonEqualityBoolean(this);
}
@Override
protected <U extends IValue> Result<U> lessThanInteger(IntegerResult that) {
// note reversed args: we need that < this
return that.widenToReal().lessThan(this);
}
@Override
protected <U extends IValue> Result<U> lessThanOrEqualInteger(IntegerResult that) {
// note reversed args: we need that <= this
return that.widenToReal().lessThanOrEqual(this);
}
@Override
protected <U extends IValue> Result<U> greaterThanInteger(IntegerResult that) {
// note reversed args: we need that > this
return that.widenToReal().greaterThan(this);
}
@Override
protected <U extends IValue> Result<U> greaterThanOrEqualInteger(IntegerResult that) {
// note reversed args: we need that >= this
return that.widenToReal().greaterThanOrEqual(this);
}
@Override
protected <U extends IValue> Result<U> compareNumber(NumberResult that) {
// note reverse arguments
INumber left = that.getValue();
INumber right = this.getValue();
int result = left.compare(right);
return makeIntegerResult(result);
}
@Override
protected <U extends IValue> Result<U> makeRangeFromInteger(IntegerResult from) {
return makeRangeWithDefaultStep(from, getValueFactory().integer(1));
}
@Override
protected <U extends IValue, V extends IValue> Result<U> makeStepRangeFromInteger(IntegerResult from, Result<V> second) {
return makeStepRangeFromToWithSecond(from, this, second, getValueFactory(), getTypeFactory(), ctx);
}
@Override
protected <U extends IValue> Result<U> makeRangeFromReal(RealResult from) {
return makeRangeWithDefaultStep(from, getValueFactory().real(1.0));
}
@Override
protected <U extends IValue, V extends IValue> Result<U> makeStepRangeFromReal(RealResult from, Result<V> second) {
return makeStepRangeFromToWithSecond(from, this, second, getValueFactory(), getTypeFactory(), ctx);
}
@Override
protected <U extends IValue> Result<U> makeRangeFromNumber(NumberResult from) {
if (getType().lub(from.getType()).isIntegerType()) {
return makeRangeWithDefaultStep(from, getValueFactory().integer(1));
}
if (getType().lub(from.getType()).isRealType()) {
return makeRangeWithDefaultStep(from, getValueFactory().real(1.0));
}
+ if (getType().lub(from.getType()).isNumberType()) {
+ return makeRangeWithDefaultStep(from, getValueFactory().integer(1));
+ }
throw new ImplementationError("Unknown number type in makeRangeFromNumber");
}
private <U extends IValue, V extends INumber> Result<U> makeRangeWithDefaultStep(Result<V> from, INumber step) {
return makeStepRangeFromToWithSecond(from, this, new NumberResult(getTypeFactory().numberType(),
from.getValue().add(step), ctx), getValueFactory(), getTypeFactory(), ctx);
}
}
| true | true |
protected <U extends IValue> Result<U> makeRangeFromNumber(NumberResult from) {
if (getType().lub(from.getType()).isIntegerType()) {
return makeRangeWithDefaultStep(from, getValueFactory().integer(1));
}
if (getType().lub(from.getType()).isRealType()) {
return makeRangeWithDefaultStep(from, getValueFactory().real(1.0));
}
throw new ImplementationError("Unknown number type in makeRangeFromNumber");
}
|
protected <U extends IValue> Result<U> makeRangeFromNumber(NumberResult from) {
if (getType().lub(from.getType()).isIntegerType()) {
return makeRangeWithDefaultStep(from, getValueFactory().integer(1));
}
if (getType().lub(from.getType()).isRealType()) {
return makeRangeWithDefaultStep(from, getValueFactory().real(1.0));
}
if (getType().lub(from.getType()).isNumberType()) {
return makeRangeWithDefaultStep(from, getValueFactory().integer(1));
}
throw new ImplementationError("Unknown number type in makeRangeFromNumber");
}
|
diff --git a/src/main/java/de/minestar/FifthElement/commands/warp/cmdWarpRandom.java b/src/main/java/de/minestar/FifthElement/commands/warp/cmdWarpRandom.java
index 436970f..5d99401 100644
--- a/src/main/java/de/minestar/FifthElement/commands/warp/cmdWarpRandom.java
+++ b/src/main/java/de/minestar/FifthElement/commands/warp/cmdWarpRandom.java
@@ -1,51 +1,55 @@
/*
* Copyright (C) 2012 MineStar.de
*
* This file is part of FifthElement.
*
* FifthElement is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* FifthElement is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FifthElement. If not, see <http://www.gnu.org/licenses/>.
*/
package de.minestar.FifthElement.commands.warp;
import java.util.List;
import java.util.Random;
import org.bukkit.entity.Player;
import de.minestar.FifthElement.core.Core;
import de.minestar.FifthElement.data.Warp;
import de.minestar.minestarlibrary.commands.AbstractCommand;
import de.minestar.minestarlibrary.utils.PlayerUtils;
public class cmdWarpRandom extends AbstractCommand {
private static final Random rand = new Random();
public cmdWarpRandom(String syntax, String arguments, String node) {
super(Core.NAME, syntax, arguments, node);
}
@Override
public void execute(String[] args, Player player) {
// GET PUBLIC WARPS
List<Warp> publicWarps = Core.warpManager.getPublicWarps();
+ if (publicWarps.isEmpty()) {
+ PlayerUtils.sendSuccess(player, pluginName, "Es gibt keine �ffentlichen Warps.");
+ return;
+ }
// GET RANDOM WARP
int index = rand.nextInt(publicWarps.size());
Warp warp = publicWarps.get(index);
player.teleport(warp.getLocation());
PlayerUtils.sendSuccess(player, pluginName, "Willkommen beim zuf�lligen Warp '" + warp.getName() + "'.");
}
}
| true | true |
public void execute(String[] args, Player player) {
// GET PUBLIC WARPS
List<Warp> publicWarps = Core.warpManager.getPublicWarps();
// GET RANDOM WARP
int index = rand.nextInt(publicWarps.size());
Warp warp = publicWarps.get(index);
player.teleport(warp.getLocation());
PlayerUtils.sendSuccess(player, pluginName, "Willkommen beim zuf�lligen Warp '" + warp.getName() + "'.");
}
|
public void execute(String[] args, Player player) {
// GET PUBLIC WARPS
List<Warp> publicWarps = Core.warpManager.getPublicWarps();
if (publicWarps.isEmpty()) {
PlayerUtils.sendSuccess(player, pluginName, "Es gibt keine �ffentlichen Warps.");
return;
}
// GET RANDOM WARP
int index = rand.nextInt(publicWarps.size());
Warp warp = publicWarps.get(index);
player.teleport(warp.getLocation());
PlayerUtils.sendSuccess(player, pluginName, "Willkommen beim zuf�lligen Warp '" + warp.getName() + "'.");
}
|
diff --git a/conan-biosd-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/biosd/model/SampleTabAccessionParameter.java b/conan-biosd-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/biosd/model/SampleTabAccessionParameter.java
index 9cae699..0949519 100644
--- a/conan-biosd-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/biosd/model/SampleTabAccessionParameter.java
+++ b/conan-biosd-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/biosd/model/SampleTabAccessionParameter.java
@@ -1,26 +1,26 @@
package uk.ac.ebi.fgpt.conan.process.biosd.model;
import uk.ac.ebi.fgpt.conan.model.AbstractConanParameter;
public class SampleTabAccessionParameter extends AbstractConanParameter {
protected String accession = null;
public SampleTabAccessionParameter() {
super("SampleTab Accession");
}
protected SampleTabAccessionParameter(String name) {
super(name);
}
public void setAccession(String accession) throws IllegalArgumentException {
- if (!accession.startsWith("G") || !accession.contains("-"))
+ if (!accession.startsWith("G"))
throw new IllegalArgumentException("Invalid accession "+accession);
this.accession = accession;
}
public String getAccession(){
return this.accession;
}
}
| true | true |
public void setAccession(String accession) throws IllegalArgumentException {
if (!accession.startsWith("G") || !accession.contains("-"))
throw new IllegalArgumentException("Invalid accession "+accession);
this.accession = accession;
}
|
public void setAccession(String accession) throws IllegalArgumentException {
if (!accession.startsWith("G"))
throw new IllegalArgumentException("Invalid accession "+accession);
this.accession = accession;
}
|
diff --git a/src/com/nolanlawson/apptracker/AppTrackerService.java b/src/com/nolanlawson/apptracker/AppTrackerService.java
index 3b162ab..7e6127a 100644
--- a/src/com/nolanlawson/apptracker/AppTrackerService.java
+++ b/src/com/nolanlawson/apptracker/AppTrackerService.java
@@ -1,170 +1,170 @@
package com.nolanlawson.apptracker;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import com.nolanlawson.apptracker.db.AppHistoryDbHelper;
import com.nolanlawson.apptracker.util.FlagUtil;
import com.nolanlawson.apptracker.util.UtilLogger;
/**
* Reads logs. Named "AppTrackerService" in order to obfuscate, so the user
* won't get freaked out if they see e.g. "LogReaderService" running on their
* phone.
*
* @author nolan
*
*/
public class AppTrackerService extends IntentService {
private static UtilLogger log = new UtilLogger(AppTrackerService.class);
private static Pattern launcherPattern = Pattern
.compile("\\bcmp=([^/]++)/(\\.?\\S++)\\s");
private static Pattern flagPattern = Pattern.compile("\\bflg=0x(\\d+)\\b");
public AppTrackerService() {
super("AppTrackerService");
}
@Override
public void onCreate() {
super.onCreate();
// update all widgets when the screen wakes up again - that's the case where
// the user unlocks their screen and sees the home screen, so we need
// instant updates
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
log.d("Screen waking up; updating widgets");
AppHistoryDbHelper dbHelper = new AppHistoryDbHelper(getApplicationContext());
try {
WidgetUpdater.updateWidget(context, dbHelper);
} finally {
dbHelper.close();
}
}
}, new IntentFilter(Intent.ACTION_SCREEN_ON));
}
@Override
public void onDestroy() {
super.onDestroy();
}
protected void onHandleIntent(Intent intent) {
- log.d("Starting up LogReader now");
+ log.d("Starting up AppTrackerService now");
Process mLogcatProc = null;
BufferedReader reader = null;
try {
// logcat -d AndroidRuntime:E ActivityManager:V *:S
mLogcatProc = Runtime.getRuntime().exec(
new String[] { "logcat",
"AndroidRuntime:E ActivityManager:V *:S" });
reader = new BufferedReader(new InputStreamReader(mLogcatProc
.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("Starting activity")
&& line.contains("act=android.intent.action.MAIN")
&& !line.contains("(has extras)")) { // if it has extras, we can't call it (e.g. com.android.phone)
log.d("log is %s", line);
AppHistoryDbHelper dbHelper = new AppHistoryDbHelper(getApplicationContext());
try {
if (!line.contains("android.intent.category.HOME")) { // ignore home apps
Matcher flagMatcher = flagPattern.matcher(line);
if (flagMatcher.find()) {
String flagsAsString = flagMatcher.group(1);
int flags = Integer.parseInt(flagsAsString, 16);
log.d("flags are: 0x%s",flagsAsString);
// intents have to be "new tasks" and they have to have been launched by the user
// (not like e.g. the incoming call screen)
if (FlagUtil.hasFlag(flags, Intent.FLAG_ACTIVITY_NEW_TASK)
&& !FlagUtil.hasFlag(flags, Intent.FLAG_ACTIVITY_NO_USER_ACTION)) {
Matcher launcherMatcher = launcherPattern.matcher(line);
if (launcherMatcher.find()) {
String packageName = launcherMatcher.group(1);
String process = launcherMatcher.group(2);
log.d("package name is: " + packageName);
log.d("process name is: " + process);
synchronized (AppHistoryDbHelper.class) {
dbHelper.incrementAndUpdate(packageName, process);
}
}
}
}
}
// update the widget no matter what the activity is
// especially if it's the home activity, this is important to do
// so that the widgets stay up-to-date (e.g. with time estimates)
WidgetUpdater.updateWidget(this, dbHelper);
} finally {
dbHelper.close();
}
}
}
}
catch (IOException e) {
log.e(e, "unexpected exception");
}
finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
log.e(e, "unexpected exception");
}
}
log.d("AppTrackerService died for some reason");
}
}
}
| true | true |
protected void onHandleIntent(Intent intent) {
log.d("Starting up LogReader now");
Process mLogcatProc = null;
BufferedReader reader = null;
try {
// logcat -d AndroidRuntime:E ActivityManager:V *:S
mLogcatProc = Runtime.getRuntime().exec(
new String[] { "logcat",
"AndroidRuntime:E ActivityManager:V *:S" });
reader = new BufferedReader(new InputStreamReader(mLogcatProc
.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("Starting activity")
&& line.contains("act=android.intent.action.MAIN")
&& !line.contains("(has extras)")) { // if it has extras, we can't call it (e.g. com.android.phone)
log.d("log is %s", line);
AppHistoryDbHelper dbHelper = new AppHistoryDbHelper(getApplicationContext());
try {
if (!line.contains("android.intent.category.HOME")) { // ignore home apps
Matcher flagMatcher = flagPattern.matcher(line);
if (flagMatcher.find()) {
String flagsAsString = flagMatcher.group(1);
int flags = Integer.parseInt(flagsAsString, 16);
log.d("flags are: 0x%s",flagsAsString);
// intents have to be "new tasks" and they have to have been launched by the user
// (not like e.g. the incoming call screen)
if (FlagUtil.hasFlag(flags, Intent.FLAG_ACTIVITY_NEW_TASK)
&& !FlagUtil.hasFlag(flags, Intent.FLAG_ACTIVITY_NO_USER_ACTION)) {
Matcher launcherMatcher = launcherPattern.matcher(line);
if (launcherMatcher.find()) {
String packageName = launcherMatcher.group(1);
String process = launcherMatcher.group(2);
log.d("package name is: " + packageName);
log.d("process name is: " + process);
synchronized (AppHistoryDbHelper.class) {
dbHelper.incrementAndUpdate(packageName, process);
}
}
}
}
}
// update the widget no matter what the activity is
// especially if it's the home activity, this is important to do
// so that the widgets stay up-to-date (e.g. with time estimates)
WidgetUpdater.updateWidget(this, dbHelper);
} finally {
dbHelper.close();
}
}
}
}
catch (IOException e) {
log.e(e, "unexpected exception");
}
finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
log.e(e, "unexpected exception");
}
}
log.d("AppTrackerService died for some reason");
}
}
|
protected void onHandleIntent(Intent intent) {
log.d("Starting up AppTrackerService now");
Process mLogcatProc = null;
BufferedReader reader = null;
try {
// logcat -d AndroidRuntime:E ActivityManager:V *:S
mLogcatProc = Runtime.getRuntime().exec(
new String[] { "logcat",
"AndroidRuntime:E ActivityManager:V *:S" });
reader = new BufferedReader(new InputStreamReader(mLogcatProc
.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("Starting activity")
&& line.contains("act=android.intent.action.MAIN")
&& !line.contains("(has extras)")) { // if it has extras, we can't call it (e.g. com.android.phone)
log.d("log is %s", line);
AppHistoryDbHelper dbHelper = new AppHistoryDbHelper(getApplicationContext());
try {
if (!line.contains("android.intent.category.HOME")) { // ignore home apps
Matcher flagMatcher = flagPattern.matcher(line);
if (flagMatcher.find()) {
String flagsAsString = flagMatcher.group(1);
int flags = Integer.parseInt(flagsAsString, 16);
log.d("flags are: 0x%s",flagsAsString);
// intents have to be "new tasks" and they have to have been launched by the user
// (not like e.g. the incoming call screen)
if (FlagUtil.hasFlag(flags, Intent.FLAG_ACTIVITY_NEW_TASK)
&& !FlagUtil.hasFlag(flags, Intent.FLAG_ACTIVITY_NO_USER_ACTION)) {
Matcher launcherMatcher = launcherPattern.matcher(line);
if (launcherMatcher.find()) {
String packageName = launcherMatcher.group(1);
String process = launcherMatcher.group(2);
log.d("package name is: " + packageName);
log.d("process name is: " + process);
synchronized (AppHistoryDbHelper.class) {
dbHelper.incrementAndUpdate(packageName, process);
}
}
}
}
}
// update the widget no matter what the activity is
// especially if it's the home activity, this is important to do
// so that the widgets stay up-to-date (e.g. with time estimates)
WidgetUpdater.updateWidget(this, dbHelper);
} finally {
dbHelper.close();
}
}
}
}
catch (IOException e) {
log.e(e, "unexpected exception");
}
finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
log.e(e, "unexpected exception");
}
}
log.d("AppTrackerService died for some reason");
}
}
|
diff --git a/framework/src/org/apache/cordova/InAppBrowser.java b/framework/src/org/apache/cordova/InAppBrowser.java
index 02aa002d..0d5d4965 100644
--- a/framework/src/org/apache/cordova/InAppBrowser.java
+++ b/framework/src/org/apache/cordova/InAppBrowser.java
@@ -1,708 +1,708 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova;
import java.util.HashMap;
import java.util.StringTokenizer;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.LOG;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
@SuppressLint("SetJavaScriptEnabled")
public class InAppBrowser extends CordovaPlugin {
private static final String NULL = "null";
protected static final String LOG_TAG = "InAppBrowser";
private static final String SELF = "_self";
private static final String SYSTEM = "_system";
// private static final String BLANK = "_blank";
private static final String LOCATION = "location";
private static final String EXIT_EVENT = "exit";
private static final String LOAD_START_EVENT = "loadstart";
private static final String LOAD_STOP_EVENT = "loadstop";
private static final String LOAD_ERROR_EVENT = "loaderror";
private static final String CLOSE_BUTTON_CAPTION = "closebuttoncaption";
private long MAX_QUOTA = 100 * 1024 * 1024;
private Dialog dialog;
private WebView inAppWebView;
private EditText edittext;
private boolean showLocationBar = true;
private CallbackContext callbackContext;
private String buttonLabel = "Done";
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
this.callbackContext = callbackContext;
try {
if (action.equals("open")) {
String url = args.getString(0);
String target = args.optString(1);
if (target == null || target.equals("") || target.equals(NULL)) {
target = SELF;
}
HashMap<String, Boolean> features = parseFeature(args.optString(2));
Log.d(LOG_TAG, "target = " + target);
url = updateUrl(url);
// SELF
if (SELF.equals(target)) {
Log.d(LOG_TAG, "in self");
// load in webview
if (url.startsWith("file://") || url.startsWith("javascript:")
|| Config.isUrlWhiteListed(url)) {
this.webView.loadUrl(url);
}
//Load the dialer
else if (url.startsWith(WebView.SCHEME_TEL))
{
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
this.cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
}
// load in InAppBrowser
else {
result = this.showWebPage(url, features);
}
}
// SYSTEM
else if (SYSTEM.equals(target)) {
Log.d(LOG_TAG, "in system");
result = this.openExternal(url);
}
// BLANK - or anything else
else {
Log.d(LOG_TAG, "in blank");
result = this.showWebPage(url, features);
}
}
else if (action.equals("close")) {
closeDialog();
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(false);
this.callbackContext.sendPluginResult(pluginResult);
}
else if (action.equals("injectScriptCode")) {
String source = args.getString(0);
org.json.JSONArray jsonEsc = new org.json.JSONArray();
jsonEsc.put(source);
String jsonRepr = jsonEsc.toString();
String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1);
String scriptEnclosure = "(function(d){var c=d.createElement('script');c.type='text/javascript';c.innerText="
+ jsonSourceString
+ ";d.getElementsByTagName('head')[0].appendChild(c);})(document)";
this.inAppWebView.loadUrl("javascript:" + scriptEnclosure);
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
this.callbackContext.sendPluginResult(pluginResult);
}
else {
status = PluginResult.Status.INVALID_ACTION;
}
PluginResult pluginResult = new PluginResult(status, result);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
} catch (JSONException e) {
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
}
return true;
}
/**
* Put the list of features into a hash map
*
* @param optString
* @return
*/
private HashMap<String, Boolean> parseFeature(String optString) {
if (optString.equals(NULL)) {
return null;
} else {
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
StringTokenizer features = new StringTokenizer(optString, ",");
StringTokenizer option;
while(features.hasMoreElements()) {
option = new StringTokenizer(features.nextToken(), "=");
if (option.hasMoreElements()) {
String key = option.nextToken();
if (key.equalsIgnoreCase(CLOSE_BUTTON_CAPTION)) {
this.buttonLabel = option.nextToken();
} else {
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
map.put(key, value);
}
}
}
return map;
}
}
/**
* Convert relative URL to full path
*
* @param url
* @return
*/
private String updateUrl(String url) {
Uri newUrl = Uri.parse(url);
if (newUrl.isRelative()) {
url = this.webView.getUrl().substring(0, this.webView.getUrl().lastIndexOf("/")+1) + url;
}
return url;
}
/**
* Display a new browser with the specified URL.
*
* @param url The url to load.
* @param usePhoneGap Load url in PhoneGap webview
* @return "" if ok, or error message.
*/
public String openExternal(String url) {
try {
Intent intent = null;
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
this.cordova.getActivity().startActivity(intent);
return "";
} catch (android.content.ActivityNotFoundException e) {
Log.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString());
return e.toString();
}
}
/**
* Closes the dialog
*/
private void closeDialog() {
try {
this.inAppWebView.loadUrl("about:blank");
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendUpdate(obj, false);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
if (dialog != null) {
dialog.dismiss();
}
}
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
private void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
/**
* Checks to see if it is possible to go forward one page in history, then does so.
*/
private void goForward() {
if (this.inAppWebView.canGoForward()) {
this.inAppWebView.goForward();
}
}
/**
* Navigate to the new page
*
* @param url to load
*/
private void navigate(String url) {
InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
if (!url.startsWith("http") && !url.startsWith("file:")) {
this.inAppWebView.loadUrl("http://" + url);
} else {
this.inAppWebView.loadUrl(url);
}
this.inAppWebView.requestFocus();
}
/**
* Should we show the location bar?
*
* @return boolean
*/
private boolean getShowLocationBar() {
return this.showLocationBar;
}
/**
* Display a new browser with the specified URL.
*
* @param url The url to load.
* @param jsonObject
*/
public String showWebPage(final String url, HashMap<String, Boolean> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
if (features != null) {
Boolean show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.booleanValue();
}
}
final CordovaWebView thatWebView = this.webView;
// Create dialog in new thread
Runnable runnable = new Runnable() {
/**
* Convert our DIP units to Pixels
*
* @return int
*/
private int dpToPixels(int dipValue) {
int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
(float) dipValue,
cordova.getActivity().getResources().getDisplayMetrics()
);
return value;
}
public void run() {
// Let's create the main dialog
dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
try {
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendUpdate(obj, false);
} catch (JSONException e) {
Log.d(LOG_TAG, "Should never happen");
}
}
});
// Main container layout
LinearLayout main = new LinearLayout(cordova.getActivity());
main.setOrientation(LinearLayout.VERTICAL);
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
toolbar.setHorizontalGravity(Gravity.LEFT);
toolbar.setVerticalGravity(Gravity.TOP);
// Action Button Container layout
RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(1);
// Back button
Button back = new Button(cordova.getActivity());
RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
back.setLayoutParams(backLayoutParams);
back.setContentDescription("Back Button");
back.setId(2);
back.setText("<");
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack();
}
});
// Forward button
Button forward = new Button(cordova.getActivity());
RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
forward.setLayoutParams(forwardLayoutParams);
forward.setContentDescription("Forward Button");
forward.setId(3);
forward.setText(">");
forward.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goForward();
}
});
// Edit Text Box
edittext = new EditText(cordova.getActivity());
RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
edittext.setLayoutParams(textLayoutParams);
edittext.setId(4);
edittext.setSingleLine(true);
edittext.setText(url);
edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
navigate(edittext.getText().toString());
return true;
}
return false;
}
});
// Close button
Button close = new Button(cordova.getActivity());
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
close.setLayoutParams(closeLayoutParams);
forward.setContentDescription("Close Button");
close.setId(5);
close.setText(buttonLabel);
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
// WebView
inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setWebChromeClient(new InAppChromeClient());
WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
inAppWebView.setWebViewClient(client);
WebSettings settings = inAppWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(true);
/**
* We need to be careful of this line as a future Android release may deprecate it out of existence.
* Can't replace it with the API 8 level call right now as our minimum SDK is 7 until May 2013
*/
// @TODO: replace with settings.setPluginState(android.webkit.WebSettings.PluginState.ON)
settings.setPluginsEnabled(true);
//Toggle whether this is enabled or not!
Bundle appSettings = cordova.getActivity().getIntent().getExtras();
- boolean enableDatabase = appSettings.getBoolean("InAppBrowserStorageEnabled", true);
+ boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
if(enableDatabase)
{
String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
settings.setDatabaseEnabled(true);
}
settings.setDomStorageEnabled(true);
inAppWebView.loadUrl(url);
inAppWebView.setId(6);
inAppWebView.getSettings().setLoadWithOverviewMode(true);
inAppWebView.getSettings().setUseWideViewPort(true);
inAppWebView.requestFocus();
inAppWebView.requestFocusFromTouch();
// Add the back and forward buttons to our action button container layout
actionButtonContainer.addView(back);
actionButtonContainer.addView(forward);
// Add the views to our toolbar
toolbar.addView(actionButtonContainer);
toolbar.addView(edittext);
toolbar.addView(close);
// Don't add the toolbar if its been disabled
if (getShowLocationBar()) {
// Add our toolbar to our main view/layout
main.addView(toolbar);
}
// Add our webview to our main view/layout
main.addView(inAppWebView);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
dialog.setContentView(main);
dialog.show();
dialog.getWindow().setAttributes(lp);
}
};
this.cordova.getActivity().runOnUiThread(runnable);
return "";
}
/**
* Create a new plugin success result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
*/
private void sendUpdate(JSONObject obj, boolean keepCallback) {
sendUpdate(obj, keepCallback, PluginResult.Status.OK);
}
/**
* Create a new plugin result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
* @param status the status code to return to the JavaScript environment
*/ private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) {
PluginResult result = new PluginResult(status, obj);
result.setKeepCallback(keepCallback);
this.callbackContext.sendPluginResult(result);
}
public class InAppChromeClient extends WebChromeClient {
/**
* Handle database quota exceeded notification.
*
* @param url
* @param databaseIdentifier
* @param currentQuota
* @param estimatedSize
* @param totalUsedQuota
* @param quotaUpdater
*/
@Override
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize,
long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater)
{
LOG.d(LOG_TAG, "onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota);
if (estimatedSize < MAX_QUOTA)
{
//increase for 1Mb
long newQuota = estimatedSize;
LOG.d(LOG_TAG, "calling quotaUpdater.updateQuota newQuota: %d", newQuota);
quotaUpdater.updateQuota(newQuota);
}
else
{
// Set the quota to whatever it is and force an error
// TODO: get docs on how to handle this properly
quotaUpdater.updateQuota(currentQuota);
}
}
/**
* Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin.
*
* @param origin
* @param callback
*/
@Override
public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
}
/**
* The webview client receives notifications about appView
*/
public class InAppBrowserClient extends WebViewClient {
EditText edittext;
CordovaWebView webView;
/**
* Constructor.
*
* @param mContext
* @param edittext
*/
public InAppBrowserClient(CordovaWebView webView, EditText mEditText) {
this.webView = webView;
this.edittext = mEditText;
}
/**
* Notify the host application that a page has started loading.
*
* @param view The webview initiating the callback.
* @param url The url of the page.
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
String newloc = "";
if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
newloc = url;
}
// If dialing phone (tel:5551212)
else if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
}
else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString());
}
}
// If sms:5551212?body=This is the message
else if (url.startsWith("sms:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// Get address
String address = null;
int parmIndex = url.indexOf('?');
if (parmIndex == -1) {
address = url.substring(4);
}
else {
address = url.substring(4, parmIndex);
// If body, then set sms body
Uri uri = Uri.parse(url);
String query = uri.getQuery();
if (query != null) {
if (query.startsWith("body=")) {
intent.putExtra("sms_body", query.substring(5));
}
}
}
intent.setData(Uri.parse("sms:" + address));
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString());
}
}
else {
newloc = "http://" + url;
}
if (!newloc.equals(edittext.getText().toString())) {
edittext.setText(newloc);
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_START_EVENT);
obj.put("url", newloc);
sendUpdate(obj, true);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_STOP_EVENT);
obj.put("url", url);
sendUpdate(obj, true);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_ERROR_EVENT);
obj.put("url", failingUrl);
obj.put("code", errorCode);
obj.put("message", description);
sendUpdate(obj, true, PluginResult.Status.ERROR);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
}
}
| true | true |
public String showWebPage(final String url, HashMap<String, Boolean> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
if (features != null) {
Boolean show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.booleanValue();
}
}
final CordovaWebView thatWebView = this.webView;
// Create dialog in new thread
Runnable runnable = new Runnable() {
/**
* Convert our DIP units to Pixels
*
* @return int
*/
private int dpToPixels(int dipValue) {
int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
(float) dipValue,
cordova.getActivity().getResources().getDisplayMetrics()
);
return value;
}
public void run() {
// Let's create the main dialog
dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
try {
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendUpdate(obj, false);
} catch (JSONException e) {
Log.d(LOG_TAG, "Should never happen");
}
}
});
// Main container layout
LinearLayout main = new LinearLayout(cordova.getActivity());
main.setOrientation(LinearLayout.VERTICAL);
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
toolbar.setHorizontalGravity(Gravity.LEFT);
toolbar.setVerticalGravity(Gravity.TOP);
// Action Button Container layout
RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(1);
// Back button
Button back = new Button(cordova.getActivity());
RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
back.setLayoutParams(backLayoutParams);
back.setContentDescription("Back Button");
back.setId(2);
back.setText("<");
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack();
}
});
// Forward button
Button forward = new Button(cordova.getActivity());
RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
forward.setLayoutParams(forwardLayoutParams);
forward.setContentDescription("Forward Button");
forward.setId(3);
forward.setText(">");
forward.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goForward();
}
});
// Edit Text Box
edittext = new EditText(cordova.getActivity());
RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
edittext.setLayoutParams(textLayoutParams);
edittext.setId(4);
edittext.setSingleLine(true);
edittext.setText(url);
edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
navigate(edittext.getText().toString());
return true;
}
return false;
}
});
// Close button
Button close = new Button(cordova.getActivity());
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
close.setLayoutParams(closeLayoutParams);
forward.setContentDescription("Close Button");
close.setId(5);
close.setText(buttonLabel);
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
// WebView
inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setWebChromeClient(new InAppChromeClient());
WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
inAppWebView.setWebViewClient(client);
WebSettings settings = inAppWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(true);
/**
* We need to be careful of this line as a future Android release may deprecate it out of existence.
* Can't replace it with the API 8 level call right now as our minimum SDK is 7 until May 2013
*/
// @TODO: replace with settings.setPluginState(android.webkit.WebSettings.PluginState.ON)
settings.setPluginsEnabled(true);
//Toggle whether this is enabled or not!
Bundle appSettings = cordova.getActivity().getIntent().getExtras();
boolean enableDatabase = appSettings.getBoolean("InAppBrowserStorageEnabled", true);
if(enableDatabase)
{
String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
settings.setDatabaseEnabled(true);
}
settings.setDomStorageEnabled(true);
inAppWebView.loadUrl(url);
inAppWebView.setId(6);
inAppWebView.getSettings().setLoadWithOverviewMode(true);
inAppWebView.getSettings().setUseWideViewPort(true);
inAppWebView.requestFocus();
inAppWebView.requestFocusFromTouch();
// Add the back and forward buttons to our action button container layout
actionButtonContainer.addView(back);
actionButtonContainer.addView(forward);
// Add the views to our toolbar
toolbar.addView(actionButtonContainer);
toolbar.addView(edittext);
toolbar.addView(close);
// Don't add the toolbar if its been disabled
if (getShowLocationBar()) {
// Add our toolbar to our main view/layout
main.addView(toolbar);
}
// Add our webview to our main view/layout
main.addView(inAppWebView);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
dialog.setContentView(main);
dialog.show();
dialog.getWindow().setAttributes(lp);
}
};
this.cordova.getActivity().runOnUiThread(runnable);
return "";
}
|
public String showWebPage(final String url, HashMap<String, Boolean> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
if (features != null) {
Boolean show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.booleanValue();
}
}
final CordovaWebView thatWebView = this.webView;
// Create dialog in new thread
Runnable runnable = new Runnable() {
/**
* Convert our DIP units to Pixels
*
* @return int
*/
private int dpToPixels(int dipValue) {
int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
(float) dipValue,
cordova.getActivity().getResources().getDisplayMetrics()
);
return value;
}
public void run() {
// Let's create the main dialog
dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
try {
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendUpdate(obj, false);
} catch (JSONException e) {
Log.d(LOG_TAG, "Should never happen");
}
}
});
// Main container layout
LinearLayout main = new LinearLayout(cordova.getActivity());
main.setOrientation(LinearLayout.VERTICAL);
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
toolbar.setHorizontalGravity(Gravity.LEFT);
toolbar.setVerticalGravity(Gravity.TOP);
// Action Button Container layout
RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(1);
// Back button
Button back = new Button(cordova.getActivity());
RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
back.setLayoutParams(backLayoutParams);
back.setContentDescription("Back Button");
back.setId(2);
back.setText("<");
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack();
}
});
// Forward button
Button forward = new Button(cordova.getActivity());
RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
forward.setLayoutParams(forwardLayoutParams);
forward.setContentDescription("Forward Button");
forward.setId(3);
forward.setText(">");
forward.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goForward();
}
});
// Edit Text Box
edittext = new EditText(cordova.getActivity());
RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
edittext.setLayoutParams(textLayoutParams);
edittext.setId(4);
edittext.setSingleLine(true);
edittext.setText(url);
edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
navigate(edittext.getText().toString());
return true;
}
return false;
}
});
// Close button
Button close = new Button(cordova.getActivity());
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
close.setLayoutParams(closeLayoutParams);
forward.setContentDescription("Close Button");
close.setId(5);
close.setText(buttonLabel);
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
// WebView
inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setWebChromeClient(new InAppChromeClient());
WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
inAppWebView.setWebViewClient(client);
WebSettings settings = inAppWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(true);
/**
* We need to be careful of this line as a future Android release may deprecate it out of existence.
* Can't replace it with the API 8 level call right now as our minimum SDK is 7 until May 2013
*/
// @TODO: replace with settings.setPluginState(android.webkit.WebSettings.PluginState.ON)
settings.setPluginsEnabled(true);
//Toggle whether this is enabled or not!
Bundle appSettings = cordova.getActivity().getIntent().getExtras();
boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
if(enableDatabase)
{
String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
settings.setDatabaseEnabled(true);
}
settings.setDomStorageEnabled(true);
inAppWebView.loadUrl(url);
inAppWebView.setId(6);
inAppWebView.getSettings().setLoadWithOverviewMode(true);
inAppWebView.getSettings().setUseWideViewPort(true);
inAppWebView.requestFocus();
inAppWebView.requestFocusFromTouch();
// Add the back and forward buttons to our action button container layout
actionButtonContainer.addView(back);
actionButtonContainer.addView(forward);
// Add the views to our toolbar
toolbar.addView(actionButtonContainer);
toolbar.addView(edittext);
toolbar.addView(close);
// Don't add the toolbar if its been disabled
if (getShowLocationBar()) {
// Add our toolbar to our main view/layout
main.addView(toolbar);
}
// Add our webview to our main view/layout
main.addView(inAppWebView);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
dialog.setContentView(main);
dialog.show();
dialog.getWindow().setAttributes(lp);
}
};
this.cordova.getActivity().runOnUiThread(runnable);
return "";
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.