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/evostrattest/FuncTest2.java b/src/evostrattest/FuncTest2.java
index aca8964..92036c2 100644
--- a/src/evostrattest/FuncTest2.java
+++ b/src/evostrattest/FuncTest2.java
@@ -1,69 +1,69 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package evostrattest;
import java.util.HashMap;
import java.util.HashSet;
import net.mkonrad.evostrat.EvoOptimizable;
import net.mkonrad.evostrat.EvoParam;
import net.mkonrad.evostrat.EvoParamConditionMinMax;
import net.mkonrad.evostrat.EvoParamProperties;
/**
*
* @author markus
*/
public class FuncTest2 implements EvoOptimizable {
private HashMap<String, EvoParam> params;
private HashSet<EvoParamProperties> paramProps;
public FuncTest2() {
params = new HashMap<String,EvoParam>();
paramProps = new HashSet<EvoParamProperties>();
EvoParamProperties propX = new EvoParamProperties("x", 0.0f, 1.0f, 0.9f, 0.1f);
EvoParamProperties propY = new EvoParamProperties("y", 0.0f, 1.0f, 0.9f, 0.1f);
propX.addParamCondition(new EvoParamConditionMinMax(0.0f, 1.0f));
paramProps.add(propX);
propY.addParamCondition(new EvoParamConditionMinMax(0.0f, 1.0f));
paramProps.add(propY);
}
@Override
public HashSet<EvoParamProperties> getParamPropertiesSet() {
return paramProps;
}
@Override
public void setParam(EvoParam param) {
params.put(param.name, param);
}
@Override
public float makeTestRun() {
float x = params.get("x").val;
float y = params.get("y").val;
float n = 9.0f;
- // optimal sol.: x = 0.5, y = 0.5, z = 0.878
+ // maximum at x = 0.5, y = 0.5 with z = 0.878
float z = (float)Math.pow(
15.0f * x * y * (1.0f - x) * (1.0f - y)
* (float)Math.sin(n * Math.PI * x)
* (float)Math.sin(n * Math.PI * y),
2);
return z;
}
@Override
public void setParamSet(HashSet<EvoParam> params) {
for (EvoParam p : params) {
setParam(p);
}
}
}
| true | true | public float makeTestRun() {
float x = params.get("x").val;
float y = params.get("y").val;
float n = 9.0f;
// optimal sol.: x = 0.5, y = 0.5, z = 0.878
float z = (float)Math.pow(
15.0f * x * y * (1.0f - x) * (1.0f - y)
* (float)Math.sin(n * Math.PI * x)
* (float)Math.sin(n * Math.PI * y),
2);
return z;
}
| public float makeTestRun() {
float x = params.get("x").val;
float y = params.get("y").val;
float n = 9.0f;
// maximum at x = 0.5, y = 0.5 with z = 0.878
float z = (float)Math.pow(
15.0f * x * y * (1.0f - x) * (1.0f - y)
* (float)Math.sin(n * Math.PI * x)
* (float)Math.sin(n * Math.PI * y),
2);
return z;
}
|
diff --git a/TantalumLibrary/src/org/tantalum/util/CryptoUtils.java b/TantalumLibrary/src/org/tantalum/util/CryptoUtils.java
index 91f09657..9e393324 100644
--- a/TantalumLibrary/src/org/tantalum/util/CryptoUtils.java
+++ b/TantalumLibrary/src/org/tantalum/util/CryptoUtils.java
@@ -1,140 +1,139 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.tantalum.util;
import java.io.UnsupportedEncodingException;
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Simplified cryptography routines
*
* @author phou
*/
public class CryptoUtils {
/**
* The length of each digest in bytes
*
* A digest is a byte[] of this length
*/
public static final int DIGEST_LENGTH = 16;
private MessageDigest messageDigest;
private static class CryptoUtilsHolder {
static final CryptoUtils instance = new CryptoUtils();
}
/**
* Get the singleton
*
* @return
*/
public static CryptoUtils getInstance() {
return CryptoUtilsHolder.instance;
}
private CryptoUtils() {
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
//#debug
L.e("Can not init CryptoUtils", "", ex);
}
}
/**
* Convert from String form, which may take a lot of RAM, into a fixed size
* cryptographic digest.
*
* @param key
* @return 16 byte cryptographic has
* @throws DigestException
* @throws UnsupportedEncodingException
*/
public synchronized long toDigest(final String key) throws DigestException, UnsupportedEncodingException {
if (key == null) {
throw new IllegalArgumentException("You attempted to convert a null string into a hash digest");
}
final byte[] bytes = key.getBytes("UTF-8");
return toDigest(bytes);
}
/**
* Generate a cryptographic MD5 digest from a byte array
*
* @param bytes
* @return
* @throws DigestException
* @throws UnsupportedEncodingException
*/
public synchronized long toDigest(final byte[] bytes) throws DigestException, UnsupportedEncodingException {
if (bytes == null) {
throw new IllegalArgumentException("You attempted to convert a null byte[] into a hash digest");
}
final byte[] hashKey = new byte[DIGEST_LENGTH];
messageDigest.update(bytes, 0, bytes.length);
messageDigest.digest(hashKey, 0, DIGEST_LENGTH);
final byte[] l = new byte[8];
- int j = 0;
for (int i = 0; i < l.length; i++) {
- l[i] = (byte)(bytes[j++] ^ bytes[j++]);
+ l[i] = (byte)(hashKey[2*i] ^ hashKey[1 + (2*i)]);
}
return bytesToLong(l, 0);
}
/**
* Encode 8 bytes into one Long
*
* @param bytes
* @param start
* @return
*/
public long bytesToLong(final byte[] bytes, final int start) {
if (bytes == null || bytes.length != 8) {
throw new IllegalArgumentException("Bad byteLength != 8 or null: can not convert digest to Long");
}
long l = 0;
for (int i = 0; i < 8; i++) {
l |= ((long) (bytes[start + i] & 0xFF)) << (8 * i);
}
return l;
}
/**
* Encode one Long to 8 bytes
*
* @param l
* @return
*/
public byte[] longToBytes(final long l) {
final byte[] bytes = new byte[8];
longToBytes(l, bytes, 0);
return bytes;
}
/**
* Encode one Long to 8 bytes inserted into an existing array
*
* @param l
* @param bytes
* @param start
*/
public void longToBytes(final long l, final byte[] bytes, final int start) {
for (int i = 0; i < 8; i++) {
bytes[start + i] = (byte)(((int)(l >>> (8*i))) & 0xFF);
}
}
}
| false | true | public synchronized long toDigest(final byte[] bytes) throws DigestException, UnsupportedEncodingException {
if (bytes == null) {
throw new IllegalArgumentException("You attempted to convert a null byte[] into a hash digest");
}
final byte[] hashKey = new byte[DIGEST_LENGTH];
messageDigest.update(bytes, 0, bytes.length);
messageDigest.digest(hashKey, 0, DIGEST_LENGTH);
final byte[] l = new byte[8];
int j = 0;
for (int i = 0; i < l.length; i++) {
l[i] = (byte)(bytes[j++] ^ bytes[j++]);
}
return bytesToLong(l, 0);
}
| public synchronized long toDigest(final byte[] bytes) throws DigestException, UnsupportedEncodingException {
if (bytes == null) {
throw new IllegalArgumentException("You attempted to convert a null byte[] into a hash digest");
}
final byte[] hashKey = new byte[DIGEST_LENGTH];
messageDigest.update(bytes, 0, bytes.length);
messageDigest.digest(hashKey, 0, DIGEST_LENGTH);
final byte[] l = new byte[8];
for (int i = 0; i < l.length; i++) {
l[i] = (byte)(hashKey[2*i] ^ hashKey[1 + (2*i)]);
}
return bytesToLong(l, 0);
}
|
diff --git a/test/testStorage/TestStorage.java b/test/testStorage/TestStorage.java
index a960047..042a1a8 100644
--- a/test/testStorage/TestStorage.java
+++ b/test/testStorage/TestStorage.java
@@ -1,79 +1,79 @@
package testStorage;
import java.util.ArrayList;
import junit.framework.*;
import storage.*;
public class TestStorage extends TestCase{
private int expectedValue;
private int actualValue;
boolean failed;
public void testAddNewPlayer() {
Statistics jack = Storage.loadPlayer("jack","Black");
assertEquals(Storage.savePlayer(jack), true);
}
public void testSavePlayer() {
Statistics abc = Storage.loadPlayer("abc","123");
abc.setChips(5);
Storage.savePlayer(abc);
abc = Storage.loadPlayer("abc","123");
actualValue = abc.getChips();
expectedValue = 5;
assertEquals(actualValue, expectedValue);
}
public void testLoadPlayerPeriod() {
failed = false;
try {
Storage.loadPlayer("John.Test", "password");
} catch (IllegalArgumentException e) {
failed = true;
} finally {
assertEquals(failed, true);
}
}
public void testLoadPlayerComma() {
failed = false;
try {
Storage.loadPlayer("john,test", "password");
} catch (IllegalArgumentException e) {
failed = true;
} finally{
assertEquals(failed, true);
}
}
public void testAddToHallOfFame() {
Statistics billyjoe = Storage.loadPlayer("billyjoe","abc");
billyjoe.addWin(100000);
Storage.savePlayer(billyjoe);
ArrayList<Statistics> hallOfFame = new ArrayList<Statistics>();
hallOfFame = HallOfFame.getHallOfFame();
assertEquals(hallOfFame.get(0).getUsername(), "billyjoe");
}
public void testAddEqualScore() {
Statistics equalScoreOne = Storage.loadPlayer("one", "one");
Statistics equalScoreTwo = Storage.loadPlayer("two", "two");
equalScoreOne.addWin(100000);
equalScoreTwo.addWin(100000);
ArrayList<Statistics> hallOfFame = new ArrayList<Statistics>();
hallOfFame = HallOfFame.getHallOfFame();
- assertEquals(hallOfFame.get(1).getUsername(), "two");
- assertEquals(hallOfFame.get(2).getUsername(), "one");
+ assertEquals(hallOfFame.get(0).getUsername(), "two");
+ assertEquals(hallOfFame.get(1).getUsername(), "one");
}
public void testDisplayHallOfFame() {
HallOfFame.display();
}
}
| true | true | public void testAddEqualScore() {
Statistics equalScoreOne = Storage.loadPlayer("one", "one");
Statistics equalScoreTwo = Storage.loadPlayer("two", "two");
equalScoreOne.addWin(100000);
equalScoreTwo.addWin(100000);
ArrayList<Statistics> hallOfFame = new ArrayList<Statistics>();
hallOfFame = HallOfFame.getHallOfFame();
assertEquals(hallOfFame.get(1).getUsername(), "two");
assertEquals(hallOfFame.get(2).getUsername(), "one");
}
| public void testAddEqualScore() {
Statistics equalScoreOne = Storage.loadPlayer("one", "one");
Statistics equalScoreTwo = Storage.loadPlayer("two", "two");
equalScoreOne.addWin(100000);
equalScoreTwo.addWin(100000);
ArrayList<Statistics> hallOfFame = new ArrayList<Statistics>();
hallOfFame = HallOfFame.getHallOfFame();
assertEquals(hallOfFame.get(0).getUsername(), "two");
assertEquals(hallOfFame.get(1).getUsername(), "one");
}
|
diff --git a/src/gov/nih/ncgc/bard/rest/BARDSearchResource.java b/src/gov/nih/ncgc/bard/rest/BARDSearchResource.java
index 6b90abb..451447a 100644
--- a/src/gov/nih/ncgc/bard/rest/BARDSearchResource.java
+++ b/src/gov/nih/ncgc/bard/rest/BARDSearchResource.java
@@ -1,132 +1,132 @@
package gov.nih.ncgc.bard.rest;
import gov.nih.ncgc.bard.search.AssaySearch;
import gov.nih.ncgc.bard.search.CompoundSearch;
import gov.nih.ncgc.bard.search.ISolrSearch;
import gov.nih.ncgc.bard.search.ProjectSearch;
import gov.nih.ncgc.bard.search.SearchResult;
import gov.nih.ncgc.bard.tools.Util;
import org.apache.solr.client.solrj.SolrServerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
/**
* A resource to expose full-text and faceted search.
*
* @author Rajarshi Guha
*/
@Path("/search")
public class BARDSearchResource extends BARDResource {
@Context
ServletContext servletContext;
Logger log;
public BARDSearchResource() {
log = LoggerFactory.getLogger(this.getClass());
}
@GET
@Produces("text/plain")
@Path("/_info")
public String info() {
StringBuilder msg = new StringBuilder("General search resource\n\nAvailable resources:\n");
List<String> paths = Util.getResourcePaths(this.getClass());
for (String path : paths) msg.append(path).append("\n");
msg.append("/search/" + BARDConstants.API_EXTRA_PARAM_SPEC + "\n");
return msg.toString();
}
public Response getResources(@QueryParam("filter") String filter, @QueryParam("expand") String expand, @QueryParam("skip") Integer skip, @QueryParam("top") Integer top) {
return null;
}
public Response getResources(@PathParam("name") String resourceId, @QueryParam("filter") String filter, @QueryParam("expand") String expand) {
return null;
}
@GET
@Path("/")
public Response runSearch(@QueryParam("q") String q,
@QueryParam("skip") Integer skip,
@QueryParam("top") Integer top,
@QueryParam("expand") String expand) throws IOException, SolrServerException {
if (q == null) throw new WebApplicationException(400);
ISolrSearch as = new AssaySearch(q);
as.run(expand != null && expand.toLowerCase().equals("true"), null, top, skip);
SearchResult s = as.getSearchResults();
return Response.ok(Util.toJson(s)).type("application/json").build();
}
@GET
@Path("/compounds")
public Response runCompoundSearch(@QueryParam("q") String q,
@QueryParam("skip") Integer skip,
@QueryParam("top") Integer top,
@QueryParam("expand") String expand) throws IOException, SolrServerException {
if (q == null) throw new WebApplicationException(400);
SearchResult s = doSearch(new CompoundSearch(q), skip, top, expand, null);
return Response.ok(Util.toJson(s)).type("application/json").build();
}
@GET
@Path("/assays")
public Response runAssaySearch(@QueryParam("q") String q,
@QueryParam("skip") Integer skip,
@QueryParam("top") Integer top,
@QueryParam("expand") String expand) throws IOException, SolrServerException {
if (q == null) throw new WebApplicationException(400);
SearchResult s = doSearch(new AssaySearch(q), skip, top, expand, null);
return Response.ok(Util.toJson(s)).type("application/json").build();
}
@GET
@Path("/projects")
public Response runProjectSearch(@QueryParam("q") String q,
@QueryParam("skip") Integer skip,
@QueryParam("top") Integer top,
@QueryParam("expand") String expand) throws IOException, SolrServerException {
if (q == null) throw new WebApplicationException(400);
SearchResult s = doSearch(new ProjectSearch(q), skip, top, expand, null);
return Response.ok(Util.toJson(s)).type("application/json").build();
}
private SearchResult doSearch(ISolrSearch s, Integer skip, Integer top, String expand, String filter) throws MalformedURLException, SolrServerException {
if (top == null) top = 10;
if (skip == null) skip = 0;
s.run(expand != null && expand.toLowerCase().equals("true"), null, top, skip);
SearchResult sr = s.getSearchResults();
String link = null;
if (skip + top <= sr.getMetaData().getNhit()) {
- if (s instanceof AssaySearch) link = "/search/assays/" + s.getQuery();
- else if (s instanceof CompoundSearch) link = "/search/compounds/" + s.getQuery();
- else if (s instanceof ProjectSearch) link = "/search/projects/" + s.getQuery();
+ if (s instanceof AssaySearch) link = "/search/assays?q=" + s.getQuery();
+ else if (s instanceof CompoundSearch) link = "/search/compounds?q=" + s.getQuery();
+ else if (s instanceof ProjectSearch) link = "/search/projects?q=" + s.getQuery();
if (filter == null) filter = "";
else filter = "&" + filter;
- link = link + "?skip=" + (skip + top) + "&top=" + top + filter;
+ link = link + "&skip=" + (skip + top) + "&top=" + top + filter;
if (expand == null) expand = "&expand=false";
else expand = "&expand=" + expand;
link += expand;
}
sr.setLink(link);
return sr;
}
}
| false | true | private SearchResult doSearch(ISolrSearch s, Integer skip, Integer top, String expand, String filter) throws MalformedURLException, SolrServerException {
if (top == null) top = 10;
if (skip == null) skip = 0;
s.run(expand != null && expand.toLowerCase().equals("true"), null, top, skip);
SearchResult sr = s.getSearchResults();
String link = null;
if (skip + top <= sr.getMetaData().getNhit()) {
if (s instanceof AssaySearch) link = "/search/assays/" + s.getQuery();
else if (s instanceof CompoundSearch) link = "/search/compounds/" + s.getQuery();
else if (s instanceof ProjectSearch) link = "/search/projects/" + s.getQuery();
if (filter == null) filter = "";
else filter = "&" + filter;
link = link + "?skip=" + (skip + top) + "&top=" + top + filter;
if (expand == null) expand = "&expand=false";
else expand = "&expand=" + expand;
link += expand;
}
sr.setLink(link);
return sr;
}
| private SearchResult doSearch(ISolrSearch s, Integer skip, Integer top, String expand, String filter) throws MalformedURLException, SolrServerException {
if (top == null) top = 10;
if (skip == null) skip = 0;
s.run(expand != null && expand.toLowerCase().equals("true"), null, top, skip);
SearchResult sr = s.getSearchResults();
String link = null;
if (skip + top <= sr.getMetaData().getNhit()) {
if (s instanceof AssaySearch) link = "/search/assays?q=" + s.getQuery();
else if (s instanceof CompoundSearch) link = "/search/compounds?q=" + s.getQuery();
else if (s instanceof ProjectSearch) link = "/search/projects?q=" + s.getQuery();
if (filter == null) filter = "";
else filter = "&" + filter;
link = link + "&skip=" + (skip + top) + "&top=" + top + filter;
if (expand == null) expand = "&expand=false";
else expand = "&expand=" + expand;
link += expand;
}
sr.setLink(link);
return sr;
}
|
diff --git a/Koordinator/src/coordinator/CoordinatorImpl.java b/Koordinator/src/coordinator/CoordinatorImpl.java
index ad7fe89..effd218 100644
--- a/Koordinator/src/coordinator/CoordinatorImpl.java
+++ b/Koordinator/src/coordinator/CoordinatorImpl.java
@@ -1,148 +1,153 @@
package coordinator;
import ggTCalculator.CoordinatorPOA;
import ggTCalculator.Log;
import ggTCalculator.Process;
import ggTCalculator.Starter;
import ggTCalculator.CoordinatorPackage.alreadyRunning;
import ggTCalculator.CoordinatorPackage.noStarter;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.Semaphore;
public class CoordinatorImpl extends CoordinatorPOA {
ArrayList<Starter> starterlist = new ArrayList<Starter>();
ArrayList<String> starter_names = new ArrayList<String>();
ArrayList<Process> processlist = new ArrayList<Process>();
Semaphore finished = new Semaphore(0);
boolean termination_in_process = false;
int result = 0;
int def_numproc_max = 5;
int def_numproc_min = 2;
String name;
public CoordinatorImpl(String name) {
this.name = name;
}
@Override
public void addProcess(String startername, int id, Process process) {
processlist.add(process);
System.out.println("Process " + startername + "-" + Integer.toString(id) + " connected");
}
@Override
public void addStarter(String startername, Starter starter) {
System.out.println("added " + startername + " to list");
starterlist.add(starter);
starter_names.add(startername);
}
@Override
public int calculate(int timeout, int mindelay, int maxdelay, int minprocess, int maxprocess, int ggT, Log log)
throws noStarter, alreadyRunning {
termination_in_process = false;
Random rnd = new Random();
int procnum = 0;
// start random amount of processes
for (Starter starter : starterlist) {
int cnt = rnd.nextInt(maxprocess - minprocess + 1) + minprocess;
starter.createProcess(cnt);
log.log(name, "added " + cnt + " processes to Starter " + starter.getName());
// TODO: use this?
procnum += cnt;
}
try {
// sleep to wait for client registration
Thread.sleep(400);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Process[] procs = processlist.toArray(new Process[0]);
for (int i = 0; i < procs.length; i++) {
Process tmp_left;
Process tmp_right;
// build ring
if (i == 0) {
tmp_left = procs[procs.length - 1];
} else {
tmp_left = procs[i - 1];
}
if (i == procs.length - 1) {
tmp_right = procs[0];
} else {
tmp_right = procs[i + 1];
}
// give parameters to processes
procs[i].set_params(tmp_left, tmp_right, (ggT * (rnd.nextInt(100) + 1) * (rnd.nextInt(100) + 1)), log,
(rnd.nextInt(maxdelay - mindelay + 1) + mindelay), timeout);
}
log.log(name, "params set for each process");
// choose three processes randomly
int p1 = 0, p2 = 0, p3 = 0;
while ((p1 == p2) || (p2 == p3) || (p1 == p3)) {
p1 = rnd.nextInt(procs.length - 1);
p2 = rnd.nextInt(procs.length - 1);
p3 = rnd.nextInt(procs.length - 1);
}
// hand random large numbers to processes
//TODO change back?
/*
procs[p1].message(ggT * rnd.nextInt(9900) + 100);
procs[p2].message(ggT * rnd.nextInt(9900) + 100);
procs[p3].message(ggT * rnd.nextInt(9900) + 100);
*/
- procs[p1].message(ggT * rnd.nextInt(100) + 1);
- procs[p2].message(ggT * rnd.nextInt(100) + 1);
- procs[p3].message(ggT * rnd.nextInt(100) + 1);
- log.log(name, "three processes started");
+ int p1_n = ggT * (rnd.nextInt(100) + 1);
+ int p2_n = ggT * (rnd.nextInt(100) + 1);
+ int p3_n = ggT * (rnd.nextInt(100) + 1);
+ log.log(name, "sending "+p1_n);
+ procs[p1].message(p1_n);
+ log.log(name, "sending "+p2_n);
+ procs[p2].message(p2_n);
+ log.log(name, "sending "+p3_n);
+ procs[p3].message(p3_n);
try {
// wait for a process to finish
finished.acquire();
} catch (InterruptedException e) {
System.err.println(e);
}
log.log(name, "finished with " + result);
return result;
}
@Override
public void finished(int r) {
result = r;
for (Starter starter : starterlist) {
starter.quitProcess();
}
processlist.clear();
finished.release();
}
@Override
public String[] getStarterList() {
return starter_names.toArray(new String[0]);
}
@Override
public void quit() {
for (Starter starter : starterlist) {
starter.quit();
}
}
@Override
public synchronized boolean terminationStart() {
if (!termination_in_process) {
termination_in_process = true;
return true;
}
return false;
}
@Override
public boolean terminationStop() {
termination_in_process = false;
return false;
}
}
| true | true | public int calculate(int timeout, int mindelay, int maxdelay, int minprocess, int maxprocess, int ggT, Log log)
throws noStarter, alreadyRunning {
termination_in_process = false;
Random rnd = new Random();
int procnum = 0;
// start random amount of processes
for (Starter starter : starterlist) {
int cnt = rnd.nextInt(maxprocess - minprocess + 1) + minprocess;
starter.createProcess(cnt);
log.log(name, "added " + cnt + " processes to Starter " + starter.getName());
// TODO: use this?
procnum += cnt;
}
try {
// sleep to wait for client registration
Thread.sleep(400);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Process[] procs = processlist.toArray(new Process[0]);
for (int i = 0; i < procs.length; i++) {
Process tmp_left;
Process tmp_right;
// build ring
if (i == 0) {
tmp_left = procs[procs.length - 1];
} else {
tmp_left = procs[i - 1];
}
if (i == procs.length - 1) {
tmp_right = procs[0];
} else {
tmp_right = procs[i + 1];
}
// give parameters to processes
procs[i].set_params(tmp_left, tmp_right, (ggT * (rnd.nextInt(100) + 1) * (rnd.nextInt(100) + 1)), log,
(rnd.nextInt(maxdelay - mindelay + 1) + mindelay), timeout);
}
log.log(name, "params set for each process");
// choose three processes randomly
int p1 = 0, p2 = 0, p3 = 0;
while ((p1 == p2) || (p2 == p3) || (p1 == p3)) {
p1 = rnd.nextInt(procs.length - 1);
p2 = rnd.nextInt(procs.length - 1);
p3 = rnd.nextInt(procs.length - 1);
}
// hand random large numbers to processes
//TODO change back?
/*
procs[p1].message(ggT * rnd.nextInt(9900) + 100);
procs[p2].message(ggT * rnd.nextInt(9900) + 100);
procs[p3].message(ggT * rnd.nextInt(9900) + 100);
*/
procs[p1].message(ggT * rnd.nextInt(100) + 1);
procs[p2].message(ggT * rnd.nextInt(100) + 1);
procs[p3].message(ggT * rnd.nextInt(100) + 1);
log.log(name, "three processes started");
try {
// wait for a process to finish
finished.acquire();
} catch (InterruptedException e) {
System.err.println(e);
}
log.log(name, "finished with " + result);
return result;
}
| public int calculate(int timeout, int mindelay, int maxdelay, int minprocess, int maxprocess, int ggT, Log log)
throws noStarter, alreadyRunning {
termination_in_process = false;
Random rnd = new Random();
int procnum = 0;
// start random amount of processes
for (Starter starter : starterlist) {
int cnt = rnd.nextInt(maxprocess - minprocess + 1) + minprocess;
starter.createProcess(cnt);
log.log(name, "added " + cnt + " processes to Starter " + starter.getName());
// TODO: use this?
procnum += cnt;
}
try {
// sleep to wait for client registration
Thread.sleep(400);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Process[] procs = processlist.toArray(new Process[0]);
for (int i = 0; i < procs.length; i++) {
Process tmp_left;
Process tmp_right;
// build ring
if (i == 0) {
tmp_left = procs[procs.length - 1];
} else {
tmp_left = procs[i - 1];
}
if (i == procs.length - 1) {
tmp_right = procs[0];
} else {
tmp_right = procs[i + 1];
}
// give parameters to processes
procs[i].set_params(tmp_left, tmp_right, (ggT * (rnd.nextInt(100) + 1) * (rnd.nextInt(100) + 1)), log,
(rnd.nextInt(maxdelay - mindelay + 1) + mindelay), timeout);
}
log.log(name, "params set for each process");
// choose three processes randomly
int p1 = 0, p2 = 0, p3 = 0;
while ((p1 == p2) || (p2 == p3) || (p1 == p3)) {
p1 = rnd.nextInt(procs.length - 1);
p2 = rnd.nextInt(procs.length - 1);
p3 = rnd.nextInt(procs.length - 1);
}
// hand random large numbers to processes
//TODO change back?
/*
procs[p1].message(ggT * rnd.nextInt(9900) + 100);
procs[p2].message(ggT * rnd.nextInt(9900) + 100);
procs[p3].message(ggT * rnd.nextInt(9900) + 100);
*/
int p1_n = ggT * (rnd.nextInt(100) + 1);
int p2_n = ggT * (rnd.nextInt(100) + 1);
int p3_n = ggT * (rnd.nextInt(100) + 1);
log.log(name, "sending "+p1_n);
procs[p1].message(p1_n);
log.log(name, "sending "+p2_n);
procs[p2].message(p2_n);
log.log(name, "sending "+p3_n);
procs[p3].message(p3_n);
try {
// wait for a process to finish
finished.acquire();
} catch (InterruptedException e) {
System.err.println(e);
}
log.log(name, "finished with " + result);
return result;
}
|
diff --git a/platforms/android/src/com/example/SanAngeles/DemoActivity.java b/platforms/android/src/com/example/SanAngeles/DemoActivity.java
index 1792967..b99f777 100644
--- a/platforms/android/src/com/example/SanAngeles/DemoActivity.java
+++ b/platforms/android/src/com/example/SanAngeles/DemoActivity.java
@@ -1,502 +1,528 @@
// Jon Bardin GPL
package com.example.SanAngeles;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.app.Activity;
import android.content.DialogInterface;
import android.app.AlertDialog;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.View;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebChromeClient;
import android.webkit.WebViewClient;
import android.util.Log;
import java.util.Queue;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.content.res.AssetManager;
import android.opengl.GLUtils;
import android.opengl.GLES10;
import android.content.res.Configuration;
import java.io.InputStream;
import java.io.IOException;
import android.view.ViewGroup.LayoutParams;
import android.graphics.Color;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.io.UnsupportedEncodingException;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
class DemoRenderer implements GLSurfaceView.Renderer {
Context mContext;
public DemoRenderer(Context context) {
mContext = context;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
try {
AssetManager am = mContext.getAssets();
String path = "textures";
String[] texture_file_names = am.list(path);
int[] textures = new int[texture_file_names.length];
int[] tmp_tex = new int[texture_file_names.length];
gl.glGenTextures(texture_file_names.length, tmp_tex, 0);
int glError;
if ((glError = gl.glGetError()) != 0) {
Log.v(this.toString(), "unable to glGenTextures");
}
textures = tmp_tex;
for (int i=0; i<texture_file_names.length; i++) {
InputStream stream = am.open(path + "/" + texture_file_names[i]);
Bitmap bitmap = BitmapFactory.decodeStream(stream);
int t = textures[i];
gl.glBindTexture(GL10.GL_TEXTURE_2D, t);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
if ((glError = gl.glGetError()) != 0) {
Log.v(this.toString(), "unable to GLUtils.texImage2D");
}
gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);
}
nativeOnSurfaceCreated(texture_file_names.length, textures);
} catch(IOException e) {
Log.v(this.toString(), e.toString());
}
}
public void onSurfaceChanged(GL10 gl, int w, int h) {
nativeResize(w, h);
}
public void onDrawFrame(GL10 gl) {
if (Global.wtf == -1) {
nativeRender();
} else {
Global.mFooWtf.onFoo(Global.wtf);
Global.wtf = -1;
//Integer.parseInt(queryfalse
}
}
private native void nativeOnSurfaceCreated(int count, int[] textures);
private static native void nativeResize(int w, int h);
private static native void nativeRender();
}
class DemoGLSurfaceView extends GLSurfaceView {
private DemoRenderer mRenderer;
public DemoGLSurfaceView(Context context) {
super(context);
mRenderer = new DemoRenderer(context);
setRenderer(mRenderer);
}
@Override
public boolean onTouchEvent(final MotionEvent event) {
// queueEvent(new Runnable() {
// public void run() {
float x = event.getX();
float y = event.getY();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
nativeTouch(x, y, 0);
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
nativeTouch(x, y, 1);
}
if (event.getAction() == MotionEvent.ACTION_UP) {
nativeTouch(x, y, 2);
}
// }
// });
return true;
}
@Override
public void onPause() {
super.onPause();
nativePause();
}
@Override
public void onResume() {
super.onResume();
nativeResume();
}
public void onFoo(int i) {
final int ii = i;
//queueEvent(new Runnable() { public void run() {
nativeStartGame(ii);
//}});
}
private static native void nativePause();
private static native void nativeResume();
private static native void nativeTouch(float x, float y, int hitState);
private static native void nativeStartGame(int i);
}
class Global {
public static DemoGLSurfaceView mFooWtf;
public static int wtf = -1;
}
public class DemoActivity extends Activity {
protected static AudioTrack at1;
private DemoGLSurfaceView mGLView;
private WebView mWebView;
private JavascriptBridge mJavascriptBridge;
public static BlockingQueue<String> mWebViewMessages;
public static void writeAudio(short[] bytes, int offset, int size) {
int written = at1.write(bytes, offset, size);
}
public InputStream getInputStreamFromUrl(String url) {
InputStream content = null;
try {
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
} catch (Exception e) {
Log.v(this.toString(), e.toString());
}
return content;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DemoActivity.mWebViewMessages = new LinkedBlockingQueue<String>();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Context myApp = this;
final Activity MyActivity = this;
mGLView = new DemoGLSurfaceView(this);
Global.mFooWtf = mGLView;
setContentView(mGLView);
mWebView = new WebView(this);
mJavascriptBridge = new JavascriptBridge(this);
mWebView.addJavascriptInterface(mJavascriptBridge, "javascriptBridge");
mWebView.setBackgroundColor(Color.argb(0,0,0,0));
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result) {
new AlertDialog.Builder(myApp).setTitle("javaScript dialog").setMessage(message).setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
}).setCancelable(false).create().show();
return true;
};
+ /*
+ @Override
+ public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
+ Log.v(this.toString(), "holy shit");
+ super.onShowCustomView(view, callback);
+ if (view instanceof FrameLayout){
+ FrameLayout frame = (FrameLayout) view;
+ if (frame.getFocusedChild() instanceof VideoView){
+ VideoView video = (VideoView) frame.getFocusedChild();
+ frame.removeView(video);
+ a.setContentView(video);
+ video.setOnCompletionListener(this);
+ video.setOnErrorListener(this);
+ video.start();
+ }
+ }
+ }
+ */
+/*
+ public void onCompletion(MediaPlayer mp) {
+ Log.d(TAG, "Video completo");
+ a.setContentView(R.layout.main);
+ WebView wb = (WebView) a.findViewById(R.id.webview);
+ a.initWebView();
+ }
+*/
});
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.v(this.toString(), "WTF!@#!@#" + description);
}
});
AssetManager am = getAssets();
String path;
String[] files;
WebSettings webSettings = mWebView.getSettings();
webSettings.setLoadsImagesAutomatically(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setRenderPriority(WebSettings.RenderPriority.LOW);
webSettings.setBuiltInZoomControls(false);
webSettings.setPluginsEnabled(true);
/*
mWebView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return (event.getAction() == MotionEvent.ACTION_MOVE);
}
});
*/
try {
//String url = "http://radiant-fire-861.heroku.com/index.html";
//String url = "file:///android_asset/offline/index.html";
//getInputStreamFromUrl(url)
String base_url = "https://api.openfeint.com/?key=lxJAPbgkzhW91LqMeXEIg&secret=anQAUrXZTMfJxP8bLOMzmhfBlpuZMH9UPw45wCkGsQ";
InputStream inputStream = am.open("offline/index.html");
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream), 4096);
String line;
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
Log.v(this.toString(), line);
sb.append(line);
}
rd.close();
String contentOfMyInputStream = sb.toString();
mWebView.loadDataWithBaseURL(base_url, contentOfMyInputStream, "text/html", "utf-8", "about:blank");
} catch (java.lang.Exception e) {
Log.v(this.toString(), "WTF!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
Log.v(this.toString(), e.toString());
}
addContentView(mWebView, new LayoutParams(LayoutParams.FILL_PARENT, 200));
int model_count;
java.io.FileDescriptor[] fd1;
int[] off1;
int[] len1;
int level_count;
java.io.FileDescriptor[] fd2;
int[] off2;
int[] len2;
int sound_count;
int sound_count_actual;
java.io.FileDescriptor[] fd3;
int[] off3;
int[] len3;
int rate = 44100;
int min = AudioTrack.getMinBufferSize(rate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
setMinBuffer(min);
at1 = new AudioTrack(AudioManager.STREAM_MUSIC, rate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, min, AudioTrack.MODE_STREAM);
at1.play();
at1.setStereoVolume(1.0f, 1.0f);
try {
path = "models";
files = am.list(path);
model_count = files.length;
android.content.res.AssetFileDescriptor afd1;
fd1 = new java.io.FileDescriptor[model_count];
off1 = new int[model_count];
len1 = new int[model_count];
for (int i=0; i<model_count; i++) {
afd1 = getAssets().openFd(path + "/" + files[i]);
if (afd1 != null) {
fd1[i] = afd1.getFileDescriptor();
off1[i] = (int)afd1.getStartOffset();
len1[i] = (int)afd1.getLength();
}
}
path = "levels";
files = am.list(path);
level_count = files.length;
android.content.res.AssetFileDescriptor afd2;
fd2 = new java.io.FileDescriptor[level_count];
off2 = new int[level_count];
len2 = new int[level_count];
for (int i=0; i<level_count; i++) {
afd2 = getAssets().openFd(path + "/" + files[i]);
if (afd2 != null) {
fd2[i] = afd2.getFileDescriptor();
off2[i] = (int)afd2.getStartOffset();
len2[i] = (int)afd2.getLength();
}
}
path = "sounds";
files = am.list(path);
sound_count = files.length;
sound_count_actual = 0;
android.content.res.AssetFileDescriptor afd3;
fd3 = new java.io.FileDescriptor[sound_count];
off3 = new int[sound_count];
len3 = new int[sound_count];
for (int i=0; i<sound_count; i++) {
if (!files[i].contains("raw")) {
System.out.println(path + "/" + files[i]);
afd3 = getAssets().openFd(path + "/" + files[i]);
if (afd3 != null) {
fd3[i] = afd3.getFileDescriptor();
off3[i] = (int)afd3.getStartOffset();
len3[i] = (int)afd3.getLength();
sound_count_actual++;
}
}
}
int res = initNative(model_count, fd1, off1, len1, level_count, fd2, off2, len2, sound_count_actual, fd3, off3, len3);
} catch (java.io.IOException e) {
Log.v(this.toString(), e.toString());
}
}
public boolean pushMessageToWebView(String messageToPush) {
boolean r = false;
int p = mWebView.getProgress();
if (p == 100) {
final String f = new String(messageToPush);
// runOnUiThread(new Runnable() {
// public void run() {
mWebView.loadUrl(f);
// }
// });
r = true;
}
messageToPush = null;
return r;
}
public String popMessageFromWebView() {
// Popped messages are JSON structures that indicate status of operations, etc
if (mWebView.getProgress() < 100) {
return "wtfc";
}
if (DemoActivity.mWebViewMessages == null) {
return "wtf3";
}
final String mLastMessagePopped;
try {
if (DemoActivity.mWebViewMessages.isEmpty()) {
// runOnUiThread(new Runnable() {
// public void run() {
final String messagePopBridge = "javascript:(function() { var foo = dequeue(); if (foo) { window.javascriptBridge.pushToJava(foo); } })()";
mWebView.loadUrl(messagePopBridge);
// }
// });
return "empty_in_java";
} else {
mLastMessagePopped = DemoActivity.mWebViewMessages.take();
// new Thread(new Runnable() {
// public void run() {
//runOnUiThread(new Runnable() {
// public void run() {
try {
URI action = new URI(mLastMessagePopped);
//Log.v(this.toString(), action.toString());
String scheme = action.getScheme();
String path = action.getPath();
String query = action.getQuery();
if ("memoryleak".equals(scheme)) {
if ("/start".equals(path)) {
//Global.mFooWtf.onFoo(Integer.parseInt(query));
Global.wtf = Integer.parseInt(query);
} else if ("/show".equals(path)) {
} else if ("/hide".equals(path)) {
}
}
} catch(java.net.URISyntaxException wtf) {
Log.v(this.toString(), wtf.toString());
}
// }
//});
return mLastMessagePopped;
}
} catch (java.lang.InterruptedException wtf) {
Log.v(this.toString(), wtf.toString());
return "wtfa";
}
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
protected void onPause() {
super.onPause();
mGLView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mGLView.onResume();
}
private native int initNative(int model_count, java.io.FileDescriptor[] fd1, int[] off1, int[] len1, int level_count, java.io.FileDescriptor[] fd2, int[] off2, int[] len2, int sound_count, java.io.FileDescriptor[] fd3, int[] off3, int[] len3);
private static native void setMinBuffer(int size);
static {
System.loadLibrary("sanangeles");
}
}
class JavascriptBridge {
private DemoActivity mActivity;
public JavascriptBridge(DemoActivity theActivity) {
mActivity = theActivity;
}
public void pushToJava(String messageFromJavascript) {
DemoActivity.mWebViewMessages.offer(messageFromJavascript);
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DemoActivity.mWebViewMessages = new LinkedBlockingQueue<String>();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Context myApp = this;
final Activity MyActivity = this;
mGLView = new DemoGLSurfaceView(this);
Global.mFooWtf = mGLView;
setContentView(mGLView);
mWebView = new WebView(this);
mJavascriptBridge = new JavascriptBridge(this);
mWebView.addJavascriptInterface(mJavascriptBridge, "javascriptBridge");
mWebView.setBackgroundColor(Color.argb(0,0,0,0));
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result) {
new AlertDialog.Builder(myApp).setTitle("javaScript dialog").setMessage(message).setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
}).setCancelable(false).create().show();
return true;
};
});
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.v(this.toString(), "WTF!@#!@#" + description);
}
});
AssetManager am = getAssets();
String path;
String[] files;
WebSettings webSettings = mWebView.getSettings();
webSettings.setLoadsImagesAutomatically(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setRenderPriority(WebSettings.RenderPriority.LOW);
webSettings.setBuiltInZoomControls(false);
webSettings.setPluginsEnabled(true);
/*
mWebView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return (event.getAction() == MotionEvent.ACTION_MOVE);
}
});
*/
try {
//String url = "http://radiant-fire-861.heroku.com/index.html";
//String url = "file:///android_asset/offline/index.html";
//getInputStreamFromUrl(url)
String base_url = "https://api.openfeint.com/?key=lxJAPbgkzhW91LqMeXEIg&secret=anQAUrXZTMfJxP8bLOMzmhfBlpuZMH9UPw45wCkGsQ";
InputStream inputStream = am.open("offline/index.html");
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream), 4096);
String line;
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
Log.v(this.toString(), line);
sb.append(line);
}
rd.close();
String contentOfMyInputStream = sb.toString();
mWebView.loadDataWithBaseURL(base_url, contentOfMyInputStream, "text/html", "utf-8", "about:blank");
} catch (java.lang.Exception e) {
Log.v(this.toString(), "WTF!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
Log.v(this.toString(), e.toString());
}
addContentView(mWebView, new LayoutParams(LayoutParams.FILL_PARENT, 200));
int model_count;
java.io.FileDescriptor[] fd1;
int[] off1;
int[] len1;
int level_count;
java.io.FileDescriptor[] fd2;
int[] off2;
int[] len2;
int sound_count;
int sound_count_actual;
java.io.FileDescriptor[] fd3;
int[] off3;
int[] len3;
int rate = 44100;
int min = AudioTrack.getMinBufferSize(rate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
setMinBuffer(min);
at1 = new AudioTrack(AudioManager.STREAM_MUSIC, rate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, min, AudioTrack.MODE_STREAM);
at1.play();
at1.setStereoVolume(1.0f, 1.0f);
try {
path = "models";
files = am.list(path);
model_count = files.length;
android.content.res.AssetFileDescriptor afd1;
fd1 = new java.io.FileDescriptor[model_count];
off1 = new int[model_count];
len1 = new int[model_count];
for (int i=0; i<model_count; i++) {
afd1 = getAssets().openFd(path + "/" + files[i]);
if (afd1 != null) {
fd1[i] = afd1.getFileDescriptor();
off1[i] = (int)afd1.getStartOffset();
len1[i] = (int)afd1.getLength();
}
}
path = "levels";
files = am.list(path);
level_count = files.length;
android.content.res.AssetFileDescriptor afd2;
fd2 = new java.io.FileDescriptor[level_count];
off2 = new int[level_count];
len2 = new int[level_count];
for (int i=0; i<level_count; i++) {
afd2 = getAssets().openFd(path + "/" + files[i]);
if (afd2 != null) {
fd2[i] = afd2.getFileDescriptor();
off2[i] = (int)afd2.getStartOffset();
len2[i] = (int)afd2.getLength();
}
}
path = "sounds";
files = am.list(path);
sound_count = files.length;
sound_count_actual = 0;
android.content.res.AssetFileDescriptor afd3;
fd3 = new java.io.FileDescriptor[sound_count];
off3 = new int[sound_count];
len3 = new int[sound_count];
for (int i=0; i<sound_count; i++) {
if (!files[i].contains("raw")) {
System.out.println(path + "/" + files[i]);
afd3 = getAssets().openFd(path + "/" + files[i]);
if (afd3 != null) {
fd3[i] = afd3.getFileDescriptor();
off3[i] = (int)afd3.getStartOffset();
len3[i] = (int)afd3.getLength();
sound_count_actual++;
}
}
}
int res = initNative(model_count, fd1, off1, len1, level_count, fd2, off2, len2, sound_count_actual, fd3, off3, len3);
} catch (java.io.IOException e) {
Log.v(this.toString(), e.toString());
}
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DemoActivity.mWebViewMessages = new LinkedBlockingQueue<String>();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Context myApp = this;
final Activity MyActivity = this;
mGLView = new DemoGLSurfaceView(this);
Global.mFooWtf = mGLView;
setContentView(mGLView);
mWebView = new WebView(this);
mJavascriptBridge = new JavascriptBridge(this);
mWebView.addJavascriptInterface(mJavascriptBridge, "javascriptBridge");
mWebView.setBackgroundColor(Color.argb(0,0,0,0));
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result) {
new AlertDialog.Builder(myApp).setTitle("javaScript dialog").setMessage(message).setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
}).setCancelable(false).create().show();
return true;
};
/*
@Override
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Log.v(this.toString(), "holy shit");
super.onShowCustomView(view, callback);
if (view instanceof FrameLayout){
FrameLayout frame = (FrameLayout) view;
if (frame.getFocusedChild() instanceof VideoView){
VideoView video = (VideoView) frame.getFocusedChild();
frame.removeView(video);
a.setContentView(video);
video.setOnCompletionListener(this);
video.setOnErrorListener(this);
video.start();
}
}
}
*/
/*
public void onCompletion(MediaPlayer mp) {
Log.d(TAG, "Video completo");
a.setContentView(R.layout.main);
WebView wb = (WebView) a.findViewById(R.id.webview);
a.initWebView();
}
*/
});
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.v(this.toString(), "WTF!@#!@#" + description);
}
});
AssetManager am = getAssets();
String path;
String[] files;
WebSettings webSettings = mWebView.getSettings();
webSettings.setLoadsImagesAutomatically(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setRenderPriority(WebSettings.RenderPriority.LOW);
webSettings.setBuiltInZoomControls(false);
webSettings.setPluginsEnabled(true);
/*
mWebView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return (event.getAction() == MotionEvent.ACTION_MOVE);
}
});
*/
try {
//String url = "http://radiant-fire-861.heroku.com/index.html";
//String url = "file:///android_asset/offline/index.html";
//getInputStreamFromUrl(url)
String base_url = "https://api.openfeint.com/?key=lxJAPbgkzhW91LqMeXEIg&secret=anQAUrXZTMfJxP8bLOMzmhfBlpuZMH9UPw45wCkGsQ";
InputStream inputStream = am.open("offline/index.html");
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream), 4096);
String line;
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
Log.v(this.toString(), line);
sb.append(line);
}
rd.close();
String contentOfMyInputStream = sb.toString();
mWebView.loadDataWithBaseURL(base_url, contentOfMyInputStream, "text/html", "utf-8", "about:blank");
} catch (java.lang.Exception e) {
Log.v(this.toString(), "WTF!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
Log.v(this.toString(), e.toString());
}
addContentView(mWebView, new LayoutParams(LayoutParams.FILL_PARENT, 200));
int model_count;
java.io.FileDescriptor[] fd1;
int[] off1;
int[] len1;
int level_count;
java.io.FileDescriptor[] fd2;
int[] off2;
int[] len2;
int sound_count;
int sound_count_actual;
java.io.FileDescriptor[] fd3;
int[] off3;
int[] len3;
int rate = 44100;
int min = AudioTrack.getMinBufferSize(rate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
setMinBuffer(min);
at1 = new AudioTrack(AudioManager.STREAM_MUSIC, rate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, min, AudioTrack.MODE_STREAM);
at1.play();
at1.setStereoVolume(1.0f, 1.0f);
try {
path = "models";
files = am.list(path);
model_count = files.length;
android.content.res.AssetFileDescriptor afd1;
fd1 = new java.io.FileDescriptor[model_count];
off1 = new int[model_count];
len1 = new int[model_count];
for (int i=0; i<model_count; i++) {
afd1 = getAssets().openFd(path + "/" + files[i]);
if (afd1 != null) {
fd1[i] = afd1.getFileDescriptor();
off1[i] = (int)afd1.getStartOffset();
len1[i] = (int)afd1.getLength();
}
}
path = "levels";
files = am.list(path);
level_count = files.length;
android.content.res.AssetFileDescriptor afd2;
fd2 = new java.io.FileDescriptor[level_count];
off2 = new int[level_count];
len2 = new int[level_count];
for (int i=0; i<level_count; i++) {
afd2 = getAssets().openFd(path + "/" + files[i]);
if (afd2 != null) {
fd2[i] = afd2.getFileDescriptor();
off2[i] = (int)afd2.getStartOffset();
len2[i] = (int)afd2.getLength();
}
}
path = "sounds";
files = am.list(path);
sound_count = files.length;
sound_count_actual = 0;
android.content.res.AssetFileDescriptor afd3;
fd3 = new java.io.FileDescriptor[sound_count];
off3 = new int[sound_count];
len3 = new int[sound_count];
for (int i=0; i<sound_count; i++) {
if (!files[i].contains("raw")) {
System.out.println(path + "/" + files[i]);
afd3 = getAssets().openFd(path + "/" + files[i]);
if (afd3 != null) {
fd3[i] = afd3.getFileDescriptor();
off3[i] = (int)afd3.getStartOffset();
len3[i] = (int)afd3.getLength();
sound_count_actual++;
}
}
}
int res = initNative(model_count, fd1, off1, len1, level_count, fd2, off2, len2, sound_count_actual, fd3, off3, len3);
} catch (java.io.IOException e) {
Log.v(this.toString(), e.toString());
}
}
|
diff --git a/Syncro/src/uk/me/grambo/syncro/SyncroService.java b/Syncro/src/uk/me/grambo/syncro/SyncroService.java
index 932bf3e..b80f393 100644
--- a/Syncro/src/uk/me/grambo/syncro/SyncroService.java
+++ b/Syncro/src/uk/me/grambo/syncro/SyncroService.java
@@ -1,523 +1,523 @@
/* This file is part of Syncro.
Copyright (c) Graeme Coupar <[email protected]>
Syncro 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.
Syncro 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 Syncro. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.me.grambo.syncro;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Vector;
import uk.me.grambo.syncro.comms.Connection;
import uk.me.grambo.syncro.comms.ConnectionDetails;
import uk.me.grambo.syncro.comms.FolderContentsHandler;
import uk.me.grambo.syncro.comms.FolderListHandler;
import uk.me.grambo.syncro.comms.ProgressHandler;
import uk.me.grambo.syncro.comms.RemoteFileData;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.PowerManager;
import android.util.Log;
public class SyncroService
extends IntentService
implements FolderContentsHandler,FolderListHandler, ProgressHandler
{
private Vector<RemoteFileData> m_filesToDownload;
private FilterFactory m_oFilterFactory;
private ArrayList<IncludeFilter> m_includeFilters;
private ArrayList<FilenameFilter> m_filenameFilters;
private ProgressNotification m_progressNotification;
private SQLiteDatabase m_db;
private SQLiteStatement m_folderInsertStatement;
private Connection m_conn;
String m_sCurrentLocalPath;
private int m_serverId;
public SyncroService() {
super("SyncroService");
// TODO Auto-generated constructor stub
m_filesToDownload = new Vector<RemoteFileData>();
m_includeFilters = new ArrayList<IncludeFilter>();
m_filenameFilters = new ArrayList<FilenameFilter>();
m_oFilterFactory = new FilterFactory(this);
m_conn = new Connection(this);
}
@Override
protected void onHandleIntent(Intent arg0) {
if( arg0.getAction().equals("uk.me.grambo.syncro.SYNCRO_SYNC") ) {
//Temporary hack - only run on wifi.
//TODO: Make the logic of this better - check user preferences etc.
WifiManager wifiMan = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if( !wifiMan.isWifiEnabled() )
{
return;
}
WifiInfo wifiInfo = wifiMan.getConnectionInfo();
if( wifiInfo == null )
return;
String ssid = wifiInfo.getSSID();
if( ssid == null )
return;
//Otherwise, attempt to sync.
Uri oURI = arg0.getData();
if( oURI != null ) {
String oScheme = oURI.getScheme();
if( oScheme.equals("syncro") ) {
String sHost = oURI.getHost();
int nPort = oURI.getPort();
//RunSync(0,sHost,nPort);
} else if( oScheme.equals("syncroid") ) {
DBHelper oHelper = new DBHelper( this );
SQLiteDatabase oDB = oHelper.getReadableDatabase();
String aSQLArgs[] = new String[1];
aSQLArgs[0] = oURI.getHost();
Cursor oResults = oDB.rawQuery("SELECT ID,IP,Port FROM servers WHERE ID=?", aSQLArgs);
if( oResults.moveToFirst() ) {
int nID,nPort;
String sAddress;
nID = oResults.getInt(0);
sAddress = oResults.getString(1);
nPort = oResults.getInt(2);
oResults.close();
oDB.close();
boolean retry;
int retryCount = 5;
do {
retry = !RunSync( nID, sAddress, nPort );
retryCount--;
if( retry && ( retryCount > 0 ) )
{
Log.w("Syncro", "Syncro failed. Retrying in 10 seconds");
try {
Thread.sleep( 10000 );
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
retry = false;
}
Log.i("Syncro", "Retrying now...");
}else if( retry )
{
Log.e("Syncro", "Syncro failed, but ran out of retries");
}
}while( retry && ( retryCount > 0 ) );
} else {
oDB.close();
}
}
}
}
}
/**
* Runs an entire sync with the server specified
* @param innServerID The ID of the server in the database
* @param insHost The hostname of the server
* @param innPort The port of the server
* @return True if we should not retry, false if we should
*/
protected boolean RunSync(int innServerID,String insHost,int innPort) {
boolean retry = false;
boolean gotInitialConnection = false;
m_serverId = innServerID;
//TODO: probably want to move innServerID into a member variable or something
m_progressNotification = new ProgressNotification(this);
m_progressNotification.setShowRate(true);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Syncro");
wl.acquire();
try {
ConnectionDetails details =
ConnectionDetails.createInstance()
.setHostname(insHost)
.setPort( innPort );
boolean handshakeOk = m_conn.Connect(details);
gotInitialConnection = true;
//Start the progress notification
m_progressNotification.update();
if( handshakeOk ) {
DBHelper oHelper = new DBHelper( this );
m_db = oHelper.getWritableDatabase();
m_folderInsertStatement =
m_db.compileStatement(
"INSERT INTO folders" +
"(IDOnServer,ServerID,Name,ServerPath,LocalPath) " +
"VALUES(?," + innServerID + ",?,?,'/mnt/sdcard/Syncro/')"
);
m_conn.GetFolderList( this );
//
// Send a folder list update broadcast to update the UI
//
Intent broadcast = new Intent();
broadcast.setAction("uk.me.grambo.syncro.ui.FOLDER_LIST_UPDATE");
//TODO: Uncomment this next line and add in data to send the folder id
//broadcast.setData("syncro://folderid=");
sendBroadcast( broadcast );
PerformDownloads( );
PerformUploads( );
}
//
// TEMPORARY HACK: Start a timer to make us sync again in a bit
// ( but only if we've not crashed or anything )
//
//TODO: Replace this shit with some user preference controlled thing
/* AlarmManager alarmMan = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent( this, SyncroService.class );
i.setAction("uk.me.grambo.syncro.SYNCRO_SYNC");
i.setData( Uri.parse( "syncroid://" + innServerID ) );
PendingIntent pendingIntent = PendingIntent.getService(this, 0, i, 0);
alarmMan.setInexactRepeating(
AlarmManager.ELAPSED_REALTIME,
System.currentTimeMillis() + 60000,
AlarmManager.INTERVAL_HOUR,
pendingIntent
);*/
}
catch ( SocketException e )
{
if( gotInitialConnection )
retry = true;
else {
Log.e("Syncro","Couldn't connect to server");
e.printStackTrace();
}
//TODO: Need to work out the difference between can't connect at all,
// and have been disconnected
}
catch( EOFException e )
{
//TODO: Need to determine between network EOF and file EOF
if( gotInitialConnection )
retry = true;
else {
Log.e("Syncro","Couldn't connect to server");
e.printStackTrace();
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//TODO: update notification or something here?
} catch( Exception e ) {
e.printStackTrace();
}
finally
{
if( m_db != null )
{
m_db.close();
m_db = null;
}
m_conn.Disconnect();
+ m_progressNotification.stop();
+ wl.release();
}
- wl.release();
- m_progressNotification.stop();
return !retry;
}
//
// Remote file/folder handler callbacks
//
@Override
public void handleRemoteFile(RemoteFileData inoFile) {
if( CheckIncludeFilters(inoFile) )
m_filesToDownload.add(inoFile);
}
@Override
public void handlerFolder(FolderInfo folder) {
m_folderInsertStatement.bindLong( 1, folder.Id );
m_folderInsertStatement.bindString( 2, folder.Name );
m_folderInsertStatement.bindString( 3, folder.Path );
m_folderInsertStatement.executeInsert();
//TODO: Should probably add some pruning logic etc. in here
// for folders no longer on the server
}
//
// Progress Handler Callbacks
//
@Override
public void setTotalProgress(long total) {
//TODO: Implement me
}
@Override
public void setCurrentProgress(long progress) {
// TODO: Fix the long/int conversion in here
m_progressNotification.setProgress( (int)progress );
}
//
// File downloading functions
//
/**
* Gets folder contents, and downloads any neccesary files
* @throws Exception
*/
protected void PerformDownloads() throws Exception
{
String[] aArgs = new String[1];
aArgs[0] = String.valueOf( m_serverId );
Cursor folders =
m_db.rawQuery(
"SELECT IDOnServer,LocalPath " +
"FROM folders WHERE ServerID=? " +
"AND SyncToPhone=1",
aArgs
);
folders.moveToFirst();
while (folders.isAfterLast() == false) {
int folderId = (int)folders.getLong(0);
m_sCurrentLocalPath = folders.getString(1);
m_includeFilters.clear();
m_oFilterFactory.getIncludeFilters(
m_db,
folderId,
m_includeFilters
);
m_conn.GetFolderContents( folderId, this );
if( m_filesToDownload.size() > 0 ) {
m_filenameFilters.clear();
m_oFilterFactory.getFilenameFilters(
m_db,
folderId,
m_filenameFilters
);
GetFiles();
}
//TODO: Tidy up excess clears sometime?
m_filesToDownload.clear();
m_includeFilters.clear();
m_filenameFilters.clear();
folders.moveToNext();
}
folders.close();
}
/**
* Attempts to download all the files in the files to download array
* @return True on success, false on failure
* @throws Exception
* @throws IOException
*/
private boolean GetFiles() throws Exception,IOException {
//android.os.Debug.startMethodTracing("syncro-download");
boolean fOK = false;
int nPrevFolderId = -1;
m_progressNotification.setTotalNumFiles( m_filesToDownload.size() );
for(int nFile = 0;nFile < m_filesToDownload.size();nFile++) {
RemoteFileData oFile = m_filesToDownload.elementAt(nFile);
if( (nPrevFolderId != -1) && (nPrevFolderId != oFile.FolderId) ) {
throw new Exception("GetFiles called with contents of different folders");
}
String destFilename;
try {
destFilename = GetDestinationFilename(oFile);
}catch(Exception e) {
e.printStackTrace();
continue;
}
if( CheckIncludeFilters(oFile,destFilename) ) {
//TODO: To get accurate total file numbers, need to run include filters etc. before this loop
// but never mind for now...
m_progressNotification.setCurrentFileDetails( oFile, nFile );
m_progressNotification.setProgress( 0 );
fOK = m_conn.GetFile( oFile, destFilename, this );
if( !fOK )
return false;
}
nPrevFolderId = oFile.FolderId;
}
//android.os.Debug.stopMethodTracing();
return fOK;
}
//
// File download utility functions
//
/**
* GetDestinationFilename
* @return Returns the destination filename of the specified remote file data
*/
private String GetDestinationFilename(RemoteFileData inoFile) throws Exception {
for( int n=0; n < m_filenameFilters.size(); n++ ) {
FilenameFilter oFilter = m_filenameFilters.get(n);
if( oFilter.canHandle(inoFile) ) {
return oFilter.getDestinationFilename(inoFile);
}
}
throw new Exception("Could not find suitable Filename filter for " + inoFile.Filename + " (FolderID: " + inoFile.FolderId + ")");
}
/**
* Checks if we should download the file specified
* @param inoFile The details of the file to check
* @return True if we should download it
*/
private boolean CheckIncludeFilters(RemoteFileData inoFile) {
for( int n=0; n < m_includeFilters.size(); n++ ) {
IncludeFilter oFilter = m_includeFilters.get( n );
if( !oFilter.needsFilename() ) {
if( oFilter.shouldInclude(inoFile) ) {
return true;
}
//TODO: probably a better way to handle this should end list stuff...
if( oFilter.shouldEndList() )
return false;
}
}
return false;
}
/**
* Checks again if we should download the file specified, based on dest filename
* @param inoFile The details of the file to check
* @param insDestFilename The destination filename
* @return True if we should download the file
*/
private boolean CheckIncludeFilters(RemoteFileData inoFile,String insDestFilename) {
for( int n=0; n < m_includeFilters.size(); n++ ) {
IncludeFilter oFilter = m_includeFilters.get( n );
if( oFilter.needsFilename() ) {
if( oFilter.shouldInclude(inoFile,insDestFilename) ) {
return true;
}
//TODO: probably a better way to handle this should end list stuff...
if( oFilter.shouldEndList() )
return false;
}
}
return false;
}
//
// Send File functions
//
/**
* Runs the upload stage of a sync
*/
protected void PerformUploads() throws IOException,Exception {
//android.os.Debug.startMethodTracing("syncro-upload");
String args[] = { Integer.valueOf( m_serverId ).toString() };
Cursor results = m_db.rawQuery(
"SELECT ID,IDOnServer,LocalPath " +
"FROM folders WHERE SyncFromPhone=1 AND ServerID=?",
args);
//TODO: use the actual number of files here....
m_progressNotification.setTotalNumFiles(1);
while( results.moveToNext() )
{
String folderPath = results.getString(2);
File folder = new File(folderPath);
if( !folder.isDirectory() || !folder.canRead() )
{
continue;
}
m_sCurrentLocalPath = folder.getAbsolutePath();
if( !m_sCurrentLocalPath.endsWith( File.separator ) )
m_sCurrentLocalPath =
m_sCurrentLocalPath.concat( File.separator );
SendFolder( results.getInt(1), folder );
}
//android.os.Debug.stopMethodTracing();
}
/**
* Processes a folder, sending all it's contents to the server
* @param folderId The current folderID we're using
* @param folder The File object that represents this older
* @throws Exception
*/
private void SendFolder(int folderId,File folder) throws Exception
{
File[] files = folder.listFiles();
for( int nFile=0; nFile < files.length; nFile++ )
{
if( files[nFile].isDirectory() )
{
SendFolder( folderId, files[ nFile ] );
}
else
{
String sendPath =
files[ nFile ].getAbsolutePath().substring(
m_sCurrentLocalPath.length()
);
m_progressNotification.setCurrentFileDetails(
sendPath,
(int)files[ nFile ].length(),
1
);
m_conn.SendFile(
folderId,
files[ nFile ].getAbsolutePath(),
sendPath,
this
);
}
}
}
}
| false | true | protected boolean RunSync(int innServerID,String insHost,int innPort) {
boolean retry = false;
boolean gotInitialConnection = false;
m_serverId = innServerID;
//TODO: probably want to move innServerID into a member variable or something
m_progressNotification = new ProgressNotification(this);
m_progressNotification.setShowRate(true);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Syncro");
wl.acquire();
try {
ConnectionDetails details =
ConnectionDetails.createInstance()
.setHostname(insHost)
.setPort( innPort );
boolean handshakeOk = m_conn.Connect(details);
gotInitialConnection = true;
//Start the progress notification
m_progressNotification.update();
if( handshakeOk ) {
DBHelper oHelper = new DBHelper( this );
m_db = oHelper.getWritableDatabase();
m_folderInsertStatement =
m_db.compileStatement(
"INSERT INTO folders" +
"(IDOnServer,ServerID,Name,ServerPath,LocalPath) " +
"VALUES(?," + innServerID + ",?,?,'/mnt/sdcard/Syncro/')"
);
m_conn.GetFolderList( this );
//
// Send a folder list update broadcast to update the UI
//
Intent broadcast = new Intent();
broadcast.setAction("uk.me.grambo.syncro.ui.FOLDER_LIST_UPDATE");
//TODO: Uncomment this next line and add in data to send the folder id
//broadcast.setData("syncro://folderid=");
sendBroadcast( broadcast );
PerformDownloads( );
PerformUploads( );
}
//
// TEMPORARY HACK: Start a timer to make us sync again in a bit
// ( but only if we've not crashed or anything )
//
//TODO: Replace this shit with some user preference controlled thing
/* AlarmManager alarmMan = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent( this, SyncroService.class );
i.setAction("uk.me.grambo.syncro.SYNCRO_SYNC");
i.setData( Uri.parse( "syncroid://" + innServerID ) );
PendingIntent pendingIntent = PendingIntent.getService(this, 0, i, 0);
alarmMan.setInexactRepeating(
AlarmManager.ELAPSED_REALTIME,
System.currentTimeMillis() + 60000,
AlarmManager.INTERVAL_HOUR,
pendingIntent
);*/
}
catch ( SocketException e )
{
if( gotInitialConnection )
retry = true;
else {
Log.e("Syncro","Couldn't connect to server");
e.printStackTrace();
}
//TODO: Need to work out the difference between can't connect at all,
// and have been disconnected
}
catch( EOFException e )
{
//TODO: Need to determine between network EOF and file EOF
if( gotInitialConnection )
retry = true;
else {
Log.e("Syncro","Couldn't connect to server");
e.printStackTrace();
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//TODO: update notification or something here?
} catch( Exception e ) {
e.printStackTrace();
}
finally
{
if( m_db != null )
{
m_db.close();
m_db = null;
}
m_conn.Disconnect();
}
wl.release();
m_progressNotification.stop();
return !retry;
}
| protected boolean RunSync(int innServerID,String insHost,int innPort) {
boolean retry = false;
boolean gotInitialConnection = false;
m_serverId = innServerID;
//TODO: probably want to move innServerID into a member variable or something
m_progressNotification = new ProgressNotification(this);
m_progressNotification.setShowRate(true);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Syncro");
wl.acquire();
try {
ConnectionDetails details =
ConnectionDetails.createInstance()
.setHostname(insHost)
.setPort( innPort );
boolean handshakeOk = m_conn.Connect(details);
gotInitialConnection = true;
//Start the progress notification
m_progressNotification.update();
if( handshakeOk ) {
DBHelper oHelper = new DBHelper( this );
m_db = oHelper.getWritableDatabase();
m_folderInsertStatement =
m_db.compileStatement(
"INSERT INTO folders" +
"(IDOnServer,ServerID,Name,ServerPath,LocalPath) " +
"VALUES(?," + innServerID + ",?,?,'/mnt/sdcard/Syncro/')"
);
m_conn.GetFolderList( this );
//
// Send a folder list update broadcast to update the UI
//
Intent broadcast = new Intent();
broadcast.setAction("uk.me.grambo.syncro.ui.FOLDER_LIST_UPDATE");
//TODO: Uncomment this next line and add in data to send the folder id
//broadcast.setData("syncro://folderid=");
sendBroadcast( broadcast );
PerformDownloads( );
PerformUploads( );
}
//
// TEMPORARY HACK: Start a timer to make us sync again in a bit
// ( but only if we've not crashed or anything )
//
//TODO: Replace this shit with some user preference controlled thing
/* AlarmManager alarmMan = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent( this, SyncroService.class );
i.setAction("uk.me.grambo.syncro.SYNCRO_SYNC");
i.setData( Uri.parse( "syncroid://" + innServerID ) );
PendingIntent pendingIntent = PendingIntent.getService(this, 0, i, 0);
alarmMan.setInexactRepeating(
AlarmManager.ELAPSED_REALTIME,
System.currentTimeMillis() + 60000,
AlarmManager.INTERVAL_HOUR,
pendingIntent
);*/
}
catch ( SocketException e )
{
if( gotInitialConnection )
retry = true;
else {
Log.e("Syncro","Couldn't connect to server");
e.printStackTrace();
}
//TODO: Need to work out the difference between can't connect at all,
// and have been disconnected
}
catch( EOFException e )
{
//TODO: Need to determine between network EOF and file EOF
if( gotInitialConnection )
retry = true;
else {
Log.e("Syncro","Couldn't connect to server");
e.printStackTrace();
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//TODO: update notification or something here?
} catch( Exception e ) {
e.printStackTrace();
}
finally
{
if( m_db != null )
{
m_db.close();
m_db = null;
}
m_conn.Disconnect();
m_progressNotification.stop();
wl.release();
}
return !retry;
}
|
diff --git a/src/com/matburt/mobileorg/SynchronizerPreferences.java b/src/com/matburt/mobileorg/SynchronizerPreferences.java
index 300c271..f9bc26b 100644
--- a/src/com/matburt/mobileorg/SynchronizerPreferences.java
+++ b/src/com/matburt/mobileorg/SynchronizerPreferences.java
@@ -1,90 +1,90 @@
package com.matburt.mobileorg;
import android.content.Context;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceManager;
import android.widget.Toast;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.Gravity;
import android.graphics.Typeface;
public class SynchronizerPreferences extends Preference {
public SynchronizerPreferences(Context context) {
super(context);
}
public SynchronizerPreferences(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SynchronizerPreferences(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected View onCreateView(ViewGroup parent){
LinearLayout layout = new LinearLayout(getContext());
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params1.gravity = Gravity.LEFT;
params1.weight = 1.0f;
LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
80,
LinearLayout.LayoutParams.WRAP_CONTENT);
params2.gravity = Gravity.RIGHT;
LinearLayout.LayoutParams params3 = new LinearLayout.LayoutParams(
30,
LinearLayout.LayoutParams.WRAP_CONTENT);
params3.gravity = Gravity.CENTER;
layout.setPadding(15, 5, 10, 5);
layout.setOrientation(LinearLayout.HORIZONTAL);
TextView view = new TextView(getContext());
view.setText("Configure Synchronizer Settings...");
view.setTextSize(18);
view.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
view.setGravity(Gravity.LEFT);
view.setLayoutParams(params1);
//NOTE: Need a way to dynamically pick a preferences activity based on the
//synchro mode selected, replace with a plugin architecture
this.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference arg0) {
SharedPreferences appSettings = PreferenceManager.getDefaultSharedPreferences(getContext());
String synchroMode = appSettings.getString("syncSource","");
Intent synchroIntent = new Intent();
synchroIntent.setClassName("com.matburt.mobileorg",
"com.matburt.mobileorg.SettingsActivity");
if (synchroMode.equals("webdav")) {
synchroIntent.putExtra("prefs",R.xml.webdav_preferences);
getContext().startActivity(synchroIntent);
}
else if (synchroMode.equals("sdcard")) {
synchroIntent.putExtra("prefs",R.xml.sdsync_preferences);
getContext().startActivity(synchroIntent);
}
else {
- throw new ReportableError(R.string.error_synchronizer_type_unknown,
- synchroMode);
+ //throw new ReportableError(R.string.error_synchronizer_type_unknown,
+ // synchroMode);
}
return true;
}
});
layout.addView(view);
layout.setId(android.R.id.widget_frame);
return layout;
}
}
| true | true | protected View onCreateView(ViewGroup parent){
LinearLayout layout = new LinearLayout(getContext());
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params1.gravity = Gravity.LEFT;
params1.weight = 1.0f;
LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
80,
LinearLayout.LayoutParams.WRAP_CONTENT);
params2.gravity = Gravity.RIGHT;
LinearLayout.LayoutParams params3 = new LinearLayout.LayoutParams(
30,
LinearLayout.LayoutParams.WRAP_CONTENT);
params3.gravity = Gravity.CENTER;
layout.setPadding(15, 5, 10, 5);
layout.setOrientation(LinearLayout.HORIZONTAL);
TextView view = new TextView(getContext());
view.setText("Configure Synchronizer Settings...");
view.setTextSize(18);
view.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
view.setGravity(Gravity.LEFT);
view.setLayoutParams(params1);
//NOTE: Need a way to dynamically pick a preferences activity based on the
//synchro mode selected, replace with a plugin architecture
this.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference arg0) {
SharedPreferences appSettings = PreferenceManager.getDefaultSharedPreferences(getContext());
String synchroMode = appSettings.getString("syncSource","");
Intent synchroIntent = new Intent();
synchroIntent.setClassName("com.matburt.mobileorg",
"com.matburt.mobileorg.SettingsActivity");
if (synchroMode.equals("webdav")) {
synchroIntent.putExtra("prefs",R.xml.webdav_preferences);
getContext().startActivity(synchroIntent);
}
else if (synchroMode.equals("sdcard")) {
synchroIntent.putExtra("prefs",R.xml.sdsync_preferences);
getContext().startActivity(synchroIntent);
}
else {
throw new ReportableError(R.string.error_synchronizer_type_unknown,
synchroMode);
}
return true;
}
});
layout.addView(view);
layout.setId(android.R.id.widget_frame);
return layout;
}
| protected View onCreateView(ViewGroup parent){
LinearLayout layout = new LinearLayout(getContext());
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params1.gravity = Gravity.LEFT;
params1.weight = 1.0f;
LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
80,
LinearLayout.LayoutParams.WRAP_CONTENT);
params2.gravity = Gravity.RIGHT;
LinearLayout.LayoutParams params3 = new LinearLayout.LayoutParams(
30,
LinearLayout.LayoutParams.WRAP_CONTENT);
params3.gravity = Gravity.CENTER;
layout.setPadding(15, 5, 10, 5);
layout.setOrientation(LinearLayout.HORIZONTAL);
TextView view = new TextView(getContext());
view.setText("Configure Synchronizer Settings...");
view.setTextSize(18);
view.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
view.setGravity(Gravity.LEFT);
view.setLayoutParams(params1);
//NOTE: Need a way to dynamically pick a preferences activity based on the
//synchro mode selected, replace with a plugin architecture
this.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference arg0) {
SharedPreferences appSettings = PreferenceManager.getDefaultSharedPreferences(getContext());
String synchroMode = appSettings.getString("syncSource","");
Intent synchroIntent = new Intent();
synchroIntent.setClassName("com.matburt.mobileorg",
"com.matburt.mobileorg.SettingsActivity");
if (synchroMode.equals("webdav")) {
synchroIntent.putExtra("prefs",R.xml.webdav_preferences);
getContext().startActivity(synchroIntent);
}
else if (synchroMode.equals("sdcard")) {
synchroIntent.putExtra("prefs",R.xml.sdsync_preferences);
getContext().startActivity(synchroIntent);
}
else {
//throw new ReportableError(R.string.error_synchronizer_type_unknown,
// synchroMode);
}
return true;
}
});
layout.addView(view);
layout.setId(android.R.id.widget_frame);
return layout;
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/scripts/requirements/RequirementChecker.java b/src/main/java/net/aufdemrand/denizen/scripts/requirements/RequirementChecker.java
index 116e6a55d..0437c5d1a 100644
--- a/src/main/java/net/aufdemrand/denizen/scripts/requirements/RequirementChecker.java
+++ b/src/main/java/net/aufdemrand/denizen/scripts/requirements/RequirementChecker.java
@@ -1,148 +1,148 @@
package net.aufdemrand.denizen.scripts.requirements;
import java.util.ArrayList;
import java.util.List;
import net.aufdemrand.denizen.Denizen;
import net.aufdemrand.denizen.exceptions.RequirementCheckException;
import net.aufdemrand.denizen.utilities.debugging.Debugger;
import net.aufdemrand.denizen.utilities.debugging.Debugger.DebugElement;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.command.exception.RequirementMissingException;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class RequirementChecker {
private Denizen plugin;
private Debugger dB;
public RequirementChecker(Denizen denizen) {
plugin = denizen;
dB = plugin.getDebugger();
}
public boolean check(String scriptName, NPC npc, Player player) throws RequirementMissingException {
String reqMode = plugin.getScripts().getString(scriptName + ".REQUIREMENTS.MODE", "NONE");
List<String> reqList = plugin.getScripts().getStringList(scriptName + ".REQUIREMENTS.LIST");
dB.echoDebug(ChatColor.YELLOW + "CHECK! Now checking '%s'", scriptName);
// No requirements met yet, we just started!
int numberMet = 0;
boolean negativeRequirement;
// Requirements list null? This script is probably named wrong, or doesn't exist!
- if (reqList.isEmpty() && !reqMode.equals("NONE")) {
+ if (reqList.isEmpty() && !reqMode.equalsIgnoreCase("NONE")) {
dB.echoError("Non-valid requirements structure at:");
dB.echoDebug(ChatColor.GRAY + scriptName + ":");
dB.echoDebug(ChatColor.GRAY + " Requirements:");
dB.echoDebug(ChatColor.GRAY + " Mode: ???");
dB.echoDebug(ChatColor.GRAY + " List:");
dB.echoDebug(ChatColor.GRAY + " - ???");
dB.echoDebug("* Check spacing, validate structure and spelling.");
return false;
}
// Requirement node "NONE"? No requirements in the LIST? No need to continue, return TRUE
if (reqMode.equals("NONE") || reqList.isEmpty()) return true;
dB.echoDebug("Requirement mode: '%s'", reqMode.toUpperCase());
// Set up checks for requirement mode 'FIRST AND ANY #'
boolean firstReqMet = false;
boolean firstReqChecked = false;
// Check all requirements
for (String reqEntry : reqList) {
// Check if this is a Negative Requirement
if (reqEntry.startsWith("-")) {
negativeRequirement = true;
reqEntry = reqEntry.substring(1);
} else negativeRequirement = false;
// Check requirement with RequirementRegistry
if (plugin.getRequirementRegistry().list().containsKey(reqEntry.split(" ")[0])) {
AbstractRequirement requirement = plugin.getRequirementRegistry().get(reqEntry.split(" ")[0]);
String[] arguments = null;
if (reqEntry.split(" ").length > 1) arguments = plugin.getScriptEngine().getScriptBuilder().buildArgs(reqEntry.split(" ", 2)[1]);
// Replace tags
List<String> argumentList = new ArrayList<String>();
if (arguments != null) argumentList = plugin.tagManager().fillArguments(arguments, player, plugin.getNPCRegistry().getDenizen(npc));
try {
// Check if # of required args are met
if ((arguments == null && requirement.requirementOptions.REQUIRED_ARGS > 0) ||
arguments.length < requirement.requirementOptions.REQUIRED_ARGS) throw new RequirementCheckException("");
// Check the Requirement
if (requirement.check(player, plugin.getNPCRegistry().getDenizen(npc), scriptName, argumentList) != negativeRequirement) {
// Check first requirement for mode 'FIRST AND ANY #'
if (!firstReqChecked) {
firstReqMet = true;
firstReqChecked = true;
}
numberMet++;
dB.echoApproval("Checking Requirement '" + requirement.getName() + "'" + " ...requirement met!");
} else {
if (!firstReqChecked) {
firstReqMet = false;
firstReqChecked = true;
}
dB.echoApproval("Checking Requirement '" + requirement.getName() + "'" + " ...requirement not met!");
}
} catch (Throwable e) {
if (e instanceof RequirementCheckException) {
dB.echoError("Woah! Invalid arguments were specified!");
dB.echoError("Usage: " + requirement.getUsageHint());
} else {
dB.echoError("Woah! An exception has been called for Requirement '" + requirement.getName() + "'!");
if (!dB.showStackTraces) dB.echoError("Enable '/denizen stacktrace' for the nitty-gritty.");
else e.printStackTrace();
}
}
}
// If the requirement is not registered with the Requirement Registry
else {
dB.echoError("Requirement '" + reqEntry.split(" ")[0] + "' not found! Check that the requirement is installed!");
}
}
// Check numberMet with mode...
String[] ModeArgs = reqMode.split(" ");
// ALL mode
if (reqMode.equalsIgnoreCase("ALL") && numberMet == reqList.size()) return true;
// ANY # mode
else if (ModeArgs[0].equalsIgnoreCase("ANY")) {
if (ModeArgs.length == 1) {
if (numberMet >= 1) return true;
else return false;
} else {
if (numberMet >= Integer.parseInt(ModeArgs[1])) return true;
else return false;
}
}
// FIRST AND ANY # mode
else if (ModeArgs[0].equalsIgnoreCase("FIRST") && ModeArgs[3].matches("\\d+")) {
if (firstReqMet) {
if (numberMet > Integer.parseInt(ModeArgs[3])) return true;
else return false;
} else return false;
}
else if (!ModeArgs[0].equalsIgnoreCase("ALL")) dB.echoError("Invalid Requirement Mode!");
// Nothing met, return FALSE
return false;
}
}
| true | true | public boolean check(String scriptName, NPC npc, Player player) throws RequirementMissingException {
String reqMode = plugin.getScripts().getString(scriptName + ".REQUIREMENTS.MODE", "NONE");
List<String> reqList = plugin.getScripts().getStringList(scriptName + ".REQUIREMENTS.LIST");
dB.echoDebug(ChatColor.YELLOW + "CHECK! Now checking '%s'", scriptName);
// No requirements met yet, we just started!
int numberMet = 0;
boolean negativeRequirement;
// Requirements list null? This script is probably named wrong, or doesn't exist!
if (reqList.isEmpty() && !reqMode.equals("NONE")) {
dB.echoError("Non-valid requirements structure at:");
dB.echoDebug(ChatColor.GRAY + scriptName + ":");
dB.echoDebug(ChatColor.GRAY + " Requirements:");
dB.echoDebug(ChatColor.GRAY + " Mode: ???");
dB.echoDebug(ChatColor.GRAY + " List:");
dB.echoDebug(ChatColor.GRAY + " - ???");
dB.echoDebug("* Check spacing, validate structure and spelling.");
return false;
}
// Requirement node "NONE"? No requirements in the LIST? No need to continue, return TRUE
if (reqMode.equals("NONE") || reqList.isEmpty()) return true;
dB.echoDebug("Requirement mode: '%s'", reqMode.toUpperCase());
// Set up checks for requirement mode 'FIRST AND ANY #'
boolean firstReqMet = false;
boolean firstReqChecked = false;
// Check all requirements
for (String reqEntry : reqList) {
// Check if this is a Negative Requirement
if (reqEntry.startsWith("-")) {
negativeRequirement = true;
reqEntry = reqEntry.substring(1);
} else negativeRequirement = false;
// Check requirement with RequirementRegistry
if (plugin.getRequirementRegistry().list().containsKey(reqEntry.split(" ")[0])) {
AbstractRequirement requirement = plugin.getRequirementRegistry().get(reqEntry.split(" ")[0]);
String[] arguments = null;
if (reqEntry.split(" ").length > 1) arguments = plugin.getScriptEngine().getScriptBuilder().buildArgs(reqEntry.split(" ", 2)[1]);
// Replace tags
List<String> argumentList = new ArrayList<String>();
if (arguments != null) argumentList = plugin.tagManager().fillArguments(arguments, player, plugin.getNPCRegistry().getDenizen(npc));
try {
// Check if # of required args are met
if ((arguments == null && requirement.requirementOptions.REQUIRED_ARGS > 0) ||
arguments.length < requirement.requirementOptions.REQUIRED_ARGS) throw new RequirementCheckException("");
// Check the Requirement
if (requirement.check(player, plugin.getNPCRegistry().getDenizen(npc), scriptName, argumentList) != negativeRequirement) {
// Check first requirement for mode 'FIRST AND ANY #'
if (!firstReqChecked) {
firstReqMet = true;
firstReqChecked = true;
}
numberMet++;
dB.echoApproval("Checking Requirement '" + requirement.getName() + "'" + " ...requirement met!");
} else {
if (!firstReqChecked) {
firstReqMet = false;
firstReqChecked = true;
}
dB.echoApproval("Checking Requirement '" + requirement.getName() + "'" + " ...requirement not met!");
}
} catch (Throwable e) {
if (e instanceof RequirementCheckException) {
dB.echoError("Woah! Invalid arguments were specified!");
dB.echoError("Usage: " + requirement.getUsageHint());
} else {
dB.echoError("Woah! An exception has been called for Requirement '" + requirement.getName() + "'!");
if (!dB.showStackTraces) dB.echoError("Enable '/denizen stacktrace' for the nitty-gritty.");
else e.printStackTrace();
}
}
}
// If the requirement is not registered with the Requirement Registry
else {
dB.echoError("Requirement '" + reqEntry.split(" ")[0] + "' not found! Check that the requirement is installed!");
}
}
// Check numberMet with mode...
String[] ModeArgs = reqMode.split(" ");
// ALL mode
if (reqMode.equalsIgnoreCase("ALL") && numberMet == reqList.size()) return true;
// ANY # mode
else if (ModeArgs[0].equalsIgnoreCase("ANY")) {
if (ModeArgs.length == 1) {
if (numberMet >= 1) return true;
else return false;
} else {
if (numberMet >= Integer.parseInt(ModeArgs[1])) return true;
else return false;
}
}
// FIRST AND ANY # mode
else if (ModeArgs[0].equalsIgnoreCase("FIRST") && ModeArgs[3].matches("\\d+")) {
if (firstReqMet) {
if (numberMet > Integer.parseInt(ModeArgs[3])) return true;
else return false;
} else return false;
}
else if (!ModeArgs[0].equalsIgnoreCase("ALL")) dB.echoError("Invalid Requirement Mode!");
// Nothing met, return FALSE
return false;
}
| public boolean check(String scriptName, NPC npc, Player player) throws RequirementMissingException {
String reqMode = plugin.getScripts().getString(scriptName + ".REQUIREMENTS.MODE", "NONE");
List<String> reqList = plugin.getScripts().getStringList(scriptName + ".REQUIREMENTS.LIST");
dB.echoDebug(ChatColor.YELLOW + "CHECK! Now checking '%s'", scriptName);
// No requirements met yet, we just started!
int numberMet = 0;
boolean negativeRequirement;
// Requirements list null? This script is probably named wrong, or doesn't exist!
if (reqList.isEmpty() && !reqMode.equalsIgnoreCase("NONE")) {
dB.echoError("Non-valid requirements structure at:");
dB.echoDebug(ChatColor.GRAY + scriptName + ":");
dB.echoDebug(ChatColor.GRAY + " Requirements:");
dB.echoDebug(ChatColor.GRAY + " Mode: ???");
dB.echoDebug(ChatColor.GRAY + " List:");
dB.echoDebug(ChatColor.GRAY + " - ???");
dB.echoDebug("* Check spacing, validate structure and spelling.");
return false;
}
// Requirement node "NONE"? No requirements in the LIST? No need to continue, return TRUE
if (reqMode.equals("NONE") || reqList.isEmpty()) return true;
dB.echoDebug("Requirement mode: '%s'", reqMode.toUpperCase());
// Set up checks for requirement mode 'FIRST AND ANY #'
boolean firstReqMet = false;
boolean firstReqChecked = false;
// Check all requirements
for (String reqEntry : reqList) {
// Check if this is a Negative Requirement
if (reqEntry.startsWith("-")) {
negativeRequirement = true;
reqEntry = reqEntry.substring(1);
} else negativeRequirement = false;
// Check requirement with RequirementRegistry
if (plugin.getRequirementRegistry().list().containsKey(reqEntry.split(" ")[0])) {
AbstractRequirement requirement = plugin.getRequirementRegistry().get(reqEntry.split(" ")[0]);
String[] arguments = null;
if (reqEntry.split(" ").length > 1) arguments = plugin.getScriptEngine().getScriptBuilder().buildArgs(reqEntry.split(" ", 2)[1]);
// Replace tags
List<String> argumentList = new ArrayList<String>();
if (arguments != null) argumentList = plugin.tagManager().fillArguments(arguments, player, plugin.getNPCRegistry().getDenizen(npc));
try {
// Check if # of required args are met
if ((arguments == null && requirement.requirementOptions.REQUIRED_ARGS > 0) ||
arguments.length < requirement.requirementOptions.REQUIRED_ARGS) throw new RequirementCheckException("");
// Check the Requirement
if (requirement.check(player, plugin.getNPCRegistry().getDenizen(npc), scriptName, argumentList) != negativeRequirement) {
// Check first requirement for mode 'FIRST AND ANY #'
if (!firstReqChecked) {
firstReqMet = true;
firstReqChecked = true;
}
numberMet++;
dB.echoApproval("Checking Requirement '" + requirement.getName() + "'" + " ...requirement met!");
} else {
if (!firstReqChecked) {
firstReqMet = false;
firstReqChecked = true;
}
dB.echoApproval("Checking Requirement '" + requirement.getName() + "'" + " ...requirement not met!");
}
} catch (Throwable e) {
if (e instanceof RequirementCheckException) {
dB.echoError("Woah! Invalid arguments were specified!");
dB.echoError("Usage: " + requirement.getUsageHint());
} else {
dB.echoError("Woah! An exception has been called for Requirement '" + requirement.getName() + "'!");
if (!dB.showStackTraces) dB.echoError("Enable '/denizen stacktrace' for the nitty-gritty.");
else e.printStackTrace();
}
}
}
// If the requirement is not registered with the Requirement Registry
else {
dB.echoError("Requirement '" + reqEntry.split(" ")[0] + "' not found! Check that the requirement is installed!");
}
}
// Check numberMet with mode...
String[] ModeArgs = reqMode.split(" ");
// ALL mode
if (reqMode.equalsIgnoreCase("ALL") && numberMet == reqList.size()) return true;
// ANY # mode
else if (ModeArgs[0].equalsIgnoreCase("ANY")) {
if (ModeArgs.length == 1) {
if (numberMet >= 1) return true;
else return false;
} else {
if (numberMet >= Integer.parseInt(ModeArgs[1])) return true;
else return false;
}
}
// FIRST AND ANY # mode
else if (ModeArgs[0].equalsIgnoreCase("FIRST") && ModeArgs[3].matches("\\d+")) {
if (firstReqMet) {
if (numberMet > Integer.parseInt(ModeArgs[3])) return true;
else return false;
} else return false;
}
else if (!ModeArgs[0].equalsIgnoreCase("ALL")) dB.echoError("Invalid Requirement Mode!");
// Nothing met, return FALSE
return false;
}
|
diff --git a/src/main/java/com/github/ucchyocean/ct/DelayedTeleportTask.java b/src/main/java/com/github/ucchyocean/ct/DelayedTeleportTask.java
index fb64b83..fcd0cab 100644
--- a/src/main/java/com/github/ucchyocean/ct/DelayedTeleportTask.java
+++ b/src/main/java/com/github/ucchyocean/ct/DelayedTeleportTask.java
@@ -1,88 +1,89 @@
/*
* @author ucchy
* @license LGPLv3
* @copyright Copyright ucchy 2013
*/
package com.github.ucchyocean.ct;
import java.util.HashMap;
import java.util.concurrent.ArrayBlockingQueue;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
/**
* 遅延つきテレポート実行タスク
* @author ucchy
*/
public class DelayedTeleportTask extends BukkitRunnable {
private HashMap<Player, Location> locationMap;
private ArrayBlockingQueue<Player> players;
private int delay;
private BukkitTask task;
/**
* コンストラクタ
* @param locationMap
* @param delay
*/
public DelayedTeleportTask(HashMap<Player, Location> locationMap, int delay) {
this.locationMap = locationMap;
this.delay = delay;
players = new ArrayBlockingQueue<Player>(locationMap.size());
for ( Player p : locationMap.keySet() ) {
players.add(p);
}
}
/**
* タスクを開始する
*/
public void startTask() {
task = Bukkit.getScheduler().runTaskTimer(ColorTeaming.instance, this, delay, delay);
}
/**
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
if ( players.isEmpty() ) {
// プレイヤー表示パケットを送信する (see issue #78)
int packetDelay =
ColorTeaming.instance.getCTConfig().getTeleportVisiblePacketSendDelay();
if ( packetDelay > 0 ) {
Bukkit.getScheduler().runTaskLater(ColorTeaming.instance, new BukkitRunnable() {
public void run() {
for ( Player playerA : locationMap.keySet() ) {
for ( Player playerB : locationMap.keySet() ) {
+ playerA.hidePlayer(playerB);
playerA.showPlayer(playerB);
}
}
}
}, packetDelay);
}
// 自己キャンセル
if ( task != null ) {
Bukkit.getScheduler().cancelTask(task.getTaskId());
}
return;
}
Player player = players.poll();
Location location = locationMap.get(player);
if ( player != null && location != null ) {
player.teleport(location, TeleportCause.PLUGIN);
}
}
}
| true | true | public void run() {
if ( players.isEmpty() ) {
// プレイヤー表示パケットを送信する (see issue #78)
int packetDelay =
ColorTeaming.instance.getCTConfig().getTeleportVisiblePacketSendDelay();
if ( packetDelay > 0 ) {
Bukkit.getScheduler().runTaskLater(ColorTeaming.instance, new BukkitRunnable() {
public void run() {
for ( Player playerA : locationMap.keySet() ) {
for ( Player playerB : locationMap.keySet() ) {
playerA.showPlayer(playerB);
}
}
}
}, packetDelay);
}
// 自己キャンセル
if ( task != null ) {
Bukkit.getScheduler().cancelTask(task.getTaskId());
}
return;
}
Player player = players.poll();
Location location = locationMap.get(player);
if ( player != null && location != null ) {
player.teleport(location, TeleportCause.PLUGIN);
}
}
| public void run() {
if ( players.isEmpty() ) {
// プレイヤー表示パケットを送信する (see issue #78)
int packetDelay =
ColorTeaming.instance.getCTConfig().getTeleportVisiblePacketSendDelay();
if ( packetDelay > 0 ) {
Bukkit.getScheduler().runTaskLater(ColorTeaming.instance, new BukkitRunnable() {
public void run() {
for ( Player playerA : locationMap.keySet() ) {
for ( Player playerB : locationMap.keySet() ) {
playerA.hidePlayer(playerB);
playerA.showPlayer(playerB);
}
}
}
}, packetDelay);
}
// 自己キャンセル
if ( task != null ) {
Bukkit.getScheduler().cancelTask(task.getTaskId());
}
return;
}
Player player = players.poll();
Location location = locationMap.get(player);
if ( player != null && location != null ) {
player.teleport(location, TeleportCause.PLUGIN);
}
}
|
diff --git a/broadcast-transcoder-commandline/src/main/java/dk/statsbiblioteket/broadcasttranscoder/cli/parsers/SingleTranscodingOptionsParser.java b/broadcast-transcoder-commandline/src/main/java/dk/statsbiblioteket/broadcasttranscoder/cli/parsers/SingleTranscodingOptionsParser.java
index a5d1581..e00ffe8 100644
--- a/broadcast-transcoder-commandline/src/main/java/dk/statsbiblioteket/broadcasttranscoder/cli/parsers/SingleTranscodingOptionsParser.java
+++ b/broadcast-transcoder-commandline/src/main/java/dk/statsbiblioteket/broadcasttranscoder/cli/parsers/SingleTranscodingOptionsParser.java
@@ -1,150 +1,151 @@
package dk.statsbiblioteket.broadcasttranscoder.cli.parsers;
import dk.statsbiblioteket.broadcasttranscoder.cli.OptionParseException;
import dk.statsbiblioteket.broadcasttranscoder.cli.SingleTranscodingContext;
import dk.statsbiblioteket.broadcasttranscoder.cli.UsageException;
import dk.statsbiblioteket.broadcasttranscoder.persistence.entities.TranscodingRecord;
import org.apache.commons.cli.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import static dk.statsbiblioteket.broadcasttranscoder.cli.PropertyNames.*;
/**
*
*/
public class SingleTranscodingOptionsParser<T extends TranscodingRecord> extends InfrastructureOptionsParser<T> {
protected static final Option PID_OPTION = new Option("programpid", true, "The DOMS pid of the program to be transcoded");
protected static final Option TIMESTAMP_OPTION = new Option("timestamp", true, "The timestamp (milliseconds) for which transcoding is required");
protected static final Option BEHAVIOURAL_CONFIG_FILE_OPTION = new Option("behavioural_configfile", true, "The behavioural config file");
private SingleTranscodingContext<T> context;
public SingleTranscodingOptionsParser() {
super();
context = new SingleTranscodingContext<T>();
getOptions().addOption(PID_OPTION);
getOptions().addOption(TIMESTAMP_OPTION);
getOptions().addOption(BEHAVIOURAL_CONFIG_FILE_OPTION);
}
public SingleTranscodingContext<T> parseOptions(String[] args) throws OptionParseException, UsageException {
CommandLineParser parser = new PosixParser();
CommandLine cmd;
try {
cmd = parser.parse(getOptions(), args);
} catch (ParseException e) {
parseError(e.toString());
throw new OptionParseException(e.getMessage(), e);
}
parseUsageOption(cmd);
parseInfrastructureConfigFileOption(cmd);
parseBehaviouralConfigFileOption(cmd);
parseHibernateConfigFileOption(cmd);
parseProgramPid(cmd);
parseTimestampOption(cmd);
try {
readInfrastructureProperties(context);
readBehaviouralProperties(context);
} catch (IOException e) {
throw new OptionParseException("Error reading properties.", e);
}
return context;
}
protected static void readBehaviouralProperties(SingleTranscodingContext context) throws IOException, OptionParseException {
Properties props = new Properties();
props.load(new FileInputStream(context.getBehaviourConfigFile()));
context.setVideoBitrate(readIntegerProperty(VIDEO_BITRATE, props));
context.setAudioBitrate(readIntegerProperty(AUDIO_BITRATE, props));
context.setVideoHeight(readIntegerProperty(HEIGHT, props));
context.setVlcTranscodingString(readStringProperty(VLC_TRANSCODING_STRING, props));
context.setFfmpegTranscodingString(readStringProperty(FFMPEG_TRANSCODING_STRING, props));
context.setTranscodingTimeoutDivisor(readFloatProperty(TRANSCODING_DIVISOR, props));
context.setAnalysisClipLength(readLongProperty(ANALYSIS_CLIP_LENGTH, props));
context.setStartOffsetTS(readIntegerProperty(START_OFFSET_TS, props));
context.setEndOffsetTS(readIntegerProperty(END_OFFSET_TS, props));
context.setStartOffsetTSWithTVMeter(readIntegerProperty(START_OFFSET_TS_WITH_TVMETER, props));
context.setEndOffsetTSWithTVMeter(readIntegerProperty(END_OFFSET_TS_WITH_TVMETER, props));
context.setStartOffsetPS(readIntegerProperty(START_OFFSET_PS, props));
context.setEndOffsetPS(readIntegerProperty(END_OFFSET_PS, props));
context.setStartOffsetPSWithTVMeter(readIntegerProperty(START_OFFSET_PS_WITH_TVMETER, props));
context.setEndOffsetPSWithTVMeter(readIntegerProperty(END_OFFSET_PS_WITH_TVMETER, props));
context.setStartOffsetWAV(readIntegerProperty(START_OFFSET_WAV, props));
context.setEndOffsetWAV(readIntegerProperty(END_OFFSET_WAV, props));
context.setMaxMissingStart(readIntegerProperty(MAX_MISSING_START, props));
context.setMaxMissingEnd(readIntegerProperty(MAX_MISSING_END, props));
context.setMaxHole(readIntegerProperty(MAX_HOLE_SIZE, props));
context.setGapToleranceSeconds(readIntegerProperty(GAP_TOLERANCE, props));
context.setPreviewLength(readIntegerProperty(PREVIEW_LENGTH, props));
context.setPreviewTimeout(readIntegerProperty(PREVIEW_TIMEOUT, props));
context.setSnapshotFrames(readIntegerProperty(SNAPSHOT_FRAMES, props));
context.setSnapshotPaddingSeconds(readIntegerProperty(SNAPSHOT_PADDING, props));
context.setSnapshotScale(readIntegerProperty(SNAPSHOT_SCALE, props));
context.setSnapshotTargetDenominator(readIntegerProperty(SNAPSHOT_TARGET_DENOMINATIOR, props));
context.setSnapshotTargetNumerator(readIntegerProperty(SNAPSHOT_TARGET_NUMERATOR, props));
context.setSnapshotTimeoutDivisor(readFloatProperty(SNAPSHOT_TIMEOUT_DIVISOR, props));
context.setSoxTranscodeParams(readStringProperty(SOX_TRANSCODE_PARAMS, props));
context.setDefaultTranscodingTimestamp(readLongProperty(DEFAULT_TIMESTAMP, props));
context.setOverwrite(readBooleanProperty(OVERWRITE,props));
context.setOnlyTranscodeChanges(readBooleanProperty(ONLYTRANSCODECHANGES, props));
context.setVideoOutputSuffix(readStringProperty(VIDEO_OUTPUT_SUFFIX, props));
context.setVlcRemuxingString(readStringProperty(VLC_REMUXING_STRING, props));
+ context.setDomsViewAngle(readStringProperty(DOMS_VIEWANGLE, props));
}
protected void parseBehaviouralConfigFileOption(CommandLine cmd) throws OptionParseException {
String configFileString = cmd.getOptionValue(BEHAVIOURAL_CONFIG_FILE_OPTION.getOpt());
if (configFileString == null) {
parseError(BEHAVIOURAL_CONFIG_FILE_OPTION.toString());
throw new OptionParseException(BEHAVIOURAL_CONFIG_FILE_OPTION.toString());
}
File configFile = new File(configFileString);
if (!configFile.exists() || configFile.isDirectory()) {
throw new OptionParseException(configFile.getAbsolutePath() + " is not a file.");
}
context.setBehaviourConfigFile(configFile);
}
@Override
protected SingleTranscodingContext<T> getContext() {
return context;
}
protected void parseProgramPid(CommandLine cmd) throws OptionParseException {
String programPid = cmd.getOptionValue(PID_OPTION.getOpt());
if (programPid == null) {
parseError(PID_OPTION.toString());
throw new OptionParseException(PID_OPTION.toString());
} else {
context.setProgrampid(programPid);
}
}
protected void parseTimestampOption(CommandLine cmd) throws OptionParseException {
String timestampString = cmd.getOptionValue(TIMESTAMP_OPTION.getOpt());
if (timestampString == null) {
parseError(TIMESTAMP_OPTION.toString());
throw new OptionParseException(TIMESTAMP_OPTION.toString());
} else {
context.setTranscodingTimestamp(Long.parseLong(timestampString));
}
}
}
| true | true | protected static void readBehaviouralProperties(SingleTranscodingContext context) throws IOException, OptionParseException {
Properties props = new Properties();
props.load(new FileInputStream(context.getBehaviourConfigFile()));
context.setVideoBitrate(readIntegerProperty(VIDEO_BITRATE, props));
context.setAudioBitrate(readIntegerProperty(AUDIO_BITRATE, props));
context.setVideoHeight(readIntegerProperty(HEIGHT, props));
context.setVlcTranscodingString(readStringProperty(VLC_TRANSCODING_STRING, props));
context.setFfmpegTranscodingString(readStringProperty(FFMPEG_TRANSCODING_STRING, props));
context.setTranscodingTimeoutDivisor(readFloatProperty(TRANSCODING_DIVISOR, props));
context.setAnalysisClipLength(readLongProperty(ANALYSIS_CLIP_LENGTH, props));
context.setStartOffsetTS(readIntegerProperty(START_OFFSET_TS, props));
context.setEndOffsetTS(readIntegerProperty(END_OFFSET_TS, props));
context.setStartOffsetTSWithTVMeter(readIntegerProperty(START_OFFSET_TS_WITH_TVMETER, props));
context.setEndOffsetTSWithTVMeter(readIntegerProperty(END_OFFSET_TS_WITH_TVMETER, props));
context.setStartOffsetPS(readIntegerProperty(START_OFFSET_PS, props));
context.setEndOffsetPS(readIntegerProperty(END_OFFSET_PS, props));
context.setStartOffsetPSWithTVMeter(readIntegerProperty(START_OFFSET_PS_WITH_TVMETER, props));
context.setEndOffsetPSWithTVMeter(readIntegerProperty(END_OFFSET_PS_WITH_TVMETER, props));
context.setStartOffsetWAV(readIntegerProperty(START_OFFSET_WAV, props));
context.setEndOffsetWAV(readIntegerProperty(END_OFFSET_WAV, props));
context.setMaxMissingStart(readIntegerProperty(MAX_MISSING_START, props));
context.setMaxMissingEnd(readIntegerProperty(MAX_MISSING_END, props));
context.setMaxHole(readIntegerProperty(MAX_HOLE_SIZE, props));
context.setGapToleranceSeconds(readIntegerProperty(GAP_TOLERANCE, props));
context.setPreviewLength(readIntegerProperty(PREVIEW_LENGTH, props));
context.setPreviewTimeout(readIntegerProperty(PREVIEW_TIMEOUT, props));
context.setSnapshotFrames(readIntegerProperty(SNAPSHOT_FRAMES, props));
context.setSnapshotPaddingSeconds(readIntegerProperty(SNAPSHOT_PADDING, props));
context.setSnapshotScale(readIntegerProperty(SNAPSHOT_SCALE, props));
context.setSnapshotTargetDenominator(readIntegerProperty(SNAPSHOT_TARGET_DENOMINATIOR, props));
context.setSnapshotTargetNumerator(readIntegerProperty(SNAPSHOT_TARGET_NUMERATOR, props));
context.setSnapshotTimeoutDivisor(readFloatProperty(SNAPSHOT_TIMEOUT_DIVISOR, props));
context.setSoxTranscodeParams(readStringProperty(SOX_TRANSCODE_PARAMS, props));
context.setDefaultTranscodingTimestamp(readLongProperty(DEFAULT_TIMESTAMP, props));
context.setOverwrite(readBooleanProperty(OVERWRITE,props));
context.setOnlyTranscodeChanges(readBooleanProperty(ONLYTRANSCODECHANGES, props));
context.setVideoOutputSuffix(readStringProperty(VIDEO_OUTPUT_SUFFIX, props));
context.setVlcRemuxingString(readStringProperty(VLC_REMUXING_STRING, props));
}
| protected static void readBehaviouralProperties(SingleTranscodingContext context) throws IOException, OptionParseException {
Properties props = new Properties();
props.load(new FileInputStream(context.getBehaviourConfigFile()));
context.setVideoBitrate(readIntegerProperty(VIDEO_BITRATE, props));
context.setAudioBitrate(readIntegerProperty(AUDIO_BITRATE, props));
context.setVideoHeight(readIntegerProperty(HEIGHT, props));
context.setVlcTranscodingString(readStringProperty(VLC_TRANSCODING_STRING, props));
context.setFfmpegTranscodingString(readStringProperty(FFMPEG_TRANSCODING_STRING, props));
context.setTranscodingTimeoutDivisor(readFloatProperty(TRANSCODING_DIVISOR, props));
context.setAnalysisClipLength(readLongProperty(ANALYSIS_CLIP_LENGTH, props));
context.setStartOffsetTS(readIntegerProperty(START_OFFSET_TS, props));
context.setEndOffsetTS(readIntegerProperty(END_OFFSET_TS, props));
context.setStartOffsetTSWithTVMeter(readIntegerProperty(START_OFFSET_TS_WITH_TVMETER, props));
context.setEndOffsetTSWithTVMeter(readIntegerProperty(END_OFFSET_TS_WITH_TVMETER, props));
context.setStartOffsetPS(readIntegerProperty(START_OFFSET_PS, props));
context.setEndOffsetPS(readIntegerProperty(END_OFFSET_PS, props));
context.setStartOffsetPSWithTVMeter(readIntegerProperty(START_OFFSET_PS_WITH_TVMETER, props));
context.setEndOffsetPSWithTVMeter(readIntegerProperty(END_OFFSET_PS_WITH_TVMETER, props));
context.setStartOffsetWAV(readIntegerProperty(START_OFFSET_WAV, props));
context.setEndOffsetWAV(readIntegerProperty(END_OFFSET_WAV, props));
context.setMaxMissingStart(readIntegerProperty(MAX_MISSING_START, props));
context.setMaxMissingEnd(readIntegerProperty(MAX_MISSING_END, props));
context.setMaxHole(readIntegerProperty(MAX_HOLE_SIZE, props));
context.setGapToleranceSeconds(readIntegerProperty(GAP_TOLERANCE, props));
context.setPreviewLength(readIntegerProperty(PREVIEW_LENGTH, props));
context.setPreviewTimeout(readIntegerProperty(PREVIEW_TIMEOUT, props));
context.setSnapshotFrames(readIntegerProperty(SNAPSHOT_FRAMES, props));
context.setSnapshotPaddingSeconds(readIntegerProperty(SNAPSHOT_PADDING, props));
context.setSnapshotScale(readIntegerProperty(SNAPSHOT_SCALE, props));
context.setSnapshotTargetDenominator(readIntegerProperty(SNAPSHOT_TARGET_DENOMINATIOR, props));
context.setSnapshotTargetNumerator(readIntegerProperty(SNAPSHOT_TARGET_NUMERATOR, props));
context.setSnapshotTimeoutDivisor(readFloatProperty(SNAPSHOT_TIMEOUT_DIVISOR, props));
context.setSoxTranscodeParams(readStringProperty(SOX_TRANSCODE_PARAMS, props));
context.setDefaultTranscodingTimestamp(readLongProperty(DEFAULT_TIMESTAMP, props));
context.setOverwrite(readBooleanProperty(OVERWRITE,props));
context.setOnlyTranscodeChanges(readBooleanProperty(ONLYTRANSCODECHANGES, props));
context.setVideoOutputSuffix(readStringProperty(VIDEO_OUTPUT_SUFFIX, props));
context.setVlcRemuxingString(readStringProperty(VLC_REMUXING_STRING, props));
context.setDomsViewAngle(readStringProperty(DOMS_VIEWANGLE, props));
}
|
diff --git a/src/core/org/luaj/vm/LThread.java b/src/core/org/luaj/vm/LThread.java
index 4b56cbb..2b3ddae 100644
--- a/src/core/org/luaj/vm/LThread.java
+++ b/src/core/org/luaj/vm/LThread.java
@@ -1,168 +1,169 @@
/*******************************************************************************
* Copyright (c) 2007 LuaJ. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package org.luaj.vm;
/**
* Implementation of lua coroutines using Java Threads
*/
public class LThread extends LValue implements Runnable {
private static final int STATUS_SUSPENDED = 0;
private static final int STATUS_RUNNING = 1;
private static final int STATUS_NORMAL = 2;
private static final int STATUS_DEAD = 3;
private static final String[] NAMES = {
"suspended",
"running",
"normal",
"dead" };
private int status = STATUS_SUSPENDED;
LuaState threadVm;
Thread thread;
static LThread running;
public LThread(LFunction c, LTable env) {
threadVm = new LuaState(env);
threadVm.pushlvalue(c);
}
public int luaGetType() {
return Lua.LUA_TTHREAD;
}
public String toJavaString() {
return "thread: "+hashCode();
}
/** Set the environment if a thread, or closure, and return 1, otherwise return 0 */
public boolean luaSetEnv(LTable t) {
threadVm._G = t;
return true;
}
public String getStatus() {
return NAMES[status];
}
public static LThread getRunning() {
return running;
}
public void run() {
synchronized ( this ) {
try {
threadVm.execute();
} finally {
status = STATUS_DEAD;
this.notify();
}
}
}
public boolean yield() {
synchronized ( this ) {
if ( status != STATUS_RUNNING )
threadVm.error(this+" not running");
status = STATUS_SUSPENDED;
this.notify();
try {
this.wait();
status = STATUS_RUNNING;
} catch ( InterruptedException e ) {
status = STATUS_DEAD;
threadVm.error(this+" "+e);
}
return false;
}
}
/** This needs to leave any values returned by yield in the coroutine
* on the calling vm stack
* @param vm
* @param nargs
*/
public void resumeFrom(LuaState vm, int nargs) {
synchronized ( this ) {
if ( status == STATUS_DEAD ) {
vm.resettop();
vm.pushboolean(false);
vm.pushstring("cannot resume dead coroutine");
return;
}
// set prior thread to normal status while we are running
LThread prior = running;
try {
// set our status to running
if ( prior != null )
prior.status = STATUS_NORMAL;
running = this;
status = STATUS_RUNNING;
// copy args in
if ( thread == null ) {
vm.xmove(threadVm, nargs);
threadVm.prepStackCall();
thread = new Thread(this);
thread.start();
} else {
threadVm.resettop();
vm.xmove(threadVm, nargs);
}
// run this vm until it yields
this.notify();
this.wait();
// copy return values from yielding stack state
vm.resettop();
- vm.pushboolean(true);
if ( threadVm.cc >= 0 ) {
+ vm.pushboolean(status != STATUS_DEAD);
threadVm.xmove(vm, threadVm.gettop() - 1);
} else {
+ vm.pushboolean(true);
threadVm.base = 0;
threadVm.xmove(vm, threadVm.gettop());
}
} catch ( Throwable t ) {
status = STATUS_DEAD;
vm.resettop();
vm.pushboolean(false);
vm.pushstring("thread: "+t);
this.notify();
} finally {
// previous thread is now running again
running = prior;
}
}
}
}
| false | true | public void resumeFrom(LuaState vm, int nargs) {
synchronized ( this ) {
if ( status == STATUS_DEAD ) {
vm.resettop();
vm.pushboolean(false);
vm.pushstring("cannot resume dead coroutine");
return;
}
// set prior thread to normal status while we are running
LThread prior = running;
try {
// set our status to running
if ( prior != null )
prior.status = STATUS_NORMAL;
running = this;
status = STATUS_RUNNING;
// copy args in
if ( thread == null ) {
vm.xmove(threadVm, nargs);
threadVm.prepStackCall();
thread = new Thread(this);
thread.start();
} else {
threadVm.resettop();
vm.xmove(threadVm, nargs);
}
// run this vm until it yields
this.notify();
this.wait();
// copy return values from yielding stack state
vm.resettop();
vm.pushboolean(true);
if ( threadVm.cc >= 0 ) {
threadVm.xmove(vm, threadVm.gettop() - 1);
} else {
threadVm.base = 0;
threadVm.xmove(vm, threadVm.gettop());
}
} catch ( Throwable t ) {
status = STATUS_DEAD;
vm.resettop();
vm.pushboolean(false);
vm.pushstring("thread: "+t);
this.notify();
} finally {
// previous thread is now running again
running = prior;
}
}
}
| public void resumeFrom(LuaState vm, int nargs) {
synchronized ( this ) {
if ( status == STATUS_DEAD ) {
vm.resettop();
vm.pushboolean(false);
vm.pushstring("cannot resume dead coroutine");
return;
}
// set prior thread to normal status while we are running
LThread prior = running;
try {
// set our status to running
if ( prior != null )
prior.status = STATUS_NORMAL;
running = this;
status = STATUS_RUNNING;
// copy args in
if ( thread == null ) {
vm.xmove(threadVm, nargs);
threadVm.prepStackCall();
thread = new Thread(this);
thread.start();
} else {
threadVm.resettop();
vm.xmove(threadVm, nargs);
}
// run this vm until it yields
this.notify();
this.wait();
// copy return values from yielding stack state
vm.resettop();
if ( threadVm.cc >= 0 ) {
vm.pushboolean(status != STATUS_DEAD);
threadVm.xmove(vm, threadVm.gettop() - 1);
} else {
vm.pushboolean(true);
threadVm.base = 0;
threadVm.xmove(vm, threadVm.gettop());
}
} catch ( Throwable t ) {
status = STATUS_DEAD;
vm.resettop();
vm.pushboolean(false);
vm.pushstring("thread: "+t);
this.notify();
} finally {
// previous thread is now running again
running = prior;
}
}
}
|
diff --git a/src/main/java/org/spout/vanilla/protocol/handler/PlayerDiggingMessageHandler.java b/src/main/java/org/spout/vanilla/protocol/handler/PlayerDiggingMessageHandler.java
index 72b46800..55b9d612 100644
--- a/src/main/java/org/spout/vanilla/protocol/handler/PlayerDiggingMessageHandler.java
+++ b/src/main/java/org/spout/vanilla/protocol/handler/PlayerDiggingMessageHandler.java
@@ -1,192 +1,192 @@
/*
* This file is part of Vanilla.
*
* Copyright (c) 2011-2012, VanillaDev <http://www.spout.org/>
* Vanilla is licensed under the SpoutDev License Version 1.
*
* Vanilla 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.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* Vanilla 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,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.vanilla.protocol.handler;
import java.util.Collection;
import org.spout.api.Spout;
import org.spout.api.chat.style.ChatStyle;
import org.spout.api.event.player.PlayerInteractEvent;
import org.spout.api.event.player.PlayerInteractEvent.Action;
import org.spout.api.geo.Protection;
import org.spout.api.geo.World;
import org.spout.api.geo.cuboid.Block;
import org.spout.api.geo.discrete.Point;
import org.spout.api.inventory.ItemStack;
import org.spout.api.inventory.special.InventorySlot;
import org.spout.api.material.BlockMaterial;
import org.spout.api.material.basic.BasicAir;
import org.spout.api.material.block.BlockFace;
import org.spout.api.player.Player;
import org.spout.api.plugin.services.ProtectionService;
import org.spout.api.protocol.MessageHandler;
import org.spout.api.protocol.Session;
import org.spout.vanilla.controller.living.player.VanillaPlayer;
import org.spout.vanilla.data.ExhaustionLevel;
import org.spout.vanilla.data.effect.store.GeneralEffects;
import org.spout.vanilla.material.Mineable;
import org.spout.vanilla.material.VanillaMaterial;
import org.spout.vanilla.material.VanillaMaterials;
import org.spout.vanilla.material.item.Food;
import org.spout.vanilla.material.item.tool.Tool;
import org.spout.vanilla.protocol.msg.BlockChangeMessage;
import org.spout.vanilla.protocol.msg.PlayerDiggingMessage;
import org.spout.vanilla.util.VanillaPlayerUtil;
public final class PlayerDiggingMessageHandler extends MessageHandler<PlayerDiggingMessage> {
@Override
public void handleServer(Session session, PlayerDiggingMessage message) {
if(!session.hasPlayer()) {
return;
}
Player player = session.getPlayer();
int x = message.getX();
int y = message.getY();
int z = message.getZ();
int state = message.getState();
World w = player.getWorld();
Point point = new Point(w, x, y, z);
Block block = w.getBlock(point, player);
BlockMaterial blockMaterial = block.getMaterial();
short minecraftID = VanillaMaterials.getMinecraftId(blockMaterial);
BlockFace clickedFace = message.getFace();
VanillaPlayer vp = ((VanillaPlayer) player.getController());
//Don't block protections if dropping an item, silly Notch...
if (state != PlayerDiggingMessage.STATE_DROP_ITEM) {
Collection<Protection> protections = Spout.getEngine().getServiceManager().getRegistration(ProtectionService.class).getProvider().getAllProtections(point);
for (Protection p : protections) {
if (p.contains(point) && !vp.isOp()) {
player.getSession().send(false, new BlockChangeMessage(x, y, z, minecraftID, block.getData() & 0xF));
player.sendMessage(ChatStyle.DARK_RED, "This area is a protected spawn point!");
return;
}
}
}
if (state == PlayerDiggingMessage.STATE_DROP_ITEM && x == 0 && y == 0 && z == 0) {
((VanillaPlayer) player.getController()).dropItem();
return;
}
boolean isInteractable = true;
// FIXME: How so not interactable? I am pretty sure I can interact with water to place a boat, no?
if (blockMaterial == VanillaMaterials.AIR || blockMaterial == BasicAir.AIR || blockMaterial == VanillaMaterials.WATER || blockMaterial == VanillaMaterials.LAVA) {
isInteractable = false;
}
InventorySlot currentSlot = VanillaPlayerUtil.getCurrentSlot(player);
ItemStack heldItem = currentSlot.getItem();
if (state == PlayerDiggingMessage.STATE_START_DIGGING) {
PlayerInteractEvent event = new PlayerInteractEvent(player, block.getPosition(), heldItem, Action.LEFT_CLICK, isInteractable);
if (Spout.getEngine().getEventManager().callEvent(event).isCancelled()) {
return;
}
// Perform interactions
if (!isInteractable && heldItem == null) {
// interacting with nothing using fist
return;
} else if (heldItem == null) {
// interacting with block using fist
blockMaterial.onInteractBy(player, block, Action.LEFT_CLICK, clickedFace);
} else if (!isInteractable) {
// interacting with nothing using item
heldItem.getMaterial().onInteract(player, Action.LEFT_CLICK);
} else {
// interacting with block using item
heldItem.getMaterial().onInteract(player, block, Action.LEFT_CLICK, clickedFace);
blockMaterial.onInteractBy(player, block, Action.LEFT_CLICK, clickedFace);
}
// Interaction with controller
if (blockMaterial.hasController()) {
blockMaterial.getController(block).onInteract(player, Action.LEFT_CLICK);
}
if (isInteractable) {
Block neigh = block.translate(clickedFace);
boolean fire = neigh.getMaterial().equals(VanillaMaterials.FIRE);
if (fire) {
// put out fire
VanillaMaterials.FIRE.onDestroy(neigh);
GeneralEffects.RANDOM_FIZZ.playGlobal(block.getPosition());
} else if (vp.isSurvival() && blockMaterial.getHardness() != 0.0f) {
vp.startDigging(new Point(w, x, y, z));
} else {
// insta-break
blockMaterial.onDestroy(block);
GeneralEffects.BREAKBLOCK.playGlobal(block.getPosition(), blockMaterial, player);
}
}
} else if (state == PlayerDiggingMessage.STATE_DONE_DIGGING) {
if (!vp.stopDigging(new Point(w, x, y, z)) || !isInteractable) {
return;
}
if (VanillaPlayerUtil.isSurvival(player)) {
- ((VanillaPlayer) player).setExhaustion(((VanillaPlayer) player).getExhaustion() + ExhaustionLevel.BREAK_BLOCK.getAmount());
+ ((VanillaPlayer) player.getController()).setExhaustion(((VanillaPlayer) player.getController()).getExhaustion() + ExhaustionLevel.BREAK_BLOCK.getAmount());
}
long diggingTicks = vp.getDiggingTicks();
int damageDone;
int totalDamage;
if (heldItem != null) {
if (heldItem.getMaterial() instanceof Tool && blockMaterial instanceof Mineable) {
short penalty = ((Tool) heldItem.getMaterial()).getDurabilityPenalty((Mineable) blockMaterial, heldItem);
currentSlot.addItemData(penalty);
}
}
if (heldItem == null) {
damageDone = ((int) diggingTicks * 1);
} else {
damageDone = ((int) diggingTicks * ((VanillaMaterial) heldItem.getMaterial()).getDamage());
}
// TODO: Take into account EFFICIENCY enchantment
// TODO: Digging is slower while under water, on ladders, etc. AQUA_AFFINITY enchantment speeds up underwater digging
totalDamage = ((int) blockMaterial.getHardness() - damageDone);
if (totalDamage <= 40) { // Yes, this is a very high allowance - this is because this is only over a single block, and this will spike due to varying latency.
blockMaterial.onDestroy(block);
}
if (block.getMaterial() != VanillaMaterials.AIR) {
GeneralEffects.BREAKBLOCK.playGlobal(block.getPosition(), blockMaterial, player);
}
} else if (state == PlayerDiggingMessage.STATE_SHOOT_ARROW_EAT_FOOD) {
if (heldItem.getMaterial() instanceof Food) {
((Food) heldItem.getMaterial()).onEat(player, currentSlot);
}
}
}
}
| true | true | public void handleServer(Session session, PlayerDiggingMessage message) {
if(!session.hasPlayer()) {
return;
}
Player player = session.getPlayer();
int x = message.getX();
int y = message.getY();
int z = message.getZ();
int state = message.getState();
World w = player.getWorld();
Point point = new Point(w, x, y, z);
Block block = w.getBlock(point, player);
BlockMaterial blockMaterial = block.getMaterial();
short minecraftID = VanillaMaterials.getMinecraftId(blockMaterial);
BlockFace clickedFace = message.getFace();
VanillaPlayer vp = ((VanillaPlayer) player.getController());
//Don't block protections if dropping an item, silly Notch...
if (state != PlayerDiggingMessage.STATE_DROP_ITEM) {
Collection<Protection> protections = Spout.getEngine().getServiceManager().getRegistration(ProtectionService.class).getProvider().getAllProtections(point);
for (Protection p : protections) {
if (p.contains(point) && !vp.isOp()) {
player.getSession().send(false, new BlockChangeMessage(x, y, z, minecraftID, block.getData() & 0xF));
player.sendMessage(ChatStyle.DARK_RED, "This area is a protected spawn point!");
return;
}
}
}
if (state == PlayerDiggingMessage.STATE_DROP_ITEM && x == 0 && y == 0 && z == 0) {
((VanillaPlayer) player.getController()).dropItem();
return;
}
boolean isInteractable = true;
// FIXME: How so not interactable? I am pretty sure I can interact with water to place a boat, no?
if (blockMaterial == VanillaMaterials.AIR || blockMaterial == BasicAir.AIR || blockMaterial == VanillaMaterials.WATER || blockMaterial == VanillaMaterials.LAVA) {
isInteractable = false;
}
InventorySlot currentSlot = VanillaPlayerUtil.getCurrentSlot(player);
ItemStack heldItem = currentSlot.getItem();
if (state == PlayerDiggingMessage.STATE_START_DIGGING) {
PlayerInteractEvent event = new PlayerInteractEvent(player, block.getPosition(), heldItem, Action.LEFT_CLICK, isInteractable);
if (Spout.getEngine().getEventManager().callEvent(event).isCancelled()) {
return;
}
// Perform interactions
if (!isInteractable && heldItem == null) {
// interacting with nothing using fist
return;
} else if (heldItem == null) {
// interacting with block using fist
blockMaterial.onInteractBy(player, block, Action.LEFT_CLICK, clickedFace);
} else if (!isInteractable) {
// interacting with nothing using item
heldItem.getMaterial().onInteract(player, Action.LEFT_CLICK);
} else {
// interacting with block using item
heldItem.getMaterial().onInteract(player, block, Action.LEFT_CLICK, clickedFace);
blockMaterial.onInteractBy(player, block, Action.LEFT_CLICK, clickedFace);
}
// Interaction with controller
if (blockMaterial.hasController()) {
blockMaterial.getController(block).onInteract(player, Action.LEFT_CLICK);
}
if (isInteractable) {
Block neigh = block.translate(clickedFace);
boolean fire = neigh.getMaterial().equals(VanillaMaterials.FIRE);
if (fire) {
// put out fire
VanillaMaterials.FIRE.onDestroy(neigh);
GeneralEffects.RANDOM_FIZZ.playGlobal(block.getPosition());
} else if (vp.isSurvival() && blockMaterial.getHardness() != 0.0f) {
vp.startDigging(new Point(w, x, y, z));
} else {
// insta-break
blockMaterial.onDestroy(block);
GeneralEffects.BREAKBLOCK.playGlobal(block.getPosition(), blockMaterial, player);
}
}
} else if (state == PlayerDiggingMessage.STATE_DONE_DIGGING) {
if (!vp.stopDigging(new Point(w, x, y, z)) || !isInteractable) {
return;
}
if (VanillaPlayerUtil.isSurvival(player)) {
((VanillaPlayer) player).setExhaustion(((VanillaPlayer) player).getExhaustion() + ExhaustionLevel.BREAK_BLOCK.getAmount());
}
long diggingTicks = vp.getDiggingTicks();
int damageDone;
int totalDamage;
if (heldItem != null) {
if (heldItem.getMaterial() instanceof Tool && blockMaterial instanceof Mineable) {
short penalty = ((Tool) heldItem.getMaterial()).getDurabilityPenalty((Mineable) blockMaterial, heldItem);
currentSlot.addItemData(penalty);
}
}
if (heldItem == null) {
damageDone = ((int) diggingTicks * 1);
} else {
damageDone = ((int) diggingTicks * ((VanillaMaterial) heldItem.getMaterial()).getDamage());
}
// TODO: Take into account EFFICIENCY enchantment
// TODO: Digging is slower while under water, on ladders, etc. AQUA_AFFINITY enchantment speeds up underwater digging
totalDamage = ((int) blockMaterial.getHardness() - damageDone);
if (totalDamage <= 40) { // Yes, this is a very high allowance - this is because this is only over a single block, and this will spike due to varying latency.
blockMaterial.onDestroy(block);
}
if (block.getMaterial() != VanillaMaterials.AIR) {
GeneralEffects.BREAKBLOCK.playGlobal(block.getPosition(), blockMaterial, player);
}
} else if (state == PlayerDiggingMessage.STATE_SHOOT_ARROW_EAT_FOOD) {
if (heldItem.getMaterial() instanceof Food) {
((Food) heldItem.getMaterial()).onEat(player, currentSlot);
}
}
}
| public void handleServer(Session session, PlayerDiggingMessage message) {
if(!session.hasPlayer()) {
return;
}
Player player = session.getPlayer();
int x = message.getX();
int y = message.getY();
int z = message.getZ();
int state = message.getState();
World w = player.getWorld();
Point point = new Point(w, x, y, z);
Block block = w.getBlock(point, player);
BlockMaterial blockMaterial = block.getMaterial();
short minecraftID = VanillaMaterials.getMinecraftId(blockMaterial);
BlockFace clickedFace = message.getFace();
VanillaPlayer vp = ((VanillaPlayer) player.getController());
//Don't block protections if dropping an item, silly Notch...
if (state != PlayerDiggingMessage.STATE_DROP_ITEM) {
Collection<Protection> protections = Spout.getEngine().getServiceManager().getRegistration(ProtectionService.class).getProvider().getAllProtections(point);
for (Protection p : protections) {
if (p.contains(point) && !vp.isOp()) {
player.getSession().send(false, new BlockChangeMessage(x, y, z, minecraftID, block.getData() & 0xF));
player.sendMessage(ChatStyle.DARK_RED, "This area is a protected spawn point!");
return;
}
}
}
if (state == PlayerDiggingMessage.STATE_DROP_ITEM && x == 0 && y == 0 && z == 0) {
((VanillaPlayer) player.getController()).dropItem();
return;
}
boolean isInteractable = true;
// FIXME: How so not interactable? I am pretty sure I can interact with water to place a boat, no?
if (blockMaterial == VanillaMaterials.AIR || blockMaterial == BasicAir.AIR || blockMaterial == VanillaMaterials.WATER || blockMaterial == VanillaMaterials.LAVA) {
isInteractable = false;
}
InventorySlot currentSlot = VanillaPlayerUtil.getCurrentSlot(player);
ItemStack heldItem = currentSlot.getItem();
if (state == PlayerDiggingMessage.STATE_START_DIGGING) {
PlayerInteractEvent event = new PlayerInteractEvent(player, block.getPosition(), heldItem, Action.LEFT_CLICK, isInteractable);
if (Spout.getEngine().getEventManager().callEvent(event).isCancelled()) {
return;
}
// Perform interactions
if (!isInteractable && heldItem == null) {
// interacting with nothing using fist
return;
} else if (heldItem == null) {
// interacting with block using fist
blockMaterial.onInteractBy(player, block, Action.LEFT_CLICK, clickedFace);
} else if (!isInteractable) {
// interacting with nothing using item
heldItem.getMaterial().onInteract(player, Action.LEFT_CLICK);
} else {
// interacting with block using item
heldItem.getMaterial().onInteract(player, block, Action.LEFT_CLICK, clickedFace);
blockMaterial.onInteractBy(player, block, Action.LEFT_CLICK, clickedFace);
}
// Interaction with controller
if (blockMaterial.hasController()) {
blockMaterial.getController(block).onInteract(player, Action.LEFT_CLICK);
}
if (isInteractable) {
Block neigh = block.translate(clickedFace);
boolean fire = neigh.getMaterial().equals(VanillaMaterials.FIRE);
if (fire) {
// put out fire
VanillaMaterials.FIRE.onDestroy(neigh);
GeneralEffects.RANDOM_FIZZ.playGlobal(block.getPosition());
} else if (vp.isSurvival() && blockMaterial.getHardness() != 0.0f) {
vp.startDigging(new Point(w, x, y, z));
} else {
// insta-break
blockMaterial.onDestroy(block);
GeneralEffects.BREAKBLOCK.playGlobal(block.getPosition(), blockMaterial, player);
}
}
} else if (state == PlayerDiggingMessage.STATE_DONE_DIGGING) {
if (!vp.stopDigging(new Point(w, x, y, z)) || !isInteractable) {
return;
}
if (VanillaPlayerUtil.isSurvival(player)) {
((VanillaPlayer) player.getController()).setExhaustion(((VanillaPlayer) player.getController()).getExhaustion() + ExhaustionLevel.BREAK_BLOCK.getAmount());
}
long diggingTicks = vp.getDiggingTicks();
int damageDone;
int totalDamage;
if (heldItem != null) {
if (heldItem.getMaterial() instanceof Tool && blockMaterial instanceof Mineable) {
short penalty = ((Tool) heldItem.getMaterial()).getDurabilityPenalty((Mineable) blockMaterial, heldItem);
currentSlot.addItemData(penalty);
}
}
if (heldItem == null) {
damageDone = ((int) diggingTicks * 1);
} else {
damageDone = ((int) diggingTicks * ((VanillaMaterial) heldItem.getMaterial()).getDamage());
}
// TODO: Take into account EFFICIENCY enchantment
// TODO: Digging is slower while under water, on ladders, etc. AQUA_AFFINITY enchantment speeds up underwater digging
totalDamage = ((int) blockMaterial.getHardness() - damageDone);
if (totalDamage <= 40) { // Yes, this is a very high allowance - this is because this is only over a single block, and this will spike due to varying latency.
blockMaterial.onDestroy(block);
}
if (block.getMaterial() != VanillaMaterials.AIR) {
GeneralEffects.BREAKBLOCK.playGlobal(block.getPosition(), blockMaterial, player);
}
} else if (state == PlayerDiggingMessage.STATE_SHOOT_ARROW_EAT_FOOD) {
if (heldItem.getMaterial() instanceof Food) {
((Food) heldItem.getMaterial()).onEat(player, currentSlot);
}
}
}
|
diff --git a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/presentationTier/widgets/TakenProcessesWidget.java b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/presentationTier/widgets/TakenProcessesWidget.java
index 7c4e1a24..68e25cca 100644
--- a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/presentationTier/widgets/TakenProcessesWidget.java
+++ b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/presentationTier/widgets/TakenProcessesWidget.java
@@ -1,19 +1,21 @@
package pt.ist.expenditureTrackingSystem.presentationTier.widgets;
import java.util.List;
import module.dashBoard.presentationTier.WidgetRequest;
import module.dashBoard.widgets.WidgetController;
import myorg.util.ClassNameBundle;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.PaymentProcess;
import pt.ist.expenditureTrackingSystem.domain.organization.Person;
@ClassNameBundle(bundle = "resources/ExpenditureResources", key = "process.title.takenProcesses")
public class TakenProcessesWidget extends WidgetController {
@Override
public void doView(WidgetRequest request) {
- List<PaymentProcess> takenProcesses = Person.getLoggedPerson().getProcesses(PaymentProcess.class);
+ Person loggedPerson = Person.getLoggedPerson();
+ List<PaymentProcess> takenProcesses = loggedPerson.getProcesses(PaymentProcess.class);
request.setAttribute("takenProcesses", takenProcesses.subList(0, Math.min(10, takenProcesses.size())));
+ request.setAttribute("person", loggedPerson);
}
}
| false | true | public void doView(WidgetRequest request) {
List<PaymentProcess> takenProcesses = Person.getLoggedPerson().getProcesses(PaymentProcess.class);
request.setAttribute("takenProcesses", takenProcesses.subList(0, Math.min(10, takenProcesses.size())));
}
| public void doView(WidgetRequest request) {
Person loggedPerson = Person.getLoggedPerson();
List<PaymentProcess> takenProcesses = loggedPerson.getProcesses(PaymentProcess.class);
request.setAttribute("takenProcesses", takenProcesses.subList(0, Math.min(10, takenProcesses.size())));
request.setAttribute("person", loggedPerson);
}
|
diff --git a/src/me/ellbristow/greylistVote/greylistVote.java b/src/me/ellbristow/greylistVote/greylistVote.java
index f64e8ad..ddbbb9e 100644
--- a/src/me/ellbristow/greylistVote/greylistVote.java
+++ b/src/me/ellbristow/greylistVote/greylistVote.java
@@ -1,420 +1,432 @@
package me.ellbristow.greylistVote;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class greylistVote extends JavaPlugin {
public static greylistVote plugin;
public final Logger logger = Logger.getLogger("Minecraft");
public final greyBlockListener blockListener = new greyBlockListener(this);
protected FileConfiguration config;
private FileConfiguration usersConfig = null;
private File usersFile = null;
@Override
public void onDisable() {
PluginDescriptionFile pdfFile = this.getDescription();
this.logger.info("[" + pdfFile.getName() + "] is now disabled.");
}
@Override
public void onEnable() {
PluginDescriptionFile pdfFile = this.getDescription();
this.logger.info("[" + pdfFile.getName() + "] version " + pdfFile.getVersion() + " is enabled.");
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.BLOCK_PLACE, this.blockListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_BREAK, this.blockListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_IGNITE, this.blockListener, Event.Priority.Normal, this);
this.config = this.getConfig();
this.config.set("required_votes", this.config.getInt("required_votes"));
this.saveConfig();
this.usersConfig = this.getUsersConfig();
}
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (commandLabel.equalsIgnoreCase("glv")) {
if (args.length == 0) {
PluginDescriptionFile pdfFile = this.getDescription();
sender.sendMessage(ChatColor.GOLD + pdfFile.getName() + " version " + pdfFile.getVersion() + " by " + pdfFile.getAuthors());
sender.sendMessage(ChatColor.GOLD + "Commands: {optional} [required]");
sender.sendMessage(ChatColor.GOLD + " /glv " + ChatColor.GRAY + ": View all GreylistVote commands");
sender.sendMessage(ChatColor.GOLD + " /greylist [player] " + ChatColor.GRAY + "Increase [player]s reputation");
sender.sendMessage(ChatColor.GOLD + " /gl [player] " + ChatColor.GRAY + "Same as /greylist");
sender.sendMessage(ChatColor.GOLD + " /griefer [player] " + ChatColor.GRAY + "Decrease [player]s reputation");
sender.sendMessage(ChatColor.GOLD + " /votelist {player} " + ChatColor.GRAY + "View your (or {player}s) reputation");
sender.sendMessage(ChatColor.GOLD + " /glvlist {player} " + ChatColor.GRAY + "Same as /votelist");
if (sender.hasPermission("greylistvote.admin")) {
sender.sendMessage(ChatColor.GOLD + "Admin Commands:");
sender.sendMessage(ChatColor.GOLD + " /glv setrep [req. votes] " + ChatColor.GRAY + ": Set required reputation");
}
return true;
}
else if (args.length == 2) {
if (!sender.hasPermission("greylistvote.admin")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to do this!");
return false;
}
int reqVotes = config.getInt("required_votes", 2);
if (!args[0].equalsIgnoreCase("setrep")) {
sender.sendMessage(ChatColor.RED + "Command not recognised!");
return false;
}
try {
reqVotes = Integer.parseInt(args[1]);
}
catch(NumberFormatException nfe) {
// Failed. Number not an integer
sender.sendMessage(ChatColor.RED + "[req. votes] must be a number!" );
return false;
}
this.config.set("required_votes", reqVotes);
this.saveConfig();
sender.sendMessage(ChatColor.GOLD + "Reputation requirement now set to " + ChatColor.WHITE + args[1]);
sender.sendMessage(ChatColor.GOLD + "Player approval will not be updated until they receive their next vote.");
return true;
}
return false;
}
else if (commandLabel.equalsIgnoreCase("greylist") || commandLabel.equalsIgnoreCase("gl")) {
if (args.length != 1) {
// No player specified or too many arguments
return false;
}
else {
Player target = getServer().getOfflinePlayer(args[0]).getPlayer();
if (target == null) {
// Player not online
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
int reqVotes = this.config.getInt("required_votes");
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
}
+ else {
+ voteList = "";
+ }
if (griefList != null) {
griefArray = griefList.split(",");
}
+ else {
+ griefList = "";
+ }
if (!(sender instanceof Player)) {
// Voter is the console
this.usersConfig.set(target.getName().toLowerCase() + ".votes", "Server");
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", null);
this.setApproved(target);
this.saveUsersConfig();
sender.sendMessage(args[0] + ChatColor.GOLD + " has been greylisted!");
return true;
}
if (sender.getName() == target.getName()) {
// Player voting for self
sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!");
return true;
}
boolean found = false;
if (voteArray != null) {
for (String vote : voteArray) {
if (vote.equalsIgnoreCase(sender.getName())) {
found = true;
}
}
}
if (found) {
// Voter has already voted for this target player
sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName());
return true;
}
sender.sendMessage(ChatColor.GOLD + "Your greylist vote for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " has been accepted!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " to be greylisted!");
}
else if (chatPlayer.getName() != sender.getName()) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for you to be greylisted!");
}
}
this.usersConfig.set(target.getName().toLowerCase() + ".votes", voteList + "," + sender.getName());
int rep = 0;
if (voteArray != null) {
rep += voteArray.length + 1;
}
if (griefArray != null) {
rep -= griefArray.length;
}
if (rep >= reqVotes && !target.hasPermission("greylistvote.approved")) {
// Enough votes received
this.setApproved(target);
}
this.saveUsersConfig();
return true;
}
}
else if (commandLabel.equalsIgnoreCase("griefer")) {
if (args.length != 1) {
// No player specified or too many arguments
return false;
}
else {
Player target = getServer().getOfflinePlayer(args[0]).getPlayer();
if (target == null) {
// Player not online
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
int reqVotes = this.config.getInt("required_votes");
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
}
+ else {
+ voteList = "";
+ }
if (griefList != null) {
griefArray = griefList.split(",");
}
+ else {
+ griefList = "";
+ }
if (!(sender instanceof Player)) {
// Voter is the console
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", "Server");
this.usersConfig.set(target.getName().toLowerCase() + ".votes", null);
this.setGriefer(target);
this.saveUsersConfig();
sender.sendMessage(args[0] + ChatColor.GOLD + " has been " + ChatColor.DARK_GRAY +"Black-Balled!");
return true;
}
if (sender.getName() == target.getName()) {
// Player voting for self
sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!");
return true;
}
boolean found = false;
if (griefArray != null) {
for (String vote : griefArray) {
if (vote.equalsIgnoreCase(sender.getName())) {
found = true;
}
}
}
if (found) {
// Voter has already voted for this target player
sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName());
return true;
}
sender.sendMessage(ChatColor.GOLD + "Your griefer vote for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " has been accepted!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " to be " + ChatColor.DARK_GRAY + "black-balled" + ChatColor.GOLD + " for griefing!");
}
else if (chatPlayer.getName() != sender.getName()) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for you to be " + ChatColor.DARK_GRAY + " black-balled" + ChatColor.GOLD + " for " + ChatColor.RED + "griefing" + ChatColor.GOLD + "!");
}
}
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", voteList + "," + sender.getName());
int rep = 0;
if (voteArray != null) {
rep += voteArray.length;
}
if (griefArray != null) {
rep -= griefArray.length + 1;
}
if (rep < reqVotes) {
// Enough votes received
this.setGriefer(target);
}
this.saveUsersConfig();
return true;
}
}
else if (commandLabel.equalsIgnoreCase("votelist") || commandLabel.equalsIgnoreCase("glvlist")) {
if (args.length == 0) {
String voteList = this.usersConfig.getString(sender.getName().toLowerCase() + ".votes", null);
String griefList = this.usersConfig.getString(sender.getName().toLowerCase() + ".griefer", null);
if (voteList == null && griefList == null) {
sender.sendMessage(ChatColor.GOLD + "You have not received any votes.");
sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0");
}
else {
sender.sendMessage(ChatColor.GOLD + "You have received votes from:");
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
if (voteArray.length != 0) {
String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD;
for (String vote : voteArray) {
votes = votes + vote + " ";
}
sender.sendMessage(votes);
}
}
if (griefList != null) {
griefArray = griefList.split(",");
if (griefArray.length != 0) {
String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD;
for (String vote : griefArray) {
votes = votes + vote + " ";
}
sender.sendMessage(votes);
}
}
int reputation = 0;
if (voteArray != null) {
reputation += voteArray.length;
}
if (griefArray != null) {
reputation -= griefArray.length;
}
int reqVotes = config.getInt("required_votes");
String repText = "";
if (reputation >= reqVotes) {
repText = " " + ChatColor.GREEN + reputation;
}
else {
repText = " " + ChatColor.RED + reputation;
}
sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText);
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes);
}
return true;
}
else {
OfflinePlayer checktarget = getServer().getOfflinePlayer(args[0]);
String DN = null;
String target = null;
if (checktarget.isOnline()) {
target = checktarget.getPlayer().getName();
DN = checktarget.getPlayer().getDisplayName();
}
else {
if (checktarget != null) {
target = checktarget.getName();
DN = checktarget.getName();
}
}
if (target == null) {
// Player not found
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
String voteList = this.usersConfig.getString(target.toLowerCase() + ".votes", null);
String griefList = this.usersConfig.getString(target.toLowerCase() + ".griefer", null);
if (voteList == null && griefList == null) {
sender.sendMessage(DN + ChatColor.GOLD + " has not received any votes.");
sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0");
}
else {
sender.sendMessage(DN + ChatColor.GOLD + " has received votes from:");
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
if (voteArray.length != 0) {
String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD;
for (String vote : voteArray) {
votes = votes + vote + " ";
}
sender.sendMessage(votes);
}
}
if (griefList != null) {
griefArray = griefList.split(",");
if (griefArray.length != 0) {
String votes = ChatColor.BLACK + " Black-Balls: " + ChatColor.GOLD;
for (String vote : griefArray) {
votes = votes + vote + " ";
}
sender.sendMessage(votes);
}
}
int reputation = 0;
if (voteArray != null) {
reputation += voteArray.length;
}
if (griefArray != null) {
reputation -= griefArray.length;
}
int reqVotes = config.getInt("required_votes");
String repText = "";
if (reputation >= reqVotes) {
repText = " " + ChatColor.GREEN + reputation;
}
else {
repText = " " + ChatColor.RED + reputation;
}
sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText);
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes);
}
return true;
}
}
return false;
}
public void setApproved(Player target) {
target.addAttachment(this, "greylistvote.approved", true);
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (chatPlayer.getName() != target.getName()) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + " has been greylisted!");
}
else {
chatPlayer.sendMessage("You have been greylisted! Go forth and buildify!");
}
}
}
public void setGriefer(Player target) {
target.addAttachment(this, "greylistvote.approved",false);
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (chatPlayer.getName() != target.getName()) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + " has been " + ChatColor.DARK_GRAY + "black-balled" + ChatColor.GOLD + " for " + ChatColor.RED + " griefing" + ChatColor.GOLD + "!");
}
else {
chatPlayer.sendMessage(ChatColor.RED + "You have been " + ChatColor.DARK_GRAY + "black-balled" + ChatColor.RED + " for griefing!");
}
}
}
public void loadUsersConfig() {
if (this.usersFile == null) {
this.usersFile = new File(getDataFolder(),"users.yml");
}
this.usersConfig = YamlConfiguration.loadConfiguration(this.usersFile);
}
public FileConfiguration getUsersConfig() {
if (this.usersConfig == null) {
this.loadUsersConfig();
}
return this.usersConfig;
}
public void saveUsersConfig() {
if (this.usersConfig == null || this.usersFile == null) {
return;
}
try {
this.usersConfig.save(this.usersFile);
} catch (IOException ex) {
this.logger.log(Level.SEVERE, "Could not save " + this.usersFile, ex );
}
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (commandLabel.equalsIgnoreCase("glv")) {
if (args.length == 0) {
PluginDescriptionFile pdfFile = this.getDescription();
sender.sendMessage(ChatColor.GOLD + pdfFile.getName() + " version " + pdfFile.getVersion() + " by " + pdfFile.getAuthors());
sender.sendMessage(ChatColor.GOLD + "Commands: {optional} [required]");
sender.sendMessage(ChatColor.GOLD + " /glv " + ChatColor.GRAY + ": View all GreylistVote commands");
sender.sendMessage(ChatColor.GOLD + " /greylist [player] " + ChatColor.GRAY + "Increase [player]s reputation");
sender.sendMessage(ChatColor.GOLD + " /gl [player] " + ChatColor.GRAY + "Same as /greylist");
sender.sendMessage(ChatColor.GOLD + " /griefer [player] " + ChatColor.GRAY + "Decrease [player]s reputation");
sender.sendMessage(ChatColor.GOLD + " /votelist {player} " + ChatColor.GRAY + "View your (or {player}s) reputation");
sender.sendMessage(ChatColor.GOLD + " /glvlist {player} " + ChatColor.GRAY + "Same as /votelist");
if (sender.hasPermission("greylistvote.admin")) {
sender.sendMessage(ChatColor.GOLD + "Admin Commands:");
sender.sendMessage(ChatColor.GOLD + " /glv setrep [req. votes] " + ChatColor.GRAY + ": Set required reputation");
}
return true;
}
else if (args.length == 2) {
if (!sender.hasPermission("greylistvote.admin")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to do this!");
return false;
}
int reqVotes = config.getInt("required_votes", 2);
if (!args[0].equalsIgnoreCase("setrep")) {
sender.sendMessage(ChatColor.RED + "Command not recognised!");
return false;
}
try {
reqVotes = Integer.parseInt(args[1]);
}
catch(NumberFormatException nfe) {
// Failed. Number not an integer
sender.sendMessage(ChatColor.RED + "[req. votes] must be a number!" );
return false;
}
this.config.set("required_votes", reqVotes);
this.saveConfig();
sender.sendMessage(ChatColor.GOLD + "Reputation requirement now set to " + ChatColor.WHITE + args[1]);
sender.sendMessage(ChatColor.GOLD + "Player approval will not be updated until they receive their next vote.");
return true;
}
return false;
}
else if (commandLabel.equalsIgnoreCase("greylist") || commandLabel.equalsIgnoreCase("gl")) {
if (args.length != 1) {
// No player specified or too many arguments
return false;
}
else {
Player target = getServer().getOfflinePlayer(args[0]).getPlayer();
if (target == null) {
// Player not online
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
int reqVotes = this.config.getInt("required_votes");
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
}
if (griefList != null) {
griefArray = griefList.split(",");
}
if (!(sender instanceof Player)) {
// Voter is the console
this.usersConfig.set(target.getName().toLowerCase() + ".votes", "Server");
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", null);
this.setApproved(target);
this.saveUsersConfig();
sender.sendMessage(args[0] + ChatColor.GOLD + " has been greylisted!");
return true;
}
if (sender.getName() == target.getName()) {
// Player voting for self
sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!");
return true;
}
boolean found = false;
if (voteArray != null) {
for (String vote : voteArray) {
if (vote.equalsIgnoreCase(sender.getName())) {
found = true;
}
}
}
if (found) {
// Voter has already voted for this target player
sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName());
return true;
}
sender.sendMessage(ChatColor.GOLD + "Your greylist vote for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " has been accepted!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " to be greylisted!");
}
else if (chatPlayer.getName() != sender.getName()) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for you to be greylisted!");
}
}
this.usersConfig.set(target.getName().toLowerCase() + ".votes", voteList + "," + sender.getName());
int rep = 0;
if (voteArray != null) {
rep += voteArray.length + 1;
}
if (griefArray != null) {
rep -= griefArray.length;
}
if (rep >= reqVotes && !target.hasPermission("greylistvote.approved")) {
// Enough votes received
this.setApproved(target);
}
this.saveUsersConfig();
return true;
}
}
else if (commandLabel.equalsIgnoreCase("griefer")) {
if (args.length != 1) {
// No player specified or too many arguments
return false;
}
else {
Player target = getServer().getOfflinePlayer(args[0]).getPlayer();
if (target == null) {
// Player not online
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
int reqVotes = this.config.getInt("required_votes");
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
}
if (griefList != null) {
griefArray = griefList.split(",");
}
if (!(sender instanceof Player)) {
// Voter is the console
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", "Server");
this.usersConfig.set(target.getName().toLowerCase() + ".votes", null);
this.setGriefer(target);
this.saveUsersConfig();
sender.sendMessage(args[0] + ChatColor.GOLD + " has been " + ChatColor.DARK_GRAY +"Black-Balled!");
return true;
}
if (sender.getName() == target.getName()) {
// Player voting for self
sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!");
return true;
}
boolean found = false;
if (griefArray != null) {
for (String vote : griefArray) {
if (vote.equalsIgnoreCase(sender.getName())) {
found = true;
}
}
}
if (found) {
// Voter has already voted for this target player
sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName());
return true;
}
sender.sendMessage(ChatColor.GOLD + "Your griefer vote for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " has been accepted!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " to be " + ChatColor.DARK_GRAY + "black-balled" + ChatColor.GOLD + " for griefing!");
}
else if (chatPlayer.getName() != sender.getName()) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for you to be " + ChatColor.DARK_GRAY + " black-balled" + ChatColor.GOLD + " for " + ChatColor.RED + "griefing" + ChatColor.GOLD + "!");
}
}
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", voteList + "," + sender.getName());
int rep = 0;
if (voteArray != null) {
rep += voteArray.length;
}
if (griefArray != null) {
rep -= griefArray.length + 1;
}
if (rep < reqVotes) {
// Enough votes received
this.setGriefer(target);
}
this.saveUsersConfig();
return true;
}
}
else if (commandLabel.equalsIgnoreCase("votelist") || commandLabel.equalsIgnoreCase("glvlist")) {
if (args.length == 0) {
String voteList = this.usersConfig.getString(sender.getName().toLowerCase() + ".votes", null);
String griefList = this.usersConfig.getString(sender.getName().toLowerCase() + ".griefer", null);
if (voteList == null && griefList == null) {
sender.sendMessage(ChatColor.GOLD + "You have not received any votes.");
sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0");
}
else {
sender.sendMessage(ChatColor.GOLD + "You have received votes from:");
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
if (voteArray.length != 0) {
String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD;
for (String vote : voteArray) {
votes = votes + vote + " ";
}
sender.sendMessage(votes);
}
}
if (griefList != null) {
griefArray = griefList.split(",");
if (griefArray.length != 0) {
String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD;
for (String vote : griefArray) {
votes = votes + vote + " ";
}
sender.sendMessage(votes);
}
}
int reputation = 0;
if (voteArray != null) {
reputation += voteArray.length;
}
if (griefArray != null) {
reputation -= griefArray.length;
}
int reqVotes = config.getInt("required_votes");
String repText = "";
if (reputation >= reqVotes) {
repText = " " + ChatColor.GREEN + reputation;
}
else {
repText = " " + ChatColor.RED + reputation;
}
sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText);
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes);
}
return true;
}
else {
OfflinePlayer checktarget = getServer().getOfflinePlayer(args[0]);
String DN = null;
String target = null;
if (checktarget.isOnline()) {
target = checktarget.getPlayer().getName();
DN = checktarget.getPlayer().getDisplayName();
}
else {
if (checktarget != null) {
target = checktarget.getName();
DN = checktarget.getName();
}
}
if (target == null) {
// Player not found
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
String voteList = this.usersConfig.getString(target.toLowerCase() + ".votes", null);
String griefList = this.usersConfig.getString(target.toLowerCase() + ".griefer", null);
if (voteList == null && griefList == null) {
sender.sendMessage(DN + ChatColor.GOLD + " has not received any votes.");
sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0");
}
else {
sender.sendMessage(DN + ChatColor.GOLD + " has received votes from:");
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
if (voteArray.length != 0) {
String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD;
for (String vote : voteArray) {
votes = votes + vote + " ";
}
sender.sendMessage(votes);
}
}
if (griefList != null) {
griefArray = griefList.split(",");
if (griefArray.length != 0) {
String votes = ChatColor.BLACK + " Black-Balls: " + ChatColor.GOLD;
for (String vote : griefArray) {
votes = votes + vote + " ";
}
sender.sendMessage(votes);
}
}
int reputation = 0;
if (voteArray != null) {
reputation += voteArray.length;
}
if (griefArray != null) {
reputation -= griefArray.length;
}
int reqVotes = config.getInt("required_votes");
String repText = "";
if (reputation >= reqVotes) {
repText = " " + ChatColor.GREEN + reputation;
}
else {
repText = " " + ChatColor.RED + reputation;
}
sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText);
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes);
}
return true;
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (commandLabel.equalsIgnoreCase("glv")) {
if (args.length == 0) {
PluginDescriptionFile pdfFile = this.getDescription();
sender.sendMessage(ChatColor.GOLD + pdfFile.getName() + " version " + pdfFile.getVersion() + " by " + pdfFile.getAuthors());
sender.sendMessage(ChatColor.GOLD + "Commands: {optional} [required]");
sender.sendMessage(ChatColor.GOLD + " /glv " + ChatColor.GRAY + ": View all GreylistVote commands");
sender.sendMessage(ChatColor.GOLD + " /greylist [player] " + ChatColor.GRAY + "Increase [player]s reputation");
sender.sendMessage(ChatColor.GOLD + " /gl [player] " + ChatColor.GRAY + "Same as /greylist");
sender.sendMessage(ChatColor.GOLD + " /griefer [player] " + ChatColor.GRAY + "Decrease [player]s reputation");
sender.sendMessage(ChatColor.GOLD + " /votelist {player} " + ChatColor.GRAY + "View your (or {player}s) reputation");
sender.sendMessage(ChatColor.GOLD + " /glvlist {player} " + ChatColor.GRAY + "Same as /votelist");
if (sender.hasPermission("greylistvote.admin")) {
sender.sendMessage(ChatColor.GOLD + "Admin Commands:");
sender.sendMessage(ChatColor.GOLD + " /glv setrep [req. votes] " + ChatColor.GRAY + ": Set required reputation");
}
return true;
}
else if (args.length == 2) {
if (!sender.hasPermission("greylistvote.admin")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to do this!");
return false;
}
int reqVotes = config.getInt("required_votes", 2);
if (!args[0].equalsIgnoreCase("setrep")) {
sender.sendMessage(ChatColor.RED + "Command not recognised!");
return false;
}
try {
reqVotes = Integer.parseInt(args[1]);
}
catch(NumberFormatException nfe) {
// Failed. Number not an integer
sender.sendMessage(ChatColor.RED + "[req. votes] must be a number!" );
return false;
}
this.config.set("required_votes", reqVotes);
this.saveConfig();
sender.sendMessage(ChatColor.GOLD + "Reputation requirement now set to " + ChatColor.WHITE + args[1]);
sender.sendMessage(ChatColor.GOLD + "Player approval will not be updated until they receive their next vote.");
return true;
}
return false;
}
else if (commandLabel.equalsIgnoreCase("greylist") || commandLabel.equalsIgnoreCase("gl")) {
if (args.length != 1) {
// No player specified or too many arguments
return false;
}
else {
Player target = getServer().getOfflinePlayer(args[0]).getPlayer();
if (target == null) {
// Player not online
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
int reqVotes = this.config.getInt("required_votes");
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
}
else {
voteList = "";
}
if (griefList != null) {
griefArray = griefList.split(",");
}
else {
griefList = "";
}
if (!(sender instanceof Player)) {
// Voter is the console
this.usersConfig.set(target.getName().toLowerCase() + ".votes", "Server");
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", null);
this.setApproved(target);
this.saveUsersConfig();
sender.sendMessage(args[0] + ChatColor.GOLD + " has been greylisted!");
return true;
}
if (sender.getName() == target.getName()) {
// Player voting for self
sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!");
return true;
}
boolean found = false;
if (voteArray != null) {
for (String vote : voteArray) {
if (vote.equalsIgnoreCase(sender.getName())) {
found = true;
}
}
}
if (found) {
// Voter has already voted for this target player
sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName());
return true;
}
sender.sendMessage(ChatColor.GOLD + "Your greylist vote for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " has been accepted!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " to be greylisted!");
}
else if (chatPlayer.getName() != sender.getName()) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for you to be greylisted!");
}
}
this.usersConfig.set(target.getName().toLowerCase() + ".votes", voteList + "," + sender.getName());
int rep = 0;
if (voteArray != null) {
rep += voteArray.length + 1;
}
if (griefArray != null) {
rep -= griefArray.length;
}
if (rep >= reqVotes && !target.hasPermission("greylistvote.approved")) {
// Enough votes received
this.setApproved(target);
}
this.saveUsersConfig();
return true;
}
}
else if (commandLabel.equalsIgnoreCase("griefer")) {
if (args.length != 1) {
// No player specified or too many arguments
return false;
}
else {
Player target = getServer().getOfflinePlayer(args[0]).getPlayer();
if (target == null) {
// Player not online
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
int reqVotes = this.config.getInt("required_votes");
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
}
else {
voteList = "";
}
if (griefList != null) {
griefArray = griefList.split(",");
}
else {
griefList = "";
}
if (!(sender instanceof Player)) {
// Voter is the console
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", "Server");
this.usersConfig.set(target.getName().toLowerCase() + ".votes", null);
this.setGriefer(target);
this.saveUsersConfig();
sender.sendMessage(args[0] + ChatColor.GOLD + " has been " + ChatColor.DARK_GRAY +"Black-Balled!");
return true;
}
if (sender.getName() == target.getName()) {
// Player voting for self
sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!");
return true;
}
boolean found = false;
if (griefArray != null) {
for (String vote : griefArray) {
if (vote.equalsIgnoreCase(sender.getName())) {
found = true;
}
}
}
if (found) {
// Voter has already voted for this target player
sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName());
return true;
}
sender.sendMessage(ChatColor.GOLD + "Your griefer vote for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " has been accepted!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " to be " + ChatColor.DARK_GRAY + "black-balled" + ChatColor.GOLD + " for griefing!");
}
else if (chatPlayer.getName() != sender.getName()) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for you to be " + ChatColor.DARK_GRAY + " black-balled" + ChatColor.GOLD + " for " + ChatColor.RED + "griefing" + ChatColor.GOLD + "!");
}
}
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", voteList + "," + sender.getName());
int rep = 0;
if (voteArray != null) {
rep += voteArray.length;
}
if (griefArray != null) {
rep -= griefArray.length + 1;
}
if (rep < reqVotes) {
// Enough votes received
this.setGriefer(target);
}
this.saveUsersConfig();
return true;
}
}
else if (commandLabel.equalsIgnoreCase("votelist") || commandLabel.equalsIgnoreCase("glvlist")) {
if (args.length == 0) {
String voteList = this.usersConfig.getString(sender.getName().toLowerCase() + ".votes", null);
String griefList = this.usersConfig.getString(sender.getName().toLowerCase() + ".griefer", null);
if (voteList == null && griefList == null) {
sender.sendMessage(ChatColor.GOLD + "You have not received any votes.");
sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0");
}
else {
sender.sendMessage(ChatColor.GOLD + "You have received votes from:");
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
if (voteArray.length != 0) {
String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD;
for (String vote : voteArray) {
votes = votes + vote + " ";
}
sender.sendMessage(votes);
}
}
if (griefList != null) {
griefArray = griefList.split(",");
if (griefArray.length != 0) {
String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD;
for (String vote : griefArray) {
votes = votes + vote + " ";
}
sender.sendMessage(votes);
}
}
int reputation = 0;
if (voteArray != null) {
reputation += voteArray.length;
}
if (griefArray != null) {
reputation -= griefArray.length;
}
int reqVotes = config.getInt("required_votes");
String repText = "";
if (reputation >= reqVotes) {
repText = " " + ChatColor.GREEN + reputation;
}
else {
repText = " " + ChatColor.RED + reputation;
}
sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText);
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes);
}
return true;
}
else {
OfflinePlayer checktarget = getServer().getOfflinePlayer(args[0]);
String DN = null;
String target = null;
if (checktarget.isOnline()) {
target = checktarget.getPlayer().getName();
DN = checktarget.getPlayer().getDisplayName();
}
else {
if (checktarget != null) {
target = checktarget.getName();
DN = checktarget.getName();
}
}
if (target == null) {
// Player not found
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
String voteList = this.usersConfig.getString(target.toLowerCase() + ".votes", null);
String griefList = this.usersConfig.getString(target.toLowerCase() + ".griefer", null);
if (voteList == null && griefList == null) {
sender.sendMessage(DN + ChatColor.GOLD + " has not received any votes.");
sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0");
}
else {
sender.sendMessage(DN + ChatColor.GOLD + " has received votes from:");
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
if (voteArray.length != 0) {
String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD;
for (String vote : voteArray) {
votes = votes + vote + " ";
}
sender.sendMessage(votes);
}
}
if (griefList != null) {
griefArray = griefList.split(",");
if (griefArray.length != 0) {
String votes = ChatColor.BLACK + " Black-Balls: " + ChatColor.GOLD;
for (String vote : griefArray) {
votes = votes + vote + " ";
}
sender.sendMessage(votes);
}
}
int reputation = 0;
if (voteArray != null) {
reputation += voteArray.length;
}
if (griefArray != null) {
reputation -= griefArray.length;
}
int reqVotes = config.getInt("required_votes");
String repText = "";
if (reputation >= reqVotes) {
repText = " " + ChatColor.GREEN + reputation;
}
else {
repText = " " + ChatColor.RED + reputation;
}
sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText);
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes);
}
return true;
}
}
return false;
}
|
diff --git a/src/com/github/triarry/PvPRestore/PvPRestorePlayerListener.java b/src/com/github/triarry/PvPRestore/PvPRestorePlayerListener.java
index 50c11d0..4025fb1 100644
--- a/src/com/github/triarry/PvPRestore/PvPRestorePlayerListener.java
+++ b/src/com/github/triarry/PvPRestore/PvPRestorePlayerListener.java
@@ -1,149 +1,149 @@
package com.github.triarry.PvPRestore;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.inventory.ItemStack;
public class PvPRestorePlayerListener implements Listener {
private PvPRestore plugin;
public PvPRestorePlayerListener(PvPRestore plugin) {
this.plugin = plugin;
}
public HashMap<Player , ItemStack[]> items = new HashMap<Player , ItemStack[]>();
public HashMap<Player , ItemStack[]> armor = new HashMap<Player , ItemStack[]>();
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = null;
if (event.getEntity() instanceof Player) {
player = event.getEntity();
}
Player killer = player.getKiller();
if (killer != null) {
- if (player.hasPermission("pvprestore.keep")) {
+ if (player.hasPermission("pvprestore.keep") && plugin.getConfig().getBoolean("keep-inventory") == true && plugin.getConfig().getBoolean("keep-xp") == true) {
event.setKeepLevel(true);
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your inventory and XP have been saved.");
event.setDroppedExp(0);
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their XP and inventory was saved!");
}
ItemStack[] content = player.getInventory().getContents();
ItemStack[] content_armor = player.getInventory().getArmorContents();
armor.put(player, content_armor);
items.put(player, content);
player.getInventory().clear();
event.getDrops().clear();
}
- else if (player.hasPermission("pvprestore.keep.xp") && plugin.getConfig().getBoolean("keep-xp") == true) {
+ else if ((player.hasPermission("pvprestore.keep.xp") || player.hasPermission("pvprestore.keep")) && plugin.getConfig().getBoolean("keep-xp") == true) {
if (player.hasPermission("pvprestore.keep.inventory")) {
event.setKeepLevel(true);
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your inventory and XP have been saved.");
event.setDroppedExp(0);
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their XP and inventory was saved!");
}
ItemStack[] content = player.getInventory().getContents();
ItemStack[] content_armor = player.getInventory().getArmorContents();
armor.put(player, content_armor);
items.put(player, content);
player.getInventory().clear();
event.getDrops().clear();
}
else {
event.setKeepLevel(true);
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your XP has been saved.");
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their XP was saved!");
}
event.setDroppedExp(0);
}
}
- else if (player.hasPermission("pvprestore.keep.inventory") && plugin.getConfig().getBoolean("keep-inventory") == true) {
+ else if ((player.hasPermission("pvprestore.keep.inventory") || player.hasPermission("pvprestore.keep")) && plugin.getConfig().getBoolean("keep-inventory") == true) {
if (player.hasPermission("pvprestore.keep.xp")) {
event.setKeepLevel(true);
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your inventory and XP have been saved.");
event.setDroppedExp(0);
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their XP and inventory was saved!");
}
ItemStack[] content = player.getInventory().getContents();
ItemStack[] content_armor = player.getInventory().getArmorContents();
armor.put(player, content_armor);
items.put(player, content);
player.getInventory().clear();
event.getDrops().clear();
}
else {
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your inventory has been saved.");
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their inventory was saved!");
}
ItemStack[] content = player.getInventory().getContents();
ItemStack[] content_armor = player.getInventory().getArmorContents();
armor.put(player, content_armor);
items.put(player, content);
player.getInventory().clear();
event.getDrops().clear();
}
}
else {
player.sendMessage(ChatColor.RED + "Your death was not player related, so your inventory and XP have dropped where you died.");
}
} else {
player.sendMessage(ChatColor.RED + "Your death was not player related, so your inventory and XP have dropped where you died.");
}
}
@EventHandler
public void onPlayerRespawn(PlayerRespawnEvent event) {
if(items.containsKey(event.getPlayer())){
event.getPlayer().getInventory().clear();
event.getPlayer().getInventory().setContents(items.get(event.getPlayer()));
items.remove(event.getPlayer());
}
if(armor.containsKey(event.getPlayer()) && armor.size() != 0) {
event.getPlayer().getInventory().setArmorContents(armor.get(event.getPlayer()));
armor.remove(event.getPlayer());
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
if (event.getPlayer().isDead()) {
if(items.containsKey(event.getPlayer())){
event.getPlayer().getInventory().clear();
event.getPlayer().getInventory().setContents(items.get(event.getPlayer()));
items.remove(event.getPlayer());
}
if(armor.containsKey(event.getPlayer()) && armor.size() != 0) {
event.getPlayer().getInventory().setArmorContents(armor.get(event.getPlayer()));
armor.remove(event.getPlayer());
}
}
}
public void onPlayerKick(PlayerKickEvent event) {
if (event.getPlayer().isDead()) {
if(items.containsKey(event.getPlayer())){
event.getPlayer().getInventory().clear();
event.getPlayer().getInventory().setContents(items.get(event.getPlayer()));
items.remove(event.getPlayer());
}
if(armor.containsKey(event.getPlayer()) && armor.size() != 0) {
event.getPlayer().getInventory().setArmorContents(armor.get(event.getPlayer()));
armor.remove(event.getPlayer());
}
}
}
}
| false | true | public void onPlayerDeath(PlayerDeathEvent event) {
Player player = null;
if (event.getEntity() instanceof Player) {
player = event.getEntity();
}
Player killer = player.getKiller();
if (killer != null) {
if (player.hasPermission("pvprestore.keep")) {
event.setKeepLevel(true);
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your inventory and XP have been saved.");
event.setDroppedExp(0);
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their XP and inventory was saved!");
}
ItemStack[] content = player.getInventory().getContents();
ItemStack[] content_armor = player.getInventory().getArmorContents();
armor.put(player, content_armor);
items.put(player, content);
player.getInventory().clear();
event.getDrops().clear();
}
else if (player.hasPermission("pvprestore.keep.xp") && plugin.getConfig().getBoolean("keep-xp") == true) {
if (player.hasPermission("pvprestore.keep.inventory")) {
event.setKeepLevel(true);
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your inventory and XP have been saved.");
event.setDroppedExp(0);
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their XP and inventory was saved!");
}
ItemStack[] content = player.getInventory().getContents();
ItemStack[] content_armor = player.getInventory().getArmorContents();
armor.put(player, content_armor);
items.put(player, content);
player.getInventory().clear();
event.getDrops().clear();
}
else {
event.setKeepLevel(true);
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your XP has been saved.");
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their XP was saved!");
}
event.setDroppedExp(0);
}
}
else if (player.hasPermission("pvprestore.keep.inventory") && plugin.getConfig().getBoolean("keep-inventory") == true) {
if (player.hasPermission("pvprestore.keep.xp")) {
event.setKeepLevel(true);
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your inventory and XP have been saved.");
event.setDroppedExp(0);
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their XP and inventory was saved!");
}
ItemStack[] content = player.getInventory().getContents();
ItemStack[] content_armor = player.getInventory().getArmorContents();
armor.put(player, content_armor);
items.put(player, content);
player.getInventory().clear();
event.getDrops().clear();
}
else {
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your inventory has been saved.");
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their inventory was saved!");
}
ItemStack[] content = player.getInventory().getContents();
ItemStack[] content_armor = player.getInventory().getArmorContents();
armor.put(player, content_armor);
items.put(player, content);
player.getInventory().clear();
event.getDrops().clear();
}
}
else {
player.sendMessage(ChatColor.RED + "Your death was not player related, so your inventory and XP have dropped where you died.");
}
} else {
player.sendMessage(ChatColor.RED + "Your death was not player related, so your inventory and XP have dropped where you died.");
}
}
| public void onPlayerDeath(PlayerDeathEvent event) {
Player player = null;
if (event.getEntity() instanceof Player) {
player = event.getEntity();
}
Player killer = player.getKiller();
if (killer != null) {
if (player.hasPermission("pvprestore.keep") && plugin.getConfig().getBoolean("keep-inventory") == true && plugin.getConfig().getBoolean("keep-xp") == true) {
event.setKeepLevel(true);
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your inventory and XP have been saved.");
event.setDroppedExp(0);
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their XP and inventory was saved!");
}
ItemStack[] content = player.getInventory().getContents();
ItemStack[] content_armor = player.getInventory().getArmorContents();
armor.put(player, content_armor);
items.put(player, content);
player.getInventory().clear();
event.getDrops().clear();
}
else if ((player.hasPermission("pvprestore.keep.xp") || player.hasPermission("pvprestore.keep")) && plugin.getConfig().getBoolean("keep-xp") == true) {
if (player.hasPermission("pvprestore.keep.inventory")) {
event.setKeepLevel(true);
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your inventory and XP have been saved.");
event.setDroppedExp(0);
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their XP and inventory was saved!");
}
ItemStack[] content = player.getInventory().getContents();
ItemStack[] content_armor = player.getInventory().getArmorContents();
armor.put(player, content_armor);
items.put(player, content);
player.getInventory().clear();
event.getDrops().clear();
}
else {
event.setKeepLevel(true);
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your XP has been saved.");
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their XP was saved!");
}
event.setDroppedExp(0);
}
}
else if ((player.hasPermission("pvprestore.keep.inventory") || player.hasPermission("pvprestore.keep")) && plugin.getConfig().getBoolean("keep-inventory") == true) {
if (player.hasPermission("pvprestore.keep.xp")) {
event.setKeepLevel(true);
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your inventory and XP have been saved.");
event.setDroppedExp(0);
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their XP and inventory was saved!");
}
ItemStack[] content = player.getInventory().getContents();
ItemStack[] content_armor = player.getInventory().getArmorContents();
armor.put(player, content_armor);
items.put(player, content);
player.getInventory().clear();
event.getDrops().clear();
}
else {
player.sendMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.GREEN + "Your death was player related, so your inventory has been saved.");
if (plugin.getConfig().getBoolean("death-message") == true) {
event.setDeathMessage(ChatColor.YELLOW + "[PVP_Restore] " + ChatColor.RED + player.getName() + ChatColor.GREEN + " was killed by " + ChatColor.RED + killer.getName() + ChatColor.GREEN + ", and their inventory was saved!");
}
ItemStack[] content = player.getInventory().getContents();
ItemStack[] content_armor = player.getInventory().getArmorContents();
armor.put(player, content_armor);
items.put(player, content);
player.getInventory().clear();
event.getDrops().clear();
}
}
else {
player.sendMessage(ChatColor.RED + "Your death was not player related, so your inventory and XP have dropped where you died.");
}
} else {
player.sendMessage(ChatColor.RED + "Your death was not player related, so your inventory and XP have dropped where you died.");
}
}
|
diff --git a/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/study/StudyGrant.java b/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/study/StudyGrant.java
index 3bfe31686..1e41cf5f7 100644
--- a/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/study/StudyGrant.java
+++ b/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/study/StudyGrant.java
@@ -1,184 +1,184 @@
/*
* StudyAuthor.java
*
* Created on August 7, 2006, 9:49 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package edu.harvard.hmdc.vdcnet.study;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Version;
import javax.persistence.*;
/**
*
* @author Ellen Kraffmiller
*/
@Entity
public class StudyGrant {
/** Creates a new instance of StudyGrant */
public StudyGrant() {
}
/**
* Holds value of property id.
*/
@Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="studygrant_gen")
@SequenceGenerator(name="studygrant_gen", sequenceName="studygrant_id_seq")
private Long id;
/**
* Getter for property id.
* @return Value of property id.
*/
public Long getId() {
return this.id;
}
/**
* Setter for property id.
* @param id New value of property id.
*/
public void setId(Long id) {
this.id = id;
}
/**
* Holds value of property agency.
*/
private String agency;
/**
* Getter for property value.
* @return Value of property value.
*/
public String getAgency() {
return this.agency;
}
/**
* Setter for property value.
* @param value New value of property value.
*/
public void setAgency(String agency) {
this.agency = agency;
}
/**
* Holds value of property displayOrder.
*/
private int displayOrder;
/**
* Getter for property order.
* @return Value of property order.
*/
public int getDisplayOrder() {
return this.displayOrder;
}
/**
* Setter for property order.
* @param order New value of property order.
*/
public void setDisplayOrder(int displayOrder) {
this.displayOrder = displayOrder;
}
/**
* Holds value of property study.
*/
@ManyToOne
@JoinColumn(nullable=false)
private Study study;
/**
* Getter for property study.
* @return Value of property study.
*/
public Study getStudy() {
return this.study;
}
/**
* Setter for property study.
* @param study New value of property study.
*/
public void setStudy(Study study) {
this.study = study;
}
/**
* Holds value of property version.
*/
@Version
private Long version;
/**
* Getter for property version.
* @return Value of property version.
*/
public Long getVersion() {
return this.version;
}
/**
* Setter for property version.
* @param version New value of property version.
*/
public void setVersion(Long version) {
this.version = version;
}
/**
* Holds value of property number.
*/
private String number;
/**
* Getter for property affiliation.
* @return Value of property affiliation.
*/
public String getNumber() {
return this.number;
}
/**
* Setter for property affiliation.
* @param affiliation New value of property affiliation.
*/
public void setNumber(String number) {
this.number = number;
}
public boolean isEmpty() {
return ((agency==null || agency.trim().equals(""))
&& (number==null || number.trim().equals("")));
}
public int hashCode() {
int hash = 0;
hash += (this.id != null ? this.id.hashCode() : 0);
return hash;
}
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
- if (!(object instanceof Study)) {
+ if (!(object instanceof StudyGrant)) {
return false;
}
StudyGrant other = (StudyGrant)object;
if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) return false;
return true;
}
}
| true | true | public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Study)) {
return false;
}
StudyGrant other = (StudyGrant)object;
if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) return false;
return true;
}
| public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof StudyGrant)) {
return false;
}
StudyGrant other = (StudyGrant)object;
if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) return false;
return true;
}
|
diff --git a/ShoppingSidekick/src/com/ISU/shoppingsidekick/FoodResultsActivity.java b/ShoppingSidekick/src/com/ISU/shoppingsidekick/FoodResultsActivity.java
index a461870..38fdf5e 100644
--- a/ShoppingSidekick/src/com/ISU/shoppingsidekick/FoodResultsActivity.java
+++ b/ShoppingSidekick/src/com/ISU/shoppingsidekick/FoodResultsActivity.java
@@ -1,148 +1,148 @@
package com.ISU.shoppingsidekick;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.Database.API.Account;
import com.Database.API.DatabaseAPI;
import com.Database.API.Expiration;
import com.Database.API.Food;
import com.Database.API.Price;
import com.Database.API.Review;
public class FoodResultsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_results);
final Account a = (Account) getIntent().getExtras().get("account");
Bundle scanVal = null;
Intent scannerValue = getIntent();
scanVal = scannerValue.getExtras();
TextView productName = (TextView) findViewById(R.id.productName);
TextView productBrand = (TextView) findViewById(R.id.productBrand);
TextView expInformation = (TextView) findViewById(R.id.expInformation);
TextView priceInformation = (TextView) findViewById(R.id.priceInformation);
TextView reviewInformation = (TextView) findViewById(R.id.reviewInformation);
String name = "";
String brand= "";
String id ="";
Food scannedFood = new Food();
if(scanVal != null){
final String scanValue = scanVal.getString("scanID");
ExecutorService pool = Executors.newFixedThreadPool(3);
Callable task = new Callable(){
@Override
public Object call() throws Exception{
DatabaseAPI database = new DatabaseAPI();
Food food = database.getFoodItemByID(scanValue);
if(food.getName() != null){
return food;
}
else{
return null;
}
}
};
Future<Food> future = pool.submit(task);
try {
scannedFood = future.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(scannedFood.getID() != null){
Expiration expirationInfo = scannedFood.getExpirationInformation();
Price priceInfo = scannedFood.getPriceInformation();
List<Review> reviewInfo = scannedFood.getReviewInformation();
name = scannedFood.getName();
brand = scannedFood.getBrand();
id = scannedFood.getID();
productName.setText("Product: " + name);
productBrand.setText("Product brand: " + brand);
expInformation.setText("Average Expiration: " + expirationInfo.getAvgHours() + " Hours");
priceInformation.setText("Average Price: " + "$" + priceInfo.getAvgPrice());
- String str = "Review: ";
+ String str = "Reviews:\n\n";
for(int i = 0; i < 3 && i < reviewInfo.size(); i++)
{
Review itemToAdd = reviewInfo.get(i);
- str += itemToAdd != null ? itemToAdd.getReview() + "\n" : "";
+ str += itemToAdd != null ? itemToAdd.getReview() + "\n\n" : "";
}
reviewInformation.setText(str);
}
else{
productName.setText("Item not found");
productBrand.setVisibility(View.INVISIBLE);
expInformation.setVisibility(View.INVISIBLE);
priceInformation.setVisibility(View.INVISIBLE);
reviewInformation.setVisibility(View.INVISIBLE);
}
}
else{
productName.setText("Item not found");
productBrand.setVisibility(View.INVISIBLE);
expInformation.setVisibility(View.INVISIBLE);
priceInformation.setVisibility(View.INVISIBLE);
reviewInformation.setVisibility(View.INVISIBLE);
}
//home button
Button goToFoodFinderBtn = (Button) findViewById(R.id.addItem);
goToFoodFinderBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(){
@Override
public void run()
{
Account account = (Account) getIntent().getExtras().get("account");
final String scanValue = getIntent().getExtras().getString("scanID");
DatabaseAPI database = new DatabaseAPI();
Food food = database.getFoodItemByID(scanValue);
database.addFoodItemToUserTable(account.getUserID(), food);
Intent i = new Intent(FoodResultsActivity.this, HomeActivity.class);
i.putExtra("account", account);
startActivity(i);
}
};
thread.start();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.food_results, menu);
return true;
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_results);
final Account a = (Account) getIntent().getExtras().get("account");
Bundle scanVal = null;
Intent scannerValue = getIntent();
scanVal = scannerValue.getExtras();
TextView productName = (TextView) findViewById(R.id.productName);
TextView productBrand = (TextView) findViewById(R.id.productBrand);
TextView expInformation = (TextView) findViewById(R.id.expInformation);
TextView priceInformation = (TextView) findViewById(R.id.priceInformation);
TextView reviewInformation = (TextView) findViewById(R.id.reviewInformation);
String name = "";
String brand= "";
String id ="";
Food scannedFood = new Food();
if(scanVal != null){
final String scanValue = scanVal.getString("scanID");
ExecutorService pool = Executors.newFixedThreadPool(3);
Callable task = new Callable(){
@Override
public Object call() throws Exception{
DatabaseAPI database = new DatabaseAPI();
Food food = database.getFoodItemByID(scanValue);
if(food.getName() != null){
return food;
}
else{
return null;
}
}
};
Future<Food> future = pool.submit(task);
try {
scannedFood = future.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(scannedFood.getID() != null){
Expiration expirationInfo = scannedFood.getExpirationInformation();
Price priceInfo = scannedFood.getPriceInformation();
List<Review> reviewInfo = scannedFood.getReviewInformation();
name = scannedFood.getName();
brand = scannedFood.getBrand();
id = scannedFood.getID();
productName.setText("Product: " + name);
productBrand.setText("Product brand: " + brand);
expInformation.setText("Average Expiration: " + expirationInfo.getAvgHours() + " Hours");
priceInformation.setText("Average Price: " + "$" + priceInfo.getAvgPrice());
String str = "Review: ";
for(int i = 0; i < 3 && i < reviewInfo.size(); i++)
{
Review itemToAdd = reviewInfo.get(i);
str += itemToAdd != null ? itemToAdd.getReview() + "\n" : "";
}
reviewInformation.setText(str);
}
else{
productName.setText("Item not found");
productBrand.setVisibility(View.INVISIBLE);
expInformation.setVisibility(View.INVISIBLE);
priceInformation.setVisibility(View.INVISIBLE);
reviewInformation.setVisibility(View.INVISIBLE);
}
}
else{
productName.setText("Item not found");
productBrand.setVisibility(View.INVISIBLE);
expInformation.setVisibility(View.INVISIBLE);
priceInformation.setVisibility(View.INVISIBLE);
reviewInformation.setVisibility(View.INVISIBLE);
}
//home button
Button goToFoodFinderBtn = (Button) findViewById(R.id.addItem);
goToFoodFinderBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(){
@Override
public void run()
{
Account account = (Account) getIntent().getExtras().get("account");
final String scanValue = getIntent().getExtras().getString("scanID");
DatabaseAPI database = new DatabaseAPI();
Food food = database.getFoodItemByID(scanValue);
database.addFoodItemToUserTable(account.getUserID(), food);
Intent i = new Intent(FoodResultsActivity.this, HomeActivity.class);
i.putExtra("account", account);
startActivity(i);
}
};
thread.start();
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_results);
final Account a = (Account) getIntent().getExtras().get("account");
Bundle scanVal = null;
Intent scannerValue = getIntent();
scanVal = scannerValue.getExtras();
TextView productName = (TextView) findViewById(R.id.productName);
TextView productBrand = (TextView) findViewById(R.id.productBrand);
TextView expInformation = (TextView) findViewById(R.id.expInformation);
TextView priceInformation = (TextView) findViewById(R.id.priceInformation);
TextView reviewInformation = (TextView) findViewById(R.id.reviewInformation);
String name = "";
String brand= "";
String id ="";
Food scannedFood = new Food();
if(scanVal != null){
final String scanValue = scanVal.getString("scanID");
ExecutorService pool = Executors.newFixedThreadPool(3);
Callable task = new Callable(){
@Override
public Object call() throws Exception{
DatabaseAPI database = new DatabaseAPI();
Food food = database.getFoodItemByID(scanValue);
if(food.getName() != null){
return food;
}
else{
return null;
}
}
};
Future<Food> future = pool.submit(task);
try {
scannedFood = future.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(scannedFood.getID() != null){
Expiration expirationInfo = scannedFood.getExpirationInformation();
Price priceInfo = scannedFood.getPriceInformation();
List<Review> reviewInfo = scannedFood.getReviewInformation();
name = scannedFood.getName();
brand = scannedFood.getBrand();
id = scannedFood.getID();
productName.setText("Product: " + name);
productBrand.setText("Product brand: " + brand);
expInformation.setText("Average Expiration: " + expirationInfo.getAvgHours() + " Hours");
priceInformation.setText("Average Price: " + "$" + priceInfo.getAvgPrice());
String str = "Reviews:\n\n";
for(int i = 0; i < 3 && i < reviewInfo.size(); i++)
{
Review itemToAdd = reviewInfo.get(i);
str += itemToAdd != null ? itemToAdd.getReview() + "\n\n" : "";
}
reviewInformation.setText(str);
}
else{
productName.setText("Item not found");
productBrand.setVisibility(View.INVISIBLE);
expInformation.setVisibility(View.INVISIBLE);
priceInformation.setVisibility(View.INVISIBLE);
reviewInformation.setVisibility(View.INVISIBLE);
}
}
else{
productName.setText("Item not found");
productBrand.setVisibility(View.INVISIBLE);
expInformation.setVisibility(View.INVISIBLE);
priceInformation.setVisibility(View.INVISIBLE);
reviewInformation.setVisibility(View.INVISIBLE);
}
//home button
Button goToFoodFinderBtn = (Button) findViewById(R.id.addItem);
goToFoodFinderBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(){
@Override
public void run()
{
Account account = (Account) getIntent().getExtras().get("account");
final String scanValue = getIntent().getExtras().getString("scanID");
DatabaseAPI database = new DatabaseAPI();
Food food = database.getFoodItemByID(scanValue);
database.addFoodItemToUserTable(account.getUserID(), food);
Intent i = new Intent(FoodResultsActivity.this, HomeActivity.class);
i.putExtra("account", account);
startActivity(i);
}
};
thread.start();
}
});
}
|
diff --git a/src/org/broad/igv/sam/AlignmentInterval.java b/src/org/broad/igv/sam/AlignmentInterval.java
index 3196b109f..dce288231 100644
--- a/src/org/broad/igv/sam/AlignmentInterval.java
+++ b/src/org/broad/igv/sam/AlignmentInterval.java
@@ -1,613 +1,613 @@
/*
* Copyright (c) 2007-2012 The Broad Institute, Inc.
* SOFTWARE COPYRIGHT NOTICE
* This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved.
*
* This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.sam;
import com.google.common.base.Predicate;
import org.apache.log4j.Logger;
import org.broad.igv.data.Interval;
import org.broad.igv.feature.FeatureUtils;
import org.broad.igv.feature.Locus;
import org.broad.igv.feature.SpliceJunctionFeature;
import org.broad.igv.feature.Strand;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.tribble.Feature;
import java.util.*;
import static org.broad.igv.util.collections.CollUtils.filter;
/**
* @author jrobinso
*/
public class AlignmentInterval extends Locus implements Interval {
private static Logger log = Logger.getLogger(AlignmentInterval.class);
Genome genome;
private int maxCount = 0;
private AlignmentCounts counts;
private LinkedHashMap<String, List<Row>> groupedAlignmentRows; // The alignments
private List<SpliceJunctionFeature> spliceJunctions;
private List<DownsampledInterval> downsampledIntervals;
private AlignmentTrack.RenderOptions renderOptions;
public AlignmentInterval(String chr, int start, int end,
LinkedHashMap<String, List<Row>> groupedAlignmentRows,
AlignmentCounts counts,
List<SpliceJunctionFeature> spliceJunctions,
List<DownsampledInterval> downsampledIntervals,
AlignmentTrack.RenderOptions renderOptions) {
super(chr, start, end);
this.groupedAlignmentRows = groupedAlignmentRows;
genome = GenomeManager.getInstance().getCurrentGenome();
//reference = genome.getSequence(chr, start, end);
this.counts = counts;
this.maxCount = counts.getMaxCount();
this.spliceJunctions = spliceJunctions;
this.downsampledIntervals = downsampledIntervals;
this.renderOptions = renderOptions;
}
static AlignmentInterval emptyAlignmentInterval(String chr, int start, int end) {
return new AlignmentInterval(chr, start, end, null, null, null, null, null);
}
static Alignment getFeatureContaining(List<Alignment> features, int right) {
int leftBounds = 0;
int rightBounds = features.size() - 1;
int idx = features.size() / 2;
int lastIdx = -1;
while (idx != lastIdx) {
lastIdx = idx;
Alignment f = features.get(idx);
if (f.contains(right)) {
return f;
}
if (f.getStart() > right) {
rightBounds = idx;
idx = (leftBounds + idx) / 2;
} else {
leftBounds = idx;
idx = (rightBounds + idx) / 2;
}
}
// Check the extremes
if (features.get(0).contains(right)) {
return features.get(0);
}
if (features.get(rightBounds).contains(right)) {
return features.get(rightBounds);
}
return null;
}
/**
* The "packed" alignments in this interval
*/
public LinkedHashMap<String, List<Row>> getGroupedAlignments() {
return groupedAlignmentRows;
}
public int getGroupCount() {
return groupedAlignmentRows == null ? 0 : groupedAlignmentRows.size();
}
public void setAlignmentRows(LinkedHashMap<String, List<Row>> alignmentRows, AlignmentTrack.RenderOptions renderOptions) {
this.groupedAlignmentRows = alignmentRows;
this.renderOptions = renderOptions;
}
public void sortRows(AlignmentTrack.SortOption option, ReferenceFrame referenceFrame, String tag) {
double center = referenceFrame.getCenter();
sortRows(option, center, tag);
}
/**
* Sort rows group by group
*
* @param option
* @param location
*/
public void sortRows(AlignmentTrack.SortOption option, double location, String tag) {
if (groupedAlignmentRows == null) {
return;
}
for (List<AlignmentInterval.Row> alignmentRows : groupedAlignmentRows.values()) {
for (AlignmentInterval.Row row : alignmentRows) {
row.updateScore(option, location, this, tag);
}
Collections.sort(alignmentRows);
}
}
public byte getReference(int pos) {
if (genome == null) {
return 0;
}
return genome.getReference(getChr(), pos);
}
public AlignmentCounts getCounts() {
return counts;
}
/**
* Return the count of the specified nucleotide
*
* @param pos genomic position
* @param b nucleotide
* @return
*/
public int getCount(int pos, byte b) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getCount(pos, b);
}
return 0;
}
public int getMaxCount() {
return maxCount;
}
public AlignmentCounts getAlignmentCounts(int pos) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c;
}
return null;
}
public int getTotalCount(int pos) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getTotalCount(pos);
}
return 0;
}
public int getNegCount(int pos, byte b) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getNegCount(pos, b);
}
return 0;
}
public int getPosCount(int pos, byte b) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getPosCount(pos, b);
}
return 0;
}
public int getDelCount(int pos) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getDelCount(pos);
}
return 0;
}
public int getInsCount(int pos) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getInsCount(pos);
}
return 0;
}
public Iterator<Alignment> getAlignmentIterator() {
return new AlignmentIterator();
}
public List<SpliceJunctionFeature> getSpliceJunctions() {
return spliceJunctions;
}
public List<DownsampledInterval> getDownsampledIntervals() {
return downsampledIntervals;
}
@Override
public boolean contains(String chr, int start, int end, int zoom) {
return super.contains(chr, start, end);
}
@Override
public boolean overlaps(String chr, int start, int end, int zoom) {
return super.overlaps(chr, start, end);
}
@Override
public boolean canMerge(Interval i) {
if (!super.overlaps(i.getChr(), i.getStart(), i.getEnd())
|| !(i instanceof AlignmentInterval)) {
return false;
}
return getCounts().getClass().equals(((AlignmentInterval) i).getCounts().getClass());
}
@Override
public boolean merge(Interval i) {
boolean canMerge = this.canMerge(i);
if (!canMerge) return false;
AlignmentInterval other = (AlignmentInterval) i;
List<Alignment> allAlignments = (List<Alignment>) FeatureUtils.combineSortedFeatureListsNoDups(
getAlignmentIterator(), other.getAlignmentIterator(), start, end);
this.counts = counts.merge(other.getCounts(), renderOptions.bisulfiteContext);
this.spliceJunctions = FeatureUtils.combineSortedFeatureListsNoDups(this.spliceJunctions, other.getSpliceJunctions(), start, end);
this.downsampledIntervals = FeatureUtils.combineSortedFeatureListsNoDups(this.downsampledIntervals, other.getDownsampledIntervals(), start, end);
//This must be done AFTER calling combineSortedFeatureListsNoDups for the last time,
//because we rely on the original start/end
this.start = Math.min(getStart(), i.getStart());
this.end = Math.max(getEnd(), i.getEnd());
this.maxCount = Math.max(this.getMaxCount(), other.getMaxCount());
AlignmentPacker packer = new AlignmentPacker();
this.groupedAlignmentRows = packer.packAlignments(allAlignments.iterator(), this.end, renderOptions);
return true;
}
/**
* Remove data outside the specified interval.
* This interval must contain the specified interval.
*
* @param chr
* @param start
* @param end
* @param zoom
* @return true if any trimming was performed, false if not
*/
public boolean trimTo(final String chr, final int start, final int end, int zoom) {
boolean toRet = false;
if (!this.contains(chr, start, end, zoom)) {
return false;
}
for (String groupKey : groupedAlignmentRows.keySet()) {
for (AlignmentInterval.Row row : groupedAlignmentRows.get(groupKey)) {
Iterator<Alignment> alIter = row.alignments.iterator();
Alignment al;
while (alIter.hasNext()) {
al = alIter.next();
if (al.getEnd() < start || al.getStart() > end) {
alIter.remove();
toRet |= true;
}
}
}
}
Predicate<Feature> overlapPredicate = FeatureUtils.getOverlapPredicate(chr, start, end);
//getCounts().trimTo(chr, start, end);
filter(this.getDownsampledIntervals(), overlapPredicate);
filter(this.getSpliceJunctions(), overlapPredicate);
this.start = Math.max(this.start, start);
this.end = Math.min(this.end, end);
return toRet;
}
private List addToListNoDups(List self, List other) {
if (self == null) self = new ArrayList();
if (other != null) {
Set selfSet = new HashSet(self);
selfSet.addAll(other);
self = new ArrayList(selfSet);
FeatureUtils.sortFeatureList(self);
}
return self;
}
/**
* AlignmentInterval data is independent of zoom
*
* @return
*/
@Override
public int getZoom() {
return -1;
}
public static class Row implements Comparable<Row> {
int nextIdx;
private double score = 0;
List<Alignment> alignments;
private int start;
private int lastEnd;
public Row() {
nextIdx = 0;
this.alignments = new ArrayList(100);
}
public void addAlignment(Alignment alignment) {
if (alignments.isEmpty()) {
this.start = alignment.getStart();
}
alignments.add(alignment);
lastEnd = alignment.getEnd();
}
public void updateScore(AlignmentTrack.SortOption option, Locus locus, AlignmentInterval interval, String tag) {
double mean = 0;
//double sd = 0;
int number = 0;
for (int center = locus.getStart(); center < locus.getEnd(); center++) {
double value = calculateScore(option, center, interval, tag);
mean = number * (mean / (number + 1)) + (value / (number + 1));
number++;
}
setScore(mean);
}
public void updateScore(AlignmentTrack.SortOption option, double center, AlignmentInterval interval, String tag) {
setScore(calculateScore(option, center, interval, tag));
}
public double calculateScore(AlignmentTrack.SortOption option, double center, AlignmentInterval interval, String tag) {
int adjustedCenter = (int) center;
Alignment centerAlignment = getFeatureContaining(alignments, adjustedCenter);
if (centerAlignment == null) {
return Integer.MAX_VALUE;
} else {
switch (option) {
case START:
return centerAlignment.getStart();
case STRAND:
return centerAlignment.isNegativeStrand() ? -1 : 1;
case FIRST_OF_PAIR_STRAND:
Strand strand = centerAlignment.getFirstOfPairStrand();
int score = 2;
if (strand != Strand.NONE) {
score = strand == Strand.NEGATIVE ? 1 : -1;
}
return score;
case NUCELOTIDE:
byte base = centerAlignment.getBase(adjustedCenter);
byte ref = interval.getReference(adjustedCenter);
if (base == 'N' || base == 'n') {
- return -2; // Base is "n"
+ return 2; // Base is "n"
} else if (base == ref) {
- return -1; // Base is reference
+ return 3; // Base is reference
} else {
//If base is 0, base not covered (splice junction) or is deletion
if (base == 0) {
int delCount = interval.getDelCount(adjustedCenter);
if (delCount > 0) {
return -delCount;
} else {
//Base not covered, NOT a deletion
- return 0;
+ return 1;
}
} else {
int count = interval.getCount(adjustedCenter, base);
byte phred = centerAlignment.getPhred(adjustedCenter);
return -(count + (phred / 100.0f));
}
}
case QUALITY:
return -centerAlignment.getMappingQuality();
case SAMPLE:
String sample = centerAlignment.getSample();
score = sample == null ? 0 : sample.hashCode();
return score;
case READ_GROUP:
String readGroup = centerAlignment.getReadGroup();
score = readGroup == null ? 0 : readGroup.hashCode();
return score;
case INSERT_SIZE:
return -Math.abs(centerAlignment.getInferredInsertSize());
case MATE_CHR:
ReadMate mate = centerAlignment.getMate();
if (mate == null) {
return Integer.MAX_VALUE;
} else {
if (mate.getChr().equals(centerAlignment.getChr())) {
return Integer.MAX_VALUE - 1;
} else {
return mate.getChr().hashCode();
}
}
case TAG:
Object tagValue = centerAlignment.getAttribute(tag);
score = tagValue == null ? 0 : tagValue.hashCode();
return score;
default:
return Integer.MAX_VALUE;
}
}
}
// Used for iterating over all alignments, e.g. for packing
public Alignment nextAlignment() {
if (nextIdx < alignments.size()) {
Alignment tmp = alignments.get(nextIdx);
nextIdx++;
return tmp;
} else {
return null;
}
}
public int getNextStartPos() {
if (nextIdx < alignments.size()) {
return alignments.get(nextIdx).getStart();
} else {
return Integer.MAX_VALUE;
}
}
public boolean hasNext() {
return nextIdx < alignments.size();
}
public void resetIdx() {
nextIdx = 0;
}
/**
* @return the score
*/
public double getScore() {
return score;
}
/**
* @param score the score to set
*/
public void setScore(double score) {
this.score = score;
}
public int getStart() {
return start;
}
public int getLastEnd() {
return lastEnd;
}
@Override
public int compareTo(Row o) {
return (int) Math.signum(getScore() - o.getScore());
}
// @Override
// public boolean equals(Object object){
// if(!(object instanceof Row)){
// return false;
// }
// Row other = (Row) object;
// boolean equals = this.getStart() == other.getStart();
// equals &= this.getLastEnd() == other.getLastEnd();
// equals &= this.getScore() == other.getScore();
//
// return equals;
//
// }
//
// @Override
// public int hashCode(){
// int score = (int) getScore();
// score = score != 0 ? score : 1;
// return (getStart() * getLastEnd() * score);
// }
} // end class row
/**
* An alignment iterator that iterates over packed rows. Used for
* "repacking". Using the iterator avoids the need to copy alignments
* from the rows
*/
class AlignmentIterator implements Iterator<Alignment> {
PriorityQueue<AlignmentInterval.Row> rows;
Alignment nextAlignment;
AlignmentIterator() {
rows = new PriorityQueue(5, new Comparator<AlignmentInterval.Row>() {
public int compare(AlignmentInterval.Row o1, AlignmentInterval.Row o2) {
return o1.getNextStartPos() - o2.getNextStartPos();
}
});
for (List<AlignmentInterval.Row> alignmentRows : groupedAlignmentRows.values()) {
for (AlignmentInterval.Row r : alignmentRows) {
r.resetIdx();
rows.add(r);
}
}
advance();
}
public boolean hasNext() {
return nextAlignment != null;
}
public Alignment next() {
Alignment tmp = nextAlignment;
if (tmp != null) {
advance();
}
return tmp;
}
private void advance() {
nextAlignment = null;
AlignmentInterval.Row nextRow = null;
while (nextAlignment == null && !rows.isEmpty()) {
while ((nextRow = rows.poll()) != null) {
if (nextRow.hasNext()) {
nextAlignment = nextRow.nextAlignment();
break;
}
}
}
if (nextRow != null && nextAlignment != null) {
rows.add(nextRow);
}
}
public void remove() {
// ignore
}
}
}
| false | true | public double calculateScore(AlignmentTrack.SortOption option, double center, AlignmentInterval interval, String tag) {
int adjustedCenter = (int) center;
Alignment centerAlignment = getFeatureContaining(alignments, adjustedCenter);
if (centerAlignment == null) {
return Integer.MAX_VALUE;
} else {
switch (option) {
case START:
return centerAlignment.getStart();
case STRAND:
return centerAlignment.isNegativeStrand() ? -1 : 1;
case FIRST_OF_PAIR_STRAND:
Strand strand = centerAlignment.getFirstOfPairStrand();
int score = 2;
if (strand != Strand.NONE) {
score = strand == Strand.NEGATIVE ? 1 : -1;
}
return score;
case NUCELOTIDE:
byte base = centerAlignment.getBase(adjustedCenter);
byte ref = interval.getReference(adjustedCenter);
if (base == 'N' || base == 'n') {
return -2; // Base is "n"
} else if (base == ref) {
return -1; // Base is reference
} else {
//If base is 0, base not covered (splice junction) or is deletion
if (base == 0) {
int delCount = interval.getDelCount(adjustedCenter);
if (delCount > 0) {
return -delCount;
} else {
//Base not covered, NOT a deletion
return 0;
}
} else {
int count = interval.getCount(adjustedCenter, base);
byte phred = centerAlignment.getPhred(adjustedCenter);
return -(count + (phred / 100.0f));
}
}
case QUALITY:
return -centerAlignment.getMappingQuality();
case SAMPLE:
String sample = centerAlignment.getSample();
score = sample == null ? 0 : sample.hashCode();
return score;
case READ_GROUP:
String readGroup = centerAlignment.getReadGroup();
score = readGroup == null ? 0 : readGroup.hashCode();
return score;
case INSERT_SIZE:
return -Math.abs(centerAlignment.getInferredInsertSize());
case MATE_CHR:
ReadMate mate = centerAlignment.getMate();
if (mate == null) {
return Integer.MAX_VALUE;
} else {
if (mate.getChr().equals(centerAlignment.getChr())) {
return Integer.MAX_VALUE - 1;
} else {
return mate.getChr().hashCode();
}
}
case TAG:
Object tagValue = centerAlignment.getAttribute(tag);
score = tagValue == null ? 0 : tagValue.hashCode();
return score;
default:
return Integer.MAX_VALUE;
}
}
}
| public double calculateScore(AlignmentTrack.SortOption option, double center, AlignmentInterval interval, String tag) {
int adjustedCenter = (int) center;
Alignment centerAlignment = getFeatureContaining(alignments, adjustedCenter);
if (centerAlignment == null) {
return Integer.MAX_VALUE;
} else {
switch (option) {
case START:
return centerAlignment.getStart();
case STRAND:
return centerAlignment.isNegativeStrand() ? -1 : 1;
case FIRST_OF_PAIR_STRAND:
Strand strand = centerAlignment.getFirstOfPairStrand();
int score = 2;
if (strand != Strand.NONE) {
score = strand == Strand.NEGATIVE ? 1 : -1;
}
return score;
case NUCELOTIDE:
byte base = centerAlignment.getBase(adjustedCenter);
byte ref = interval.getReference(adjustedCenter);
if (base == 'N' || base == 'n') {
return 2; // Base is "n"
} else if (base == ref) {
return 3; // Base is reference
} else {
//If base is 0, base not covered (splice junction) or is deletion
if (base == 0) {
int delCount = interval.getDelCount(adjustedCenter);
if (delCount > 0) {
return -delCount;
} else {
//Base not covered, NOT a deletion
return 1;
}
} else {
int count = interval.getCount(adjustedCenter, base);
byte phred = centerAlignment.getPhred(adjustedCenter);
return -(count + (phred / 100.0f));
}
}
case QUALITY:
return -centerAlignment.getMappingQuality();
case SAMPLE:
String sample = centerAlignment.getSample();
score = sample == null ? 0 : sample.hashCode();
return score;
case READ_GROUP:
String readGroup = centerAlignment.getReadGroup();
score = readGroup == null ? 0 : readGroup.hashCode();
return score;
case INSERT_SIZE:
return -Math.abs(centerAlignment.getInferredInsertSize());
case MATE_CHR:
ReadMate mate = centerAlignment.getMate();
if (mate == null) {
return Integer.MAX_VALUE;
} else {
if (mate.getChr().equals(centerAlignment.getChr())) {
return Integer.MAX_VALUE - 1;
} else {
return mate.getChr().hashCode();
}
}
case TAG:
Object tagValue = centerAlignment.getAttribute(tag);
score = tagValue == null ? 0 : tagValue.hashCode();
return score;
default:
return Integer.MAX_VALUE;
}
}
}
|
diff --git a/src/haven/Material.java b/src/haven/Material.java
index 14156f28..ee9c29a7 100644
--- a/src/haven/Material.java
+++ b/src/haven/Material.java
@@ -1,262 +1,262 @@
/*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <[email protected]>, and
* Björn Johannessen <[email protected]>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser General Public License, version 3, as
* published by the Free Software Foundation.
*
* 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.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package haven;
import java.awt.Color;
import java.util.*;
import javax.media.opengl.*;
import static haven.Utils.c2fa;
public class Material extends GLState {
public final GLState[] states;
public static final GLState nofacecull = new GLState.StandAlone(PView.proj) {
public void apply(GOut g) {
g.gl.glDisable(GL.GL_CULL_FACE);
}
public void unapply(GOut g) {
g.gl.glEnable(GL.GL_CULL_FACE);
}
};
public static final GLState alphaclip = new GLState.StandAlone(PView.proj) {
public void apply(GOut g) {
g.gl.glEnable(GL.GL_ALPHA_TEST);
}
public void unapply(GOut g) {
g.gl.glDisable(GL.GL_ALPHA_TEST);
}
};
public static final float[] defamb = {0.2f, 0.2f, 0.2f, 1.0f};
public static final float[] defdif = {0.8f, 0.8f, 0.8f, 1.0f};
public static final float[] defspc = {0.0f, 0.0f, 0.0f, 1.0f};
public static final float[] defemi = {0.0f, 0.0f, 0.0f, 1.0f};
public static final GLState.Slot<Colors> colors = new GLState.Slot<Colors>(Colors.class);
public static class Colors extends GLState {
public float[] amb, dif, spc, emi;
public float shine;
public Colors() {
amb = defamb;
dif = defdif;
spc = defspc;
emi = defemi;
}
public Colors(Color amb, Color dif, Color spc, Color emi, float shine) {
build(amb, dif, spc, emi);
this.shine = shine;
}
public Colors(Color col) {
this(new Color((int)(col.getRed() * defamb[0]), (int)(col.getGreen() * defamb[1]), (int)(col.getBlue() * defamb[2]), col.getAlpha()),
new Color((int)(col.getRed() * defdif[0]), (int)(col.getGreen() * defdif[1]), (int)(col.getBlue() * defdif[2]), col.getAlpha()),
new Color(0, 0, 0, 0),
new Color(0, 0, 0, 0),
0);
}
public void build(Color amb, Color dif, Color spc, Color emi) {
this.amb = c2fa(amb);
this.dif = c2fa(dif);
this.spc = c2fa(spc);
this.emi = c2fa(emi);
}
public void apply(GOut g) {
GL gl = g.gl;
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT, amb, 0);
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, dif, 0);
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, spc, 0);
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_EMISSION, emi, 0);
gl.glMaterialf(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS, shine);
}
public void unapply(GOut g) {
GL gl = g.gl;
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT, defamb, 0);
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, defdif, 0);
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, defspc, 0);
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_EMISSION, defemi, 0);
gl.glMaterialf(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS, 0.0f);
}
public int capplyfrom(GLState from) {
if(from instanceof Colors)
return(5);
return(-1);
}
public void applyfrom(GOut g, GLState from) {
if(from instanceof Colors)
apply(g);
}
public void prep(Buffer buf) {
buf.put(colors, this);
}
public String toString() {
return(String.format("(%.1f, %.1f, %.1f), (%.1f, %.1f, %.1f), (%.1f, %.1f, %.1f @ %.1f)",
amb[0], amb[1], amb[2], dif[0], dif[1], dif[2], spc[0], spc[1], spc[2], shine));
}
}
public void apply(GOut g) {}
public void unapply(GOut g) {}
public Material(GLState... states) {
this.states = states;
}
public Material() {
this(new Colors(), alphaclip);
}
public Material(Color amb, Color dif, Color spc, Color emi, float shine) {
this(new Colors(amb, dif, spc, emi, shine), alphaclip);
}
public Material(Color col) {
this(new Colors(col));
}
public Material(Tex tex) {
this(new Colors(), tex, alphaclip);
}
public String toString() {
return(Arrays.asList(states).toString());
}
private static GLState deflight = Light.vlights;
public void prep(Buffer buf) {
for(GLState st : states)
st.prep(buf);
buf.cfg.deflight.prep(buf);
}
public static class Res extends Resource.Layer {
public final int id;
private transient List<GLState> states = new LinkedList<GLState>();
private transient List<Resolver> left = new LinkedList<Resolver>();
private transient Material m;
private boolean mipmap = false, linear = false;
private interface Resolver {
public GLState resolve();
}
private static Color col(byte[] buf, int[] off) {
double r = Utils.floatd(buf, off[0]); off[0] += 5;
double g = Utils.floatd(buf, off[0]); off[0] += 5;
double b = Utils.floatd(buf, off[0]); off[0] += 5;
double a = Utils.floatd(buf, off[0]); off[0] += 5;
return(new Color((float)r, (float)g, (float)b, (float)a));
}
public Res(Resource res, byte[] buf) {
res.super();
id = Utils.uint16d(buf, 0);
int[] off = {2};
while(off[0] < buf.length) {
String thing = Utils.strd(buf, off).intern();
if(thing == "col") {
Color amb = col(buf, off);
Color dif = col(buf, off);
Color spc = col(buf, off);
double shine = Utils.floatd(buf, off[0]); off[0] += 5;
Color emi = col(buf, off);
states.add(new Colors(amb, dif, spc, emi, (float)shine));
} else if(thing == "linear") {
linear = true;
} else if(thing == "mipmap") {
mipmap = true;
} else if(thing == "nofacecull") {
states.add(nofacecull);
} else if(thing == "tex") {
final int id = Utils.uint16d(buf, off[0]); off[0] += 2;
left.add(new Resolver() {
public GLState resolve() {
- for(Resource.Image img : getres().layers(Resource.imgc, false)) {
+ for(Resource.Image img : getres().layers(Resource.imgc)) {
if(img.id == id)
return(img.tex());
}
throw(new RuntimeException(String.format("Specified texture %d not found in %s", id, getres())));
}
});
} else if(thing == "texlink") {
final String nm = Utils.strd(buf, off);
final int ver = Utils.uint16d(buf, off[0]); off[0] += 2;
final int id = Utils.uint16d(buf, off[0]); off[0] += 2;
left.add(new Resolver() {
public GLState resolve() {
Resource res = Resource.load(nm, ver);
- for(Resource.Image img : res.layers(Resource.imgc, false)) {
+ for(Resource.Image img : res.layers(Resource.imgc)) {
if(img.id == id)
return(img.tex());
}
throw(new RuntimeException(String.format("Specified texture %d for %s not found in %s", id, getres(), res)));
}
});
} else {
throw(new Resource.LoadException("Unknown material part: " + thing, getres()));
}
}
states.add(alphaclip);
}
public Material get() {
synchronized(this) {
if(m == null) {
for(Iterator<Resolver> i = left.iterator(); i.hasNext();) {
Resolver r = i.next();
states.add(r.resolve());
i.remove();
}
m = new Material(states.toArray(new GLState[0]));
}
return(m);
}
}
public void init() {
for(Resource.Image img : getres().layers(Resource.imgc, false)) {
TexGL tex = (TexGL)img.tex();
if(mipmap)
tex.mipmap();
if(linear)
tex.magfilter(GL.GL_LINEAR);
}
}
}
}
| false | true | public Res(Resource res, byte[] buf) {
res.super();
id = Utils.uint16d(buf, 0);
int[] off = {2};
while(off[0] < buf.length) {
String thing = Utils.strd(buf, off).intern();
if(thing == "col") {
Color amb = col(buf, off);
Color dif = col(buf, off);
Color spc = col(buf, off);
double shine = Utils.floatd(buf, off[0]); off[0] += 5;
Color emi = col(buf, off);
states.add(new Colors(amb, dif, spc, emi, (float)shine));
} else if(thing == "linear") {
linear = true;
} else if(thing == "mipmap") {
mipmap = true;
} else if(thing == "nofacecull") {
states.add(nofacecull);
} else if(thing == "tex") {
final int id = Utils.uint16d(buf, off[0]); off[0] += 2;
left.add(new Resolver() {
public GLState resolve() {
for(Resource.Image img : getres().layers(Resource.imgc, false)) {
if(img.id == id)
return(img.tex());
}
throw(new RuntimeException(String.format("Specified texture %d not found in %s", id, getres())));
}
});
} else if(thing == "texlink") {
final String nm = Utils.strd(buf, off);
final int ver = Utils.uint16d(buf, off[0]); off[0] += 2;
final int id = Utils.uint16d(buf, off[0]); off[0] += 2;
left.add(new Resolver() {
public GLState resolve() {
Resource res = Resource.load(nm, ver);
for(Resource.Image img : res.layers(Resource.imgc, false)) {
if(img.id == id)
return(img.tex());
}
throw(new RuntimeException(String.format("Specified texture %d for %s not found in %s", id, getres(), res)));
}
});
} else {
throw(new Resource.LoadException("Unknown material part: " + thing, getres()));
}
}
states.add(alphaclip);
}
| public Res(Resource res, byte[] buf) {
res.super();
id = Utils.uint16d(buf, 0);
int[] off = {2};
while(off[0] < buf.length) {
String thing = Utils.strd(buf, off).intern();
if(thing == "col") {
Color amb = col(buf, off);
Color dif = col(buf, off);
Color spc = col(buf, off);
double shine = Utils.floatd(buf, off[0]); off[0] += 5;
Color emi = col(buf, off);
states.add(new Colors(amb, dif, spc, emi, (float)shine));
} else if(thing == "linear") {
linear = true;
} else if(thing == "mipmap") {
mipmap = true;
} else if(thing == "nofacecull") {
states.add(nofacecull);
} else if(thing == "tex") {
final int id = Utils.uint16d(buf, off[0]); off[0] += 2;
left.add(new Resolver() {
public GLState resolve() {
for(Resource.Image img : getres().layers(Resource.imgc)) {
if(img.id == id)
return(img.tex());
}
throw(new RuntimeException(String.format("Specified texture %d not found in %s", id, getres())));
}
});
} else if(thing == "texlink") {
final String nm = Utils.strd(buf, off);
final int ver = Utils.uint16d(buf, off[0]); off[0] += 2;
final int id = Utils.uint16d(buf, off[0]); off[0] += 2;
left.add(new Resolver() {
public GLState resolve() {
Resource res = Resource.load(nm, ver);
for(Resource.Image img : res.layers(Resource.imgc)) {
if(img.id == id)
return(img.tex());
}
throw(new RuntimeException(String.format("Specified texture %d for %s not found in %s", id, getres(), res)));
}
});
} else {
throw(new Resource.LoadException("Unknown material part: " + thing, getres()));
}
}
states.add(alphaclip);
}
|
diff --git a/src/com/dynamobi/ws/impl/UsersAndRolesServiceImpl.java b/src/com/dynamobi/ws/impl/UsersAndRolesServiceImpl.java
index a0f5f10..113bf90 100644
--- a/src/com/dynamobi/ws/impl/UsersAndRolesServiceImpl.java
+++ b/src/com/dynamobi/ws/impl/UsersAndRolesServiceImpl.java
@@ -1,313 +1,313 @@
package com.dynamobi.ws.impl;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.jws.WebService;
import javax.ws.rs.Path;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.dynamobi.ws.api.UsersAndRolesService;
import com.dynamobi.ws.domain.UserDetails;
import com.dynamobi.ws.domain.SessionInfo;
import com.dynamobi.ws.domain.RolesDetails;
import com.dynamobi.ws.domain.RolesDetailsHolder;
import com.dynamobi.ws.domain.PermissionsInfo;
import com.dynamobi.ws.util.AppException;
import com.dynamobi.ws.util.DBAccess;
/**
* UsersAndRolesService implementation
*
* @author Kevin Secretan
* @since June 24, 2010
*/
@WebService(endpointInterface = "com.dynamobi.ws.api.UsersAndRolesService")
@Path("/users")
public class UsersAndRolesServiceImpl implements UsersAndRolesService {
/* TODO: use prepared statements / better db interface
*/
public List<UserDetails> getUsersDetails() throws AppException {
List<UserDetails> details = new ArrayList<UserDetails>();
try {
final String query = "SELECT name, password, creation_timestamp, "
+ "modification_timestamp FROM sys_root.dba_users u WHERE "
+ "u.name <> '_SYSTEM'";
ResultSet rs = DBAccess.rawResultExec(query);
while (rs.next()) {
UserDetails ud = new UserDetails();
ud.name = rs.getString(1);
ud.password = rs.getString(2);
ud.creation_timestamp = rs.getString(3);
ud.modification_timestamp = rs.getString(4);
details.add(ud);
}
} catch (SQLException e) {
e.printStackTrace();
}
return details;
}
public List<SessionInfo> getCurrentSessions() throws AppException {
return DBAccess.getCurrentSessions();
}
private enum Action { NEW, MOD, DEL };
private String userAction(String user, String password, Action act)
throws AppException {
// TODO: rewrite this to use prepared statements
String query = "";
if (act == Action.NEW) {
query = "CREATE USER " + user + " IDENTIFIED BY '" + password + "'";
} else if (act == Action.MOD) {
query = "CREATE OR REPLACE USER " + user + " IDENTIFIED BY '" + password + "'";
} else if (act == Action.DEL) {
query = "DROP USER " + user;
}
String retval = "";
try {
ResultSet rs = DBAccess.rawResultExec(query);
} catch (SQLException e) {
e.printStackTrace();
retval = e.getMessage();
}
return retval;
}
public String addNewUser(String user, String password) throws AppException {
return userAction(user, password, Action.NEW);
}
// TODO: also adjust the roles when modifying and deleting.
// Research: what happens if I just change the name/password in
// the table rather than doing CREATE or REPLACE? That would be a better
// solution and should preserve roles due to mofIds remaining the same.
// Just gotta find out if user/pass are in more than one place.
public String modifyUser(String user, String password) throws AppException {
return userAction(user, password, Action.MOD);
}
public String deleteUser(String user) throws AppException {
return userAction(user, "", Action.DEL);
}
public RolesDetailsHolder getRolesDetails() throws AppException {
String query = "SELECT DISTINCT granted_catalog, granted_schema, granted_element, "
+ "grantee, grantor, action, "
+ "CASE WHEN r.role IS NOT NULL THEN r.role "
+ "WHEN grant_type = 'Role' THEN grantee END AS role_name, "
- + "grant_type, table_type, g.with_grant_option "
+ + "grant_type, class_name, g.with_grant_option "
+ "FROM sys_root.dba_element_grants g left outer join sys_root.dba_user_roles r "
+ "ON action = 'INHERIT_ROLE' AND r.role_mof_id = element_mof_id "
+ "WHERE (grant_type = 'Role' AND grantee <> 'PUBLIC' "
+ "AND grantee <> '_SYSTEM') OR action = 'INHERIT_ROLE'";
Map<String, RolesDetails> details = new LinkedHashMap<String, RolesDetails>();
Map<String, PermissionsInfo> perms = new LinkedHashMap<String, PermissionsInfo>();
try {
ResultSet rs = DBAccess.rawResultExec(query);
while (rs.next()) {
int col = 1;
final String catalog = rs.getString(col++);
final String schema = rs.getString(col++);
final String element = rs.getString(col++);
final String grantee = rs.getString(col++);
final String grantor = rs.getString(col++);
final String action = rs.getString(col++);
final String role_name = rs.getString(col++);
final String grant_type = rs.getString(col++);
- final String table_type = rs.getString(col++);
+ final String class_name = rs.getString(col++);
final boolean with_grant = rs.getBoolean(col++);
RolesDetails rd;
if (!details.containsKey(role_name)) {
rd = new RolesDetails();
rd.name = role_name;
details.put(role_name, rd);
} else {
rd = details.get(role_name);
}
// Dealing with a users or permissions entry?
if (grant_type.equals("User")) {
rd.users.add(grantee);
if (with_grant) {
rd.users_with_grant_option.add(grantee);
}
} else if (grant_type.equals("Role")) {
- final String key = role_name + catalog + schema + element + table_type;
+ final String key = role_name + catalog + schema + element + class_name;
PermissionsInfo p;
if (!perms.containsKey(key)) {
p = new PermissionsInfo();
p.catalog_name = catalog;
p.schema_name = schema;
p.item_name = element;
- p.item_type = table_type;
+ p.item_type = class_name;
perms.put(key, p);
rd.permissions.add(p);
} else {
p = perms.get(key);
}
p.actions.add(action);
} else {
throw new AppException("Unknown grant type");
}
}
ResultSet rs_extra_roles = DBAccess.rawResultExec("SELECT name FROM sys_root.dba_roles WHERE name <> 'PUBLIC'");
while (rs_extra_roles.next()) {
final String role_name = rs_extra_roles.getString(1);
if (!details.containsKey(role_name)) {
RolesDetails rd = new RolesDetails();
rd.name = role_name;
details.put(role_name, rd);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
RolesDetailsHolder rh = new RolesDetailsHolder();
rh.value.addAll(details.values());
return rh;
}
public String addNewRole(String role) throws AppException {
String retval = "";
String query = "CREATE ROLE " + role;
try {
ResultSet rs = DBAccess.rawResultExec(query);
} catch (SQLException e) {
e.printStackTrace();
retval = e.getMessage();
}
return retval;
}
public String deleteRole(String role) throws AppException {
String retval = "";
String query = "DROP ROLE " + role;
try {
ResultSet rs = DBAccess.rawResultExec(query);
} catch (SQLException e) {
e.printStackTrace();
retval = e.getMessage();
}
return retval;
}
public String userToRole(String user, String role, boolean added, boolean with_grant) throws AppException {
String retval = "";
String query = "";
if (added) {
query = "GRANT ROLE " + role + " TO \"" + user + "\"";
if (with_grant)
query += " WITH GRANT OPTION";
} else {
// oh yeah, I forgot.
// TODO: get ability to remove users from roles.
// Note: apparently only one user can have grant option?
retval = "Not Implemented: REVOKE";
return retval;
}
try {
ResultSet rs = DBAccess.rawResultExec(query);
} catch (SQLException e) {
e.printStackTrace();
retval = e.getMessage();
}
return retval;
}
public String grantPermissionsOnSchema(String catalog, String schema,
String permissions, String grantee) throws AppException {
String retval = "";
/*String query = "CALL APPLIB.DO_FOR_ENTIRE_SCHEMA('GRANT " +
permissions + " ON %TABLE_NAME% TO \"" + grantee + "\"', " +
"'" + schema + "', 'TABLES_AND_VIEWS')";
* cannot do above because do_for_entire_schema does not respect
* catalogs.
*/
try {
ResultSet rs = DBAccess.rawResultExec("SELECT TABLE_NAME "
+ "FROM SYS_ROOT.DBA_TABLES "
+ "WHERE CATALOG_NAME = '" + catalog + "' AND "
+ "SCHEMA_NAME = '" + schema + "'");
while (rs.next()) {
String query = "GRANT " + permissions + " ON " +
"\"" + catalog + "\".\"" + schema + "\".\"" + rs.getString(1) + "\" "
+ "TO \"" + grantee + "\"";
DBAccess.rawResultExec(query);
}
} catch (SQLException e) {
e.printStackTrace();
retval = e.getMessage();
}
return retval;
}
public String grantPermissions(String catalog, String schema, String type,
String element, String permissions, String grantee)
throws AppException {
String retval = "";
String query = "GRANT " + permissions + " ON \"" + catalog +
"\".\"" + schema + "\".\"" + element + "\" TO \"" + grantee + "\"";
try {
ResultSet rs = DBAccess.rawResultExec(query);
} catch (SQLException e) {
e.printStackTrace();
retval = e.getMessage();
}
return retval;
}
public String revokePermissionsOnSchema(String catalog, String schema,
String permissions, String grantee) throws AppException {
return "Not Implemented";
/*String retval = "";
try {
ResultSet rs = DBAccess.rawResultExec("SELECT TABLE_NAME "
+ "FROM SYS_ROOT.DBA_TABLES "
+ "WHERE CATALOG_NAME = '" + catalog + "' AND "
+ "SCHEMA_NAME = '" + schema + "'");
while (rs.next()) {
String query = "REVOKE " + permissions + " ON " +
"\"" + catalog + "\".\"" + schema + "\".\"" + rs.getString(1) + "\" "
+ "FROM \"" + grantee + "\"";
DBAccess.rawResultExec(query);
}
} catch (SQLException e) {
e.printStackTrace();
retval = e.getMessage();
}
return retval;
*/
}
public String revokePermissions(String catalog, String schema, String type,
String element, String permissions, String grantee)
throws AppException {
return "Not Implemented";
/*String retval = "";
String query = "REVOKE " + permissions + " ON \"" + catalog +
"\".\"" + schema + "\".\"" + element + "\" FROM \"" + grantee + "\"";
try {
ResultSet rs = DBAccess.rawResultExec(query);
} catch (SQLException e) {
e.printStackTrace();
retval = e.getMessage();
}
return retval;
*/
}
}
| false | true | public RolesDetailsHolder getRolesDetails() throws AppException {
String query = "SELECT DISTINCT granted_catalog, granted_schema, granted_element, "
+ "grantee, grantor, action, "
+ "CASE WHEN r.role IS NOT NULL THEN r.role "
+ "WHEN grant_type = 'Role' THEN grantee END AS role_name, "
+ "grant_type, table_type, g.with_grant_option "
+ "FROM sys_root.dba_element_grants g left outer join sys_root.dba_user_roles r "
+ "ON action = 'INHERIT_ROLE' AND r.role_mof_id = element_mof_id "
+ "WHERE (grant_type = 'Role' AND grantee <> 'PUBLIC' "
+ "AND grantee <> '_SYSTEM') OR action = 'INHERIT_ROLE'";
Map<String, RolesDetails> details = new LinkedHashMap<String, RolesDetails>();
Map<String, PermissionsInfo> perms = new LinkedHashMap<String, PermissionsInfo>();
try {
ResultSet rs = DBAccess.rawResultExec(query);
while (rs.next()) {
int col = 1;
final String catalog = rs.getString(col++);
final String schema = rs.getString(col++);
final String element = rs.getString(col++);
final String grantee = rs.getString(col++);
final String grantor = rs.getString(col++);
final String action = rs.getString(col++);
final String role_name = rs.getString(col++);
final String grant_type = rs.getString(col++);
final String table_type = rs.getString(col++);
final boolean with_grant = rs.getBoolean(col++);
RolesDetails rd;
if (!details.containsKey(role_name)) {
rd = new RolesDetails();
rd.name = role_name;
details.put(role_name, rd);
} else {
rd = details.get(role_name);
}
// Dealing with a users or permissions entry?
if (grant_type.equals("User")) {
rd.users.add(grantee);
if (with_grant) {
rd.users_with_grant_option.add(grantee);
}
} else if (grant_type.equals("Role")) {
final String key = role_name + catalog + schema + element + table_type;
PermissionsInfo p;
if (!perms.containsKey(key)) {
p = new PermissionsInfo();
p.catalog_name = catalog;
p.schema_name = schema;
p.item_name = element;
p.item_type = table_type;
perms.put(key, p);
rd.permissions.add(p);
} else {
p = perms.get(key);
}
p.actions.add(action);
} else {
throw new AppException("Unknown grant type");
}
}
ResultSet rs_extra_roles = DBAccess.rawResultExec("SELECT name FROM sys_root.dba_roles WHERE name <> 'PUBLIC'");
while (rs_extra_roles.next()) {
final String role_name = rs_extra_roles.getString(1);
if (!details.containsKey(role_name)) {
RolesDetails rd = new RolesDetails();
rd.name = role_name;
details.put(role_name, rd);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
RolesDetailsHolder rh = new RolesDetailsHolder();
rh.value.addAll(details.values());
return rh;
}
| public RolesDetailsHolder getRolesDetails() throws AppException {
String query = "SELECT DISTINCT granted_catalog, granted_schema, granted_element, "
+ "grantee, grantor, action, "
+ "CASE WHEN r.role IS NOT NULL THEN r.role "
+ "WHEN grant_type = 'Role' THEN grantee END AS role_name, "
+ "grant_type, class_name, g.with_grant_option "
+ "FROM sys_root.dba_element_grants g left outer join sys_root.dba_user_roles r "
+ "ON action = 'INHERIT_ROLE' AND r.role_mof_id = element_mof_id "
+ "WHERE (grant_type = 'Role' AND grantee <> 'PUBLIC' "
+ "AND grantee <> '_SYSTEM') OR action = 'INHERIT_ROLE'";
Map<String, RolesDetails> details = new LinkedHashMap<String, RolesDetails>();
Map<String, PermissionsInfo> perms = new LinkedHashMap<String, PermissionsInfo>();
try {
ResultSet rs = DBAccess.rawResultExec(query);
while (rs.next()) {
int col = 1;
final String catalog = rs.getString(col++);
final String schema = rs.getString(col++);
final String element = rs.getString(col++);
final String grantee = rs.getString(col++);
final String grantor = rs.getString(col++);
final String action = rs.getString(col++);
final String role_name = rs.getString(col++);
final String grant_type = rs.getString(col++);
final String class_name = rs.getString(col++);
final boolean with_grant = rs.getBoolean(col++);
RolesDetails rd;
if (!details.containsKey(role_name)) {
rd = new RolesDetails();
rd.name = role_name;
details.put(role_name, rd);
} else {
rd = details.get(role_name);
}
// Dealing with a users or permissions entry?
if (grant_type.equals("User")) {
rd.users.add(grantee);
if (with_grant) {
rd.users_with_grant_option.add(grantee);
}
} else if (grant_type.equals("Role")) {
final String key = role_name + catalog + schema + element + class_name;
PermissionsInfo p;
if (!perms.containsKey(key)) {
p = new PermissionsInfo();
p.catalog_name = catalog;
p.schema_name = schema;
p.item_name = element;
p.item_type = class_name;
perms.put(key, p);
rd.permissions.add(p);
} else {
p = perms.get(key);
}
p.actions.add(action);
} else {
throw new AppException("Unknown grant type");
}
}
ResultSet rs_extra_roles = DBAccess.rawResultExec("SELECT name FROM sys_root.dba_roles WHERE name <> 'PUBLIC'");
while (rs_extra_roles.next()) {
final String role_name = rs_extra_roles.getString(1);
if (!details.containsKey(role_name)) {
RolesDetails rd = new RolesDetails();
rd.name = role_name;
details.put(role_name, rd);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
RolesDetailsHolder rh = new RolesDetailsHolder();
rh.value.addAll(details.values());
return rh;
}
|
diff --git a/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISKeyboardListener.java b/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISKeyboardListener.java
index 49df7fd8f..921785ea4 100644
--- a/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISKeyboardListener.java
+++ b/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISKeyboardListener.java
@@ -1,153 +1,153 @@
/*
* Copyright (C) 2013 eccentric_nz
*
* 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 me.eccentric_nz.TARDIS.listeners;
import java.util.HashMap;
import java.util.Locale;
import me.eccentric_nz.TARDIS.TARDIS;
import me.eccentric_nz.TARDIS.database.ResultSetAreas;
import me.eccentric_nz.TARDIS.database.ResultSetControls;
import me.eccentric_nz.TARDIS.database.ResultSetDestinations;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.inventory.ItemStack;
/**
* Now, if the trachoid crystal contrafibulations are in synchronic resonance
* with the referential difference index, then this should take us right to the
* heart of the trouble. And they don't make sentences like that anymore.
*
* @author eccentric_nz
*/
public class TARDISKeyboardListener implements Listener {
private final TARDIS plugin;
public TARDISKeyboardListener(TARDIS plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onBlockPlace(BlockPlaceEvent event) {
Block block = event.getBlockPlaced();
if (block.getType() != Material.WALL_SIGN && block.getType() != Material.SIGN_POST) {
return;
}
Block against = event.getBlockAgainst();
// is it a TARDIS keyboard sign
String loc_str = against.getLocation().toString();
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("type", 7);
where.put("location", loc_str);
ResultSetControls rsc = new ResultSetControls(plugin, where, false);
if (rsc.resultSet()) {
Sign keyboard = (Sign) against.getState();
// track this sign
plugin.trackSign.put(block.getLocation().toString(), keyboard);
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onSignChange(SignChangeEvent event) {
String loc = event.getBlock().getLocation().toString();
if (!plugin.trackSign.containsKey(loc)) {
return;
}
Sign keyboard = plugin.trackSign.get(loc);
int i = 0;
for (String l : event.getLines()) {
keyboard.setLine(i, l);
i++;
}
keyboard.update();
Player p = event.getPlayer();
plugin.trackSign.remove(loc);
// cancel the edit and give the sign back to the player
event.setCancelled(true);
event.getBlock().setType(Material.AIR);
if (p.getGameMode() != GameMode.CREATIVE) {
ItemStack itemInHand = p.getItemInHand();
if ((itemInHand == null) || (itemInHand.getType() == Material.AIR)) {
p.setItemInHand(new ItemStack(Material.SIGN, 1));
} else {
itemInHand.setAmount(itemInHand.getAmount() + 1);
}
}
// process the lines...
// player?
if (plugin.getServer().getPlayer(event.getLine(0)) != null) {
// set location player
p.performCommand("tardistravel " + event.getLine(0));
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel " + event.getLine(0));
return;
}
// location?
if (plugin.getServer().getWorld(event.getLine(0)) != null) {
// set location to coords
String command = event.getLine(0) + " " + event.getLine(1) + " " + event.getLine(2) + " " + event.getLine(3);
p.performCommand("tardistravel " + command);
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel " + command);
return;
}
// home?
if (event.getLine(0).equalsIgnoreCase("home")) {
p.performCommand("tardistravel home");
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel home");
return;
}
// biome ?
try {
String upper = event.getLine(0).toUpperCase(Locale.ENGLISH);
Biome biome = Biome.valueOf(upper);
if (!upper.equals("HELL") && !upper.equals("SKY")) {
p.performCommand("tardistravel biome " + upper);
- plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel home");
+ plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel biome " + upper);
return;
}
} catch (IllegalArgumentException iae) {
plugin.debug("Biome type not valid!");
}
// dest?
HashMap<String, Object> whered = new HashMap<String, Object>();
whered.put("dest_name", event.getLine(0));
ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false);
if (rsd.resultSet()) {
p.performCommand("tardistravel dest " + event.getLine(0));
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel dest " + event.getLine(0));
return;
}
// area?
HashMap<String, Object> wherea = new HashMap<String, Object>();
wherea.put("area_name", event.getLine(0));
ResultSetAreas rsa = new ResultSetAreas(plugin, wherea, false);
if (rsa.resultSet()) {
p.performCommand("tardistravel area " + event.getLine(0));
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel area " + event.getLine(0));
return;
}
p.sendMessage(plugin.pluginName + "Keyboard not responding, press any key to continue.");
}
}
| true | true | public void onSignChange(SignChangeEvent event) {
String loc = event.getBlock().getLocation().toString();
if (!plugin.trackSign.containsKey(loc)) {
return;
}
Sign keyboard = plugin.trackSign.get(loc);
int i = 0;
for (String l : event.getLines()) {
keyboard.setLine(i, l);
i++;
}
keyboard.update();
Player p = event.getPlayer();
plugin.trackSign.remove(loc);
// cancel the edit and give the sign back to the player
event.setCancelled(true);
event.getBlock().setType(Material.AIR);
if (p.getGameMode() != GameMode.CREATIVE) {
ItemStack itemInHand = p.getItemInHand();
if ((itemInHand == null) || (itemInHand.getType() == Material.AIR)) {
p.setItemInHand(new ItemStack(Material.SIGN, 1));
} else {
itemInHand.setAmount(itemInHand.getAmount() + 1);
}
}
// process the lines...
// player?
if (plugin.getServer().getPlayer(event.getLine(0)) != null) {
// set location player
p.performCommand("tardistravel " + event.getLine(0));
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel " + event.getLine(0));
return;
}
// location?
if (plugin.getServer().getWorld(event.getLine(0)) != null) {
// set location to coords
String command = event.getLine(0) + " " + event.getLine(1) + " " + event.getLine(2) + " " + event.getLine(3);
p.performCommand("tardistravel " + command);
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel " + command);
return;
}
// home?
if (event.getLine(0).equalsIgnoreCase("home")) {
p.performCommand("tardistravel home");
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel home");
return;
}
// biome ?
try {
String upper = event.getLine(0).toUpperCase(Locale.ENGLISH);
Biome biome = Biome.valueOf(upper);
if (!upper.equals("HELL") && !upper.equals("SKY")) {
p.performCommand("tardistravel biome " + upper);
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel home");
return;
}
} catch (IllegalArgumentException iae) {
plugin.debug("Biome type not valid!");
}
// dest?
HashMap<String, Object> whered = new HashMap<String, Object>();
whered.put("dest_name", event.getLine(0));
ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false);
if (rsd.resultSet()) {
p.performCommand("tardistravel dest " + event.getLine(0));
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel dest " + event.getLine(0));
return;
}
// area?
HashMap<String, Object> wherea = new HashMap<String, Object>();
wherea.put("area_name", event.getLine(0));
ResultSetAreas rsa = new ResultSetAreas(plugin, wherea, false);
if (rsa.resultSet()) {
p.performCommand("tardistravel area " + event.getLine(0));
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel area " + event.getLine(0));
return;
}
p.sendMessage(plugin.pluginName + "Keyboard not responding, press any key to continue.");
}
| public void onSignChange(SignChangeEvent event) {
String loc = event.getBlock().getLocation().toString();
if (!plugin.trackSign.containsKey(loc)) {
return;
}
Sign keyboard = plugin.trackSign.get(loc);
int i = 0;
for (String l : event.getLines()) {
keyboard.setLine(i, l);
i++;
}
keyboard.update();
Player p = event.getPlayer();
plugin.trackSign.remove(loc);
// cancel the edit and give the sign back to the player
event.setCancelled(true);
event.getBlock().setType(Material.AIR);
if (p.getGameMode() != GameMode.CREATIVE) {
ItemStack itemInHand = p.getItemInHand();
if ((itemInHand == null) || (itemInHand.getType() == Material.AIR)) {
p.setItemInHand(new ItemStack(Material.SIGN, 1));
} else {
itemInHand.setAmount(itemInHand.getAmount() + 1);
}
}
// process the lines...
// player?
if (plugin.getServer().getPlayer(event.getLine(0)) != null) {
// set location player
p.performCommand("tardistravel " + event.getLine(0));
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel " + event.getLine(0));
return;
}
// location?
if (plugin.getServer().getWorld(event.getLine(0)) != null) {
// set location to coords
String command = event.getLine(0) + " " + event.getLine(1) + " " + event.getLine(2) + " " + event.getLine(3);
p.performCommand("tardistravel " + command);
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel " + command);
return;
}
// home?
if (event.getLine(0).equalsIgnoreCase("home")) {
p.performCommand("tardistravel home");
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel home");
return;
}
// biome ?
try {
String upper = event.getLine(0).toUpperCase(Locale.ENGLISH);
Biome biome = Biome.valueOf(upper);
if (!upper.equals("HELL") && !upper.equals("SKY")) {
p.performCommand("tardistravel biome " + upper);
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel biome " + upper);
return;
}
} catch (IllegalArgumentException iae) {
plugin.debug("Biome type not valid!");
}
// dest?
HashMap<String, Object> whered = new HashMap<String, Object>();
whered.put("dest_name", event.getLine(0));
ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false);
if (rsd.resultSet()) {
p.performCommand("tardistravel dest " + event.getLine(0));
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel dest " + event.getLine(0));
return;
}
// area?
HashMap<String, Object> wherea = new HashMap<String, Object>();
wherea.put("area_name", event.getLine(0));
ResultSetAreas rsa = new ResultSetAreas(plugin, wherea, false);
if (rsa.resultSet()) {
p.performCommand("tardistravel area " + event.getLine(0));
plugin.console.sendMessage(p.getName() + " issued server command: /tardistravel area " + event.getLine(0));
return;
}
p.sendMessage(plugin.pluginName + "Keyboard not responding, press any key to continue.");
}
|
diff --git a/InterviewAnnihilator/src/com/huskysoft/interviewannihilator/ui/QuestionActivity.java b/InterviewAnnihilator/src/com/huskysoft/interviewannihilator/ui/QuestionActivity.java
index 59fc17c..73f699d 100644
--- a/InterviewAnnihilator/src/com/huskysoft/interviewannihilator/ui/QuestionActivity.java
+++ b/InterviewAnnihilator/src/com/huskysoft/interviewannihilator/ui/QuestionActivity.java
@@ -1,383 +1,385 @@
/**
*
* After a question is clicked on MainActivity, this activity is brought up.
* It display the question clicked, and a hidden list of solutions that pop
* up when a "Solutions" button is clicked.
*
* @author Cody Andrews, Phillip Leland, Justin Robb 05/01/2013
*
*/
package com.huskysoft.interviewannihilator.ui;
import java.util.List;
import com.huskysoft.interviewannihilator.R;
import com.huskysoft.interviewannihilator.model.Question;
import com.huskysoft.interviewannihilator.model.Solution;
import com.huskysoft.interviewannihilator.runtime.FetchSolutionsTask;
import com.huskysoft.interviewannihilator.runtime.VoteSolutionTask;
import com.huskysoft.interviewannihilator.util.UIConstants;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ActionBar.LayoutParams;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.TextAppearanceSpan;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.content.Context;
import android.content.Intent;
/**
* Activity for viewing a question before reading solutions
*/
public class QuestionActivity extends AbstractPostingActivity {
public final static String EXTRA_MESSAGE =
"com.huskysoft.interviewannihilator.QUESTION";
/** Layout that the question and solutions will populate */
private LinearLayout solutionsLayout;
/** The question the user is viewing */
private Question question;
/** true when the solutions have finished loading */
private boolean solutionsLoaded;
/** true when the user presses the "show solutions button" */
private boolean showSolutionsPressed;
/** Thread in which solutions are loaded */
private FetchSolutionsTask loadingThread;
@SuppressLint("NewApi")
@Override
public synchronized void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
setBehindContentView(R.layout.activity_menu);
getActionBar().setHomeButtonEnabled(true);
buildSlideMenu();
// Get intent
Intent intent = getIntent();
question = (Question) intent.getSerializableExtra(
MainActivity.EXTRA_MESSAGE);
this.setTitle(question.getTitle());
// Grab Linear Layout
solutionsLayout =
(LinearLayout) findViewById(R.id.question_layout_solutions);
//build text
String questionBody = question.getText();
String questionDate = question.getDateCreated().toString();
String questionDiff = question.getDifficulty().toString();
String questionCat = question.getCategory().toString();
int pos = 0;
SpannableStringBuilder sb = new SpannableStringBuilder();
// body
sb.append(questionBody);
sb.setSpan(new TextAppearanceSpan(
this, R.style.question_appearance), pos,
sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sb.append('\n');
pos += questionBody.length() + 1;
// descriptors
sb.append('\n');
sb.append(questionCat);
sb.append("\t\t\t");
sb.append(questionDiff);
sb.setSpan(new TextAppearanceSpan(
this, R.style.question_descriptors_appearance),
pos, sb.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sb.append('\n');
pos += questionDiff.length() + questionCat.length() + 4;
// date
sb.append('\n');
sb.append(questionDate);
sb.setSpan(new TextAppearanceSpan(
this, R.style.question_date_appearance), pos,
sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// done
TextView textview = (TextView) findViewById(R.id.question_text_view);
textview.setBackground(
getResources().getDrawable( R.drawable.listitem));
textview.setText(sb);
// Initialize values
solutionsLoaded = false;
showSolutionsPressed = false;
//Start loading solutions. This makes a network call.
loadSolutions();
}
/**
* Appends a list of solutions to a hidden list.
* If the showSolutions button has already been pressed, it will reveal
* the solutions upon completion. If the button has not been pressed,
* solutions will be hidden.
*
* @param solutions
*/
public synchronized void addSolutionList(List<Solution> solutions){
if(solutions == null || solutions.size() <= 0){
TextView t = new TextView(this);
t.setText("There doesn't seem to be any solutions");
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f);
llp.setMargins(40, 10, 40, 10);
llp.gravity = 1; // Horizontal Center
t.setLayoutParams(llp);
solutionsLayout.addView(t);
} else {
for(int i = 0; i < solutions.size(); i++){
Solution solution = solutions.get(i);
if(solution != null && solution.getText() != null){
addSolution(solution);
}
}
}
solutionsLoaded = true;
if(showSolutionsPressed){
revealSolutions();
}
}
/**
* Adds a single solution to the UI. This includes the solution TextView
* and upvote/downvote arrows.
*
* @param solution solution that will populate the text view
* @param llp layout parameters
*/
private void addSolution(Solution solution){
// get layout from xml
LayoutInflater li = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- View solutionView = li.inflate(R.layout.solution_view, null, false);
+ View solutionView = li.inflate(R.layout.solution_view, solutionsLayout, false);
// build text
String solutionBody = solution.getText();
String solutionDate = solution.getDateCreated().toString();
int pos = 0;
SpannableStringBuilder sb = new SpannableStringBuilder();
// body
sb.append(solutionBody);
sb.setSpan(new TextAppearanceSpan(
this, R.style.solution_appearance), pos,
sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sb.append('\n');
pos += solutionBody.length() + 1;
// date
sb.append('\n');
sb.append(solutionDate);
sb.setSpan(new TextAppearanceSpan(
this, R.style.question_date_appearance), pos,
sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// get the solution TextView from solution_view.xml
TextView solnView = (TextView)
solutionView.findViewById(R.id.solution_text);
solnView.setText(sb);
solnView.setId(solution.getSolutionId());
// get the score TextView from solution_view.xml
TextView scoreView = (TextView)
solutionView.findViewById(R.id.score_text);
int score = solution.getLikes() - solution.getDislikes();
scoreView.setText(Integer.toString(score));
// store the context and solution so that when a button is pressed,
// we can access it
solutionView.setTag(R.id.TAG_CONTEXT_ID, this);
solutionView.setTag(R.id.TAG_SOLUTION_VIEW_ID, solution);
// yes I know this is redundant but it is difficult to code around
// get upvote button
Button upvoteButton = (Button)
solutionView.findViewById(R.id.button_upvote);
upvoteButton.setTag(solutionView);
upvoteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v){
View solutionView = (View) v.getTag();
QuestionActivity context = (QuestionActivity)
solutionView.getTag(R.id.TAG_CONTEXT_ID);
Solution solution = (Solution)
solutionView.getTag(R.id.TAG_SOLUTION_VIEW_ID);
new VoteSolutionTask(context,
solutionView, solution, true).execute();
}
});
// get downvote button
Button downvoteButton = (Button)
solutionView.findViewById(R.id.button_downvote);
downvoteButton.setTag(solutionView);
downvoteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v){
View solutionView = (View) v.getTag();
QuestionActivity context = (QuestionActivity)
solutionView.getTag(R.id.TAG_CONTEXT_ID);
Solution solution = (Solution)
solutionView.getTag(R.id.TAG_SOLUTION_VIEW_ID);
new VoteSolutionTask(context,
solutionView, solution, false).execute();
}
});
+ /*
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f);
int verticalMargin = UIConstants.DEFAULT_VERTICAL_MARGIN;
llp.setMargins(0, verticalMargin, 0, verticalMargin);
solutionView.setLayoutParams(llp);
+ */
solutionsLayout.addView(solutionView);
}
/**
* Button handler for the "Solutions" button.
* Attempts to reveal solutions. If it cannot (solutions have not been
* loaded yet), it will set a flag to
*
* @param v
*/
public synchronized void onShowSolutions(View v){
if(!showSolutionsPressed){
if(solutionsLoaded){
revealSolutions();
}else{
View loadingText = findViewById(R.id.loading_text_layout);
loadingText.setVisibility(View.VISIBLE);
showSolutionsPressed = true;
}
}
}
/**
* Reveals solutions. Should only be called once solutions are loaded.
*/
private synchronized void revealSolutions(){
// Dismiss loading window
View loadingText = findViewById(R.id.loading_text_layout);
loadingText.setVisibility(View.GONE);
// Dismiss show solutions button
Button showSolutions =
(Button) findViewById(R.id.question_button_show_solutions);
showSolutions.setVisibility(View.GONE);
// Reveal hidden solutions
solutionsLayout.setVisibility(View.VISIBLE);
// Add post solution button to end of list
Button post = new Button(this);
post.setText(R.string.button_post_solution);
float dp = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 1,
getResources().getDisplayMetrics());
int height = (int) (40 * dp);
int margin = (int) (16 * dp);
LinearLayout.LayoutParams lp =
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, height, 1f);
lp.gravity = Gravity.CENTER_HORIZONTAL;
lp.setMargins(0, margin, 0, 0);
post.setLayoutParams(lp);
post.setPadding(margin, 0, margin, 0);
post.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v){
postSolution(v);
}
});
solutionsLayout.addView(post);
}
private void loadSolutions(){
solutionsLoaded = false;
loadingThread = new FetchSolutionsTask(this, question);
loadingThread.execute();
}
/**
* Pops up a dialog menu with "Retry" and "Cancel" options when a network
* operation fails.
*/
public void onNetworkError(){
// Stop loadingDialog
View loadingText = findViewById(R.id.loading_text_layout);
loadingText.setVisibility(View.GONE);
// Create a dialog
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.retrydialogcustom);
TextView text = (TextView) dialog.findViewById(R.id.dialog_text);
text.setText(R.string.retryDialog_title);
Button dialogButton = (Button) dialog.findViewById(R.id.button_retry);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Try reloading
loadSolutions();
}
});
dialogButton = (Button) dialog.findViewById(R.id.button_cancel);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Probably don't want to send them back to questions
// screen here, so just dismiss
dialog.dismiss();
}
});
dialog.show();
}
/** Called when the user clicks the post solution button */
public void postSolution(View view) {
if (isUserInfoLoaded()){
Intent intent = new Intent(this, PostSolutionActivity.class);
intent.putExtra(EXTRA_MESSAGE, question);
startActivity(intent);
} else {
// helpful message
onValidationIssue();
}
}
}
| false | true | private void addSolution(Solution solution){
// get layout from xml
LayoutInflater li = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View solutionView = li.inflate(R.layout.solution_view, null, false);
// build text
String solutionBody = solution.getText();
String solutionDate = solution.getDateCreated().toString();
int pos = 0;
SpannableStringBuilder sb = new SpannableStringBuilder();
// body
sb.append(solutionBody);
sb.setSpan(new TextAppearanceSpan(
this, R.style.solution_appearance), pos,
sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sb.append('\n');
pos += solutionBody.length() + 1;
// date
sb.append('\n');
sb.append(solutionDate);
sb.setSpan(new TextAppearanceSpan(
this, R.style.question_date_appearance), pos,
sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// get the solution TextView from solution_view.xml
TextView solnView = (TextView)
solutionView.findViewById(R.id.solution_text);
solnView.setText(sb);
solnView.setId(solution.getSolutionId());
// get the score TextView from solution_view.xml
TextView scoreView = (TextView)
solutionView.findViewById(R.id.score_text);
int score = solution.getLikes() - solution.getDislikes();
scoreView.setText(Integer.toString(score));
// store the context and solution so that when a button is pressed,
// we can access it
solutionView.setTag(R.id.TAG_CONTEXT_ID, this);
solutionView.setTag(R.id.TAG_SOLUTION_VIEW_ID, solution);
// yes I know this is redundant but it is difficult to code around
// get upvote button
Button upvoteButton = (Button)
solutionView.findViewById(R.id.button_upvote);
upvoteButton.setTag(solutionView);
upvoteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v){
View solutionView = (View) v.getTag();
QuestionActivity context = (QuestionActivity)
solutionView.getTag(R.id.TAG_CONTEXT_ID);
Solution solution = (Solution)
solutionView.getTag(R.id.TAG_SOLUTION_VIEW_ID);
new VoteSolutionTask(context,
solutionView, solution, true).execute();
}
});
// get downvote button
Button downvoteButton = (Button)
solutionView.findViewById(R.id.button_downvote);
downvoteButton.setTag(solutionView);
downvoteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v){
View solutionView = (View) v.getTag();
QuestionActivity context = (QuestionActivity)
solutionView.getTag(R.id.TAG_CONTEXT_ID);
Solution solution = (Solution)
solutionView.getTag(R.id.TAG_SOLUTION_VIEW_ID);
new VoteSolutionTask(context,
solutionView, solution, false).execute();
}
});
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f);
int verticalMargin = UIConstants.DEFAULT_VERTICAL_MARGIN;
llp.setMargins(0, verticalMargin, 0, verticalMargin);
solutionView.setLayoutParams(llp);
solutionsLayout.addView(solutionView);
}
| private void addSolution(Solution solution){
// get layout from xml
LayoutInflater li = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View solutionView = li.inflate(R.layout.solution_view, solutionsLayout, false);
// build text
String solutionBody = solution.getText();
String solutionDate = solution.getDateCreated().toString();
int pos = 0;
SpannableStringBuilder sb = new SpannableStringBuilder();
// body
sb.append(solutionBody);
sb.setSpan(new TextAppearanceSpan(
this, R.style.solution_appearance), pos,
sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sb.append('\n');
pos += solutionBody.length() + 1;
// date
sb.append('\n');
sb.append(solutionDate);
sb.setSpan(new TextAppearanceSpan(
this, R.style.question_date_appearance), pos,
sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// get the solution TextView from solution_view.xml
TextView solnView = (TextView)
solutionView.findViewById(R.id.solution_text);
solnView.setText(sb);
solnView.setId(solution.getSolutionId());
// get the score TextView from solution_view.xml
TextView scoreView = (TextView)
solutionView.findViewById(R.id.score_text);
int score = solution.getLikes() - solution.getDislikes();
scoreView.setText(Integer.toString(score));
// store the context and solution so that when a button is pressed,
// we can access it
solutionView.setTag(R.id.TAG_CONTEXT_ID, this);
solutionView.setTag(R.id.TAG_SOLUTION_VIEW_ID, solution);
// yes I know this is redundant but it is difficult to code around
// get upvote button
Button upvoteButton = (Button)
solutionView.findViewById(R.id.button_upvote);
upvoteButton.setTag(solutionView);
upvoteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v){
View solutionView = (View) v.getTag();
QuestionActivity context = (QuestionActivity)
solutionView.getTag(R.id.TAG_CONTEXT_ID);
Solution solution = (Solution)
solutionView.getTag(R.id.TAG_SOLUTION_VIEW_ID);
new VoteSolutionTask(context,
solutionView, solution, true).execute();
}
});
// get downvote button
Button downvoteButton = (Button)
solutionView.findViewById(R.id.button_downvote);
downvoteButton.setTag(solutionView);
downvoteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v){
View solutionView = (View) v.getTag();
QuestionActivity context = (QuestionActivity)
solutionView.getTag(R.id.TAG_CONTEXT_ID);
Solution solution = (Solution)
solutionView.getTag(R.id.TAG_SOLUTION_VIEW_ID);
new VoteSolutionTask(context,
solutionView, solution, false).execute();
}
});
/*
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f);
int verticalMargin = UIConstants.DEFAULT_VERTICAL_MARGIN;
llp.setMargins(0, verticalMargin, 0, verticalMargin);
solutionView.setLayoutParams(llp);
*/
solutionsLayout.addView(solutionView);
}
|
diff --git a/illaeasynpc/src/illarion/easynpc/parser/talk/TalkingLine.java b/illaeasynpc/src/illarion/easynpc/parser/talk/TalkingLine.java
index 030540a8..501890ab 100644
--- a/illaeasynpc/src/illarion/easynpc/parser/talk/TalkingLine.java
+++ b/illaeasynpc/src/illarion/easynpc/parser/talk/TalkingLine.java
@@ -1,288 +1,288 @@
/*
* This file is part of the Illarion easyNPC Editor.
*
* Copyright © 2012 - Illarion e.V.
*
* The Illarion easyNPC Editor 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.
*
* The Illarion easyNPC Editor 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 the Illarion easyNPC Editor. If not, see <http://www.gnu.org/licenses/>.
*/
package illarion.easynpc.parser.talk;
import illarion.easynpc.EasyNpcScript;
import illarion.easynpc.Lang;
import illarion.easynpc.ParsedNpc;
import illarion.easynpc.docu.DocuEntry;
import illarion.easynpc.parsed.ParsedTalk;
import illarion.easynpc.parsed.talk.TalkCondition;
import illarion.easynpc.parsed.talk.TalkConsequence;
import org.fife.ui.rsyntaxtextarea.TokenMap;
import java.util.ArrayList;
import java.util.List;
/**
* This class is used to store talking informations of a NPC. It stores the data
* about one line of talking with all triggers, answers, consequences and
* conditions.
*
* @author Martin Karing <[email protected]>
*/
public final class TalkingLine {
/**
* The string used to split the conditions and the consequences of the
* talking line.
*/
@SuppressWarnings("nls")
private static final String SPLIT_STRING = "->";
/**
* The documentation entry for the conditions.
*/
private final DocuEntry conditionDocu;
/**
* The list of condition parsers.
*/
private final ArrayList<ConditionParser> condPar;
/**
* The documentation entry for the consequences.
*/
private final DocuEntry consequenceDocu;
/**
* The list of consequence parsers.
*/
private final ArrayList<ConsequenceParser> consPar;
/**
* The constructor that sets up all known parsers this class requires to
* work properly.
*/
public TalkingLine() {
condPar = new ArrayList<ConditionParser>();
consPar = new ArrayList<ConsequenceParser>();
condPar.add(new illarion.easynpc.parser.talk.conditions.State());
condPar.add(new illarion.easynpc.parser.talk.conditions.Skill());
condPar.add(new illarion.easynpc.parser.talk.conditions.Attribute());
condPar.add(new illarion.easynpc.parser.talk.conditions.MagicType());
condPar.add(new illarion.easynpc.parser.talk.conditions.Money());
condPar.add(new illarion.easynpc.parser.talk.conditions.Race());
condPar.add(new illarion.easynpc.parser.talk.conditions.Queststatus());
condPar.add(new illarion.easynpc.parser.talk.conditions.Item());
condPar.add(new illarion.easynpc.parser.talk.conditions.Language());
condPar.add(new illarion.easynpc.parser.talk.conditions.Chance());
condPar.add(new illarion.easynpc.parser.talk.conditions.Town());
condPar.add(new illarion.easynpc.parser.talk.conditions.Number());
condPar.add(new illarion.easynpc.parser.talk.conditions.Talkstate());
condPar.add(new illarion.easynpc.parser.talk.conditions.Sex());
condPar.add(new illarion.easynpc.parser.talk.conditions.Admin());
condPar.add(new illarion.easynpc.parser.talk.conditions.Trigger());
consPar.add(new illarion.easynpc.parser.talk.consequences.Inform());
+ consPar.add(new illarion.easynpc.parser.talk.consequences.Answer());
consPar.add(new illarion.easynpc.parser.talk.consequences.State());
consPar.add(new illarion.easynpc.parser.talk.consequences.Skill());
consPar.add(new illarion.easynpc.parser.talk.consequences.Attribute());
consPar.add(new illarion.easynpc.parser.talk.consequences.Rune());
consPar.add(new illarion.easynpc.parser.talk.consequences.Money());
consPar.add(new illarion.easynpc.parser.talk.consequences.DeleteItem());
consPar.add(new illarion.easynpc.parser.talk.consequences.Item());
consPar.add(new illarion.easynpc.parser.talk.consequences.Queststatus());
consPar.add(new illarion.easynpc.parser.talk.consequences.Rankpoints());
consPar.add(new illarion.easynpc.parser.talk.consequences.Talkstate());
consPar.add(new illarion.easynpc.parser.talk.consequences.Trade());
consPar.add(new illarion.easynpc.parser.talk.consequences.Treasure());
consPar.add(new illarion.easynpc.parser.talk.consequences.Introduce());
consPar.add(new illarion.easynpc.parser.talk.consequences.Warp());
- consPar.add(new illarion.easynpc.parser.talk.consequences.Answer());
final List<ConditionParser> conditionsList = condPar;
final List<ConsequenceParser> consequenceList = consPar;
conditionDocu = new DocuEntry() {
@SuppressWarnings("nls")
@Override
public DocuEntry getChild(final int index) {
if ((index < 0) || (index >= conditionsList.size())) {
throw new IllegalArgumentException("Index out of range");
}
return conditionsList.get(index);
}
@Override
public int getChildCount() {
return conditionsList.size();
}
@SuppressWarnings("nls")
@Override
public String getDescription() {
return Lang.getMsg(TalkingLine.class,
"Conditions.Docu.description");
}
@Override
public String getExample() {
return null;
}
@Override
public String getSyntax() {
return null;
}
@Override
@SuppressWarnings("nls")
public String getTitle() {
return Lang.getMsg(TalkingLine.class, "Conditions.Docu.title");
}
};
consequenceDocu = new DocuEntry() {
@SuppressWarnings("nls")
@Override
public DocuEntry getChild(final int index) {
if ((index < 0) || (index >= consequenceList.size())) {
throw new IllegalArgumentException("Index out of range");
}
return consequenceList.get(index);
}
@Override
public int getChildCount() {
return consequenceList.size();
}
@SuppressWarnings("nls")
@Override
public String getDescription() {
return Lang.getMsg(TalkingLine.class,
"Consequence.Docu.description");
}
@Override
public String getExample() {
return null;
}
@Override
public String getSyntax() {
return null;
}
@Override
@SuppressWarnings("nls")
public String getTitle() {
return Lang
.getMsg(TalkingLine.class, "Consequence.Docu.title");
}
};
}
/**
* Get the documentation entry for the conditions.
*
* @return the conditions documentation entry
*/
public DocuEntry getConditionDocuEntry() {
return conditionDocu;
}
/**
* Get the documentation entry for the consequences.
*
* @return the consequences documentation entry
*/
public DocuEntry getConsequenceDocuEntry() {
return consequenceDocu;
}
/**
* Parse a talking line into a properly parsed line.
*
* @param line the line to parse
* @param npc the npc that receives the data parsed here
*/
@SuppressWarnings("nls")
public void parseLine(final EasyNpcScript.Line line, final ParsedNpc npc) {
final String[] workingLines = line.getLine().split(SPLIT_STRING);
if (workingLines.length != 2) {
npc.addError(line, "Invalid line fetched!");
return;
}
String conditions = workingLines[0] + ',';
String consequences = workingLines[1] + ',';
final ParsedTalk parsedLine = new ParsedTalk();
for (final ConditionParser parser : condPar) {
parser.setLine(conditions);
parser.setErrorParent(npc, line);
TalkCondition con = null;
while (true) {
con = parser.extract();
if (con == null) {
break;
}
parsedLine.addCondition(con);
}
conditions = parser.getNewLine();
parser.cleanup();
}
for (final ConsequenceParser parser : consPar) {
parser.setLine(consequences);
parser.setErrorParent(npc, line);
TalkConsequence con = null;
while (true) {
con = parser.extract();
if (con == null) {
break;
}
parsedLine.addConsequence(con);
}
consequences = parser.getNewLine();
parser.cleanup();
}
if (!conditions.isEmpty()) {
npc.addError(line, Lang.getMsg(getClass(), "remainConditions")
+ ' ' + conditions);
}
if (!consequences.isEmpty()) {
npc.addError(line, Lang.getMsg(getClass(), "remainConsequences")
+ ' ' + consequences);
}
npc.addNpcData(parsedLine);
}
public void enlistHighlightedWords(final TokenMap map) {
for (final ConditionParser parser : condPar) {
parser.enlistHighlightedWords(map);
}
for (final ConsequenceParser parser : consPar) {
parser.enlistHighlightedWords(map);
}
}
}
| false | true | public TalkingLine() {
condPar = new ArrayList<ConditionParser>();
consPar = new ArrayList<ConsequenceParser>();
condPar.add(new illarion.easynpc.parser.talk.conditions.State());
condPar.add(new illarion.easynpc.parser.talk.conditions.Skill());
condPar.add(new illarion.easynpc.parser.talk.conditions.Attribute());
condPar.add(new illarion.easynpc.parser.talk.conditions.MagicType());
condPar.add(new illarion.easynpc.parser.talk.conditions.Money());
condPar.add(new illarion.easynpc.parser.talk.conditions.Race());
condPar.add(new illarion.easynpc.parser.talk.conditions.Queststatus());
condPar.add(new illarion.easynpc.parser.talk.conditions.Item());
condPar.add(new illarion.easynpc.parser.talk.conditions.Language());
condPar.add(new illarion.easynpc.parser.talk.conditions.Chance());
condPar.add(new illarion.easynpc.parser.talk.conditions.Town());
condPar.add(new illarion.easynpc.parser.talk.conditions.Number());
condPar.add(new illarion.easynpc.parser.talk.conditions.Talkstate());
condPar.add(new illarion.easynpc.parser.talk.conditions.Sex());
condPar.add(new illarion.easynpc.parser.talk.conditions.Admin());
condPar.add(new illarion.easynpc.parser.talk.conditions.Trigger());
consPar.add(new illarion.easynpc.parser.talk.consequences.Inform());
consPar.add(new illarion.easynpc.parser.talk.consequences.State());
consPar.add(new illarion.easynpc.parser.talk.consequences.Skill());
consPar.add(new illarion.easynpc.parser.talk.consequences.Attribute());
consPar.add(new illarion.easynpc.parser.talk.consequences.Rune());
consPar.add(new illarion.easynpc.parser.talk.consequences.Money());
consPar.add(new illarion.easynpc.parser.talk.consequences.DeleteItem());
consPar.add(new illarion.easynpc.parser.talk.consequences.Item());
consPar.add(new illarion.easynpc.parser.talk.consequences.Queststatus());
consPar.add(new illarion.easynpc.parser.talk.consequences.Rankpoints());
consPar.add(new illarion.easynpc.parser.talk.consequences.Talkstate());
consPar.add(new illarion.easynpc.parser.talk.consequences.Trade());
consPar.add(new illarion.easynpc.parser.talk.consequences.Treasure());
consPar.add(new illarion.easynpc.parser.talk.consequences.Introduce());
consPar.add(new illarion.easynpc.parser.talk.consequences.Warp());
consPar.add(new illarion.easynpc.parser.talk.consequences.Answer());
final List<ConditionParser> conditionsList = condPar;
final List<ConsequenceParser> consequenceList = consPar;
conditionDocu = new DocuEntry() {
@SuppressWarnings("nls")
@Override
public DocuEntry getChild(final int index) {
if ((index < 0) || (index >= conditionsList.size())) {
throw new IllegalArgumentException("Index out of range");
}
return conditionsList.get(index);
}
@Override
public int getChildCount() {
return conditionsList.size();
}
@SuppressWarnings("nls")
@Override
public String getDescription() {
return Lang.getMsg(TalkingLine.class,
"Conditions.Docu.description");
}
@Override
public String getExample() {
return null;
}
@Override
public String getSyntax() {
return null;
}
@Override
@SuppressWarnings("nls")
public String getTitle() {
return Lang.getMsg(TalkingLine.class, "Conditions.Docu.title");
}
};
consequenceDocu = new DocuEntry() {
@SuppressWarnings("nls")
@Override
public DocuEntry getChild(final int index) {
if ((index < 0) || (index >= consequenceList.size())) {
throw new IllegalArgumentException("Index out of range");
}
return consequenceList.get(index);
}
@Override
public int getChildCount() {
return consequenceList.size();
}
@SuppressWarnings("nls")
@Override
public String getDescription() {
return Lang.getMsg(TalkingLine.class,
"Consequence.Docu.description");
}
@Override
public String getExample() {
return null;
}
@Override
public String getSyntax() {
return null;
}
@Override
@SuppressWarnings("nls")
public String getTitle() {
return Lang
.getMsg(TalkingLine.class, "Consequence.Docu.title");
}
};
}
| public TalkingLine() {
condPar = new ArrayList<ConditionParser>();
consPar = new ArrayList<ConsequenceParser>();
condPar.add(new illarion.easynpc.parser.talk.conditions.State());
condPar.add(new illarion.easynpc.parser.talk.conditions.Skill());
condPar.add(new illarion.easynpc.parser.talk.conditions.Attribute());
condPar.add(new illarion.easynpc.parser.talk.conditions.MagicType());
condPar.add(new illarion.easynpc.parser.talk.conditions.Money());
condPar.add(new illarion.easynpc.parser.talk.conditions.Race());
condPar.add(new illarion.easynpc.parser.talk.conditions.Queststatus());
condPar.add(new illarion.easynpc.parser.talk.conditions.Item());
condPar.add(new illarion.easynpc.parser.talk.conditions.Language());
condPar.add(new illarion.easynpc.parser.talk.conditions.Chance());
condPar.add(new illarion.easynpc.parser.talk.conditions.Town());
condPar.add(new illarion.easynpc.parser.talk.conditions.Number());
condPar.add(new illarion.easynpc.parser.talk.conditions.Talkstate());
condPar.add(new illarion.easynpc.parser.talk.conditions.Sex());
condPar.add(new illarion.easynpc.parser.talk.conditions.Admin());
condPar.add(new illarion.easynpc.parser.talk.conditions.Trigger());
consPar.add(new illarion.easynpc.parser.talk.consequences.Inform());
consPar.add(new illarion.easynpc.parser.talk.consequences.Answer());
consPar.add(new illarion.easynpc.parser.talk.consequences.State());
consPar.add(new illarion.easynpc.parser.talk.consequences.Skill());
consPar.add(new illarion.easynpc.parser.talk.consequences.Attribute());
consPar.add(new illarion.easynpc.parser.talk.consequences.Rune());
consPar.add(new illarion.easynpc.parser.talk.consequences.Money());
consPar.add(new illarion.easynpc.parser.talk.consequences.DeleteItem());
consPar.add(new illarion.easynpc.parser.talk.consequences.Item());
consPar.add(new illarion.easynpc.parser.talk.consequences.Queststatus());
consPar.add(new illarion.easynpc.parser.talk.consequences.Rankpoints());
consPar.add(new illarion.easynpc.parser.talk.consequences.Talkstate());
consPar.add(new illarion.easynpc.parser.talk.consequences.Trade());
consPar.add(new illarion.easynpc.parser.talk.consequences.Treasure());
consPar.add(new illarion.easynpc.parser.talk.consequences.Introduce());
consPar.add(new illarion.easynpc.parser.talk.consequences.Warp());
final List<ConditionParser> conditionsList = condPar;
final List<ConsequenceParser> consequenceList = consPar;
conditionDocu = new DocuEntry() {
@SuppressWarnings("nls")
@Override
public DocuEntry getChild(final int index) {
if ((index < 0) || (index >= conditionsList.size())) {
throw new IllegalArgumentException("Index out of range");
}
return conditionsList.get(index);
}
@Override
public int getChildCount() {
return conditionsList.size();
}
@SuppressWarnings("nls")
@Override
public String getDescription() {
return Lang.getMsg(TalkingLine.class,
"Conditions.Docu.description");
}
@Override
public String getExample() {
return null;
}
@Override
public String getSyntax() {
return null;
}
@Override
@SuppressWarnings("nls")
public String getTitle() {
return Lang.getMsg(TalkingLine.class, "Conditions.Docu.title");
}
};
consequenceDocu = new DocuEntry() {
@SuppressWarnings("nls")
@Override
public DocuEntry getChild(final int index) {
if ((index < 0) || (index >= consequenceList.size())) {
throw new IllegalArgumentException("Index out of range");
}
return consequenceList.get(index);
}
@Override
public int getChildCount() {
return consequenceList.size();
}
@SuppressWarnings("nls")
@Override
public String getDescription() {
return Lang.getMsg(TalkingLine.class,
"Consequence.Docu.description");
}
@Override
public String getExample() {
return null;
}
@Override
public String getSyntax() {
return null;
}
@Override
@SuppressWarnings("nls")
public String getTitle() {
return Lang
.getMsg(TalkingLine.class, "Consequence.Docu.title");
}
};
}
|
diff --git a/src/org/jets3t/service/impl/rest/httpclient/RestS3Service.java b/src/org/jets3t/service/impl/rest/httpclient/RestS3Service.java
index dcf3cd6..3ddeb32 100644
--- a/src/org/jets3t/service/impl/rest/httpclient/RestS3Service.java
+++ b/src/org/jets3t/service/impl/rest/httpclient/RestS3Service.java
@@ -1,1272 +1,1276 @@
/*
* jets3t : Java Extra-Tasty S3 Toolkit (for Amazon S3 online storage service)
* This is a java.net project, see https://jets3t.dev.java.net/
*
* Copyright 2006 James Murty
*
* 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.jets3t.service.impl.rest.httpclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpMethodRetryHandler;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.ProxyHost;
import org.apache.commons.httpclient.auth.CredentialsProvider;
import org.apache.commons.httpclient.contrib.proxy.PluginProxyUtil;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jets3t.service.Constants;
import org.jets3t.service.Jets3tProperties;
import org.jets3t.service.S3ObjectsChunk;
import org.jets3t.service.S3Service;
import org.jets3t.service.S3ServiceException;
import org.jets3t.service.acl.AccessControlList;
import org.jets3t.service.impl.rest.XmlResponsesSaxParser;
import org.jets3t.service.impl.rest.XmlResponsesSaxParser.ListBucketHandler;
import org.jets3t.service.io.UnrecoverableIOException;
import org.jets3t.service.model.S3Bucket;
import org.jets3t.service.model.S3BucketLoggingStatus;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.security.AWSCredentials;
import org.jets3t.service.utils.Mimetypes;
import org.jets3t.service.utils.RestUtils;
import org.jets3t.service.utils.ServiceUtils;
import org.jets3t.service.utils.signedurl.SignedUrlHandler;
/**
* REST/HTTP implementation of an {@link S3Service} based on the
* <a href="http://jakarta.apache.org/commons/httpclient/">HttpClient</a> library.
* <p>
* <p><b>Properties</b></p>
* <p>This HttpClient-based implementation uses a small subset of the many
* <a href="http://jakarta.apache.org/commons/httpclient/preference-api.html">options available for HttpClient</a>.
* The following properties, obtained through {@link Jets3tProperties}, are used by this class:</p>
* <table>
* <tr><th>Property</th><th>Description</th><th>Default</th></tr>
* <tr><td>httpclient.connection-timeout-ms</td>
* <td>How many milliseconds to wait before a connection times out. 0 means infinity</td>
* <td>60000</td></tr>
* <tr><td>httpclient.socket-timeout-ms</td>
* <td>How many milliseconds to wait before a socket connection times out. 0 means infinity</td>
* <td>60000</td></tr>
* <tr><td>httpclient.max-connections</td>
* <td>The maximum number of simultaneous connections to allow</td><td>10</td></tr>
* <tr><td>httpclient.stale-checking-enabled</td>
* <td>"Determines whether stale connection check is to be used. Disabling stale connection check may
* result in slight performance improvement at the risk of getting an I/O error when executing a request
* over a connection that has been closed at the server side."</td><td>true</td></tr>
* <tr><td>httpclient.retry-on-errors</td><td></td><td>true</td></tr>
* <tr><td>httpclient.useragent</td><td>Overrides the default jets3t user agent string</td>
* <td>The value set by {@link S3Service#setUserAgentDescription()}</td></tr>
* </table>
*
* @author James Murty
*/
public class RestS3Service extends S3Service implements SignedUrlHandler {
private final Log log = LogFactory.getLog(RestS3Service.class);
private static final String PROTOCOL_SECURE = "https";
private static final String PROTOCOL_INSECURE = "http";
private static final int PORT_SECURE = 443;
private static final int PORT_INSECURE = 80;
private final HostConfiguration insecureHostConfig = new HostConfiguration();
private final HostConfiguration secureHostConfig = new HostConfiguration();
private HttpClient httpClient = null;
private MultiThreadedHttpConnectionManager connectionManager = null;
/**
* Constructs the service and initialises the properties.
*
* @param awsCredentials
* the S3 user credentials to use when communicating with S3, may be null in which case the
* communication is done as an anonymous user.
*
* @throws S3ServiceException
*/
public RestS3Service(AWSCredentials awsCredentials) throws S3ServiceException {
this(awsCredentials, null, null);
}
/**
* Constructs the service and initialises the properties.
*
* @param awsCredentials
* the S3 user credentials to use when communicating with S3, may be null in which case the
* communication is done as an anonymous user.
* @param invokingApplicationDescription
* a short description of the application using the service, suitable for inclusion in a
* user agent string for REST/HTTP requests. Ideally this would include the application's
* version number, for example: <code>Cockpit/0.5.0</code> or <code>My App Name/1.0</code>
* @param credentialsProvider
* an implementation of the HttpClient CredentialsProvider interface, to provide a means for
* prompting for credentials when necessary.
*
* @throws S3ServiceException
*/
public RestS3Service(AWSCredentials awsCredentials, String invokingApplicationDescription,
CredentialsProvider credentialsProvider) throws S3ServiceException
{
super(awsCredentials, invokingApplicationDescription);
Jets3tProperties jets3tProperties = Jets3tProperties.getInstance(Constants.JETS3T_PROPERTIES_FILENAME);
// Set HttpClient properties based on Jets3t Properties.
insecureHostConfig.setHost(Constants.REST_SERVER_DNS, PORT_INSECURE, PROTOCOL_INSECURE);
secureHostConfig.setHost(Constants.REST_SERVER_DNS, PORT_SECURE, PROTOCOL_SECURE);
HttpConnectionManagerParams connectionParams = new HttpConnectionManagerParams();
connectionParams.setConnectionTimeout(jets3tProperties.
getIntProperty("httpclient.connection-timeout-ms", 60000));
connectionParams.setSoTimeout(jets3tProperties.
getIntProperty("httpclient.socket-timeout-ms", 60000));
connectionParams.setMaxConnectionsPerHost(insecureHostConfig, jets3tProperties.
getIntProperty("httpclient.max-connections", 10));
connectionParams.setMaxConnectionsPerHost(secureHostConfig, jets3tProperties.
getIntProperty("httpclient.max-connections", 10));
connectionParams.setStaleCheckingEnabled(jets3tProperties.
getBoolProperty("httpclient.stale-checking-enabled", true));
connectionParams.setBooleanParameter("http.protocol.expect-continue", true);
connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.setParams(connectionParams);
// Set user agent string.
HttpClientParams clientParams = new HttpClientParams();
String userAgent = jets3tProperties.getStringProperty("httpclient.useragent", null);
if (userAgent == null) {
userAgent = ServiceUtils.getUserAgentDescription(
getInvokingApplicationDescription());
}
log.debug("Setting user agent string: " + userAgent);
clientParams.setParameter(HttpMethodParams.USER_AGENT, userAgent);
// Replace default error retry handler.
final boolean retryOnErrors = jets3tProperties.getBoolProperty("httpclient.retry-on-errors", true);
final int maximumRetryCount = 3;
clientParams.setParameter(HttpClientParams.RETRY_HANDLER, new HttpMethodRetryHandler() {
public boolean retryMethod(HttpMethod method, IOException ioe, int executionCount) {
if (ioe instanceof UnrecoverableIOException) {
log.debug("Deliberate interruption, will not retry");
return false;
}
if (executionCount > maximumRetryCount) {
log.debug("Retried connection " + maximumRetryCount + " times, it's time to give up");
return false;
}
if (retryOnErrors) {
log.warn("Retrying request - attempt " + executionCount + " of " + maximumRetryCount);
}
return retryOnErrors;
}
});
httpClient = new HttpClient(clientParams, connectionManager);
// Try to detect any proxy settings from applet.
ProxyHost proxyHost = null;
try {
HostConfiguration hostConfig = null;
if (isHttpsOnly()) {
hostConfig = secureHostConfig;
} else {
hostConfig = insecureHostConfig;
}
proxyHost = PluginProxyUtil.detectProxy(new URL(hostConfig.getHostURL()));
if (proxyHost != null) {
hostConfig.setProxyHost(proxyHost);
httpClient.setHostConfiguration(hostConfig);
}
} catch (Throwable t) {
log.error("Unable to set proxy configuration", t);
}
if (credentialsProvider != null) {
log.debug("Using credentials provider class: " + credentialsProvider.getClass().getName());
httpClient.getParams().setParameter(CredentialsProvider.PROVIDER, credentialsProvider);
httpClient.getParams().setAuthenticationPreemptive(true);
}
}
/**
* Performs an HTTP/S request by invoking the provided HttpMethod object. If the HTTP
* response code doesn't match the expected value, an exception is thrown.
*
* @param httpMethod
* the object containing a request target and all other information necessary to perform the
* request
* @param expectedResponseCode
* the HTTP response code that indicates a successful request. If the response code received
* does not match this value an error must have occurred, so an exception is thrown.
* @throws S3ServiceException
* all exceptions are wrapped in an S3ServiceException. Depending on the kind of error that
* occurred, this exception may contain additional error information available from an XML
* error response document.
*/
protected void performRequest(HttpMethodBase httpMethod, int expectedResponseCode)
throws S3ServiceException
{
// httpMethod.setRequestHeader("Cache-Control", "no-cache"); // TODO
try {
log.debug("Performing " + httpMethod.getName()
+ " request, expecting response code " + expectedResponseCode);
// Variables to manage occasional S3 Internal Server 500 errors.
boolean completedWithoutRecoverableError = true;
int internalErrorCount = 0;
int requestTimeoutErrorCount = 0;
// Perform the request, sleeping and retrying when S3 Internal Errors are encountered.
int responseCode = -1;
do {
responseCode = httpClient.executeMethod(httpMethod);
if (responseCode == 500) {
// Retry on S3 Internal Server 500 errors.
completedWithoutRecoverableError = false;
sleepOnInternalError(++internalErrorCount);
} else {
completedWithoutRecoverableError = true;
}
String contentType = "";
if (httpMethod.getResponseHeader("Content-Type") != null) {
contentType = httpMethod.getResponseHeader("Content-Type").getValue();
}
log.debug("Request returned with headers: " + Arrays.asList(httpMethod.getResponseHeaders()));
log.debug("Request returned with Content-Type: " + contentType);
// Check we received the expected result code.
if (responseCode != expectedResponseCode) {
log.debug("Unexpected response code " + responseCode + ", expected " + expectedResponseCode);
if (Mimetypes.MIMETYPE_XML.equals(contentType)
&& httpMethod.getResponseBodyAsStream() != null
&& httpMethod.getResponseContentLength() != 0)
{
log.debug("Received error response with XML message");
StringBuffer sb = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new HttpMethodReleaseInputStream(httpMethod)));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
// Throw exception containing the XML message document.
S3ServiceException exception =
new S3ServiceException("S3 " + httpMethod.getName()
+ " failed.", sb.toString());
if ("RequestTimeout".equals(exception.getS3ErrorCode())) {
if (requestTimeoutErrorCount < 3) { // TODO
requestTimeoutErrorCount++;
log.warn("Retrying connection that failed with RequestTimeout error"
+ ", attempt number " + requestTimeoutErrorCount + " of "
+ 3); // TODO
completedWithoutRecoverableError = false;
} else {
log.warn("Exceeded maximum number of retries for RequestTimeout errors: "
+ 3); // TODO
throw exception;
}
} else if (responseCode == 500) {
// Retrying after InternalError 500, don't throw exception.
} else {
throw exception;
}
- } else {
+ } else {
// Consume response content and release connection.
String responseText = null;
byte[] responseBody = httpMethod.getResponseBody();
if (responseBody != null && responseBody.length > 0) {
responseText = new String(responseBody);
}
log.debug("Releasing error response without XML content");
httpMethod.releaseConnection();
- // Throw exception containing the HTTP error fields.
- throw new S3ServiceException("S3 "
- + httpMethod.getName() + " request failed. "
- + "ResponseCode=" + httpMethod.getStatusCode()
- + ", ResponseMessage=" + httpMethod.getStatusText()
- + (responseText != null ? "\n" + responseText : ""));
+ if (responseCode == 500) {
+ // Retrying after InternalError 500, don't throw exception.
+ } else {
+ // Throw exception containing the HTTP error fields.
+ throw new S3ServiceException("S3 "
+ + httpMethod.getName() + " request failed. "
+ + "ResponseCode=" + httpMethod.getStatusCode()
+ + ", ResponseMessage=" + httpMethod.getStatusText()
+ + (responseText != null ? "\n" + responseText : ""));
+ }
}
}
} while (!completedWithoutRecoverableError);
// Release immediately any connections without response bodies.
if ((httpMethod.getResponseBodyAsStream() == null
|| httpMethod.getResponseBodyAsStream().available() == 0)
&& httpMethod.getResponseContentLength() == 0)
{
log.debug("Releasing response without content");
byte[] responseBody = httpMethod.getResponseBody();
if (responseBody != null && responseBody.length > 0)
throw new S3ServiceException("Oops, too keen to release connection with a non-empty response body");
httpMethod.releaseConnection();
}
} catch (S3ServiceException e) {
throw e;
} catch (Throwable t) {
log.debug("Releasing method after error: " + t.getMessage());
httpMethod.releaseConnection();
throw new S3ServiceException("S3 " + httpMethod.getName() + " connection failed", t);
}
}
/**
* Adds all the provided request parameters to a URL in GET request format.
*
* @param urlPath
* the target URL
* @param requestParameters
* the parameters to add to the URL as GET request params.
* @return
* the target URL including the parameters.
* @throws S3ServiceException
*/
protected String addRequestParametersToUrlPath(String urlPath, Map requestParameters)
throws S3ServiceException
{
if (requestParameters != null) {
Iterator reqPropIter = requestParameters.keySet().iterator();
while (reqPropIter.hasNext()) {
Object key = reqPropIter.next();
Object value = requestParameters.get(key);
urlPath += (urlPath.indexOf("?") < 0? "?" : "&")
+ RestUtils.encodeUrlString(key.toString());
if (value != null && value.toString().length() > 0) {
urlPath += "=" + RestUtils.encodeUrlString(value.toString());
log.debug("Added request parameter: " + key + "=" + value);
} else {
log.debug("Added request parameter without value: " + key);
}
}
}
return urlPath;
}
/**
* Adds the provided request headers to the connection.
*
* @param httpMethod
* the connection object
* @param requestHeaders
* the request headers to add as name/value pairs.
*/
protected void addRequestHeadersToConnection(
HttpMethodBase httpMethod, Map requestHeaders)
{
if (requestHeaders != null) {
Iterator reqHeaderIter = requestHeaders.keySet().iterator();
while (reqHeaderIter.hasNext()) {
String key = reqHeaderIter.next().toString();
String value = requestHeaders.get(key).toString();
httpMethod.setRequestHeader(key.toString(), value.toString());
log.debug("Added request header to connection: " + key + "=" + value);
}
}
}
/**
* Converts an array of Header objects to a map of name/value pairs.
*
* @param headers
* @return
*/
private Map convertHeadersToMap(Header[] headers) {
HashMap map = new HashMap();
for (int i = 0; headers != null && i < headers.length; i++) {
map.put(headers[i].getName(), headers[i].getValue());
}
return map;
}
/**
* Adds all appropriate metadata to the given HTTP method.
*
* @param httpMethod
* @param metadata
*/
private void addMetadataToHeaders(HttpMethodBase httpMethod, Map metadata) {
Iterator metaDataIter = metadata.keySet().iterator();
while (metaDataIter.hasNext()) {
String key = (String) metaDataIter.next();
Object value = metadata.get(key);
if (key == null || !(value instanceof String)) {
// Ignore invalid metadata.
continue;
}
httpMethod.setRequestHeader(key, (String) value);
}
}
/**
* Performs an HTTP HEAD request using the {@link #performRequest} method.
*
* @param bucketName
* the bucket's name
* @param objectKey
* the object's key name, may be null if the operation is on a bucket only.
* @param requestParameters
* parameters to add to the request URL as GET params
* @param requestHeaders
* headers to add to the request
* @return
* @throws S3ServiceException
*/
protected HttpMethodBase performRestHead(String bucketName, String objectKey,
Map requestParameters, Map requestHeaders) throws S3ServiceException
{
HttpMethodBase httpMethod = setupConnection("HEAD", bucketName, objectKey, requestParameters);
// Add authorization header.
buildAuthorizationString(httpMethod);
// Add all request headers.
addRequestHeadersToConnection(httpMethod, requestHeaders);
performRequest(httpMethod, 200);
return httpMethod;
}
/**
* Performs an HTTP GET request using the {@link #performRequest} method.
*
* @param bucketName
* the bucket's name
* @param objectKey
* the object's key name, may be null if the operation is on a bucket only.
* @param requestParameters
* parameters to add to the request URL as GET params
* @param requestHeaders
* headers to add to the request
* @return
* @throws S3ServiceException
*/
protected HttpMethodBase performRestGet(String bucketName, String objectKey,
Map requestParameters, Map requestHeaders) throws S3ServiceException
{
HttpMethodBase httpMethod = setupConnection("GET", bucketName, objectKey, requestParameters);
// Add authorization header.
buildAuthorizationString(httpMethod);
// Add all request headers.
addRequestHeadersToConnection(httpMethod, requestHeaders);
int expectedStatusCode = 200;
if (requestHeaders != null && requestHeaders.containsKey("Range")) {
// Partial data responses have a status code of 206.
expectedStatusCode = 206;
}
performRequest(httpMethod, expectedStatusCode);
return httpMethod;
}
/**
* Performs an HTTP PUT request using the {@link #performRequest} method.
*
* @param path
* the URL request target
* @param metadata
* map of name/value pairs to add as metadata to any S3 objects created.
* @param requestParameters
* parameters to add to the request URL as GET params
* @param dataInputStream
* input stream containing object's data contents. If null, created objects are empty.
* @return
* @throws S3ServiceException
*/
protected HttpMethodAndByteCount performRestPut(String bucketName, String objectKey,
Map metadata, Map requestParameters, RequestEntity requestEntity) throws S3ServiceException
{
// Add any request parameters.
HttpMethodBase httpMethod = setupConnection("PUT", bucketName, objectKey, requestParameters);
Map renamedMetadata = RestUtils.renameMetadataKeys(metadata);
addMetadataToHeaders(httpMethod, renamedMetadata);
// Build the authorization string for the method.
buildAuthorizationString(httpMethod);
long contentLength = 0;
if (requestEntity != null) {
((PutMethod)httpMethod).setRequestEntity(requestEntity);
} else {
// Need an explicit Content-Length even if no data is being uploaded.
httpMethod.setRequestHeader("Content-Length", "0");
}
performRequest(httpMethod, 200);
if (requestEntity != null) {
// Respond with the actual guaranteed content length of the uploaded data.
contentLength = ((PutMethod)httpMethod).getRequestEntity().getContentLength();
}
return new HttpMethodAndByteCount(httpMethod, contentLength);
}
/**
* Performs an HTTP DELETE request using the {@link #performRequest} method.
*
* @param bucketName
* the bucket's name
* @param objectKey
* the object's key name, may be null if the operation is on a bucket only.
* @return
* @throws S3ServiceException
*/
protected HttpMethodBase performRestDelete(String bucketName, String objectKey) throws S3ServiceException {
HttpMethodBase httpMethod = setupConnection("DELETE", bucketName, objectKey, null);
buildAuthorizationString(httpMethod);
performRequest(httpMethod, 204);
// Release connection after DELETE (there's no response content)
log.debug("Releasing HttpMethod after delete");
httpMethod.releaseConnection();
return httpMethod;
}
/**
* Creates an {@link HttpMethod} object to handle a particular connection method.
*
* @param method
* the HTTP method/connection-type to use, must be one of: PUT, HEAD, GET, DELETE
* @param bucketName
* the bucket's name
* @param objectKey
* the object's key name, may be null if the operation is on a bucket only.
* @return
* @throws S3ServiceException
*/
protected HttpMethodBase setupConnection(String method, String bucketName, String objectKey, Map requestParameters) throws S3ServiceException
{
if (bucketName == null) {
throw new S3ServiceException("Cannot connect to S3 Service with a null path");
}
// Determine the resource string (ie the item's path in S3, including the bucket name)
String resourceString = "/" + bucketName +
(objectKey != null? "/" + RestUtils.encodeUrlString(objectKey) : "");
// Construct a URL representing a connection for the S3 resource.
String url = null;
if (isHttpsOnly()) {
log.debug("REST/HTTP service is using HTTPS for all communication");
url = PROTOCOL_SECURE + "://" + Constants.REST_SERVER_DNS + ":" + PORT_SECURE + resourceString;
} else {
url = PROTOCOL_INSECURE + "://" + Constants.REST_SERVER_DNS + ":" + PORT_INSECURE + resourceString;
}
// Add additional request parameters to the URL for special cases (eg ACL operations)
url = addRequestParametersToUrlPath(url, requestParameters);
HttpMethodBase httpMethod = null;
if ("PUT".equals(method)) {
httpMethod = new PutMethod(url);
} else if ("HEAD".equals(method)) {
httpMethod = new HeadMethod(url);
} else if ("GET".equals(method)) {
httpMethod = new GetMethod(url);
} else if ("DELETE".equals(method)) {
httpMethod = new DeleteMethod(url);
} else {
throw new IllegalArgumentException("Unrecognised HTTP method name: " + method);
}
// Set mandatory Request headers.
if (httpMethod.getRequestHeader("Date") == null) {
httpMethod.setRequestHeader("Date", ServiceUtils.formatRfc822Date(new Date()));
}
if (httpMethod.getRequestHeader("Content-Type") == null) {
httpMethod.setRequestHeader("Content-Type", "");
}
return httpMethod;
}
/**
* Authorizes an HTTP request by signing it. The signature is based on the target URL, and the
* signed authorization string is added to the {@link HttpMethod} object as an Authorization header.
*
* @param httpMethod
* the request object
* @throws S3ServiceException
*/
protected void buildAuthorizationString(HttpMethodBase httpMethod) throws S3ServiceException {
if (isAuthenticatedConnection()) {
log.debug("Adding authorization for AWS Access Key '" + getAWSCredentials().getAccessKey() + "'.");
} else {
log.debug("Service has no AWS Credential and is un-authenticated, skipping authorization");
return;
}
// Determine the complete URL for the S3 resource, including any S3-specific parameters.
String fullUrl = httpMethod.getPath();
String queryString = httpMethod.getQueryString();
if (queryString != null && queryString.length() > 0) {
fullUrl += "?" + queryString;
}
// Generate a canonical string representing the operation.
String canonicalString = RestUtils.makeCanonicalString(
httpMethod.getName(), fullUrl,
convertHeadersToMap(httpMethod.getRequestHeaders()), null);
log.debug("Canonical string ('|' is a newline): " + canonicalString.replace('\n', '|'));
// Sign the canonical string.
String signedCanonical = ServiceUtils.signWithHmacSha1(
getAWSCredentials().getSecretKey(), canonicalString);
// Add encoded authorization to connection as HTTP Authorization header.
String authorizationString = "AWS " + getAWSCredentials().getAccessKey() + ":" + signedCanonical;
httpMethod.setRequestHeader("Authorization", authorizationString);
}
////////////////////////////////////////////////////////////////
// Methods below this point implement S3Service abstract methods
////////////////////////////////////////////////////////////////
public boolean isBucketAccessible(String bucketName) throws S3ServiceException {
log.debug("Checking existence of bucket: " + bucketName);
HttpMethodBase httpMethod = null;
// This request may return an XML document that we're not interested in. Clean this up.
try {
// Ensure bucket exists and is accessible by performing a HEAD request
httpMethod = performRestHead(bucketName, null, null, null);
if (httpMethod.getResponseBodyAsStream() != null) {
httpMethod.getResponseBodyAsStream().close();
}
} catch (S3ServiceException e) {
log.warn("Unable to access bucket: " + bucketName, e);
return false;
} catch (IOException e) {
log.warn("Unable to close response body input stream", e);
} finally {
log.debug("Releasing un-wanted bucket HEAD response");
if (httpMethod != null) {
httpMethod.releaseConnection();
}
}
// If we get this far, the bucket exists.
return true;
}
public S3Bucket[] listAllBucketsImpl() throws S3ServiceException {
log.debug("Listing all buckets for AWS user: " + getAWSCredentials().getAccessKey());
String bucketName = ""; // Root path of S3 service lists the user's buckets.
HttpMethodBase httpMethod = performRestGet(bucketName, null, null, null);
String contentType = httpMethod.getResponseHeader("Content-Type").getValue();
if (!Mimetypes.MIMETYPE_XML.equals(contentType)) {
throw new S3ServiceException("Expected XML document response from S3 but received content type " +
contentType);
}
S3Bucket[] buckets = (new XmlResponsesSaxParser()).parseListMyBucketsResponse(
new HttpMethodReleaseInputStream(httpMethod)).getBuckets();
return buckets;
}
public S3Object[] listObjectsImpl(String bucketName, String prefix, String delimiter,
long maxListingLength) throws S3ServiceException
{
return listObjectsInternal(bucketName, prefix, delimiter, maxListingLength, true, null)
.getObjects();
}
public S3ObjectsChunk listObjectsChunkedImpl(String bucketName, String prefix, String delimiter,
long maxListingLength, String priorLastKey) throws S3ServiceException
{
return listObjectsInternal(bucketName, prefix, delimiter, maxListingLength, false, priorLastKey);
}
protected S3ObjectsChunk listObjectsInternal(String bucketName, String prefix, String delimiter,
long maxListingLength, boolean automaticallyMergeChunks, String priorLastKey) throws S3ServiceException
{
HashMap parameters = new HashMap();
if (prefix != null) {
parameters.put("prefix", prefix);
}
if (delimiter != null) {
parameters.put("delimiter", delimiter);
}
if (maxListingLength > 0) {
parameters.put("max-keys", String.valueOf(maxListingLength));
}
ArrayList objects = new ArrayList();
boolean incompleteListing = true;
while (incompleteListing) {
if (priorLastKey != null) {
parameters.put("marker", priorLastKey);
} else {
parameters.remove("marker");
}
HttpMethodBase httpMethod = performRestGet(bucketName, null, parameters, null);
ListBucketHandler listBucketHandler =
(new XmlResponsesSaxParser()).parseListBucketObjectsResponse(
new HttpMethodReleaseInputStream(httpMethod));
S3Object[] partialObjects = listBucketHandler.getObjects();
log.debug("Found " + partialObjects.length + " objects in one batch");
objects.addAll(Arrays.asList(partialObjects));
incompleteListing = listBucketHandler.isListingTruncated();
if (incompleteListing) {
priorLastKey = listBucketHandler.getLastKey();
log.debug("Yet to receive complete listing of bucket contents, "
+ "last key for prior chunk: " + priorLastKey);
} else {
priorLastKey = null;
}
if (!automaticallyMergeChunks)
break;
}
if (automaticallyMergeChunks) {
log.debug("Found " + objects.size() + " objects in total");
return new S3ObjectsChunk(
(S3Object[]) objects.toArray(new S3Object[] {}), null);
} else {
return new S3ObjectsChunk(
(S3Object[]) objects.toArray(new S3Object[] {}), priorLastKey);
}
}
public void deleteObjectImpl(String bucketName, String objectKey) throws S3ServiceException {
performRestDelete(bucketName, objectKey);
}
public AccessControlList getObjectAclImpl(String bucketName, String objectKey) throws S3ServiceException {
log.debug("Retrieving Access Control List for bucketName=" + bucketName + ", objectKkey=" + objectKey);
HashMap requestParameters = new HashMap();
requestParameters.put("acl","");
HttpMethodBase httpMethod = performRestGet(bucketName, objectKey, requestParameters, null);
return (new XmlResponsesSaxParser()).parseAccessControlListResponse(
new HttpMethodReleaseInputStream(httpMethod)).getAccessControlList();
}
public AccessControlList getBucketAclImpl(String bucketName) throws S3ServiceException {
log.debug("Retrieving Access Control List for Bucket: " + bucketName);
HashMap requestParameters = new HashMap();
requestParameters.put("acl","");
HttpMethodBase httpMethod = performRestGet(bucketName, null, requestParameters, null);
return (new XmlResponsesSaxParser()).parseAccessControlListResponse(
new HttpMethodReleaseInputStream(httpMethod)).getAccessControlList();
}
public void putObjectAclImpl(String bucketName, String objectKey, AccessControlList acl)
throws S3ServiceException
{
putAclImpl(bucketName, objectKey, acl);
}
public void putBucketAclImpl(String bucketName, AccessControlList acl)
throws S3ServiceException
{
String fullKey = bucketName;
putAclImpl(fullKey, null, acl);
}
protected void putAclImpl(String bucketName, String objectKey, AccessControlList acl) throws S3ServiceException
{
log.debug("Setting Access Control List for bucketName=" + bucketName + ", objectKey=" + objectKey);
HashMap requestParameters = new HashMap();
requestParameters.put("acl","");
HashMap metadata = new HashMap();
metadata.put("Content-Type", "text/plain");
try {
String aclAsXml = acl.toXml();
metadata.put("Content-Length", String.valueOf(aclAsXml.length()));
performRestPut(bucketName, objectKey, metadata, requestParameters,
new StringRequestEntity(aclAsXml, "text/plain", Constants.DEFAULT_ENCODING));
} catch (UnsupportedEncodingException e) {
throw new S3ServiceException("Unable to encode ACL XML document", e);
}
}
public S3Bucket createBucketImpl(String bucketName, AccessControlList acl)
throws S3ServiceException
{
log.debug("Creating bucket with name: " + bucketName);
Map map = createObjectImpl(bucketName, null, null, null, null, acl);
S3Bucket bucket = new S3Bucket(bucketName);
bucket.setAcl(acl);
bucket.replaceAllMetadata(map);
return bucket;
}
public void deleteBucketImpl(String bucketName) throws S3ServiceException {
performRestDelete(bucketName, null);
}
/**
* Beware of high memory requirements when creating large S3 objects when the Content-Length
* is not set in the object.
*/
public S3Object putObjectImpl(String bucketName, S3Object object) throws S3ServiceException
{
log.debug("Creating Object with key " + object.getKey() + " in bucket " + bucketName);
RequestEntity requestEntity = null;
if (object.getDataInputStream() != null) {
if (object.containsMetadata("Content-Length")) {
log.debug("Uploading object data with Content-Length: " + object.getContentLength());
requestEntity = new BufferedRequestEntity(
object.getDataInputStream(), object.getContentType(), object.getContentLength());
} else {
// Use InputStreamRequestEntity for objects with an unknown content length, as the
// entity will cache the results and doesn't need to know the data length in advance.
log.warn("Content-Length of data stream not set, will automatically determine data length in memory");
requestEntity = new InputStreamRequestEntity(
object.getDataInputStream(), InputStreamRequestEntity.CONTENT_LENGTH_AUTO);
}
}
Map map = createObjectImpl(bucketName, object.getKey(), object.getContentType(),
requestEntity, object.getMetadataMap(), object.getAcl());
object.replaceAllMetadata(map);
return object;
}
protected Map createObjectImpl(String bucketName, String objectKey, String contentType,
RequestEntity requestEntity, Map metadata, AccessControlList acl)
throws S3ServiceException
{
if (metadata == null) {
metadata = new HashMap();
} else {
// Use a new map object in case the one we were provided is immutable.
metadata = new HashMap(metadata);
}
if (contentType != null) {
metadata.put("Content-Type", contentType);
} else {
metadata.put("Content-Type", Mimetypes.MIMETYPE_OCTET_STREAM);
}
boolean putNonStandardAcl = false;
if (acl != null) {
if (AccessControlList.REST_CANNED_PRIVATE.equals(acl)) {
metadata.put(Constants.REST_HEADER_PREFIX + "acl", "private");
} else if (AccessControlList.REST_CANNED_PUBLIC_READ.equals(acl)) {
metadata.put(Constants.REST_HEADER_PREFIX + "acl", "public-read");
} else if (AccessControlList.REST_CANNED_PUBLIC_READ_WRITE.equals(acl)) {
metadata.put(Constants.REST_HEADER_PREFIX + "acl", "public-read-write");
} else if (AccessControlList.REST_CANNED_AUTHENTICATED_READ.equals(acl)) {
metadata.put(Constants.REST_HEADER_PREFIX + "acl", "authenticated-read");
} else {
putNonStandardAcl = true;
}
}
log.debug("Creating object bucketName=" + bucketName + ", objectKey=" + objectKey + "." +
" Content-Type=" + metadata.get("Content-Type") +
" Including data? " + (requestEntity != null) +
" Metadata: " + metadata +
" ACL: " + acl
);
HttpMethodAndByteCount methodAndByteCount = performRestPut(
bucketName, objectKey, metadata, null, requestEntity);
// Consume response content.
HttpMethodBase httpMethod = methodAndByteCount.getHttpMethod();
Map map = new HashMap();
map.putAll(metadata); // Keep existing metadata.
map.putAll(convertHeadersToMap(httpMethod.getResponseHeaders()));
map.put(S3Object.METADATA_HEADER_CONTENT_LENGTH, String.valueOf(methodAndByteCount.getByteCount()));
map = ServiceUtils.cleanRestMetadataMap(map);
if (putNonStandardAcl) {
log.debug("Creating object with a non-canned ACL using REST, so an extra ACL Put is required");
putAclImpl(bucketName, objectKey, acl);
}
return map;
}
public S3Object getObjectDetailsImpl(String bucketName, String objectKey, Calendar ifModifiedSince,
Calendar ifUnmodifiedSince, String[] ifMatchTags, String[] ifNoneMatchTags)
throws S3ServiceException
{
return getObjectImpl(true, bucketName, objectKey,
ifModifiedSince, ifUnmodifiedSince, ifMatchTags, ifNoneMatchTags, null, null);
}
public S3Object getObjectImpl(String bucketName, String objectKey, Calendar ifModifiedSince,
Calendar ifUnmodifiedSince, String[] ifMatchTags, String[] ifNoneMatchTags,
Long byteRangeStart, Long byteRangeEnd)
throws S3ServiceException
{
return getObjectImpl(false, bucketName, objectKey, ifModifiedSince, ifUnmodifiedSince,
ifMatchTags, ifNoneMatchTags, byteRangeStart, byteRangeEnd);
}
private S3Object getObjectImpl(boolean headOnly, String bucketName, String objectKey,
Calendar ifModifiedSince, Calendar ifUnmodifiedSince, String[] ifMatchTags,
String[] ifNoneMatchTags, Long byteRangeStart, Long byteRangeEnd)
throws S3ServiceException
{
log.debug("Retrieving " + (headOnly? "Head" : "All") + " information for bucket " + bucketName + " and object " + objectKey);
HashMap requestHeaders = new HashMap();
if (ifModifiedSince != null) {
requestHeaders.put("If-Modified-Since",
ServiceUtils.formatRfc822Date(ifModifiedSince.getTime()));
log.debug("Only retrieve object if-modified-since:" + ifModifiedSince);
}
if (ifUnmodifiedSince != null) {
requestHeaders.put("If-Unmodified-Since",
ServiceUtils.formatRfc822Date(ifUnmodifiedSince.getTime()));
log.debug("Only retrieve object if-unmodified-since:" + ifUnmodifiedSince);
}
if (ifMatchTags != null) {
StringBuffer tags = new StringBuffer();
for (int i = 0; i < ifMatchTags.length; i++) {
if (i > 0) {
tags.append(",");
}
tags.append(ifMatchTags[i]);
}
requestHeaders.put("If-Match", tags.toString());
log.debug("Only retrieve object by hash if-match:" + tags.toString());
}
if (ifNoneMatchTags != null) {
StringBuffer tags = new StringBuffer();
for (int i = 0; i < ifNoneMatchTags.length; i++) {
if (i > 0) {
tags.append(",");
}
tags.append(ifNoneMatchTags[i]);
}
requestHeaders.put("If-None-Match", tags.toString());
log.debug("Only retrieve object by hash if-none-match:" + tags.toString());
}
if (byteRangeStart != null || byteRangeEnd != null) {
String range = "bytes="
+ (byteRangeStart != null? byteRangeStart.toString() : "")
+ "-"
+ (byteRangeEnd != null? byteRangeEnd.toString() : "");
requestHeaders.put("Range", range);
log.debug("Only retrieve object if it is within range:" + range);
}
HttpMethodBase httpMethod = null;
if (headOnly) {
httpMethod = performRestHead(bucketName, objectKey, null, requestHeaders);
} else {
httpMethod = performRestGet(bucketName, objectKey, null, requestHeaders);
}
HashMap map = new HashMap();
map.putAll(convertHeadersToMap(httpMethod.getResponseHeaders()));
S3Object responseObject = new S3Object(objectKey);
responseObject.setBucketName(bucketName);
responseObject.replaceAllMetadata(ServiceUtils.cleanRestMetadataMap(map));
responseObject.setMetadataComplete(true); // Flag this object as having the complete metadata set.
if (!headOnly) {
HttpMethodReleaseInputStream releaseIS = new HttpMethodReleaseInputStream(httpMethod);
responseObject.setDataInputStream(releaseIS);
} else {
// Release connection after HEAD (there's no response content)
log.debug("Releasing HttpMethod after HEAD");
httpMethod.releaseConnection();
}
return responseObject;
}
public S3BucketLoggingStatus getBucketLoggingStatusImpl(String bucketName)
throws S3ServiceException
{
log.debug("Retrieving Logging Status for Bucket: " + bucketName);
HashMap requestParameters = new HashMap();
requestParameters.put("logging","");
HttpMethodBase httpMethod = performRestGet(bucketName, null, requestParameters, null);
return (new XmlResponsesSaxParser()).parseLoggingStatusResponse(
new HttpMethodReleaseInputStream(httpMethod)).getBucketLoggingStatus();
}
public void setBucketLoggingStatusImpl(String bucketName, S3BucketLoggingStatus status)
throws S3ServiceException
{
log.debug("Setting Logging Status for bucket: " + bucketName);
HashMap requestParameters = new HashMap();
requestParameters.put("logging","");
HashMap metadata = new HashMap();
metadata.put("Content-Type", "text/plain");
try {
String statusAsXml = status.toXml();
metadata.put("Content-Length", String.valueOf(statusAsXml.length()));
performRestPut(bucketName, null, metadata, requestParameters,
new StringRequestEntity(statusAsXml, "text/plain", Constants.DEFAULT_ENCODING));
} catch (UnsupportedEncodingException e) {
throw new S3ServiceException("Unable to encode LoggingStatus XML document", e);
}
}
/**
* Puts an object using a pre-signed PUT URL generated for that object.
* This method is an implementation of the interface {@link SignedUrlHandler}.
* <p>
* This operation does not required any S3 functionality as it merely
* uploads the object by performing a standard HTTP PUT using the signed URL.
*
* @param signedPutUrl
* a signed PUT URL generated with {@link S3Service.createSignedPutUrl()}.
* @param object
* the object to upload, which must correspond to the object for which the URL was signed.
* The object <b>must</b> have the correct content length set, and to apply a non-standard
* ACL policy only the REST canned ACLs can be used
* (eg {@link AccessControlList.REST_CANNED_PUBLIC_READ_WRITE}).
*
* @return
* the S3Object put to S3. The S3Object returned will be identical to the object provided,
* except that the data input stream (if any) will have been consumed.
*
* @throws S3ServiceException
*/
public S3Object putObjectWithSignedUrl(String signedPutUrl, S3Object object) throws S3ServiceException {
PutMethod putMethod = new PutMethod(signedPutUrl);
Map renamedMetadata = RestUtils.renameMetadataKeys(object.getMetadataMap());
addMetadataToHeaders(putMethod, renamedMetadata);
if (!object.containsMetadata("Content-Length")) {
throw new IllegalStateException("Content-Length must be specified for objects put using signed PUT URLs");
}
if (object.getDataInputStream() != null) {
putMethod.setRequestEntity(new BufferedRequestEntity(
object.getDataInputStream(), object.getContentType(), object.getContentLength()));
}
performRequest(putMethod, 200);
// Consume response data and release connection.
putMethod.releaseConnection();
try {
S3Object uploadedObject = ServiceUtils.buildObjectFromPath(putMethod.getPath());
object.setBucketName(uploadedObject.getBucketName());
object.setKey(uploadedObject.getKey());
object.getDataInputStream().close();
} catch (UnsupportedEncodingException e) {
throw new S3ServiceException("Unable to determine name of object created with signed PUT", e);
} catch (IOException e) {
log.warn("Unable to close object's input stream", e);
}
return object;
}
/**
* Deletes an object using a pre-signed DELETE URL generated for that object.
* This method is an implementation of the interface {@link SignedUrlHandler}.
* <p>
* This operation does not required any S3 functionality as it merely
* deletes the object by performing a standard HTTP DELETE using the signed URL.
*
* @param signedDeleteUrl
* a signed DELETE URL generated with {@link S3Service.createSignedDeleteUrl}.
*
* @throws S3ServiceException
*/
public void deleteObjectWithSignedUrl(String signedDeleteUrl) throws S3ServiceException {
DeleteMethod deleteMethod = new DeleteMethod(signedDeleteUrl);
performRequest(deleteMethod, 204);
deleteMethod.releaseConnection();
}
/**
* Gets an object using a pre-signed GET URL generated for that object.
* This method is an implementation of the interface {@link SignedUrlHandler}.
* <p>
* This operation does not required any S3 functionality as it merely
* uploads the object by performing a standard HTTP GET using the signed URL.
*
* @param signedGetUrl
* a signed GET URL generated with {@link S3Service.createSignedGetUrl()}.
*
* @return
* the S3Object in S3 including all metadata and the object's data input stream.
*
* @throws S3ServiceException
*/
public S3Object getObjectWithSignedUrl(String signedGetUrl) throws S3ServiceException {
return getObjectWithSignedUrlImpl(signedGetUrl, false);
}
/**
* Gets an object's details using a pre-signed HEAD URL generated for that object.
* This method is an implementation of the interface {@link SignedUrlHandler}.
* <p>
* This operation does not required any S3 functionality as it merely
* uploads the object by performing a standard HTTP HEAD using the signed URL.
*
* @param signedHeadUrl
* a signed HEAD URL generated with {@link S3Service.createSignedHeadUrl()}.
*
* @return
* the S3Object in S3 including all metadata, but without the object's data input stream.
*
* @throws S3ServiceException
*/
public S3Object getObjectDetailsWithSignedUrl(String signedHeadUrl) throws S3ServiceException {
return getObjectWithSignedUrlImpl(signedHeadUrl, true);
}
private S3Object getObjectWithSignedUrlImpl(String signedGetOrHeadUrl, boolean headOnly)
throws S3ServiceException
{
HttpMethodBase httpMethod = null;
if (headOnly) {
httpMethod = new HeadMethod(signedGetOrHeadUrl);
} else {
httpMethod = new GetMethod(signedGetOrHeadUrl);
}
performRequest(httpMethod, 200);
HashMap map = new HashMap();
map.putAll(convertHeadersToMap(httpMethod.getResponseHeaders()));
S3Object responseObject = null;
try {
responseObject = ServiceUtils.buildObjectFromPath(
httpMethod.getPath().substring(1));
} catch (UnsupportedEncodingException e) {
throw new S3ServiceException("Unable to determine name of object created with signed PUT", e);
}
responseObject.replaceAllMetadata(ServiceUtils.cleanRestMetadataMap(map));
responseObject.setMetadataComplete(true); // Flag this object as having the complete metadata set.
if (!headOnly) {
HttpMethodReleaseInputStream releaseIS = new HttpMethodReleaseInputStream(httpMethod);
responseObject.setDataInputStream(releaseIS);
} else {
// Release connection after HEAD (there's no response content)
log.debug("Releasing HttpMethod after HEAD");
httpMethod.releaseConnection();
}
return responseObject;
}
/**
* Simple container object to store an HttpMethod object representing a request connection, and a
* count of the byte size of the S3 object associated with the request.
* <p>
* This object is used when S3 objects are created to associate the connection and the actual size
* of the object as reported back by S3.
*
* @author James Murty
*/
private class HttpMethodAndByteCount {
private HttpMethodBase httpMethod = null;
private long byteCount = 0;
public HttpMethodAndByteCount(HttpMethodBase httpMethod, long byteCount) {
this.httpMethod = httpMethod;
this.byteCount = byteCount;
}
public HttpMethodBase getHttpMethod() {
return httpMethod;
}
public long getByteCount() {
return byteCount;
}
}
}
| false | true | protected void performRequest(HttpMethodBase httpMethod, int expectedResponseCode)
throws S3ServiceException
{
// httpMethod.setRequestHeader("Cache-Control", "no-cache"); // TODO
try {
log.debug("Performing " + httpMethod.getName()
+ " request, expecting response code " + expectedResponseCode);
// Variables to manage occasional S3 Internal Server 500 errors.
boolean completedWithoutRecoverableError = true;
int internalErrorCount = 0;
int requestTimeoutErrorCount = 0;
// Perform the request, sleeping and retrying when S3 Internal Errors are encountered.
int responseCode = -1;
do {
responseCode = httpClient.executeMethod(httpMethod);
if (responseCode == 500) {
// Retry on S3 Internal Server 500 errors.
completedWithoutRecoverableError = false;
sleepOnInternalError(++internalErrorCount);
} else {
completedWithoutRecoverableError = true;
}
String contentType = "";
if (httpMethod.getResponseHeader("Content-Type") != null) {
contentType = httpMethod.getResponseHeader("Content-Type").getValue();
}
log.debug("Request returned with headers: " + Arrays.asList(httpMethod.getResponseHeaders()));
log.debug("Request returned with Content-Type: " + contentType);
// Check we received the expected result code.
if (responseCode != expectedResponseCode) {
log.debug("Unexpected response code " + responseCode + ", expected " + expectedResponseCode);
if (Mimetypes.MIMETYPE_XML.equals(contentType)
&& httpMethod.getResponseBodyAsStream() != null
&& httpMethod.getResponseContentLength() != 0)
{
log.debug("Received error response with XML message");
StringBuffer sb = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new HttpMethodReleaseInputStream(httpMethod)));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
// Throw exception containing the XML message document.
S3ServiceException exception =
new S3ServiceException("S3 " + httpMethod.getName()
+ " failed.", sb.toString());
if ("RequestTimeout".equals(exception.getS3ErrorCode())) {
if (requestTimeoutErrorCount < 3) { // TODO
requestTimeoutErrorCount++;
log.warn("Retrying connection that failed with RequestTimeout error"
+ ", attempt number " + requestTimeoutErrorCount + " of "
+ 3); // TODO
completedWithoutRecoverableError = false;
} else {
log.warn("Exceeded maximum number of retries for RequestTimeout errors: "
+ 3); // TODO
throw exception;
}
} else if (responseCode == 500) {
// Retrying after InternalError 500, don't throw exception.
} else {
throw exception;
}
} else {
// Consume response content and release connection.
String responseText = null;
byte[] responseBody = httpMethod.getResponseBody();
if (responseBody != null && responseBody.length > 0) {
responseText = new String(responseBody);
}
log.debug("Releasing error response without XML content");
httpMethod.releaseConnection();
// Throw exception containing the HTTP error fields.
throw new S3ServiceException("S3 "
+ httpMethod.getName() + " request failed. "
+ "ResponseCode=" + httpMethod.getStatusCode()
+ ", ResponseMessage=" + httpMethod.getStatusText()
+ (responseText != null ? "\n" + responseText : ""));
}
}
} while (!completedWithoutRecoverableError);
// Release immediately any connections without response bodies.
if ((httpMethod.getResponseBodyAsStream() == null
|| httpMethod.getResponseBodyAsStream().available() == 0)
&& httpMethod.getResponseContentLength() == 0)
{
log.debug("Releasing response without content");
byte[] responseBody = httpMethod.getResponseBody();
if (responseBody != null && responseBody.length > 0)
throw new S3ServiceException("Oops, too keen to release connection with a non-empty response body");
httpMethod.releaseConnection();
}
} catch (S3ServiceException e) {
throw e;
} catch (Throwable t) {
log.debug("Releasing method after error: " + t.getMessage());
httpMethod.releaseConnection();
throw new S3ServiceException("S3 " + httpMethod.getName() + " connection failed", t);
}
}
| protected void performRequest(HttpMethodBase httpMethod, int expectedResponseCode)
throws S3ServiceException
{
// httpMethod.setRequestHeader("Cache-Control", "no-cache"); // TODO
try {
log.debug("Performing " + httpMethod.getName()
+ " request, expecting response code " + expectedResponseCode);
// Variables to manage occasional S3 Internal Server 500 errors.
boolean completedWithoutRecoverableError = true;
int internalErrorCount = 0;
int requestTimeoutErrorCount = 0;
// Perform the request, sleeping and retrying when S3 Internal Errors are encountered.
int responseCode = -1;
do {
responseCode = httpClient.executeMethod(httpMethod);
if (responseCode == 500) {
// Retry on S3 Internal Server 500 errors.
completedWithoutRecoverableError = false;
sleepOnInternalError(++internalErrorCount);
} else {
completedWithoutRecoverableError = true;
}
String contentType = "";
if (httpMethod.getResponseHeader("Content-Type") != null) {
contentType = httpMethod.getResponseHeader("Content-Type").getValue();
}
log.debug("Request returned with headers: " + Arrays.asList(httpMethod.getResponseHeaders()));
log.debug("Request returned with Content-Type: " + contentType);
// Check we received the expected result code.
if (responseCode != expectedResponseCode) {
log.debug("Unexpected response code " + responseCode + ", expected " + expectedResponseCode);
if (Mimetypes.MIMETYPE_XML.equals(contentType)
&& httpMethod.getResponseBodyAsStream() != null
&& httpMethod.getResponseContentLength() != 0)
{
log.debug("Received error response with XML message");
StringBuffer sb = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new HttpMethodReleaseInputStream(httpMethod)));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
// Throw exception containing the XML message document.
S3ServiceException exception =
new S3ServiceException("S3 " + httpMethod.getName()
+ " failed.", sb.toString());
if ("RequestTimeout".equals(exception.getS3ErrorCode())) {
if (requestTimeoutErrorCount < 3) { // TODO
requestTimeoutErrorCount++;
log.warn("Retrying connection that failed with RequestTimeout error"
+ ", attempt number " + requestTimeoutErrorCount + " of "
+ 3); // TODO
completedWithoutRecoverableError = false;
} else {
log.warn("Exceeded maximum number of retries for RequestTimeout errors: "
+ 3); // TODO
throw exception;
}
} else if (responseCode == 500) {
// Retrying after InternalError 500, don't throw exception.
} else {
throw exception;
}
} else {
// Consume response content and release connection.
String responseText = null;
byte[] responseBody = httpMethod.getResponseBody();
if (responseBody != null && responseBody.length > 0) {
responseText = new String(responseBody);
}
log.debug("Releasing error response without XML content");
httpMethod.releaseConnection();
if (responseCode == 500) {
// Retrying after InternalError 500, don't throw exception.
} else {
// Throw exception containing the HTTP error fields.
throw new S3ServiceException("S3 "
+ httpMethod.getName() + " request failed. "
+ "ResponseCode=" + httpMethod.getStatusCode()
+ ", ResponseMessage=" + httpMethod.getStatusText()
+ (responseText != null ? "\n" + responseText : ""));
}
}
}
} while (!completedWithoutRecoverableError);
// Release immediately any connections without response bodies.
if ((httpMethod.getResponseBodyAsStream() == null
|| httpMethod.getResponseBodyAsStream().available() == 0)
&& httpMethod.getResponseContentLength() == 0)
{
log.debug("Releasing response without content");
byte[] responseBody = httpMethod.getResponseBody();
if (responseBody != null && responseBody.length > 0)
throw new S3ServiceException("Oops, too keen to release connection with a non-empty response body");
httpMethod.releaseConnection();
}
} catch (S3ServiceException e) {
throw e;
} catch (Throwable t) {
log.debug("Releasing method after error: " + t.getMessage());
httpMethod.releaseConnection();
throw new S3ServiceException("S3 " + httpMethod.getName() + " connection failed", t);
}
}
|
diff --git a/src/net/bmaron/openfixmap/ErrorParsers/KeepRightCSVParser.java b/src/net/bmaron/openfixmap/ErrorParsers/KeepRightCSVParser.java
index 51eb0f7..e232d82 100644
--- a/src/net/bmaron/openfixmap/ErrorParsers/KeepRightCSVParser.java
+++ b/src/net/bmaron/openfixmap/ErrorParsers/KeepRightCSVParser.java
@@ -1,155 +1,155 @@
package net.bmaron.openfixmap.ErrorParsers;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import net.bmaron.openfixmap.ErrorItem;
import net.bmaron.openfixmap.R;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.osmdroid.util.BoundingBoxE6;
import android.text.Html;
public class KeepRightCSVParser{
private List<ErrorItem> lItems;
protected ErrorPlatform error;
public KeepRightCSVParser(ErrorPlatform e) {
lItems = new ArrayList<ErrorItem>();
error = e;
}
protected String getChosenErrorsString() {
StringBuilder sb = new StringBuilder();
String [] checkers = error.getManager().getErrorsChoices("keepright",R.array.err_type_keepright_values);
for(int i=0; i < checkers.length; i++) {
sb.append(checkers[i]+",");
}
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
public void parse(BoundingBoxE6 boundingBox , int eLevel, boolean show_closed)
{
String next[] = {};
org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(KeepRightCSVParser.class);
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
- qparams.add(new BasicNameValuePair("format", "gpx"));
+ qparams.add(new BasicNameValuePair("format", "csv"));
if(show_closed) {
qparams.add(new BasicNameValuePair("show_ign", "1")); // Show Ignored
qparams.add(new BasicNameValuePair("show_tmpign", "1")); // Show Corrected
}
else {
qparams.add(new BasicNameValuePair("show_ign", "0")); // Show Ignored
qparams.add(new BasicNameValuePair("show_tmpign", "0")); // Show Corrected
}
qparams.add(new BasicNameValuePair("lat", String.valueOf(boundingBox.getCenter().getLatitudeE6()/ 1E6) ));
qparams.add(new BasicNameValuePair("lon", String.valueOf(boundingBox.getCenter().getLongitudeE6()/ 1E6 ) ));
List<String> supportedLang= Arrays.asList("cs","da", "de", "es", "en", "et", "fa", "fi",
"fr", "hu", "it", "lt", "nb", "nl", "pl", "pt_BR", "ru", "sl", "sv", "uk");
String lang="en";
if(supportedLang.contains(Locale.getDefault().getLanguage()))
lang=Locale.getDefault().getLanguage();
qparams.add(new BasicNameValuePair("lang", lang));
URI uri;
uri = URIUtils.createURI("http", "keepright.ipax.at", -1, "/points.php",
URLEncodedUtils.format(qparams, "UTF-8") + "&ch=" + getChosenErrorsString() , null);
HttpGet httpget = new HttpGet(uri);
logger.info("Fetch "+ httpget.getURI());
HttpResponse response = httpClient.execute(httpget, localContext);
logger.info("DONE");
CSVReader reader = new CSVReader(new InputStreamReader(response.getEntity().getContent()),'\t', '\0', 1);
SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateObj;
for(;;) {
next = reader.readNext();
if(next != null){
- if(next.length == 16) {
+ if(next.length == 18) {
ErrorItem tItem = new ErrorItem(error);
tItem.setLat(Double.parseDouble(next[0]));
tItem.setLon(Double.parseDouble(next[1]));
tItem.setTitle(next[2]);
- tItem.setDescription(Html.fromHtml(next[10]).toString());
- tItem.setId(Integer.parseInt(next[9]));
- tItem.getExtendedInfo().put("schema",next[8]);
- tItem.setLink("http://keepright.ipax.at/report_map.php?schema=" +next[8]+ "&error=" + tItem.getId());
+ tItem.setDescription(Html.fromHtml(next[11]).toString());
+ tItem.setId(Integer.parseInt(next[10]));
+ tItem.getExtendedInfo().put("schema",next[9]);
+ tItem.setLink("http://keepright.ipax.at/report_map.php?schema=" +next[9]+ "&error=" + tItem.getId());
try {
dateObj = curFormater.parse(next[7]);
tItem.setDate(dateObj);
} catch (ParseException e) {
e.printStackTrace();
}
// Check status
if(next[12].equals("ignore")) {
tItem.setErrorStatus(ErrorItem.ST_INVALID);
}else if(next[12].equals("ignore_t")) {
tItem.setErrorStatus(ErrorItem.ST_CLOSE);
}else if(next[12].equals("new")) {
tItem.setErrorStatus(ErrorItem.ST_OPEN);
}
lItems.add(tItem);
}else {
logger.error("Abord number of field not expected :"+ next.length);
logger.info(Arrays.toString(next));
}
} else {
break;
}
}
//Error 20,300,360,390=> Warnings
}catch (IOException ie) {
ie.printStackTrace();
}
catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<ErrorItem> getItems() {
org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(KeepRightCSVParser.class);
logger.info("getting items : # "+ lItems.size());
return lItems;
}
}
| false | true | public void parse(BoundingBoxE6 boundingBox , int eLevel, boolean show_closed)
{
String next[] = {};
org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(KeepRightCSVParser.class);
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("format", "gpx"));
if(show_closed) {
qparams.add(new BasicNameValuePair("show_ign", "1")); // Show Ignored
qparams.add(new BasicNameValuePair("show_tmpign", "1")); // Show Corrected
}
else {
qparams.add(new BasicNameValuePair("show_ign", "0")); // Show Ignored
qparams.add(new BasicNameValuePair("show_tmpign", "0")); // Show Corrected
}
qparams.add(new BasicNameValuePair("lat", String.valueOf(boundingBox.getCenter().getLatitudeE6()/ 1E6) ));
qparams.add(new BasicNameValuePair("lon", String.valueOf(boundingBox.getCenter().getLongitudeE6()/ 1E6 ) ));
List<String> supportedLang= Arrays.asList("cs","da", "de", "es", "en", "et", "fa", "fi",
"fr", "hu", "it", "lt", "nb", "nl", "pl", "pt_BR", "ru", "sl", "sv", "uk");
String lang="en";
if(supportedLang.contains(Locale.getDefault().getLanguage()))
lang=Locale.getDefault().getLanguage();
qparams.add(new BasicNameValuePair("lang", lang));
URI uri;
uri = URIUtils.createURI("http", "keepright.ipax.at", -1, "/points.php",
URLEncodedUtils.format(qparams, "UTF-8") + "&ch=" + getChosenErrorsString() , null);
HttpGet httpget = new HttpGet(uri);
logger.info("Fetch "+ httpget.getURI());
HttpResponse response = httpClient.execute(httpget, localContext);
logger.info("DONE");
CSVReader reader = new CSVReader(new InputStreamReader(response.getEntity().getContent()),'\t', '\0', 1);
SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateObj;
for(;;) {
next = reader.readNext();
if(next != null){
if(next.length == 16) {
ErrorItem tItem = new ErrorItem(error);
tItem.setLat(Double.parseDouble(next[0]));
tItem.setLon(Double.parseDouble(next[1]));
tItem.setTitle(next[2]);
tItem.setDescription(Html.fromHtml(next[10]).toString());
tItem.setId(Integer.parseInt(next[9]));
tItem.getExtendedInfo().put("schema",next[8]);
tItem.setLink("http://keepright.ipax.at/report_map.php?schema=" +next[8]+ "&error=" + tItem.getId());
try {
dateObj = curFormater.parse(next[7]);
tItem.setDate(dateObj);
} catch (ParseException e) {
e.printStackTrace();
}
// Check status
if(next[12].equals("ignore")) {
tItem.setErrorStatus(ErrorItem.ST_INVALID);
}else if(next[12].equals("ignore_t")) {
tItem.setErrorStatus(ErrorItem.ST_CLOSE);
}else if(next[12].equals("new")) {
tItem.setErrorStatus(ErrorItem.ST_OPEN);
}
lItems.add(tItem);
}else {
logger.error("Abord number of field not expected :"+ next.length);
logger.info(Arrays.toString(next));
}
} else {
break;
}
}
//Error 20,300,360,390=> Warnings
}catch (IOException ie) {
ie.printStackTrace();
}
catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public void parse(BoundingBoxE6 boundingBox , int eLevel, boolean show_closed)
{
String next[] = {};
org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(KeepRightCSVParser.class);
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("format", "csv"));
if(show_closed) {
qparams.add(new BasicNameValuePair("show_ign", "1")); // Show Ignored
qparams.add(new BasicNameValuePair("show_tmpign", "1")); // Show Corrected
}
else {
qparams.add(new BasicNameValuePair("show_ign", "0")); // Show Ignored
qparams.add(new BasicNameValuePair("show_tmpign", "0")); // Show Corrected
}
qparams.add(new BasicNameValuePair("lat", String.valueOf(boundingBox.getCenter().getLatitudeE6()/ 1E6) ));
qparams.add(new BasicNameValuePair("lon", String.valueOf(boundingBox.getCenter().getLongitudeE6()/ 1E6 ) ));
List<String> supportedLang= Arrays.asList("cs","da", "de", "es", "en", "et", "fa", "fi",
"fr", "hu", "it", "lt", "nb", "nl", "pl", "pt_BR", "ru", "sl", "sv", "uk");
String lang="en";
if(supportedLang.contains(Locale.getDefault().getLanguage()))
lang=Locale.getDefault().getLanguage();
qparams.add(new BasicNameValuePair("lang", lang));
URI uri;
uri = URIUtils.createURI("http", "keepright.ipax.at", -1, "/points.php",
URLEncodedUtils.format(qparams, "UTF-8") + "&ch=" + getChosenErrorsString() , null);
HttpGet httpget = new HttpGet(uri);
logger.info("Fetch "+ httpget.getURI());
HttpResponse response = httpClient.execute(httpget, localContext);
logger.info("DONE");
CSVReader reader = new CSVReader(new InputStreamReader(response.getEntity().getContent()),'\t', '\0', 1);
SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateObj;
for(;;) {
next = reader.readNext();
if(next != null){
if(next.length == 18) {
ErrorItem tItem = new ErrorItem(error);
tItem.setLat(Double.parseDouble(next[0]));
tItem.setLon(Double.parseDouble(next[1]));
tItem.setTitle(next[2]);
tItem.setDescription(Html.fromHtml(next[11]).toString());
tItem.setId(Integer.parseInt(next[10]));
tItem.getExtendedInfo().put("schema",next[9]);
tItem.setLink("http://keepright.ipax.at/report_map.php?schema=" +next[9]+ "&error=" + tItem.getId());
try {
dateObj = curFormater.parse(next[7]);
tItem.setDate(dateObj);
} catch (ParseException e) {
e.printStackTrace();
}
// Check status
if(next[12].equals("ignore")) {
tItem.setErrorStatus(ErrorItem.ST_INVALID);
}else if(next[12].equals("ignore_t")) {
tItem.setErrorStatus(ErrorItem.ST_CLOSE);
}else if(next[12].equals("new")) {
tItem.setErrorStatus(ErrorItem.ST_OPEN);
}
lItems.add(tItem);
}else {
logger.error("Abord number of field not expected :"+ next.length);
logger.info(Arrays.toString(next));
}
} else {
break;
}
}
//Error 20,300,360,390=> Warnings
}catch (IOException ie) {
ie.printStackTrace();
}
catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/java/client/test/org/openqa/selenium/GetMultipleAttributeTest.java b/java/client/test/org/openqa/selenium/GetMultipleAttributeTest.java
index cb18b5a21..c666dfe76 100644
--- a/java/client/test/org/openqa/selenium/GetMultipleAttributeTest.java
+++ b/java/client/test/org/openqa/selenium/GetMultipleAttributeTest.java
@@ -1,45 +1,45 @@
package org.openqa.selenium;
import org.junit.Test;
import org.openqa.selenium.testing.JUnit4TestBase;
import static org.junit.Assert.assertEquals;
public class GetMultipleAttributeTest extends JUnit4TestBase {
@Test
- public void testMultipleAttributeShouldBeFalseWhenNotSet() {
+ public void testMultipleAttributeShouldBeNullWhenNotSet() {
driver.get(pages.selectPage);
WebElement element = driver.findElement(By.id("selectWithoutMultiple"));
assertEquals(null, element.getAttribute("multiple"));
}
@Test
public void testMultipleAttributeShouldBeTrueWhenSet() {
driver.get(pages.selectPage);
WebElement element = driver.findElement(By.id("selectWithMultipleEqualsMultiple"));
assertEquals("true", element.getAttribute("multiple"));
}
@Test
public void testMultipleAttributeShouldBeTrueWhenSelectHasMutilpeWithValueAsBlank() {
driver.get(pages.selectPage);
WebElement element = driver.findElement(By.id("selectWithEmptyStringMultiple"));
assertEquals("true", element.getAttribute("multiple"));
}
@Test
public void testMultipleAttributeShouldBeTrueWhenSelectHasMutilpeWithoutAValue() {
driver.get(pages.selectPage);
WebElement element = driver.findElement(By.id("selectWithMultipleWithoutValue"));
assertEquals("true", element.getAttribute("multiple"));
}
@Test
public void testMultipleAttributeShouldBeTrueWhenSelectHasMutilpeWithValueAsSomethingElse() {
driver.get(pages.selectPage);
WebElement element = driver.findElement(By.id("selectWithRandomMultipleValue"));
assertEquals("true", element.getAttribute("multiple"));
}
}
| true | true | public void testMultipleAttributeShouldBeFalseWhenNotSet() {
driver.get(pages.selectPage);
WebElement element = driver.findElement(By.id("selectWithoutMultiple"));
assertEquals(null, element.getAttribute("multiple"));
}
| public void testMultipleAttributeShouldBeNullWhenNotSet() {
driver.get(pages.selectPage);
WebElement element = driver.findElement(By.id("selectWithoutMultiple"));
assertEquals(null, element.getAttribute("multiple"));
}
|
diff --git a/src/com/dmdirc/addons/osd/OsdPlugin.java b/src/com/dmdirc/addons/osd/OsdPlugin.java
index a6dfea7a1..655415938 100644
--- a/src/com/dmdirc/addons/osd/OsdPlugin.java
+++ b/src/com/dmdirc/addons/osd/OsdPlugin.java
@@ -1,164 +1,164 @@
/*
* Copyright (c) 2006-2009 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.osd;
import com.dmdirc.commandparser.CommandManager;
import com.dmdirc.config.IdentityManager;
import com.dmdirc.config.prefs.CategoryChangeListener;
import com.dmdirc.config.prefs.PreferencesCategory;
import com.dmdirc.config.prefs.PreferencesInterface;
import com.dmdirc.config.prefs.PreferencesManager;
import com.dmdirc.config.prefs.PreferencesSetting;
import com.dmdirc.config.prefs.PreferencesType;
import com.dmdirc.config.prefs.SettingChangeListener;
import com.dmdirc.plugins.Plugin;
import java.util.HashMap;
import java.util.Map;
/**
* Allows the user to display on-screen-display messages.
* @author chris
*/
public final class OsdPlugin extends Plugin implements CategoryChangeListener,
PreferencesInterface, SettingChangeListener {
/** Config OSD Window. */
private OsdWindow osdWindow;
/** OSD Command. */
private OsdCommand command;
/** X-axis position of OSD. */
private int x;
/** Y-axis potion of OSD. */
private int y;
/** Setting objects with registered change listeners. */
private PreferencesSetting fontSizeSetting, backgroundSetting, foregroundSetting;
/**
* Creates a new instance of OsdPlugin.
*/
public OsdPlugin() {
super();
}
/** {@inheritDoc} */
@Override
public void onLoad() {
command = new OsdCommand(this);
}
/** {@inheritDoc} */
@Override
public void onUnload() {
CommandManager.unregisterCommand(command);
}
/** {@inheritDoc} */
@Override
public void showConfig(final PreferencesManager manager) {
x = IdentityManager.getGlobalConfig().getOptionInt(getDomain(), "locationX");
y = IdentityManager.getGlobalConfig().getOptionInt(getDomain(), "locationY");
final PreferencesCategory category = new PreferencesCategory("OSD",
"General configuration for OSD plugin.");
fontSizeSetting = new PreferencesSetting(PreferencesType.INTEGER,
getDomain(), "fontSize", "Font size", "Changes the font " +
"size of the OSD").registerChangeListener(this);
backgroundSetting = new PreferencesSetting(PreferencesType.COLOUR,
getDomain(), "bgcolour", "Background colour",
"Background colour for the OSD").registerChangeListener(this);
foregroundSetting = new PreferencesSetting(PreferencesType.COLOUR,
getDomain(), "fgcolour", "Foreground colour",
"Foreground colour for the OSD").registerChangeListener(this);
category.addSetting(fontSizeSetting);
category.addSetting(backgroundSetting);
category.addSetting(foregroundSetting);
category.addSetting(new PreferencesSetting(PreferencesType.INTEGER,
getDomain(), "timeout", "Timeout", "Length of time in " +
"seconds before the OSD window closes"));
final Map<String, String> posOptions = new HashMap<String, String>();
posOptions.put("down", "Place new windows below old ones");
posOptions.put("up", "Place new windows above old ones");
posOptions.put("close", "Close existing windows");
posOptions.put("ontop", "Place new windows on top of existing window");
category.addSetting(new PreferencesSetting(getDomain(), "newbehaviour",
- "New window policy:", "What to do when an OSD Window "
+ "New window policy", "What to do when an OSD Window "
+ "is opened when there are other, existing windows open", posOptions));
category.addChangeListener(this);
manager.getCategory("Plugins").addSubCategory(category);
manager.registerSaveListener(this);
}
/** {@inheritDoc} */
@Override
public void categorySelected(final PreferencesCategory category) {
osdWindow = new OsdWindow("Please drag this OSD to position", true, x, y, this);
osdWindow.setBackgroundColour(backgroundSetting.getValue());
osdWindow.setForegroundColour(foregroundSetting.getValue());
osdWindow.setFontSize(Integer.parseInt(fontSizeSetting.getValue()));
}
/** {@inheritDoc} */
@Override
public void categoryDeselected(final PreferencesCategory category) {
x = osdWindow.getLocationOnScreen().x;
y = osdWindow.getLocationOnScreen().y;
osdWindow.dispose();
osdWindow = null;
}
/** {@inheritDoc} */
@Override
public void save() {
IdentityManager.getConfigIdentity().setOption(getDomain(), "locationX", x);
IdentityManager.getConfigIdentity().setOption(getDomain(), "locationY", y);
}
/** {@inheritDoc} */
@Override
public void settingChanged(final PreferencesSetting setting) {
if (osdWindow == null) {
// They've changed categories but are somehow poking settings.
// Ignore the request.
return;
}
if (setting.equals(fontSizeSetting)) {
osdWindow.setFontSize(Integer.parseInt(setting.getValue()));
} else if (setting.equals(backgroundSetting)) {
osdWindow.setBackgroundColour(setting.getValue());
} else if (setting.equals(foregroundSetting)) {
osdWindow.setForegroundColour(setting.getValue());
}
}
}
| true | true | public void showConfig(final PreferencesManager manager) {
x = IdentityManager.getGlobalConfig().getOptionInt(getDomain(), "locationX");
y = IdentityManager.getGlobalConfig().getOptionInt(getDomain(), "locationY");
final PreferencesCategory category = new PreferencesCategory("OSD",
"General configuration for OSD plugin.");
fontSizeSetting = new PreferencesSetting(PreferencesType.INTEGER,
getDomain(), "fontSize", "Font size", "Changes the font " +
"size of the OSD").registerChangeListener(this);
backgroundSetting = new PreferencesSetting(PreferencesType.COLOUR,
getDomain(), "bgcolour", "Background colour",
"Background colour for the OSD").registerChangeListener(this);
foregroundSetting = new PreferencesSetting(PreferencesType.COLOUR,
getDomain(), "fgcolour", "Foreground colour",
"Foreground colour for the OSD").registerChangeListener(this);
category.addSetting(fontSizeSetting);
category.addSetting(backgroundSetting);
category.addSetting(foregroundSetting);
category.addSetting(new PreferencesSetting(PreferencesType.INTEGER,
getDomain(), "timeout", "Timeout", "Length of time in " +
"seconds before the OSD window closes"));
final Map<String, String> posOptions = new HashMap<String, String>();
posOptions.put("down", "Place new windows below old ones");
posOptions.put("up", "Place new windows above old ones");
posOptions.put("close", "Close existing windows");
posOptions.put("ontop", "Place new windows on top of existing window");
category.addSetting(new PreferencesSetting(getDomain(), "newbehaviour",
"New window policy:", "What to do when an OSD Window "
+ "is opened when there are other, existing windows open", posOptions));
category.addChangeListener(this);
manager.getCategory("Plugins").addSubCategory(category);
manager.registerSaveListener(this);
}
| public void showConfig(final PreferencesManager manager) {
x = IdentityManager.getGlobalConfig().getOptionInt(getDomain(), "locationX");
y = IdentityManager.getGlobalConfig().getOptionInt(getDomain(), "locationY");
final PreferencesCategory category = new PreferencesCategory("OSD",
"General configuration for OSD plugin.");
fontSizeSetting = new PreferencesSetting(PreferencesType.INTEGER,
getDomain(), "fontSize", "Font size", "Changes the font " +
"size of the OSD").registerChangeListener(this);
backgroundSetting = new PreferencesSetting(PreferencesType.COLOUR,
getDomain(), "bgcolour", "Background colour",
"Background colour for the OSD").registerChangeListener(this);
foregroundSetting = new PreferencesSetting(PreferencesType.COLOUR,
getDomain(), "fgcolour", "Foreground colour",
"Foreground colour for the OSD").registerChangeListener(this);
category.addSetting(fontSizeSetting);
category.addSetting(backgroundSetting);
category.addSetting(foregroundSetting);
category.addSetting(new PreferencesSetting(PreferencesType.INTEGER,
getDomain(), "timeout", "Timeout", "Length of time in " +
"seconds before the OSD window closes"));
final Map<String, String> posOptions = new HashMap<String, String>();
posOptions.put("down", "Place new windows below old ones");
posOptions.put("up", "Place new windows above old ones");
posOptions.put("close", "Close existing windows");
posOptions.put("ontop", "Place new windows on top of existing window");
category.addSetting(new PreferencesSetting(getDomain(), "newbehaviour",
"New window policy", "What to do when an OSD Window "
+ "is opened when there are other, existing windows open", posOptions));
category.addChangeListener(this);
manager.getCategory("Plugins").addSubCategory(category);
manager.registerSaveListener(this);
}
|
diff --git a/src/com/dmdirc/ui/swing/textpane/TextPane.java b/src/com/dmdirc/ui/swing/textpane/TextPane.java
index a1b22754a..bb11ba2c9 100644
--- a/src/com/dmdirc/ui/swing/textpane/TextPane.java
+++ b/src/com/dmdirc/ui/swing/textpane/TextPane.java
@@ -1,731 +1,731 @@
/*
* 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.textpane;
import com.dmdirc.FrameContainer;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.ui.IconManager;
import com.dmdirc.ui.messages.IRCTextAttribute;
import com.dmdirc.ui.messages.Styliser;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.font.ImageGraphicAttribute;
import java.awt.font.TextAttribute;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.Enumeration;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JScrollBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.StyleConstants.CharacterConstants;
import javax.swing.text.StyleConstants.ColorConstants;
import javax.swing.text.StyleConstants.FontConstants;
import javax.swing.text.StyledDocument;
import net.miginfocom.swing.MigLayout;
/**
* Styled, scrollable text pane.
*/
public final class TextPane extends JComponent implements AdjustmentListener,
MouseWheelListener, IRCDocumentListener {
/**
* 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 = 5;
/** Scrollbar for the component. */
private final JScrollBar scrollBar;
/** Canvas object, used to draw text. */
private final TextPaneCanvas canvas;
/** IRCDocument. */
private final IRCDocument document;
/** Parent Frame. */
private final FrameContainer frame;
/** Click types. */
public enum ClickType {
/** Hyperlink. */
HYPERLINK,
/** Channel. */
CHANNEL,
/** Nickname. */
NICKNAME,
/** Normal. */
NORMAL,
}
/**
* Creates a new instance of TextPane.
*
* @param frame Parent Frame
*/
public TextPane(final FrameContainer frame) {
super();
this.frame = frame;
document = new IRCDocument();
setMinimumSize(new Dimension(0, 0));
setLayout(new MigLayout("fill"));
canvas = new TextPaneCanvas(this, document);
setBorder(UIManager.getBorder("TextField.border"));
add(canvas, "dock center");
scrollBar = new JScrollBar(JScrollBar.VERTICAL);
add(scrollBar, "dock east");
setAutoscrolls(true);
scrollBar.setMaximum(document.getNumLines());
scrollBar.setBlockIncrement(10);
scrollBar.setUnitIncrement(1);
scrollBar.addAdjustmentListener(this);
addMouseWheelListener(this);
document.addIRCDocumentListener(this);
MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() {
/** {@inheritDoc} */
@Override
public void mouseDragged(MouseEvent e) {
if (e.getXOnScreen() > getLocationOnScreen().getX() && e.getXOnScreen() < (getLocationOnScreen().
getX() + getWidth()) && e.getModifiersEx() ==
MouseEvent.BUTTON1_DOWN_MASK) {
if (getLocationOnScreen().getY() > e.getYOnScreen()) {
setScrollBarPosition(scrollBar.getValue() - 1);
} else if (getLocationOnScreen().getY() + getHeight() <
e.getYOnScreen()) {
setScrollBarPosition(scrollBar.getValue() + 1);
}
canvas.highlightEvent(TextPaneCanvas.MouseEventType.DRAG, e);
}
}
};
addMouseMotionListener(doScrollRectToVisible);
}
/**
* Adds styled text to the textpane.
* @param text styled text to add
*/
public void addText(final AttributedString text) {
document.addText(text);
}
/**
* Adds styled text to the textpane.
* @param text styled text to add
*/
public void addText(final List<AttributedString> text) {
document.addText(text);
}
/**
* Stylises the specified string and adds it to the passed TextPane.
*
* @param string The line to be stylised and added
*/
public void addStyledString(final String string) {
addStyledString(new String[]{string,});
}
/**
* Stylises the specified string and adds it to the passed TextPane.
*
* @param strings The strings to be stylised and added to a line
*/
public void addStyledString(final String[] strings) {
addText(styledDocumentToAttributedString(
Styliser.getStyledString(strings)));
}
/**
* Converts a StyledDocument into an AttributedString.
*
* @param doc StyledDocument to convert
*
* @return AttributedString representing the specified StyledDocument
*/
public static AttributedString styledDocumentToAttributedString(
final StyledDocument doc) {
//Now lets get hacky, loop through the styled document and add all
//styles to an attributedString
AttributedString attString = null;
final Element line = doc.getParagraphElement(0);
try {
attString = new AttributedString(line.getDocument().getText(0,
line.getDocument().getLength()));
} catch (BadLocationException ex) {
Logger.userError(ErrorLevel.MEDIUM,
"Unable to insert styled string: " + ex.getMessage());
}
if (attString.getIterator().getEndIndex() != 0) {
attString.addAttribute(TextAttribute.SIZE,
UIManager.getFont("TextPane.font").getSize());
attString.addAttribute(TextAttribute.FAMILY,
UIManager.getFont("TextPane.font").getFamily());
}
for (int i = 0; i < line.getElementCount(); i++) {
final Element element = line.getElement(i);
final AttributeSet as = element.getAttributes();
final Enumeration<?> ae = as.getAttributeNames();
while (ae.hasMoreElements()) {
final Object attrib = ae.nextElement();
if (attrib == IRCTextAttribute.HYPERLINK) {
//Hyperlink
attString.addAttribute(IRCTextAttribute.HYPERLINK,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.NICKNAME) {
//Nicknames
attString.addAttribute(IRCTextAttribute.NICKNAME,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.CHANNEL) {
//Channels
attString.addAttribute(IRCTextAttribute.CHANNEL,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == ColorConstants.Foreground) {
//Foreground
attString.addAttribute(TextAttribute.FOREGROUND,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == ColorConstants.Background) {
//Background
attString.addAttribute(TextAttribute.BACKGROUND,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Bold) {
//Bold
attString.addAttribute(TextAttribute.WEIGHT,
TextAttribute.WEIGHT_BOLD, element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Family) {
//Family
attString.addAttribute(TextAttribute.FAMILY,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Italic) {
//italics
attString.addAttribute(TextAttribute.POSTURE,
TextAttribute.POSTURE_OBLIQUE,
element.getStartOffset(),
element.getEndOffset());
} else if (attrib == CharacterConstants.Underline) {
//Underline
attString.addAttribute(TextAttribute.UNDERLINE,
TextAttribute.UNDERLINE_ON, element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.SMILEY) {
- final Image image = IconManager.getIconManager().getImage("dmdirc").
+ final Image image = IconManager.getIconManager().getImage((String) as.getAttribute(attrib)).
getScaledInstance(14, 14, Image.SCALE_DEFAULT);
ImageGraphicAttribute iga = new ImageGraphicAttribute(image,
(int) BOTTOM_ALIGNMENT, 5, 5);
attString.addAttribute(TextAttribute.CHAR_REPLACEMENT, iga,
element.getStartOffset(), element.getEndOffset());
}
}
}
if (attString.getIterator().getEndIndex() == 0) {
return new AttributedString("\n");
}
return attString;
}
/**
* Sets the new position for the scrollbar and the associated position
* to render the text from.
* @param position new position of the scrollbar
*/
public void setScrollBarPosition(final int position) {
scrollBar.setValue(position);
canvas.setScrollBarPosition(position);
}
/**
* Enables or disabled the scrollbar for the textpane.
*
* @param enabled State for the scrollbar
*/
public void setScrollEnabled(final boolean enabled) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
scrollBar.setEnabled(enabled);
}
});
}
/**
* Returns the last visible line in the textpane.
*
* @return Last visible line index
*/
public int getLastVisibleLine() {
return scrollBar.getValue();
}
/**
* Returns the line count in the textpane.
*
* @return Line count
*/
public int getNumLines() {
return document.getNumLines();
}
/**
* Returns the specified line in the textpane.
*
* @param line Line to return
*
* @return AttributedString at the specified line
*/
public AttributedString getLine(final int line) {
return document.getLine(line);
}
/**
* Sets the scrollbar's maximum position. If the current position is
* within <code>linesAllowed</code> of the end of the document, the
* scrollbar's current position is set to the end of the document.
*
* @param linesAllowed The number of lines allowed below the current position
* @since 0.6
*/
protected void setScrollBarMax(final int linesAllowed) {
final int lines = document.getNumLines() - 1;
if (lines == 0) {
canvas.repaint();
}
scrollBar.setMaximum(lines);
if (!scrollBar.getValueIsAdjusting() && scrollBar.getValue() == lines -
linesAllowed) {
setScrollBarPosition(lines);
}
}
/**
* {@inheritDoc}
*
* @param e Mouse wheel event
*/
@Override
public void adjustmentValueChanged(final AdjustmentEvent e) {
setScrollBarPosition(e.getValue());
}
/**
* {@inheritDoc}
*
* @param e Mouse wheel event
*/
@Override
public void mouseWheelMoved(final MouseWheelEvent e) {
if (scrollBar.isEnabled()) {
if (e.getWheelRotation() > 0) {
setScrollBarPosition(scrollBar.getValue() + e.getScrollAmount());
} else {
setScrollBarPosition(scrollBar.getValue() - e.getScrollAmount());
}
}
}
/**
*
* Returns the line information from a mouse click inside the textpane.
*
* @param point mouse position
*
* @return line number, line part, position in whole line
*/
public LineInfo getClickPosition(final Point point) {
return canvas.getClickPosition(point);
}
/**
* Returns the selected text.
*
* * <li>0 = start line</li>
* <li>1 = start char</li>
* <li>2 = end line</li>
* <li>3 = end char</li>
*
* @return Selected text
*/
public String getSelectedText() {
final StringBuffer selectedText = new StringBuffer();
final LinePosition selectedRange = canvas.getSelectedRange();
for (int i = selectedRange.getStartLine(); i <=
selectedRange.getEndLine(); i++) {
if (i != selectedRange.getStartLine()) {
selectedText.append('\n');
}
if (document.getNumLines() <= i) {
return selectedText.toString();
}
final AttributedCharacterIterator iterator = document.getLine(i).
getIterator();
if (selectedRange.getEndLine() == selectedRange.getStartLine()) {
//loop through range
selectedText.append(getTextFromLine(iterator,
selectedRange.getStartPos(), selectedRange.getEndPos()));
} else if (i == selectedRange.getStartLine()) {
//loop from start of range to the end
selectedText.append(getTextFromLine(iterator,
selectedRange.getStartPos(), iterator.getEndIndex()));
} else if (i == selectedRange.getEndLine()) {
//loop from start to end of range
selectedText.append(getTextFromLine(iterator, 0,
selectedRange.getEndPos()));
} else {
//loop the whole line
selectedText.append(getTextFromLine(iterator, 0,
iterator.getEndIndex()));
}
}
return selectedText.toString();
}
/**
* Returns the selected range.
*
* @return selected range
*/
public LinePosition getSelectedRange() {
return canvas.getSelectedRange();
}
/**
* Returns whether there is a selected range.
*
* @return true iif there is a selected range
*/
public boolean hasSelectedRange() {
final LinePosition selectedRange = canvas.getSelectedRange();
return !(selectedRange.getStartLine() == selectedRange.getEndLine() &&
selectedRange.getStartPos() == selectedRange.getEndPos());
}
/**
* Selects the specified region of text.
*
* @param position Line position
*/
public void setSelectedTexT(final LinePosition position) {
canvas.setSelectedRange(position);
}
/**
* Returns the entire text from the specified line.
*
* @param line line to retrieve text from
*
* @return Text from the line
*/
public String getTextFromLine(final int line) {
final AttributedCharacterIterator iterator = document.getLine(line).
getIterator();
return getTextFromLine(iterator, 0, iterator.getEndIndex(), document);
}
/**
* Returns the entire text from the specified line.
*
* @param line line to retrieve text from
* @param document Document to retrieve text from
*
* @return Text from the line
*/
public static String getTextFromLine(final int line,
final IRCDocument document) {
final AttributedCharacterIterator iterator = document.getLine(line).
getIterator();
return getTextFromLine(iterator, 0, iterator.getEndIndex(), document);
}
/**
* Returns the range of text from the specified iterator.
*
* @param line line to retrieve text from
* @param start Start index in the iterator
* @param end End index in the iterator
*
* @return Text in the range from the line
*/
public String getTextFromLine(final int line, final int start,
final int end) {
return getTextFromLine(document.getLine(line).getIterator(), start, end,
document);
}
/**
* Returns the range of text from the specified iterator.
*
* @param line line to retrieve text from
* @param start Start index in the iterator
* @param end End index in the iterator
* @param document Document to retrieve text from
*
* @return Text in the range from the line
*/
public static String getTextFromLine(final int line, final int start,
final int end, final IRCDocument document) {
return getTextFromLine(document.getLine(line).getIterator(), start, end,
document);
}
/**
* Returns the range of text from the specified iterator.
*
* @param iterator iterator to get text from
*
* @return Text in the range from the line
*/
public String getTextFromLine(final AttributedCharacterIterator iterator) {
return getTextFromLine(iterator, iterator.getBeginIndex(),
iterator.getEndIndex(), document);
}
/**
* Returns the range of text from the specified iterator.
*
* @param iterator iterator to get text from
* @param document Document to retrieve text from
*
* @return Text in the range from the line
*/
public static String getTextFromLine(final AttributedCharacterIterator iterator,
final IRCDocument document) {
return getTextFromLine(iterator, iterator.getBeginIndex(),
iterator.getEndIndex(), document);
}
/**
* Returns the range of text from the specified iterator.
*
* @param iterator iterator to get text from
* @param start Start index in the iterator
* @param end End index in the iterator
*
* @return Text in the range from the line
*/
public String getTextFromLine(final AttributedCharacterIterator iterator,
final int start, final int end) {
return getTextFromLine(iterator, start, end, document);
}
/**
* Returns the range of text from the specified iterator.
*
* @param iterator iterator to get text from
* @param start Start index in the iterator
* @param end End index in the iterator
* @param document Document to retrieve text from
*
* @return Text in the range from the line
*/
public static String getTextFromLine(final AttributedCharacterIterator iterator,
final int start, final int end, final IRCDocument document) {
return document.getLineText(iterator, start, end);
}
/**
* Returns the type of text this click represents.
*
* @param lineInfo Line info of click.
*
* @return Click type for specified position
*/
public ClickType getClickType(final LineInfo lineInfo) {
return canvas.getClickType(lineInfo);
}
/**
* Returns the surrouding word at the specified position.
*
* @param lineNumber Line number to get word from
* @param index Position to get surrounding word
*
* @return Surrounding word
*/
public String getWordAtIndex(final int lineNumber, final int index) {
if (lineNumber == -1) {
return "";
}
final int[] indexes =
canvas.getSurroundingWordIndexes(getTextFromLine(lineNumber),
index);
return getTextFromLine(lineNumber, indexes[0], indexes[1]);
}
/**
* Returns the atrriute value for the specified location.
*
* @param lineInfo Specified location
*
* @return Specified value
*/
public Object getAttributeValueAtPoint(LineInfo lineInfo) {
return canvas.getAttributeValueAtPoint(lineInfo);
}
/** Adds the selected text to the clipboard. */
public void copy() {
if (getSelectedText() != null && !getSelectedText().isEmpty()) {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
new StringSelection(getSelectedText()), null);
}
}
/** Clears the textpane. */
public void clear() {
document.clear();
setScrollBarPosition(0);
setScrollBarMax(1);
canvas.repaint();
}
/** Clears the selection. */
public void clearSelection() {
canvas.clearSelection();
}
/**
* Trims the document to the specified number of lines.
*
* @param numLines Number of lines to trim the document to
*/
public void trim(final int numLines) {
if (document.getNumLines() < numLines) {
return;
}
final int trimmedLines = document.getNumLines() - numLines;
final LinePosition selectedRange = getSelectedRange();
selectedRange.setStartLine(selectedRange.getStartLine() - trimmedLines);
selectedRange.setEndLine(selectedRange.getEndLine() - trimmedLines);
if (selectedRange.getStartLine() < 0) {
selectedRange.setStartLine(0);
}
if (selectedRange.getEndLine() < 0) {
selectedRange.setEndLine(0);
}
setSelectedTexT(selectedRange);
document.trim(numLines);
}
/** Scrolls one page up in the textpane. */
public void pageDown() {
//setScrollBarPosition(scrollBar.getValue() + canvas.getLastVisibleLine()
// - canvas.getFirstVisibleLine() + 1);
//use this method for now, its consistent with the block unit for the scrollbar
setScrollBarPosition(scrollBar.getValue() + 10);
}
/** Scrolls one page down in the textpane. */
public void pageUp() {
//setScrollBarPosition(canvas.getFirstVisibleLine());
//use this method for now, its consistent with the block unit for the scrollbar
setScrollBarPosition(scrollBar.getValue() - 10);
}
/** {@inheritDoc}. */
@Override
public void lineAdded(final int line, final int size) {
setScrollBarMax(1);
}
/** {@inheritDoc}. */
@Override
public void trimmed(final int numLines) {
canvas.clearWrapCache();
setScrollBarMax(1);
}
/** {@inheritDoc}. */
@Override
public void cleared() {
canvas.clearWrapCache();
}
/** {@inheritDoc}. */
@Override
public void linesAdded(int line, int length, int size) {
setScrollBarMax(length);
}
/**
* Retrieves this textpane's IRCDocument.
*
* @return This textpane's IRC document
*/
public IRCDocument getDocument() {
return document;
}
}
| true | true | public static AttributedString styledDocumentToAttributedString(
final StyledDocument doc) {
//Now lets get hacky, loop through the styled document and add all
//styles to an attributedString
AttributedString attString = null;
final Element line = doc.getParagraphElement(0);
try {
attString = new AttributedString(line.getDocument().getText(0,
line.getDocument().getLength()));
} catch (BadLocationException ex) {
Logger.userError(ErrorLevel.MEDIUM,
"Unable to insert styled string: " + ex.getMessage());
}
if (attString.getIterator().getEndIndex() != 0) {
attString.addAttribute(TextAttribute.SIZE,
UIManager.getFont("TextPane.font").getSize());
attString.addAttribute(TextAttribute.FAMILY,
UIManager.getFont("TextPane.font").getFamily());
}
for (int i = 0; i < line.getElementCount(); i++) {
final Element element = line.getElement(i);
final AttributeSet as = element.getAttributes();
final Enumeration<?> ae = as.getAttributeNames();
while (ae.hasMoreElements()) {
final Object attrib = ae.nextElement();
if (attrib == IRCTextAttribute.HYPERLINK) {
//Hyperlink
attString.addAttribute(IRCTextAttribute.HYPERLINK,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.NICKNAME) {
//Nicknames
attString.addAttribute(IRCTextAttribute.NICKNAME,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.CHANNEL) {
//Channels
attString.addAttribute(IRCTextAttribute.CHANNEL,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == ColorConstants.Foreground) {
//Foreground
attString.addAttribute(TextAttribute.FOREGROUND,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == ColorConstants.Background) {
//Background
attString.addAttribute(TextAttribute.BACKGROUND,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Bold) {
//Bold
attString.addAttribute(TextAttribute.WEIGHT,
TextAttribute.WEIGHT_BOLD, element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Family) {
//Family
attString.addAttribute(TextAttribute.FAMILY,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Italic) {
//italics
attString.addAttribute(TextAttribute.POSTURE,
TextAttribute.POSTURE_OBLIQUE,
element.getStartOffset(),
element.getEndOffset());
} else if (attrib == CharacterConstants.Underline) {
//Underline
attString.addAttribute(TextAttribute.UNDERLINE,
TextAttribute.UNDERLINE_ON, element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.SMILEY) {
final Image image = IconManager.getIconManager().getImage("dmdirc").
getScaledInstance(14, 14, Image.SCALE_DEFAULT);
ImageGraphicAttribute iga = new ImageGraphicAttribute(image,
(int) BOTTOM_ALIGNMENT, 5, 5);
attString.addAttribute(TextAttribute.CHAR_REPLACEMENT, iga,
element.getStartOffset(), element.getEndOffset());
}
}
}
if (attString.getIterator().getEndIndex() == 0) {
return new AttributedString("\n");
}
return attString;
}
| public static AttributedString styledDocumentToAttributedString(
final StyledDocument doc) {
//Now lets get hacky, loop through the styled document and add all
//styles to an attributedString
AttributedString attString = null;
final Element line = doc.getParagraphElement(0);
try {
attString = new AttributedString(line.getDocument().getText(0,
line.getDocument().getLength()));
} catch (BadLocationException ex) {
Logger.userError(ErrorLevel.MEDIUM,
"Unable to insert styled string: " + ex.getMessage());
}
if (attString.getIterator().getEndIndex() != 0) {
attString.addAttribute(TextAttribute.SIZE,
UIManager.getFont("TextPane.font").getSize());
attString.addAttribute(TextAttribute.FAMILY,
UIManager.getFont("TextPane.font").getFamily());
}
for (int i = 0; i < line.getElementCount(); i++) {
final Element element = line.getElement(i);
final AttributeSet as = element.getAttributes();
final Enumeration<?> ae = as.getAttributeNames();
while (ae.hasMoreElements()) {
final Object attrib = ae.nextElement();
if (attrib == IRCTextAttribute.HYPERLINK) {
//Hyperlink
attString.addAttribute(IRCTextAttribute.HYPERLINK,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.NICKNAME) {
//Nicknames
attString.addAttribute(IRCTextAttribute.NICKNAME,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.CHANNEL) {
//Channels
attString.addAttribute(IRCTextAttribute.CHANNEL,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == ColorConstants.Foreground) {
//Foreground
attString.addAttribute(TextAttribute.FOREGROUND,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == ColorConstants.Background) {
//Background
attString.addAttribute(TextAttribute.BACKGROUND,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Bold) {
//Bold
attString.addAttribute(TextAttribute.WEIGHT,
TextAttribute.WEIGHT_BOLD, element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Family) {
//Family
attString.addAttribute(TextAttribute.FAMILY,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Italic) {
//italics
attString.addAttribute(TextAttribute.POSTURE,
TextAttribute.POSTURE_OBLIQUE,
element.getStartOffset(),
element.getEndOffset());
} else if (attrib == CharacterConstants.Underline) {
//Underline
attString.addAttribute(TextAttribute.UNDERLINE,
TextAttribute.UNDERLINE_ON, element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.SMILEY) {
final Image image = IconManager.getIconManager().getImage((String) as.getAttribute(attrib)).
getScaledInstance(14, 14, Image.SCALE_DEFAULT);
ImageGraphicAttribute iga = new ImageGraphicAttribute(image,
(int) BOTTOM_ALIGNMENT, 5, 5);
attString.addAttribute(TextAttribute.CHAR_REPLACEMENT, iga,
element.getStartOffset(), element.getEndOffset());
}
}
}
if (attString.getIterator().getEndIndex() == 0) {
return new AttributedString("\n");
}
return attString;
}
|
diff --git a/svnkit/src/test/java/org/tmatesoft/svn/test/RevertTest.java b/svnkit/src/test/java/org/tmatesoft/svn/test/RevertTest.java
index 5c6826c17..c5cc21031 100644
--- a/svnkit/src/test/java/org/tmatesoft/svn/test/RevertTest.java
+++ b/svnkit/src/test/java/org/tmatesoft/svn/test/RevertTest.java
@@ -1,316 +1,314 @@
package org.tmatesoft.svn.test;
import org.junit.Assert;
import org.junit.Test;
import org.tmatesoft.svn.core.*;
import org.tmatesoft.svn.core.wc.ISVNEventHandler;
import org.tmatesoft.svn.core.wc.SVNEvent;
import org.tmatesoft.svn.core.wc.SVNEventAction;
import org.tmatesoft.svn.core.wc.SVNStatusType;
import org.tmatesoft.svn.core.wc2.SvnOperationFactory;
import org.tmatesoft.svn.core.wc2.SvnRevert;
import org.tmatesoft.svn.core.wc2.SvnStatus;
import org.tmatesoft.svn.core.wc2.SvnTarget;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class RevertTest {
@Test
public void testRevertCopyWithoutLocalModifications() throws Exception {
testRevertCopy("testRevertCopyWithoutLocalModifications", false, false, false, false, true, SVNStatusType.STATUS_UNVERSIONED, false, null);
}
@Test
public void testRevertCopyWithLocalModifications() throws Exception {
testRevertCopy("testRevertCopyWithLocalModifications", false, false, true, false, true, SVNStatusType.STATUS_UNVERSIONED, false, null);
}
@Test
public void testRevertCopyWithoutLocalModificationsEvenWithSpecialOption() throws Exception {
testRevertCopy("testRevertCopyWithoutLocalModificationsEvenWithSpecialOption", false, true, false, false, true, SVNStatusType.STATUS_UNVERSIONED, false, null);
}
@Test
public void testDontRevertCopyWitLocalTextModificationsSpecialOption() throws Exception {
testRevertCopy("testDontRevertCopyWitLocalTextModificationsSpecialOption", false, true, true, false, true, SVNStatusType.STATUS_UNVERSIONED, true, SVNStatusType.STATUS_UNVERSIONED);
}
@Test
public void testDontRevertCopyWitLocalPropertiesModificationsSpecialOption() throws Exception {
testRevertCopy("testDontRevertCopyWitLocalPropertiesModificationsSpecialOption", false, true, false, true, true, SVNStatusType.STATUS_UNVERSIONED, true, SVNStatusType.STATUS_UNVERSIONED);
}
@Test
public void testRevertCopyWithoutLocalModificationsRecursiveRevert() throws Exception {
testRevertCopy("testRevertCopyWithoutLocalModificationsRecursiveRevert", true, false, false, false, true, SVNStatusType.STATUS_UNVERSIONED, false, null);
}
@Test
public void testRevertCopyWithLocalModificationsRecursiveRevert() throws Exception {
testRevertCopy("testRevertCopyWithLocalModificationsRecursiveRevert", true, false, true, false, true, SVNStatusType.STATUS_UNVERSIONED, false, null);
}
@Test
public void testRevertCopyWithoutLocalModificationsEvenWithSpecialOptionRecursiveRevert() throws Exception {
testRevertCopy("testRevertCopyWithoutLocalModificationsEvenWithSpecialOptionRecursiveRevert", true, true, false, false, true, SVNStatusType.STATUS_UNVERSIONED, false, null);
}
@Test
public void testDontRevertCopyWitLocalTextModificationsSpecialOptionRecursiveRevert() throws Exception {
testRevertCopy("testDontRevertCopyWitLocalTextModificationsSpecialOptionRecursiveRevert", true, true, true, false, true, SVNStatusType.STATUS_UNVERSIONED, true, SVNStatusType.STATUS_UNVERSIONED);
}
@Test
public void testDontRevertCopyWitLocalPropertiesModificationsSpecialOptionRecursiveRevert() throws Exception {
testRevertCopy("testDontRevertCopyWitLocalPropertiesModificationsSpecialOptionRecursiveRevert", true, true, false, true, true, SVNStatusType.STATUS_UNVERSIONED, true, SVNStatusType.STATUS_UNVERSIONED);
}
@Test
public void testUnmodifiedFileIsUntouchedPreserveModifiedOption() throws Exception {
final TestOptions options = TestOptions.getInstance();
final SvnOperationFactory svnOperationFactory = new SvnOperationFactory();
final Sandbox sandbox = Sandbox.createWithCleanup(getTestName() + ".testUnmodifiedFileIsUntouchedPreserveModifiedOption", options);
try {
final SVNURL url = sandbox.createSvnRepository();
final CommitBuilder commitBuilder = new CommitBuilder(url);
commitBuilder.addFile("file");
commitBuilder.commit();
final WorkingCopy workingCopy = sandbox.checkoutNewWorkingCopy(url);
final File file = workingCopy.getFile("file");
final SvnRevert revert = svnOperationFactory.createRevert();
revert.setSingleTarget(SvnTarget.fromFile(file));
revert.setDepth(SVNDepth.INFINITY);
revert.setPreserveModifiedCopies(true);
revert.run();
final Map<File, SvnStatus> statuses = TestUtil.getStatuses(svnOperationFactory, workingCopy.getWorkingCopyDirectory());
Assert.assertTrue(file.isFile());
Assert.assertEquals(SVNStatusType.STATUS_NORMAL, statuses.get(file).getNodeStatus());
} finally {
svnOperationFactory.dispose();
sandbox.dispose();
}
}
@Test
public void testModifiedFileIsRevertedPreserveModifiedOption() throws Exception {
final TestOptions options = TestOptions.getInstance();
final SvnOperationFactory svnOperationFactory = new SvnOperationFactory();
final Sandbox sandbox = Sandbox.createWithCleanup(getTestName() + ".testModifiedFileIsRevertedPreserveModifiedOption", options);
try {
final SVNURL url = sandbox.createSvnRepository();
final CommitBuilder commitBuilder = new CommitBuilder(url);
commitBuilder.addFile("file");
commitBuilder.commit();
final WorkingCopy workingCopy = sandbox.checkoutNewWorkingCopy(url);
final File file = workingCopy.getFile("file");
TestUtil.writeFileContentsString(file, "contents");
final SvnRevert revert = svnOperationFactory.createRevert();
revert.setSingleTarget(SvnTarget.fromFile(file));
revert.setDepth(SVNDepth.INFINITY);
revert.setPreserveModifiedCopies(true);
revert.run();
final Map<File, SvnStatus> statuses = TestUtil.getStatuses(svnOperationFactory, workingCopy.getWorkingCopyDirectory());
Assert.assertTrue(file.isFile());
Assert.assertEquals(SVNStatusType.STATUS_NORMAL, statuses.get(file).getNodeStatus());
} finally {
svnOperationFactory.dispose();
sandbox.dispose();
}
}
@Test
public void testUnmodifiedFileIsUntouchedPreserveModifiedOptionRecursiveRevert() throws Exception {
final TestOptions options = TestOptions.getInstance();
final SvnOperationFactory svnOperationFactory = new SvnOperationFactory();
final Sandbox sandbox = Sandbox.createWithCleanup(getTestName() + ".testUnmodifiedFileIsUntouchedPreserveModifiedOptionRecursiveRevert", options);
try {
final SVNURL url = sandbox.createSvnRepository();
final CommitBuilder commitBuilder = new CommitBuilder(url);
commitBuilder.addFile("file");
commitBuilder.commit();
final WorkingCopy workingCopy = sandbox.checkoutNewWorkingCopy(url);
final File file = workingCopy.getFile("file");
final SvnRevert revert = svnOperationFactory.createRevert();
revert.setSingleTarget(SvnTarget.fromFile(workingCopy.getWorkingCopyDirectory()));
revert.setDepth(SVNDepth.INFINITY);
revert.setPreserveModifiedCopies(true);
revert.run();
final Map<File, SvnStatus> statuses = TestUtil.getStatuses(svnOperationFactory, workingCopy.getWorkingCopyDirectory());
Assert.assertTrue(file.isFile());
Assert.assertEquals(SVNStatusType.STATUS_NORMAL, statuses.get(file).getNodeStatus());
} finally {
svnOperationFactory.dispose();
sandbox.dispose();
}
}
@Test
public void testModifiedFileIsRevertedPreserveModifiedOptionRecursiveRevert() throws Exception {
final TestOptions options = TestOptions.getInstance();
final SvnOperationFactory svnOperationFactory = new SvnOperationFactory();
final Sandbox sandbox = Sandbox.createWithCleanup(getTestName() + ".testModifiedFileIsRevertedPreserveModifiedOptionRecursiveRevert", options);
try {
final SVNURL url = sandbox.createSvnRepository();
final CommitBuilder commitBuilder = new CommitBuilder(url);
commitBuilder.addFile("file");
commitBuilder.commit();
final WorkingCopy workingCopy = sandbox.checkoutNewWorkingCopy(url);
final File file = workingCopy.getFile("file");
TestUtil.writeFileContentsString(file, "contents");
final SvnRevert revert = svnOperationFactory.createRevert();
revert.setSingleTarget(SvnTarget.fromFile(workingCopy.getWorkingCopyDirectory()));
revert.setDepth(SVNDepth.INFINITY);
revert.setPreserveModifiedCopies(true);
revert.run();
final Map<File, SvnStatus> statuses = TestUtil.getStatuses(svnOperationFactory, workingCopy.getWorkingCopyDirectory());
Assert.assertTrue(file.isFile());
Assert.assertEquals(SVNStatusType.STATUS_NORMAL, statuses.get(file).getNodeStatus());
} finally {
svnOperationFactory.dispose();
sandbox.dispose();
}
}
@Test
public void testModifiedCopiedFileSpecialOptionDeeperTree() throws Exception {
final TestOptions options = TestOptions.getInstance();
final SvnOperationFactory svnOperationFactory = new SvnOperationFactory();
final Sandbox sandbox = Sandbox.createWithCleanup(getTestName() + ".test", options);
try {
final SVNURL url = sandbox.createSvnRepository();
final CommitBuilder commitBuilder = new CommitBuilder(url);
commitBuilder.addFile("sourceDirectory/sourceFile");
commitBuilder.addDirectory("targetDirectory");
commitBuilder.commit();
final WorkingCopy workingCopy = sandbox.checkoutNewWorkingCopy(url);
final File targetFile = workingCopy.getFile("targetDirectory/targetFile");
workingCopy.copy("sourceDirectory/sourceFile", "targetDirectory/targetFile");
TestUtil.writeFileContentsString(targetFile, "contents");
final SvnRevert revert = svnOperationFactory.createRevert();
revert.setSingleTarget(SvnTarget.fromFile(workingCopy.getWorkingCopyDirectory()));
revert.setDepth(SVNDepth.INFINITY);
revert.setPreserveModifiedCopies(true);
revert.run();
final Map<File, SvnStatus> statuses = TestUtil.getStatuses(svnOperationFactory, workingCopy.getWorkingCopyDirectory());
Assert.assertEquals(SVNStatusType.STATUS_UNVERSIONED, statuses.get(targetFile).getNodeStatus());
} finally {
svnOperationFactory.dispose();
sandbox.dispose();
}
}
private void testRevertCopy(String testName, boolean recursiveRevert, boolean preserveModifiedCopies, boolean modifyFileContents, boolean modifyProperties, boolean expectedFileExistence16, SVNStatusType expectedNodeStatus16, boolean expectedFileExistence17, SVNStatusType expectedNodeStatus17) throws SVNException {
final TestOptions options = TestOptions.getInstance();
final SvnOperationFactory svnOperationFactory = new SvnOperationFactory();
final Sandbox sandbox = Sandbox.createWithCleanup(getTestName() + "." + testName, options);
try {
final SVNURL url = sandbox.createSvnRepository();
final CommitBuilder commitBuilder = new CommitBuilder(url);
commitBuilder.addFile("sourceFile");
commitBuilder.commit();
final WorkingCopy workingCopy = sandbox.checkoutNewWorkingCopy(url);
final File targetFile = workingCopy.getFile("targetFile");
workingCopy.copy("sourceFile", "targetFile");
if (modifyFileContents) {
TestUtil.writeFileContentsString(targetFile, "contents");
}
if (modifyProperties) {
workingCopy.setProperty(targetFile, "custom", SVNPropertyValue.create("custom value"));
}
final List<SVNEvent> events = new ArrayList<SVNEvent>();
svnOperationFactory.setEventHandler(new ISVNEventHandler() {
- @Override
public void handleEvent(SVNEvent event, double progress) throws SVNException {
events.add(event);
}
- @Override
public void checkCancelled() throws SVNCancelException {
}
});
final SvnRevert revert = svnOperationFactory.createRevert();
if (recursiveRevert) {
revert.setSingleTarget(SvnTarget.fromFile(workingCopy.getWorkingCopyDirectory()));
revert.setDepth(SVNDepth.INFINITY);
} else {
revert.setSingleTarget(SvnTarget.fromFile(targetFile));
}
revert.setPreserveModifiedCopies(preserveModifiedCopies);
revert.run();
Assert.assertEquals(1, events.size());
Assert.assertEquals(SVNEventAction.REVERT, events.get(0).getAction());
Assert.assertEquals(targetFile, events.get(0).getFile());
final Map<File, SvnStatus> statuses = TestUtil.getStatuses(svnOperationFactory, workingCopy.getWorkingCopyDirectory());
if (TestUtil.isNewWorkingCopyTest()) {
Assert.assertEquals(expectedFileExistence17, targetFile.exists());
if (expectedNodeStatus17 == null) {
Assert.assertNull(statuses.get(targetFile));
} else {
Assert.assertEquals(expectedNodeStatus16, statuses.get(targetFile).getNodeStatus());
}
} else {
Assert.assertEquals(expectedFileExistence16, targetFile.exists());
if (expectedNodeStatus16 == null) {
Assert.assertNull(statuses.get(targetFile));
} else {
Assert.assertEquals(expectedNodeStatus16, statuses.get(targetFile).getNodeStatus());
}
}
} finally {
svnOperationFactory.dispose();
sandbox.dispose();
}
}
private String getTestName() {
return "RevertTest";
}
}
| false | true | private void testRevertCopy(String testName, boolean recursiveRevert, boolean preserveModifiedCopies, boolean modifyFileContents, boolean modifyProperties, boolean expectedFileExistence16, SVNStatusType expectedNodeStatus16, boolean expectedFileExistence17, SVNStatusType expectedNodeStatus17) throws SVNException {
final TestOptions options = TestOptions.getInstance();
final SvnOperationFactory svnOperationFactory = new SvnOperationFactory();
final Sandbox sandbox = Sandbox.createWithCleanup(getTestName() + "." + testName, options);
try {
final SVNURL url = sandbox.createSvnRepository();
final CommitBuilder commitBuilder = new CommitBuilder(url);
commitBuilder.addFile("sourceFile");
commitBuilder.commit();
final WorkingCopy workingCopy = sandbox.checkoutNewWorkingCopy(url);
final File targetFile = workingCopy.getFile("targetFile");
workingCopy.copy("sourceFile", "targetFile");
if (modifyFileContents) {
TestUtil.writeFileContentsString(targetFile, "contents");
}
if (modifyProperties) {
workingCopy.setProperty(targetFile, "custom", SVNPropertyValue.create("custom value"));
}
final List<SVNEvent> events = new ArrayList<SVNEvent>();
svnOperationFactory.setEventHandler(new ISVNEventHandler() {
@Override
public void handleEvent(SVNEvent event, double progress) throws SVNException {
events.add(event);
}
@Override
public void checkCancelled() throws SVNCancelException {
}
});
final SvnRevert revert = svnOperationFactory.createRevert();
if (recursiveRevert) {
revert.setSingleTarget(SvnTarget.fromFile(workingCopy.getWorkingCopyDirectory()));
revert.setDepth(SVNDepth.INFINITY);
} else {
revert.setSingleTarget(SvnTarget.fromFile(targetFile));
}
revert.setPreserveModifiedCopies(preserveModifiedCopies);
revert.run();
Assert.assertEquals(1, events.size());
Assert.assertEquals(SVNEventAction.REVERT, events.get(0).getAction());
Assert.assertEquals(targetFile, events.get(0).getFile());
final Map<File, SvnStatus> statuses = TestUtil.getStatuses(svnOperationFactory, workingCopy.getWorkingCopyDirectory());
if (TestUtil.isNewWorkingCopyTest()) {
Assert.assertEquals(expectedFileExistence17, targetFile.exists());
if (expectedNodeStatus17 == null) {
Assert.assertNull(statuses.get(targetFile));
} else {
Assert.assertEquals(expectedNodeStatus16, statuses.get(targetFile).getNodeStatus());
}
} else {
Assert.assertEquals(expectedFileExistence16, targetFile.exists());
if (expectedNodeStatus16 == null) {
Assert.assertNull(statuses.get(targetFile));
} else {
Assert.assertEquals(expectedNodeStatus16, statuses.get(targetFile).getNodeStatus());
}
}
} finally {
svnOperationFactory.dispose();
sandbox.dispose();
}
}
| private void testRevertCopy(String testName, boolean recursiveRevert, boolean preserveModifiedCopies, boolean modifyFileContents, boolean modifyProperties, boolean expectedFileExistence16, SVNStatusType expectedNodeStatus16, boolean expectedFileExistence17, SVNStatusType expectedNodeStatus17) throws SVNException {
final TestOptions options = TestOptions.getInstance();
final SvnOperationFactory svnOperationFactory = new SvnOperationFactory();
final Sandbox sandbox = Sandbox.createWithCleanup(getTestName() + "." + testName, options);
try {
final SVNURL url = sandbox.createSvnRepository();
final CommitBuilder commitBuilder = new CommitBuilder(url);
commitBuilder.addFile("sourceFile");
commitBuilder.commit();
final WorkingCopy workingCopy = sandbox.checkoutNewWorkingCopy(url);
final File targetFile = workingCopy.getFile("targetFile");
workingCopy.copy("sourceFile", "targetFile");
if (modifyFileContents) {
TestUtil.writeFileContentsString(targetFile, "contents");
}
if (modifyProperties) {
workingCopy.setProperty(targetFile, "custom", SVNPropertyValue.create("custom value"));
}
final List<SVNEvent> events = new ArrayList<SVNEvent>();
svnOperationFactory.setEventHandler(new ISVNEventHandler() {
public void handleEvent(SVNEvent event, double progress) throws SVNException {
events.add(event);
}
public void checkCancelled() throws SVNCancelException {
}
});
final SvnRevert revert = svnOperationFactory.createRevert();
if (recursiveRevert) {
revert.setSingleTarget(SvnTarget.fromFile(workingCopy.getWorkingCopyDirectory()));
revert.setDepth(SVNDepth.INFINITY);
} else {
revert.setSingleTarget(SvnTarget.fromFile(targetFile));
}
revert.setPreserveModifiedCopies(preserveModifiedCopies);
revert.run();
Assert.assertEquals(1, events.size());
Assert.assertEquals(SVNEventAction.REVERT, events.get(0).getAction());
Assert.assertEquals(targetFile, events.get(0).getFile());
final Map<File, SvnStatus> statuses = TestUtil.getStatuses(svnOperationFactory, workingCopy.getWorkingCopyDirectory());
if (TestUtil.isNewWorkingCopyTest()) {
Assert.assertEquals(expectedFileExistence17, targetFile.exists());
if (expectedNodeStatus17 == null) {
Assert.assertNull(statuses.get(targetFile));
} else {
Assert.assertEquals(expectedNodeStatus16, statuses.get(targetFile).getNodeStatus());
}
} else {
Assert.assertEquals(expectedFileExistence16, targetFile.exists());
if (expectedNodeStatus16 == null) {
Assert.assertNull(statuses.get(targetFile));
} else {
Assert.assertEquals(expectedNodeStatus16, statuses.get(targetFile).getNodeStatus());
}
}
} finally {
svnOperationFactory.dispose();
sandbox.dispose();
}
}
|
diff --git a/src/com/github/dreamrec/Filter.java b/src/com/github/dreamrec/Filter.java
index 85904e9..315af4b 100644
--- a/src/com/github/dreamrec/Filter.java
+++ b/src/com/github/dreamrec/Filter.java
@@ -1,35 +1,35 @@
package com.github.dreamrec;
/**
*
*/
public abstract class Filter<T> implements IFilter {
protected int divider = 1;
protected final IFilter<T> inputData;
public Filter(IFilter<T> inputData) {
this.inputData = inputData;
}
public final int divider(){
return divider * inputData.divider();
}
public final int size() {
return inputData.size()/divider;
}
public final T get(int index) {
checkIndexBounds(index);
return doFilter(index);
}
private void checkIndexBounds(int index){
- if(index < size() || index < 0 ){
+ if(index > size() || index < 0 ){
throw new IndexOutOfBoundsException("index: "+index+",size: "+size());
}
}
protected abstract T doFilter(int index);
}
| true | true | private void checkIndexBounds(int index){
if(index < size() || index < 0 ){
throw new IndexOutOfBoundsException("index: "+index+",size: "+size());
}
}
| private void checkIndexBounds(int index){
if(index > size() || index < 0 ){
throw new IndexOutOfBoundsException("index: "+index+",size: "+size());
}
}
|
diff --git a/src/main/java/io/iron/ironmq/Client.java b/src/main/java/io/iron/ironmq/Client.java
index d8d1282..640769d 100644
--- a/src/main/java/io/iron/ironmq/Client.java
+++ b/src/main/java/io/iron/ironmq/Client.java
@@ -1,141 +1,149 @@
package io.iron.ironmq;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
/**
* The Client class provides access to the IronMQ service.
*/
public class Client {
static final private String apiVersion = "1";
static final Random rand = new Random();
private String projectId;
private String token;
private Cloud cloud;
/**
* Constructs a new Client using the specified project ID and token.
* The network is not accessed during construction and this call will
* succeed even if the credentials are invalid.
* This constructor uses the AWS cloud with the US East region.
*
* @param projectId A 24-character project ID.
* @param token An OAuth token.
*/
public Client(String projectId, String token) {
this(projectId, token, Cloud.ironAWSUSEast);
}
/**
* Constructs a new Client using the specified project ID and token.
* The network is not accessed during construction and this call will
* succeed even if the credentials are invalid.
*
* @param projectId A 24-character project ID.
* @param token An OAuth token.
* @param cloud The cloud to use.
*/
public Client(String projectId, String token, Cloud cloud) {
this.projectId = projectId;
this.token = token;
this.cloud = cloud;
}
/**
* Returns a Queue using the given name.
* The network is not accessed during this call.
*
* @param name The name of the Queue to create.
*/
public Queue queue(String name) {
return new Queue(this, name);
}
Reader delete(String endpoint) throws IOException {
return request("DELETE", endpoint, null);
}
Reader get(String endpoint) throws IOException {
return request("GET", endpoint, null);
}
Reader post(String endpoint, String body) throws IOException {
return request("POST", endpoint, body);
}
private Reader request(String method, String endpoint, String body) throws IOException {
String path = "/" + apiVersion + "/projects/" + projectId + "/" + endpoint;
URL url = new URL(cloud.scheme, cloud.host, cloud.port, path);
final int maxRetries = 5;
int retries = 0;
while (true) {
try {
return singleRequest(method, url, body);
} catch (HTTPException e) {
// ELB sometimes returns this when load is increasing.
// We retry with exponential backoff.
if (e.getStatusCode() != 503 || retries >= maxRetries) {
throw e;
}
retries++;
// random delay between 0 and 4^tries*100 milliseconds
int pow = (1 << (2*retries))*100;
int delay = rand.nextInt(pow);
try {
Thread.sleep(delay);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
}
private Reader singleRequest(String method, URL url, String body) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("Authorization", "OAuth " + token);
conn.setRequestProperty("User-Agent", "IronMQ Java Client");
if (body != null) {
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
}
conn.connect();
if (body != null) {
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(body);
- out.flush();
+ out.close();
}
int status = conn.getResponseCode();
if (status != 200) {
String msg;
- try {
- InputStreamReader reader = new InputStreamReader(conn.getErrorStream());
- Gson gson = new Gson();
- msg = gson.fromJson(reader, String.class);
- } catch (JsonSyntaxException e) {
- msg = "IronMQ's response contained invalid JSON";
+ if (conn.getContentLength() > 0 && conn.getContentType() == "application/json") {
+ InputStreamReader reader = null;
+ try {
+ reader = new InputStreamReader(conn.getErrorStream());
+ Gson gson = new Gson();
+ msg = gson.fromJson(reader, String.class);
+ } catch (JsonSyntaxException e) {
+ msg = "IronMQ's response contained invalid JSON";
+ } finally {
+ if (reader != null)
+ reader.close();
+ }
+ } else {
+ msg = "Empty or non-JSON response";
}
throw new HTTPException(status, msg);
}
return new InputStreamReader(conn.getInputStream());
}
}
| false | true | private Reader singleRequest(String method, URL url, String body) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("Authorization", "OAuth " + token);
conn.setRequestProperty("User-Agent", "IronMQ Java Client");
if (body != null) {
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
}
conn.connect();
if (body != null) {
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(body);
out.flush();
}
int status = conn.getResponseCode();
if (status != 200) {
String msg;
try {
InputStreamReader reader = new InputStreamReader(conn.getErrorStream());
Gson gson = new Gson();
msg = gson.fromJson(reader, String.class);
} catch (JsonSyntaxException e) {
msg = "IronMQ's response contained invalid JSON";
}
throw new HTTPException(status, msg);
}
return new InputStreamReader(conn.getInputStream());
}
| private Reader singleRequest(String method, URL url, String body) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("Authorization", "OAuth " + token);
conn.setRequestProperty("User-Agent", "IronMQ Java Client");
if (body != null) {
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
}
conn.connect();
if (body != null) {
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(body);
out.close();
}
int status = conn.getResponseCode();
if (status != 200) {
String msg;
if (conn.getContentLength() > 0 && conn.getContentType() == "application/json") {
InputStreamReader reader = null;
try {
reader = new InputStreamReader(conn.getErrorStream());
Gson gson = new Gson();
msg = gson.fromJson(reader, String.class);
} catch (JsonSyntaxException e) {
msg = "IronMQ's response contained invalid JSON";
} finally {
if (reader != null)
reader.close();
}
} else {
msg = "Empty or non-JSON response";
}
throw new HTTPException(status, msg);
}
return new InputStreamReader(conn.getInputStream());
}
|
diff --git a/caadapter/components/hl7Transformation/src/gov/nih/nci/caadapter/hl7/transformation/MapProcssorCSVUtil.java b/caadapter/components/hl7Transformation/src/gov/nih/nci/caadapter/hl7/transformation/MapProcssorCSVUtil.java
index 8aafdf719..e96fb2a36 100755
--- a/caadapter/components/hl7Transformation/src/gov/nih/nci/caadapter/hl7/transformation/MapProcssorCSVUtil.java
+++ b/caadapter/components/hl7Transformation/src/gov/nih/nci/caadapter/hl7/transformation/MapProcssorCSVUtil.java
@@ -1,134 +1,145 @@
package gov.nih.nci.caadapter.hl7.transformation;
import gov.nih.nci.caadapter.common.csv.data.CSVField;
import gov.nih.nci.caadapter.common.csv.data.CSVSegment;
import java.util.ArrayList;
import java.util.List;
public class MapProcssorCSVUtil {
public List<CSVSegment> findCSVSegment(CSVSegment csvSegment, String targetXmlPath) {
// System.out.println("CSVSegment "+csvSegment.getXmlPath() + "-->target"+targetXmlPath);
List<CSVSegment> csvSegments = new ArrayList<CSVSegment>();
if (csvSegment.getXmlPath().equals(targetXmlPath)) {
csvSegments.add(csvSegment);
return csvSegments;
}
if (csvSegment.getXmlPath().contains(targetXmlPath)) {
CSVSegment current = csvSegment.getParentSegment();
while (true) {
if (current.getXmlPath().equals(targetXmlPath)) {
csvSegments.add(current);
return csvSegments;
}
current = current.getParentSegment();
if (current == null) {
System.out.println("Error");
break;
/*
* TODO throw error
*/
}
}
}
if (targetXmlPath.contains(csvSegment.getXmlPath())) {
CSVSegment current = csvSegment;
+ ArrayList<CSVSegment> parentHolder = new ArrayList<CSVSegment>();
+ parentHolder.add(current);
while (true) {
boolean canStop = true;
- if (current.getChildSegments() == null || current.getChildSegments().size()==0) break;
+ if (parentHolder == null) break;
+ ArrayList<CSVSegment> childHolder = new ArrayList<CSVSegment>();
+ for(CSVSegment csvS:parentHolder)
+ {
+ current = csvS;
+ if (current.getChildSegments() == null || current.getChildSegments().size()==0) break;
- for(CSVSegment childSegment:current.getChildSegments()) {
-// System.out.println("ChildSegment" + childSegment.getXmlPath());
- if (childSegment.getXmlPath().equals(targetXmlPath)) {
- csvSegments.add(childSegment);
- }
- else {
- if (targetXmlPath.contains(childSegment.getXmlPath())) {
- current = childSegment;
- canStop=false;
- break;
+ for(CSVSegment childSegment:current.getChildSegments()) {
+// System.out.println("ChildSegment" + childSegment.getXmlPath());
+ if (childSegment.getXmlPath().equals(targetXmlPath)) {
+ csvSegments.add(childSegment);
+ }
+ else {
+ if (targetXmlPath.contains(childSegment.getXmlPath())) {
+ childHolder.add(childSegment);
+ canStop=false;
+// break;
+ }
}
}
}
+ parentHolder.clear();
+ parentHolder = childHolder;
if (canStop) break;
}
}
+// System.out.println(csvSegments.size());
return csvSegments;
}
/*
private CSVField findCSVField(CSVSegment csvSegment, String targetXmlPath) {
String targetSegmentXmlPath = targetXmlPath.substring(0,targetXmlPath.lastIndexOf('.'));
// CSVSegment current = csvSegment.getParentSegment();
CSVSegment current = csvSegment;
while (true) {
if (current.getXmlPath().equals(targetSegmentXmlPath)) {
for(CSVField csvField:current.getFields()) {
if (csvField.getXmlPath().equals(targetXmlPath)) return csvField;
}
}
current = current.getParentSegment();
if (current == null) {
System.out.println("Error");
System.out.println("csvSegment="+csvSegment.getXmlPath());
System.out.println("target="+targetXmlPath);
return null; /*
/*
* TODO throw error
*/
/* }
}
}
*/
public CSVField findCSVField(CSVSegment csvSegment, String targetXmlPath) {
String targetSegmentXmlPath = targetXmlPath.substring(0,targetXmlPath.lastIndexOf('.'));
// CSVSegment current = csvSegment.getParentSegment();
CSVSegment current = csvSegment;
while (true) {
//System.out.println("CCC1 : " + current + " : " + csvSegment.getName() + " : " + targetXmlPath);
if (current == null) return null;
String str = current.getXmlPath();
//System.out.println("CCC : " + current.getName() + str);
if (str.equals(targetSegmentXmlPath)) {
for(CSVField csvField:current.getFields()) {
if (csvField.getXmlPath().equals(targetXmlPath)) return csvField;
}
}
current = current.getParentSegment();
if (current == null) {
System.out.println("Error");
System.out.println("csvSegment="+csvSegment.getXmlPath());
System.out.println("target="+targetXmlPath);
return null;
/*
* TODO throw error
*/
}
}
}
public CSVField findCSVField(List<CSVSegment> csvSegments, String targetXmlPath) {
String targetSegmentXmlPath = targetXmlPath.substring(0,targetXmlPath.lastIndexOf('.'));
for (CSVSegment csvSegment: csvSegments) {
CSVSegment current = csvSegment.getParentSegment();
while (true) {
if (current.getXmlPath().equals(targetSegmentXmlPath)) {
for(CSVField csvField:current.getFields()) {
if (csvField.getXmlPath().equals(targetXmlPath)) return csvField;
}
}
current = current.getParentSegment();
if (current == null) {
break;
}
}
}
return null;
// Error should be thrown
}
}
| false | true | public List<CSVSegment> findCSVSegment(CSVSegment csvSegment, String targetXmlPath) {
// System.out.println("CSVSegment "+csvSegment.getXmlPath() + "-->target"+targetXmlPath);
List<CSVSegment> csvSegments = new ArrayList<CSVSegment>();
if (csvSegment.getXmlPath().equals(targetXmlPath)) {
csvSegments.add(csvSegment);
return csvSegments;
}
if (csvSegment.getXmlPath().contains(targetXmlPath)) {
CSVSegment current = csvSegment.getParentSegment();
while (true) {
if (current.getXmlPath().equals(targetXmlPath)) {
csvSegments.add(current);
return csvSegments;
}
current = current.getParentSegment();
if (current == null) {
System.out.println("Error");
break;
/*
* TODO throw error
*/
}
}
}
if (targetXmlPath.contains(csvSegment.getXmlPath())) {
CSVSegment current = csvSegment;
while (true) {
boolean canStop = true;
if (current.getChildSegments() == null || current.getChildSegments().size()==0) break;
for(CSVSegment childSegment:current.getChildSegments()) {
// System.out.println("ChildSegment" + childSegment.getXmlPath());
if (childSegment.getXmlPath().equals(targetXmlPath)) {
csvSegments.add(childSegment);
}
else {
if (targetXmlPath.contains(childSegment.getXmlPath())) {
current = childSegment;
canStop=false;
break;
}
}
}
if (canStop) break;
}
}
return csvSegments;
}
| public List<CSVSegment> findCSVSegment(CSVSegment csvSegment, String targetXmlPath) {
// System.out.println("CSVSegment "+csvSegment.getXmlPath() + "-->target"+targetXmlPath);
List<CSVSegment> csvSegments = new ArrayList<CSVSegment>();
if (csvSegment.getXmlPath().equals(targetXmlPath)) {
csvSegments.add(csvSegment);
return csvSegments;
}
if (csvSegment.getXmlPath().contains(targetXmlPath)) {
CSVSegment current = csvSegment.getParentSegment();
while (true) {
if (current.getXmlPath().equals(targetXmlPath)) {
csvSegments.add(current);
return csvSegments;
}
current = current.getParentSegment();
if (current == null) {
System.out.println("Error");
break;
/*
* TODO throw error
*/
}
}
}
if (targetXmlPath.contains(csvSegment.getXmlPath())) {
CSVSegment current = csvSegment;
ArrayList<CSVSegment> parentHolder = new ArrayList<CSVSegment>();
parentHolder.add(current);
while (true) {
boolean canStop = true;
if (parentHolder == null) break;
ArrayList<CSVSegment> childHolder = new ArrayList<CSVSegment>();
for(CSVSegment csvS:parentHolder)
{
current = csvS;
if (current.getChildSegments() == null || current.getChildSegments().size()==0) break;
for(CSVSegment childSegment:current.getChildSegments()) {
// System.out.println("ChildSegment" + childSegment.getXmlPath());
if (childSegment.getXmlPath().equals(targetXmlPath)) {
csvSegments.add(childSegment);
}
else {
if (targetXmlPath.contains(childSegment.getXmlPath())) {
childHolder.add(childSegment);
canStop=false;
// break;
}
}
}
}
parentHolder.clear();
parentHolder = childHolder;
if (canStop) break;
}
}
// System.out.println(csvSegments.size());
return csvSegments;
}
|
diff --git a/app/controllers/SearchApiController.java b/app/controllers/SearchApiController.java
index 2088f5dd..8b0d4720 100644
--- a/app/controllers/SearchApiController.java
+++ b/app/controllers/SearchApiController.java
@@ -1,100 +1,100 @@
/**
* Copyright 2013 Lennart Koopmann <[email protected]>
*
* This file is part of Graylog2.
*
* Graylog2 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.
*
* Graylog2 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 Graylog2. If not, see <http://www.gnu.org/licenses/>.
*
*/
package controllers;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import lib.APIException;
import lib.SearchTools;
import lib.timeranges.*;
import models.UniversalSearch;
import models.api.responses.FieldStatsResponse;
import play.mvc.Result;
import java.io.IOException;
import java.util.Map;
/**
* @author Lennart Koopmann <[email protected]>
*/
public class SearchApiController extends AuthenticatedController {
- public Result fieldStats(String q, String field, String rangeType, int relative, String interval) {
+ public Result fieldStats(String q, String field, String rangeType, int relative, String from, String to, String keyword, String interval) {
if (q == null || q.isEmpty()) {
q = "*";
}
// Histogram interval.
if (interval == null || interval.isEmpty() || !SearchTools.isAllowedDateHistogramInterval(interval)) {
interval = "hour";
}
// Determine timerange type.
TimeRange.Type timerangeType;
TimeRange timerange;
try {
timerangeType = TimeRange.Type.valueOf(rangeType.toUpperCase());
switch (timerangeType) {
case RELATIVE:
timerange = new RelativeRange(relative);
break;
case ABSOLUTE:
- timerange = new AbsoluteRange("foo", "bar");
+ timerange = new AbsoluteRange(from, to);
break;
case KEYWORD:
- timerange = new KeywordRange("ZOMG");
+ timerange = new KeywordRange(keyword);
break;
default:
throw new InvalidRangeParametersException();
}
} catch(InvalidRangeParametersException e2) {
return status(400, views.html.errors.error.render("Invalid range parameters provided.", e2, request()));
} catch(IllegalArgumentException e1) {
return status(400, views.html.errors.error.render("Invalid range type provided.", e1, request()));
}
try {
UniversalSearch search = new UniversalSearch(timerange, q);
FieldStatsResponse stats = search.fieldStats(field);
Map<String, Object> result = Maps.newHashMap();
result.put("count", stats.count);
result.put("sum", stats.sum);
result.put("mean", stats.mean);
result.put("min", stats.min);
result.put("max", stats.max);
result.put("variance", stats.variance);
result.put("sum_of_squares", stats.sumOfSquares);
result.put("std_deviation", stats.stdDeviation);
return ok(new Gson().toJson(result)).as("application/json");
} catch (IOException e) {
return internalServerError("io exception");
} catch (APIException e) {
if (e.getHttpCode() == 400) {
// This usually means the field does not have a numeric type. Pass through!
return badRequest();
}
return internalServerError("api exception " + e);
}
}
}
| false | true | public Result fieldStats(String q, String field, String rangeType, int relative, String interval) {
if (q == null || q.isEmpty()) {
q = "*";
}
// Histogram interval.
if (interval == null || interval.isEmpty() || !SearchTools.isAllowedDateHistogramInterval(interval)) {
interval = "hour";
}
// Determine timerange type.
TimeRange.Type timerangeType;
TimeRange timerange;
try {
timerangeType = TimeRange.Type.valueOf(rangeType.toUpperCase());
switch (timerangeType) {
case RELATIVE:
timerange = new RelativeRange(relative);
break;
case ABSOLUTE:
timerange = new AbsoluteRange("foo", "bar");
break;
case KEYWORD:
timerange = new KeywordRange("ZOMG");
break;
default:
throw new InvalidRangeParametersException();
}
} catch(InvalidRangeParametersException e2) {
return status(400, views.html.errors.error.render("Invalid range parameters provided.", e2, request()));
} catch(IllegalArgumentException e1) {
return status(400, views.html.errors.error.render("Invalid range type provided.", e1, request()));
}
try {
UniversalSearch search = new UniversalSearch(timerange, q);
FieldStatsResponse stats = search.fieldStats(field);
Map<String, Object> result = Maps.newHashMap();
result.put("count", stats.count);
result.put("sum", stats.sum);
result.put("mean", stats.mean);
result.put("min", stats.min);
result.put("max", stats.max);
result.put("variance", stats.variance);
result.put("sum_of_squares", stats.sumOfSquares);
result.put("std_deviation", stats.stdDeviation);
return ok(new Gson().toJson(result)).as("application/json");
} catch (IOException e) {
return internalServerError("io exception");
} catch (APIException e) {
if (e.getHttpCode() == 400) {
// This usually means the field does not have a numeric type. Pass through!
return badRequest();
}
return internalServerError("api exception " + e);
}
}
| public Result fieldStats(String q, String field, String rangeType, int relative, String from, String to, String keyword, String interval) {
if (q == null || q.isEmpty()) {
q = "*";
}
// Histogram interval.
if (interval == null || interval.isEmpty() || !SearchTools.isAllowedDateHistogramInterval(interval)) {
interval = "hour";
}
// Determine timerange type.
TimeRange.Type timerangeType;
TimeRange timerange;
try {
timerangeType = TimeRange.Type.valueOf(rangeType.toUpperCase());
switch (timerangeType) {
case RELATIVE:
timerange = new RelativeRange(relative);
break;
case ABSOLUTE:
timerange = new AbsoluteRange(from, to);
break;
case KEYWORD:
timerange = new KeywordRange(keyword);
break;
default:
throw new InvalidRangeParametersException();
}
} catch(InvalidRangeParametersException e2) {
return status(400, views.html.errors.error.render("Invalid range parameters provided.", e2, request()));
} catch(IllegalArgumentException e1) {
return status(400, views.html.errors.error.render("Invalid range type provided.", e1, request()));
}
try {
UniversalSearch search = new UniversalSearch(timerange, q);
FieldStatsResponse stats = search.fieldStats(field);
Map<String, Object> result = Maps.newHashMap();
result.put("count", stats.count);
result.put("sum", stats.sum);
result.put("mean", stats.mean);
result.put("min", stats.min);
result.put("max", stats.max);
result.put("variance", stats.variance);
result.put("sum_of_squares", stats.sumOfSquares);
result.put("std_deviation", stats.stdDeviation);
return ok(new Gson().toJson(result)).as("application/json");
} catch (IOException e) {
return internalServerError("io exception");
} catch (APIException e) {
if (e.getHttpCode() == 400) {
// This usually means the field does not have a numeric type. Pass through!
return badRequest();
}
return internalServerError("api exception " + e);
}
}
|
diff --git a/src/main/java/pl/project13/janbanery/core/flow/TaskMoveFlowImpl.java b/src/main/java/pl/project13/janbanery/core/flow/TaskMoveFlowImpl.java
index c8e585a..7b5b98a 100644
--- a/src/main/java/pl/project13/janbanery/core/flow/TaskMoveFlowImpl.java
+++ b/src/main/java/pl/project13/janbanery/core/flow/TaskMoveFlowImpl.java
@@ -1,135 +1,135 @@
/*
* Copyright 2011 Konrad Malawski <[email protected]>
*
* 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 pl.project13.janbanery.core.flow;
import pl.project13.janbanery.core.dao.Columns;
import pl.project13.janbanery.core.dao.Tasks;
import pl.project13.janbanery.exceptions.kanbanery.invalidentity.CanOnlyIceBoxTaskFromFirstColumnException;
import pl.project13.janbanery.exceptions.kanbanery.InternalServerErrorKanbaneryException;
import pl.project13.janbanery.exceptions.kanbanery.invalidentity.TaskAlreadyInLastColumnException;
import pl.project13.janbanery.resources.Column;
import pl.project13.janbanery.resources.Task;
import pl.project13.janbanery.resources.additions.TaskLocation;
import java.io.IOException;
/**
* This flow enables the API to fluently move tasks around the Kanban board, making it as fun and powerful as possible.
*
* @author Konrad Malawski
*/
public class TaskMoveFlowImpl implements TaskMoveFlow {
private Columns columns;
private Tasks tasks;
private Task task;
public TaskMoveFlowImpl(Tasks tasks, Columns columns, Task task) {
this.columns = columns;
this.tasks = tasks;
this.task = task;
}
/**
* {@inheritDoc}
*/
@Override
public TaskMoveFlow toIceBox() throws IOException, CanOnlyIceBoxTaskFromFirstColumnException {
return to(TaskLocation.ICEBOX);
}
/**
* {@inheritDoc}
*/
@Override
public TaskMoveFlow toBoard() throws IOException {
return to(TaskLocation.BOARD);
}
@Override
public TaskMoveFlow toLastColumn() throws IOException {
Column last = columns.last();
return to(last);
}
@Override
public TaskFlow asTaskFlow() {
return new TaskFlowImpl(tasks, columns, task);
}
/**
* {@inheritDoc}
*/
@Override
public TaskMoveFlow toNextColumn() throws IOException {
TaskMoveFlow moveFlow;
try {
moveFlow = to(TaskLocation.NEXT);
} catch (InternalServerErrorKanbaneryException e) { // fixme this is a bug workaround
// kanbanery does handle "ArrayIndexOutOfBounds" right for movement to the left,
// but for movement to the right it fails and throws a 500 Internal Server Error...
- throw new TaskAlreadyInLastColumnException("{position: 'task is already in last column'}"); // todo this is a kanbanery bug workaround
+ throw new TaskAlreadyInLastColumnException("{position: 'task is already in last column'}", e); // todo this is a kanbanery bug workaround
}
return moveFlow;
}
/**
* {@inheritDoc}
*/
@Override
public TaskMoveFlow toPreviousColumn() throws IOException {
return to(TaskLocation.PREVIOUS);
}
/**
* {@inheritDoc}
*/
@Override
public TaskMoveFlow toArchive() throws IOException {
return to(TaskLocation.ARCHIVE);
}
/**
* {@inheritDoc}
*/
@Override
public TaskMoveFlow to(TaskLocation location) throws IOException {
TaskFlow move = tasks.move(task, location);
task = move.get();
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TaskMoveFlow to(Column column) throws IOException {
TaskFlow move = tasks.move(task, column);
task = move.get();
return this;
}
/**
* {@inheritDoc}
*/
@Override
public Task get() {
return task;
}
}
| true | true | public TaskMoveFlow toNextColumn() throws IOException {
TaskMoveFlow moveFlow;
try {
moveFlow = to(TaskLocation.NEXT);
} catch (InternalServerErrorKanbaneryException e) { // fixme this is a bug workaround
// kanbanery does handle "ArrayIndexOutOfBounds" right for movement to the left,
// but for movement to the right it fails and throws a 500 Internal Server Error...
throw new TaskAlreadyInLastColumnException("{position: 'task is already in last column'}"); // todo this is a kanbanery bug workaround
}
return moveFlow;
}
| public TaskMoveFlow toNextColumn() throws IOException {
TaskMoveFlow moveFlow;
try {
moveFlow = to(TaskLocation.NEXT);
} catch (InternalServerErrorKanbaneryException e) { // fixme this is a bug workaround
// kanbanery does handle "ArrayIndexOutOfBounds" right for movement to the left,
// but for movement to the right it fails and throws a 500 Internal Server Error...
throw new TaskAlreadyInLastColumnException("{position: 'task is already in last column'}", e); // todo this is a kanbanery bug workaround
}
return moveFlow;
}
|
diff --git a/src/uk/org/ponder/rsf/templateresolver/BasicTemplateResolver.java b/src/uk/org/ponder/rsf/templateresolver/BasicTemplateResolver.java
index 78ef32d..c7fbb0e 100644
--- a/src/uk/org/ponder/rsf/templateresolver/BasicTemplateResolver.java
+++ b/src/uk/org/ponder/rsf/templateresolver/BasicTemplateResolver.java
@@ -1,212 +1,212 @@
/*
* Created on Sep 19, 2005
*/
package uk.org.ponder.rsf.templateresolver;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.springframework.core.io.ResourceLoader;
import uk.org.ponder.rsf.flow.errors.SilentRedirectException;
import uk.org.ponder.rsf.template.TPIAggregator;
import uk.org.ponder.rsf.template.XMLCompositeViewTemplate;
import uk.org.ponder.rsf.template.XMLViewTemplate;
import uk.org.ponder.rsf.template.XMLViewTemplateParser;
import uk.org.ponder.rsf.view.ViewTemplate;
import uk.org.ponder.rsf.viewstate.ViewParameters;
import uk.org.ponder.springutil.CachingInputStreamSource;
import uk.org.ponder.stringutil.StringList;
import uk.org.ponder.util.Logger;
import uk.org.ponder.util.UniversalRuntimeException;
/**
* A basic template resolver accepting a TemplateExtensionInferrer and a
* TemplateResolverStrategy to load a view template.
*
* @author Antranig Basman ([email protected])
*
*/
public class BasicTemplateResolver implements TemplateResolver {
private TemplateExtensionInferrer tei;
private int cachesecs;
private TPIAggregator aggregator;
private List strategies;
public void setResourceLoader(ResourceLoader resourceLoader) {
cachingiis = new CachingInputStreamSource(resourceLoader, cachesecs);
}
/**
* Set the lag in seconds at which the filesystem will be polled for changes
* in the view template. If this value is 0 or the resource is not a
* filesystem resource, it will always be reloaded.
*/
public void setCacheSeconds(int cachesecs) {
this.cachesecs = cachesecs;
}
public void setTemplateExtensionInferrer(TemplateExtensionInferrer tei) {
this.tei = tei;
}
public void setTemplateResolverStrategies(List strategies) {
this.strategies = strategies;
}
public void setTPIAggregator(TPIAggregator aggregator) {
this.aggregator = aggregator;
}
// this is a map of viewID onto template file.
private HashMap templates = new HashMap();
private CachingInputStreamSource cachingiis;
public ViewTemplate locateTemplate(ViewParameters viewparams) {
// NB if we really want this optimisation, it must be based on #
// of RETURNED templates, not the number of strategies!
XMLCompositeViewTemplate xcvt = strategies.size() == 1 ? null
: new XMLCompositeViewTemplate();
int highestpriority = 0;
StringList tried = new StringList();
for (int i = 0; i < strategies.size(); ++i) {
TemplateResolverStrategy trs = (TemplateResolverStrategy) strategies
.get(i);
int thispri = trs instanceof RootAwareTRS ? ((RootAwareTRS) trs)
.getRootResolverPriority()
: 1;
boolean isexpected = trs instanceof ExpectedTRS ? ((ExpectedTRS) trs)
.isExpected()
: true;
boolean ismultiple = trs instanceof MultipleTemplateResolverStrategy ? ((MultipleTemplateResolverStrategy) trs)
.isMultiple()
: false;
StringList bases = trs.resolveTemplatePath(viewparams);
StringList[] usebases;
if (ismultiple) {
usebases = new StringList[bases.size()];
for (int j = 0; j < usebases.length; ++j) {
usebases[j] = new StringList(bases.stringAt(j));
}
}
else {
usebases = new StringList[] { bases };
}
for (int j = 0; j < usebases.length; ++j) {
XMLViewTemplate template = locateTemplate(viewparams, trs, usebases[j],
isexpected ? tried : null, ismultiple && isexpected);
if (template != null) {
if (xcvt != null) {
xcvt.globalmap.aggregate(template.globalmap);
if (template.mustcollectmap != null) {
xcvt.mustcollectmap.aggregate(template.mustcollectmap);
}
if (thispri == highestpriority && thispri != 0) {
if (xcvt.roottemplate != null) {
Logger.log.warn("Duplicate root TemplateResolverStrategy " + trs
+ " found at priority " + thispri +", using first entry");
}
}
if (thispri > highestpriority) {
xcvt.roottemplate = template;
highestpriority = thispri;
}
}
else {
return template;
}
} // end if template returned
}
}
if (xcvt != null && xcvt.roottemplate == null) {
Exception eclass = viewparams.viewID.trim().length() == 0?
(Exception)new SilentRedirectException() : new IllegalArgumentException();
throw UniversalRuntimeException.accumulate(eclass,
- "No TemplateResolverStrategy which was marked as a root resolver (rootPriority > 0) " +
- "returned a template: tried paths (expected) " + tried.toString());
+ "No template found for view " + viewparams.viewID + ": tried paths (expected) " +
+ tried.toString() + " from all TemplateResolverStrategy which were marked as a root resolver (rootPriority > 0) ");
}
return xcvt;
}
public XMLViewTemplate locateTemplate(ViewParameters viewparams,
TemplateResolverStrategy strs, StringList bases, StringList tried, boolean logfailure) {
String resourcebase = "/";
if (strs instanceof BaseAwareTemplateResolverStrategy) {
BaseAwareTemplateResolverStrategy batrs = (BaseAwareTemplateResolverStrategy) strs;
resourcebase = batrs.getTemplateResourceBase();
}
String extension = tei.inferTemplateExtension(viewparams);
InputStream is = null;
String fullpath = null;
for (int i = 0; i < bases.size(); ++i) {
fullpath = resourcebase + bases.stringAt(i) + "." + extension;
if (tried != null) {
tried.add(fullpath);
}
is = cachingiis.openStream(fullpath);
if (is != null)
break;
if (is == null && logfailure) {
// This is not a real failure for other content types - see RSF-21
// Logger.log.warn("Failed to load template from " + fullpath);
}
}
if (is == null) {
return null;
}
XMLViewTemplate template = null;
if (is == CachingInputStreamSource.UP_TO_DATE) {
template = (XMLViewTemplate) templates.get(fullpath);
}
if (template == null) {
List tpis = aggregator.getFilteredTPIs();
try {
// possibly the reason is it had a parse error last time, which may have
// been corrected
if (is == CachingInputStreamSource.UP_TO_DATE) {
is = cachingiis.getNonCachingResolver().openStream(fullpath);
}
XMLViewTemplateParser parser = new XMLViewTemplateParser();
parser.setTemplateParseInterceptors(tpis);
template = (XMLViewTemplate) parser.parse(is);
// there WILL be one slash in the path.
int lastslashpos = fullpath.lastIndexOf('/');
String resourcebaseext = fullpath.substring(1, lastslashpos + 1);
if (strs instanceof BaseAwareTemplateResolverStrategy) {
BaseAwareTemplateResolverStrategy batrs = (BaseAwareTemplateResolverStrategy) strs;
String extresourcebase = batrs.getExternalURLBase();
template.setExtResourceBase(extresourcebase);
}
if (strs instanceof ForceContributingTRS) {
ForceContributingTRS fctrs = (ForceContributingTRS) strs;
if (fctrs.getMustContribute()) {
template.mustcollectmap = template.collectmap;
}
}
template.setRelativeResourceBase(resourcebaseext);
template.fullpath = fullpath;
templates.put(fullpath, template);
}
catch (Exception e) {
throw UniversalRuntimeException.accumulate(e,
"Error parsing view template file " + fullpath);
}
}
return template;
}
}
| true | true | public ViewTemplate locateTemplate(ViewParameters viewparams) {
// NB if we really want this optimisation, it must be based on #
// of RETURNED templates, not the number of strategies!
XMLCompositeViewTemplate xcvt = strategies.size() == 1 ? null
: new XMLCompositeViewTemplate();
int highestpriority = 0;
StringList tried = new StringList();
for (int i = 0; i < strategies.size(); ++i) {
TemplateResolverStrategy trs = (TemplateResolverStrategy) strategies
.get(i);
int thispri = trs instanceof RootAwareTRS ? ((RootAwareTRS) trs)
.getRootResolverPriority()
: 1;
boolean isexpected = trs instanceof ExpectedTRS ? ((ExpectedTRS) trs)
.isExpected()
: true;
boolean ismultiple = trs instanceof MultipleTemplateResolverStrategy ? ((MultipleTemplateResolverStrategy) trs)
.isMultiple()
: false;
StringList bases = trs.resolveTemplatePath(viewparams);
StringList[] usebases;
if (ismultiple) {
usebases = new StringList[bases.size()];
for (int j = 0; j < usebases.length; ++j) {
usebases[j] = new StringList(bases.stringAt(j));
}
}
else {
usebases = new StringList[] { bases };
}
for (int j = 0; j < usebases.length; ++j) {
XMLViewTemplate template = locateTemplate(viewparams, trs, usebases[j],
isexpected ? tried : null, ismultiple && isexpected);
if (template != null) {
if (xcvt != null) {
xcvt.globalmap.aggregate(template.globalmap);
if (template.mustcollectmap != null) {
xcvt.mustcollectmap.aggregate(template.mustcollectmap);
}
if (thispri == highestpriority && thispri != 0) {
if (xcvt.roottemplate != null) {
Logger.log.warn("Duplicate root TemplateResolverStrategy " + trs
+ " found at priority " + thispri +", using first entry");
}
}
if (thispri > highestpriority) {
xcvt.roottemplate = template;
highestpriority = thispri;
}
}
else {
return template;
}
} // end if template returned
}
}
if (xcvt != null && xcvt.roottemplate == null) {
Exception eclass = viewparams.viewID.trim().length() == 0?
(Exception)new SilentRedirectException() : new IllegalArgumentException();
throw UniversalRuntimeException.accumulate(eclass,
"No TemplateResolverStrategy which was marked as a root resolver (rootPriority > 0) " +
"returned a template: tried paths (expected) " + tried.toString());
}
return xcvt;
}
| public ViewTemplate locateTemplate(ViewParameters viewparams) {
// NB if we really want this optimisation, it must be based on #
// of RETURNED templates, not the number of strategies!
XMLCompositeViewTemplate xcvt = strategies.size() == 1 ? null
: new XMLCompositeViewTemplate();
int highestpriority = 0;
StringList tried = new StringList();
for (int i = 0; i < strategies.size(); ++i) {
TemplateResolverStrategy trs = (TemplateResolverStrategy) strategies
.get(i);
int thispri = trs instanceof RootAwareTRS ? ((RootAwareTRS) trs)
.getRootResolverPriority()
: 1;
boolean isexpected = trs instanceof ExpectedTRS ? ((ExpectedTRS) trs)
.isExpected()
: true;
boolean ismultiple = trs instanceof MultipleTemplateResolverStrategy ? ((MultipleTemplateResolverStrategy) trs)
.isMultiple()
: false;
StringList bases = trs.resolveTemplatePath(viewparams);
StringList[] usebases;
if (ismultiple) {
usebases = new StringList[bases.size()];
for (int j = 0; j < usebases.length; ++j) {
usebases[j] = new StringList(bases.stringAt(j));
}
}
else {
usebases = new StringList[] { bases };
}
for (int j = 0; j < usebases.length; ++j) {
XMLViewTemplate template = locateTemplate(viewparams, trs, usebases[j],
isexpected ? tried : null, ismultiple && isexpected);
if (template != null) {
if (xcvt != null) {
xcvt.globalmap.aggregate(template.globalmap);
if (template.mustcollectmap != null) {
xcvt.mustcollectmap.aggregate(template.mustcollectmap);
}
if (thispri == highestpriority && thispri != 0) {
if (xcvt.roottemplate != null) {
Logger.log.warn("Duplicate root TemplateResolverStrategy " + trs
+ " found at priority " + thispri +", using first entry");
}
}
if (thispri > highestpriority) {
xcvt.roottemplate = template;
highestpriority = thispri;
}
}
else {
return template;
}
} // end if template returned
}
}
if (xcvt != null && xcvt.roottemplate == null) {
Exception eclass = viewparams.viewID.trim().length() == 0?
(Exception)new SilentRedirectException() : new IllegalArgumentException();
throw UniversalRuntimeException.accumulate(eclass,
"No template found for view " + viewparams.viewID + ": tried paths (expected) " +
tried.toString() + " from all TemplateResolverStrategy which were marked as a root resolver (rootPriority > 0) ");
}
return xcvt;
}
|
diff --git a/src/java/com/idega/core/location/business/AddressBusinessBean.java b/src/java/com/idega/core/location/business/AddressBusinessBean.java
index 85be29daf..9d49a3aee 100644
--- a/src/java/com/idega/core/location/business/AddressBusinessBean.java
+++ b/src/java/com/idega/core/location/business/AddressBusinessBean.java
@@ -1,396 +1,396 @@
package com.idega.core.location.business;
import java.rmi.RemoteException;
import java.util.StringTokenizer;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import com.idega.business.IBOServiceBean;
import com.idega.core.contact.data.Email;
import com.idega.core.contact.data.EmailHome;
import com.idega.core.location.data.Address;
import com.idega.core.location.data.AddressHome;
import com.idega.core.location.data.AddressType;
import com.idega.core.location.data.Commune;
import com.idega.core.location.data.CommuneHome;
import com.idega.core.location.data.Country;
import com.idega.core.location.data.CountryHome;
import com.idega.core.location.data.PostalCode;
import com.idega.core.location.data.PostalCodeHome;
import com.idega.util.text.TextSoap;
/**
* <p>
* Title: com.idega.core.business.AddressBusinessBean
* </p>
* <p>
* Description: Common business class for handling all Address related IDO
* </p>
* <p>
* Copyright: (c) 2002
* </p>
* <p>
* Company: Idega Software
* </p>
*
* @author <a href="[email protected]">Eirikur S. Hrafnsson</a>
* @version 1.0
*/
public class AddressBusinessBean extends IBOServiceBean implements AddressBusiness {
public static final String NOT_AVAILABLE = "N/A";
public AddressBusinessBean() {
}
/**
* @return The Country Beans' home
*/
public CountryHome getCountryHome() throws RemoteException {
return (CountryHome) this.getIDOHome(Country.class);
}
/**
* @return The Commune Beans' home
*/
public CommuneHome getCommuneHome() throws RemoteException {
return (CommuneHome) this.getIDOHome(Commune.class);
}
/**
* @return The PostalCode Beans' home
*/
public PostalCodeHome getPostalCodeHome() throws RemoteException {
return (PostalCodeHome) this.getIDOHome(PostalCode.class);
}
/**
* @return The Email Beans' home
*/
public EmailHome getEmailHome() throws RemoteException {
return (EmailHome) this.getIDOHome(Email.class);
}
/**
* @return The Address Beans' home
*/
public AddressHome getAddressHome() throws RemoteException {
return (AddressHome) this.getIDOHome(Address.class);
}
/**
* Finds and updates or Creates a new postal code
*
* @return A new or updates PostalCode
*/
public PostalCode getPostalCodeAndCreateIfDoesNotExist(String postCode, String name, Country country)
throws CreateException, RemoteException {
PostalCode code;
PostalCodeHome home = (PostalCodeHome) this.getIDOHome(PostalCode.class);
try {
code = home.findByPostalCodeAndCountryId(postCode, ((Integer) country.getPrimaryKey()).intValue());
}
catch (FinderException ex) {
code = home.create();
code.setPostalCode(postCode);
code.setName(name);
code.setCountry(country);
code.store();
}
return code;
}
/**
* Connects the postal code with the given commune The commune code is set
* to the commune name if it is not already set. This is a simplification
* since we didn't have that data for Iceland
*/
public void connectPostalCodeToCommune(PostalCode postalCode, String Commune) throws RemoteException,
CreateException {
Commune commune = createCommuneIfNotExisting(Commune);
postalCode.setCommune(commune);
postalCode.store();
}
/**
* @param Commune
* @return
* @throws RemoteException
* @throws CreateException
*/
public Commune createCommuneIfNotExisting(String Commune) throws RemoteException, CreateException {
CommuneHome communeHome = getCommuneHome();
Commune commune;
try {
commune = communeHome.findByCommuneName(Commune);
}
catch (FinderException e) {
commune = communeHome.create();
// commune.setCommuneCode(Commune); //Set only if we find commune
// code
commune.setCommuneName(Commune);
commune.setIsValid(true);
commune.store();
}
return commune;
}
public Commune getOtherCommuneCreateIfNotExist() throws CreateException, FinderException, RemoteException {
return getCommuneHome().findOtherCommmuneCreateIfNotExist();
}
/**
* Change postal code name when only one address is related to the
* postalcode
*/
public PostalCode changePostalCodeNameWhenOnlyOneAddressRelated(PostalCode postalCode, String newName) {
java.util.Collection addresses = postalCode.getAddresses();
if (addresses != null && addresses.size() == 1) {
postalCode.setName(newName);
postalCode.store();
}
return postalCode;
}
/**
* Gets the streetname from a string with the format.<br>
* "Streetname Number ..." e.g. "My Street 24 982 NY" would return "My
* Street".<br>
* not very flexibel but handles "my street 24, 982 NY" the same way.
*
* @return Finds the first number in the string and return a sbustring to
* that point or the whole string if no number is present
*/
public String getStreetNameFromAddressString(String addressString) {
int index = TextSoap.getIndexOfFirstNumberInString(addressString);
if (index == -1) {
return addressString;
}
else {
return addressString.substring(0, index);
}
}
/**
* Gets the streetnumber from a string with the format.<br>
* "Streetname Number ..." e.g. "My Street 24" would return "24".<br>
*
* @return Finds the first number in the string and returns a substring from
* that point or null if no number found
*/
public String getStreetNumberFromAddressString(String addressString) {
int index = TextSoap.getIndexOfFirstNumberInString(addressString);
if (index != -1) {
return addressString.substring(index, addressString.length());
}
return null;
}
/**
* @return Returns a fully qualifying address string with streetname and
* number,postal code and postal address, country its ISO
* abbreviation, Commune name and commune code (uid)<br>
* Each piece is seperated by a semicolon (";") e.g. : "Stafnasel
* 6;107 Reykjavik;Iceland is_IS;Reykjavik 12345" <br>
* If a piece is missing the string "N/A" (not available) is added
* instead e.g. "Stafnasel 6;107 Reykjavik;Iceland is_IS;N/A"
*/
public String getFullAddressString(Address address) {
StringBuffer fullAddress = new StringBuffer();
String streetNameAndNumber = address.getStreetAddress();
String postalCode = address.getPostalAddress();
Country country = address.getCountry();
Commune commune = address.getCommune();
if (streetNameAndNumber != null && !"".equals(streetNameAndNumber)) {
fullAddress.append(streetNameAndNumber);
}
else {
fullAddress.append(NOT_AVAILABLE);
}
fullAddress.append(";");
if (postalCode != null) {
fullAddress.append(postalCode);
}
else {
fullAddress.append(NOT_AVAILABLE);
}
fullAddress.append(";");
if (country != null) {
String countryName = country.getName();
String isoAbbr = country.getIsoAbbreviation();
fullAddress.append(countryName);
fullAddress.append(" ");
fullAddress.append(isoAbbr);
}
else {
fullAddress.append(NOT_AVAILABLE);
}
fullAddress.append(";");
if (commune != null) {
String communeName = commune.getCommuneName();
String code = commune.getCommuneCode();
fullAddress.append(communeName);
fullAddress.append(" ");
fullAddress.append(code);
}
else {
fullAddress.append(NOT_AVAILABLE);
}
return fullAddress.toString();
}
/**
* Deserialized the fullAddressString and updates the address bean with what
* it finds and returns the address STORED
*
* @param address
* @param fullAddressString
* A fully qualifying address string with streetname and
* number,postal code and postal address, country its ISO
* abbreviation, Commune name and commune code (uid)<br>
* Each piece is seperated by a semicolon (";") and country and
* commune info by a ":"<br>
* e.g. : "Stafnasel 6;107
* Reykjavik;Iceland:is_IS;Reykjavik:12345" <br>
* If a piece is missing the string "N/A" (not available) should
* be added instead e.g. "Stafnasel 6;107
* Reykjavik;Iceland:is_IS;N/A"
* @return Deserialized the fullAddressString and updates the address bean
* with what it finds and returns the address STORED
* @throws CreateException
* @throws RemoteException
*/
public Address getUpdatedAddressByFullAddressString(Address address, String fullAddressString)
throws RemoteException, CreateException {
String streetName = null;
String streetNumber = null;
String postalCode = null;
String postalName = null;
String countryName = null;
String countryISOAbbr = null;
String communeName = null;
String communeCode = null;
PostalCode postal = null;
Country country = null;
Commune commune = null;
// deserialize the string
- StringTokenizer nizer = new StringTokenizer(";", fullAddressString);
+ StringTokenizer nizer = new StringTokenizer(fullAddressString,";");
String streetNameAndNumber = nizer.nextToken();
String postalCodeAndPostalAddress = nizer.nextToken();
String countryNameAndISOAbbreviation = nizer.nextToken();
String communeNameAndCommuneCode = nizer.nextToken();
// deserialize the string even more
if (!NOT_AVAILABLE.equals(streetNameAndNumber)) {
streetName = getStreetNameFromAddressString(streetNameAndNumber);
streetNumber = getStreetNumberFromAddressString(streetNameAndNumber);
}
if (!NOT_AVAILABLE.equals(countryNameAndISOAbbreviation)) {
countryName = countryNameAndISOAbbreviation.substring(0, countryNameAndISOAbbreviation.indexOf(":"));
countryISOAbbr = countryNameAndISOAbbreviation.substring(countryNameAndISOAbbreviation.indexOf(":") + 1);
// get country by iso...or name
country = getCountryAndCreateIfDoesNotExist(countryName, countryISOAbbr);
}
if (!NOT_AVAILABLE.equals(communeNameAndCommuneCode)) {
communeName = communeNameAndCommuneCode.substring(0, communeNameAndCommuneCode.indexOf(":"));
communeCode = communeNameAndCommuneCode.substring(communeNameAndCommuneCode.indexOf(":") + 1);
// get commune by code or name
commune = getCommuneAndCreateIfDoesNotExist(communeName, communeCode);
}
if (!NOT_AVAILABLE.equals(postalCodeAndPostalAddress) && country != null) {
postalCode = postalCodeAndPostalAddress.substring(0, postalCodeAndPostalAddress.indexOf(" "));
postalName = postalCodeAndPostalAddress.substring(postalCodeAndPostalAddress.indexOf(" ") + 1);
postal = getPostalCodeAndCreateIfDoesNotExist(postalCode, postalName, country);
}
// Set what we have and erase what we don't have
if (streetName != null) {
address.setStreetName(streetName);
}
else {
//no nasty nullpointer there please..
address.setStreetName("");
}
if (streetNumber != null) {
address.setStreetNumber(streetNumber);
}
else {
// Fix when entering unnumbered addresses, something I saw Aron do
address.setStreetNumber("");
}
address.setCountry(country);
address.setPostalCode(postal);
address.setCommune(commune);
// and store
address.store();
return address;
}
/**
* @param countryName
* @param countryISOAbbr
* @return
* @throws RemoteException
* @throws CreateException
*/
public Country getCountryAndCreateIfDoesNotExist(String countryName, String countryISOAbbr) throws RemoteException,
CreateException {
Country country = null;
try {
country = getCountryHome().findByIsoAbbreviation(countryISOAbbr);
}
catch (FinderException e) {
try {
country = getCountryHome().findByCountryName(countryName);
}
catch (FinderException e1) {
log("No record of country in database for: " + countryName + " " + countryISOAbbr + " adding it...");
country = getCountryHome().create();
country.setName(countryName);
country.setIsoAbbreviation(countryISOAbbr);
country.store();
}
}
return country;
}
/**
* @param communeName
* @param communeCode
* @return
* @throws RemoteException
* @throws CreateException
*/
public Commune getCommuneAndCreateIfDoesNotExist(String communeName, String communeCode) throws RemoteException,
CreateException {
Commune commune = null;
try {
commune = getCommuneHome().findByCommuneCode(communeCode);
}
catch (FinderException e) {
try {
commune = getCommuneHome().findByCommuneName(communeName);
}
catch (FinderException e1) {
log("No record of commune in database for: " + communeName + " " + communeCode + " adding it...");
commune = getCommuneHome().create();
commune.setCommuneName(communeName);
commune.setCommuneCode(communeCode);
commune.store();
}
}
return commune;
}
public AddressType getMainAddressType() throws RemoteException{
return getAddressHome().getAddressType1();
}
public AddressType getCOAddressType() throws RemoteException{
return getAddressHome().getAddressType2();
}
} // Class AddressBusinessBean
| true | true | public Address getUpdatedAddressByFullAddressString(Address address, String fullAddressString)
throws RemoteException, CreateException {
String streetName = null;
String streetNumber = null;
String postalCode = null;
String postalName = null;
String countryName = null;
String countryISOAbbr = null;
String communeName = null;
String communeCode = null;
PostalCode postal = null;
Country country = null;
Commune commune = null;
// deserialize the string
StringTokenizer nizer = new StringTokenizer(";", fullAddressString);
String streetNameAndNumber = nizer.nextToken();
String postalCodeAndPostalAddress = nizer.nextToken();
String countryNameAndISOAbbreviation = nizer.nextToken();
String communeNameAndCommuneCode = nizer.nextToken();
// deserialize the string even more
if (!NOT_AVAILABLE.equals(streetNameAndNumber)) {
streetName = getStreetNameFromAddressString(streetNameAndNumber);
streetNumber = getStreetNumberFromAddressString(streetNameAndNumber);
}
if (!NOT_AVAILABLE.equals(countryNameAndISOAbbreviation)) {
countryName = countryNameAndISOAbbreviation.substring(0, countryNameAndISOAbbreviation.indexOf(":"));
countryISOAbbr = countryNameAndISOAbbreviation.substring(countryNameAndISOAbbreviation.indexOf(":") + 1);
// get country by iso...or name
country = getCountryAndCreateIfDoesNotExist(countryName, countryISOAbbr);
}
if (!NOT_AVAILABLE.equals(communeNameAndCommuneCode)) {
communeName = communeNameAndCommuneCode.substring(0, communeNameAndCommuneCode.indexOf(":"));
communeCode = communeNameAndCommuneCode.substring(communeNameAndCommuneCode.indexOf(":") + 1);
// get commune by code or name
commune = getCommuneAndCreateIfDoesNotExist(communeName, communeCode);
}
if (!NOT_AVAILABLE.equals(postalCodeAndPostalAddress) && country != null) {
postalCode = postalCodeAndPostalAddress.substring(0, postalCodeAndPostalAddress.indexOf(" "));
postalName = postalCodeAndPostalAddress.substring(postalCodeAndPostalAddress.indexOf(" ") + 1);
postal = getPostalCodeAndCreateIfDoesNotExist(postalCode, postalName, country);
}
// Set what we have and erase what we don't have
if (streetName != null) {
address.setStreetName(streetName);
}
else {
//no nasty nullpointer there please..
address.setStreetName("");
}
if (streetNumber != null) {
address.setStreetNumber(streetNumber);
}
else {
// Fix when entering unnumbered addresses, something I saw Aron do
address.setStreetNumber("");
}
address.setCountry(country);
address.setPostalCode(postal);
address.setCommune(commune);
// and store
address.store();
return address;
}
| public Address getUpdatedAddressByFullAddressString(Address address, String fullAddressString)
throws RemoteException, CreateException {
String streetName = null;
String streetNumber = null;
String postalCode = null;
String postalName = null;
String countryName = null;
String countryISOAbbr = null;
String communeName = null;
String communeCode = null;
PostalCode postal = null;
Country country = null;
Commune commune = null;
// deserialize the string
StringTokenizer nizer = new StringTokenizer(fullAddressString,";");
String streetNameAndNumber = nizer.nextToken();
String postalCodeAndPostalAddress = nizer.nextToken();
String countryNameAndISOAbbreviation = nizer.nextToken();
String communeNameAndCommuneCode = nizer.nextToken();
// deserialize the string even more
if (!NOT_AVAILABLE.equals(streetNameAndNumber)) {
streetName = getStreetNameFromAddressString(streetNameAndNumber);
streetNumber = getStreetNumberFromAddressString(streetNameAndNumber);
}
if (!NOT_AVAILABLE.equals(countryNameAndISOAbbreviation)) {
countryName = countryNameAndISOAbbreviation.substring(0, countryNameAndISOAbbreviation.indexOf(":"));
countryISOAbbr = countryNameAndISOAbbreviation.substring(countryNameAndISOAbbreviation.indexOf(":") + 1);
// get country by iso...or name
country = getCountryAndCreateIfDoesNotExist(countryName, countryISOAbbr);
}
if (!NOT_AVAILABLE.equals(communeNameAndCommuneCode)) {
communeName = communeNameAndCommuneCode.substring(0, communeNameAndCommuneCode.indexOf(":"));
communeCode = communeNameAndCommuneCode.substring(communeNameAndCommuneCode.indexOf(":") + 1);
// get commune by code or name
commune = getCommuneAndCreateIfDoesNotExist(communeName, communeCode);
}
if (!NOT_AVAILABLE.equals(postalCodeAndPostalAddress) && country != null) {
postalCode = postalCodeAndPostalAddress.substring(0, postalCodeAndPostalAddress.indexOf(" "));
postalName = postalCodeAndPostalAddress.substring(postalCodeAndPostalAddress.indexOf(" ") + 1);
postal = getPostalCodeAndCreateIfDoesNotExist(postalCode, postalName, country);
}
// Set what we have and erase what we don't have
if (streetName != null) {
address.setStreetName(streetName);
}
else {
//no nasty nullpointer there please..
address.setStreetName("");
}
if (streetNumber != null) {
address.setStreetNumber(streetNumber);
}
else {
// Fix when entering unnumbered addresses, something I saw Aron do
address.setStreetNumber("");
}
address.setCountry(country);
address.setPostalCode(postal);
address.setCommune(commune);
// and store
address.store();
return address;
}
|
diff --git a/java/src/org/pocketworkstation/pckeyboard/LatinKeyboardView.java b/java/src/org/pocketworkstation/pckeyboard/LatinKeyboardView.java
index 483ad5d..3800360 100644
--- a/java/src/org/pocketworkstation/pckeyboard/LatinKeyboardView.java
+++ b/java/src/org/pocketworkstation/pckeyboard/LatinKeyboardView.java
@@ -1,594 +1,596 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import org.pocketworkstation.pckeyboard.Keyboard.Key;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.widget.PopupWindow;
public class LatinKeyboardView extends LatinKeyboardBaseView {
// The keycode list needs to stay in sync with the
// res/values/keycodes.xml file.
// FIXME: The following keycodes should really be renumbered
// since they conflict with existing KeyEvent keycodes.
static final int KEYCODE_OPTIONS = -100;
static final int KEYCODE_OPTIONS_LONGPRESS = -101;
static final int KEYCODE_VOICE = -102;
static final int KEYCODE_F1 = -103;
static final int KEYCODE_NEXT_LANGUAGE = -104;
static final int KEYCODE_PREV_LANGUAGE = -105;
static final int KEYCODE_COMPOSE = -10024;
// The following keycodes match (negative) KeyEvent keycodes.
// Would be better to use the real KeyEvent values, but many
// don't exist prior to the Honeycomb API (level 11).
static final int KEYCODE_DPAD_UP = -19;
static final int KEYCODE_DPAD_DOWN = -20;
static final int KEYCODE_DPAD_LEFT = -21;
static final int KEYCODE_DPAD_RIGHT = -22;
static final int KEYCODE_DPAD_CENTER = -23;
static final int KEYCODE_ALT_LEFT = -57;
static final int KEYCODE_PAGE_UP = -92;
static final int KEYCODE_PAGE_DOWN = -93;
static final int KEYCODE_ESCAPE = -111;
static final int KEYCODE_FORWARD_DEL = -112;
static final int KEYCODE_CTRL_LEFT = -113;
static final int KEYCODE_CAPS_LOCK = -115;
static final int KEYCODE_SCROLL_LOCK = -116;
static final int KEYCODE_FN = -119;
static final int KEYCODE_SYSRQ = -120;
static final int KEYCODE_BREAK = -121;
static final int KEYCODE_HOME = -122;
static final int KEYCODE_END = -123;
static final int KEYCODE_INSERT = -124;
static final int KEYCODE_FKEY_F1 = -131;
static final int KEYCODE_FKEY_F2 = -132;
static final int KEYCODE_FKEY_F3 = -133;
static final int KEYCODE_FKEY_F4 = -134;
static final int KEYCODE_FKEY_F5 = -135;
static final int KEYCODE_FKEY_F6 = -136;
static final int KEYCODE_FKEY_F7 = -137;
static final int KEYCODE_FKEY_F8 = -138;
static final int KEYCODE_FKEY_F9 = -139;
static final int KEYCODE_FKEY_F10 = -140;
static final int KEYCODE_FKEY_F11 = -141;
static final int KEYCODE_FKEY_F12 = -142;
static final int KEYCODE_NUM_LOCK = -143;
private Keyboard mPhoneKeyboard;
/** Whether the extension of this keyboard is visible */
private boolean mExtensionVisible;
/** The view that is shown as an extension of this keyboard view */
private LatinKeyboardView mExtension;
/** The popup window that contains the extension of this keyboard */
private PopupWindow mExtensionPopup;
/** Whether this view is an extension of another keyboard */
private boolean mIsExtensionType;
private boolean mFirstEvent;
/** Whether we've started dropping move events because we found a big jump */
private boolean mDroppingEvents;
/**
* Whether multi-touch disambiguation needs to be disabled for any reason. There are 2 reasons
* for this to happen - (1) if a real multi-touch event has occured and (2) we've opened an
* extension keyboard.
*/
private boolean mDisableDisambiguation;
/** The distance threshold at which we start treating the touch session as a multi-touch */
private int mJumpThresholdSquare = Integer.MAX_VALUE;
/** The y coordinate of the last row */
private int mLastRowY;
private int mExtensionLayoutResId = 0;
public LatinKeyboardView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public LatinKeyboardView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setPhoneKeyboard(Keyboard phoneKeyboard) {
mPhoneKeyboard = phoneKeyboard;
}
public void setExtensionLayoutResId (int id) {
mExtensionLayoutResId = id;
}
@Override
public void setPreviewEnabled(boolean previewEnabled) {
if (getKeyboard() == mPhoneKeyboard) {
// Phone keyboard never shows popup preview (except language switch).
super.setPreviewEnabled(false);
} else {
super.setPreviewEnabled(previewEnabled);
}
}
@Override
public void setKeyboard(Keyboard newKeyboard) {
final Keyboard oldKeyboard = getKeyboard();
if (oldKeyboard instanceof LatinKeyboard) {
// Reset old keyboard state before switching to new keyboard.
((LatinKeyboard)oldKeyboard).keyReleased();
}
super.setKeyboard(newKeyboard);
// One-seventh of the keyboard width seems like a reasonable threshold
mJumpThresholdSquare = newKeyboard.getMinWidth() / 7;
mJumpThresholdSquare *= mJumpThresholdSquare;
// Assuming there are 4 rows, this is the coordinate of the last row
mLastRowY = (newKeyboard.getHeight() * 3) / 4;
setKeyboardLocal(newKeyboard);
}
@Override
protected boolean onLongPress(Key key) {
int primaryCode = key.codes[0];
if (primaryCode == KEYCODE_OPTIONS) {
return invokeOnKey(KEYCODE_OPTIONS_LONGPRESS);
} else if (primaryCode == KEYCODE_DPAD_CENTER) {
return invokeOnKey(KEYCODE_COMPOSE);
} else if (primaryCode == '0' && getKeyboard() == mPhoneKeyboard) {
// Long pressing on 0 in phone number keypad gives you a '+'.
return invokeOnKey('+');
} else {
return super.onLongPress(key);
}
}
private boolean invokeOnKey(int primaryCode) {
getOnKeyboardActionListener().onKey(primaryCode, null,
LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE,
LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE);
return true;
}
@Override
protected CharSequence adjustCase(CharSequence label) {
Keyboard keyboard = getKeyboard();
if (keyboard.isShifted()
&& keyboard instanceof LatinKeyboard
&& ((LatinKeyboard) keyboard).isAlphaKeyboard()
&& !TextUtils.isEmpty(label) && label.length() < 3
&& Character.isLowerCase(label.charAt(0))) {
label = label.toString().toUpperCase();
}
return label;
}
public boolean setShiftLocked(boolean shiftLocked) {
Keyboard keyboard = getKeyboard();
if (keyboard instanceof LatinKeyboard) {
((LatinKeyboard)keyboard).setShiftLocked(shiftLocked);
invalidateAllKeys();
return true;
}
return false;
}
/**
* This function checks to see if we need to handle any sudden jumps in the pointer location
* that could be due to a multi-touch being treated as a move by the firmware or hardware.
* Once a sudden jump is detected, all subsequent move events are discarded
* until an UP is received.<P>
* When a sudden jump is detected, an UP event is simulated at the last position and when
* the sudden moves subside, a DOWN event is simulated for the second key.
* @param me the motion event
* @return true if the event was consumed, so that it doesn't continue to be handled by
* KeyboardView.
*/
private boolean handleSuddenJump(MotionEvent me) {
final int action = me.getAction();
final int x = (int) me.getX();
final int y = (int) me.getY();
boolean result = false;
// Real multi-touch event? Stop looking for sudden jumps
if (me.getPointerCount() > 1) {
mDisableDisambiguation = true;
}
if (mDisableDisambiguation) {
// If UP, reset the multi-touch flag
if (action == MotionEvent.ACTION_UP) mDisableDisambiguation = false;
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
// Reset the "session"
mDroppingEvents = false;
mDisableDisambiguation = false;
break;
case MotionEvent.ACTION_MOVE:
// Is this a big jump?
final int distanceSquare = (mLastX - x) * (mLastX - x) + (mLastY - y) * (mLastY - y);
// Check the distance and also if the move is not entirely within the bottom row
// If it's only in the bottom row, it might be an intentional slide gesture
// for language switching
if (distanceSquare > mJumpThresholdSquare
&& (mLastY < mLastRowY || y < mLastRowY)) {
// If we're not yet dropping events, start dropping and send an UP event
if (!mDroppingEvents) {
mDroppingEvents = true;
// Send an up event
MotionEvent translated = MotionEvent.obtain(me.getEventTime(), me.getEventTime(),
MotionEvent.ACTION_UP,
mLastX, mLastY, me.getMetaState());
super.onTouchEvent(translated);
translated.recycle();
}
result = true;
} else if (mDroppingEvents) {
// If moves are small and we're already dropping events, continue dropping
result = true;
}
break;
case MotionEvent.ACTION_UP:
if (mDroppingEvents) {
// Send a down event first, as we dropped a bunch of sudden jumps and assume that
// the user is releasing the touch on the second key.
MotionEvent translated = MotionEvent.obtain(me.getEventTime(), me.getEventTime(),
MotionEvent.ACTION_DOWN,
x, y, me.getMetaState());
super.onTouchEvent(translated);
translated.recycle();
mDroppingEvents = false;
// Let the up event get processed as well, result = false
}
break;
}
// Track the previous coordinate
mLastX = x;
mLastY = y;
return result;
}
@Override
public boolean onTouchEvent(MotionEvent me) {
LatinKeyboard keyboard = (LatinKeyboard) getKeyboard();
if (DEBUG_LINE) {
mLastX = (int) me.getX();
mLastY = (int) me.getY();
invalidate();
}
// If an extension keyboard is visible or this is an extension keyboard, don't look
// for sudden jumps. Otherwise, if there was a sudden jump, return without processing the
// actual motion event.
if (!mExtensionVisible && !mIsExtensionType
&& handleSuddenJump(me)) return true;
// Reset any bounding box controls in the keyboard
if (me.getAction() == MotionEvent.ACTION_DOWN) {
keyboard.keyReleased();
}
if (me.getAction() == MotionEvent.ACTION_UP) {
int languageDirection = keyboard.getLanguageChangeDirection();
if (languageDirection != 0) {
getOnKeyboardActionListener().onKey(
languageDirection == 1 ? KEYCODE_NEXT_LANGUAGE : KEYCODE_PREV_LANGUAGE,
null, mLastX, mLastY);
me.setAction(MotionEvent.ACTION_CANCEL);
keyboard.keyReleased();
return super.onTouchEvent(me);
}
}
// If we don't have an extension keyboard, don't go any further.
if (keyboard.getExtension() == 0) {
return super.onTouchEvent(me);
}
// If the motion event is above the keyboard and it's not an UP event coming
// even before the first MOVE event into the extension area
if (me.getY() < 0 && (mExtensionVisible || me.getAction() != MotionEvent.ACTION_UP)) {
if (mExtensionVisible) {
int action = me.getAction();
if (mFirstEvent) action = MotionEvent.ACTION_DOWN;
mFirstEvent = false;
MotionEvent translated = MotionEvent.obtain(me.getEventTime(), me.getEventTime(),
action,
me.getX(), me.getY() + mExtension.getHeight(), me.getMetaState());
+ if (me.getActionIndex() > 0)
+ return true; // ignore second touches to avoid "pointerIndex out of range"
boolean result = mExtension.onTouchEvent(translated);
translated.recycle();
if (me.getAction() == MotionEvent.ACTION_UP
|| me.getAction() == MotionEvent.ACTION_CANCEL) {
closeExtension();
}
return result;
} else {
if (openExtension()) {
MotionEvent cancel = MotionEvent.obtain(me.getDownTime(), me.getEventTime(),
MotionEvent.ACTION_CANCEL, me.getX() - 100, me.getY() - 100, 0);
super.onTouchEvent(cancel);
cancel.recycle();
if (mExtension.getHeight() > 0) {
MotionEvent translated = MotionEvent.obtain(me.getEventTime(),
me.getEventTime(),
MotionEvent.ACTION_DOWN,
me.getX(), me.getY() + mExtension.getHeight(),
me.getMetaState());
mExtension.onTouchEvent(translated);
translated.recycle();
} else {
mFirstEvent = true;
}
// Stop processing multi-touch errors
mDisableDisambiguation = true;
}
return true;
}
} else if (mExtensionVisible) {
closeExtension();
// Send a down event into the main keyboard first
MotionEvent down = MotionEvent.obtain(me.getEventTime(), me.getEventTime(),
MotionEvent.ACTION_DOWN,
me.getX(), me.getY(), me.getMetaState());
super.onTouchEvent(down);
down.recycle();
// Send the actual event
return super.onTouchEvent(me);
} else {
return super.onTouchEvent(me);
}
}
private void setExtensionType(boolean isExtensionType) {
mIsExtensionType = isExtensionType;
}
private boolean openExtension() {
// If the current keyboard is not visible, or if the mini keyboard is active, don't show the popup
if (!isShown() || popupKeyboardIsShowing()) {
return false;
}
if (((LatinKeyboard) getKeyboard()).getExtension() == 0) return false;
makePopupWindow();
mExtensionVisible = true;
return true;
}
private void makePopupWindow() {
dismissPopupKeyboard();
if (mExtensionPopup == null) {
int[] windowLocation = new int[2];
mExtensionPopup = new PopupWindow(getContext());
mExtensionPopup.setBackgroundDrawable(null);
LayoutInflater li = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mExtension = (LatinKeyboardView) li.inflate(mExtensionLayoutResId == 0 ?
R.layout.input_trans : mExtensionLayoutResId, null);
mExtension.setExtensionType(true);
mExtension.setOnKeyboardActionListener(
new ExtensionKeyboardListener(getOnKeyboardActionListener()));
mExtension.setPopupParent(this);
mExtension.setPopupOffset(0, -windowLocation[1]);
Keyboard keyboard;
mExtension.setKeyboard(keyboard = new LatinKeyboard(getContext(),
((LatinKeyboard) getKeyboard()).getExtension()));
mExtensionPopup.setContentView(mExtension);
mExtensionPopup.setWidth(getWidth());
mExtensionPopup.setHeight(keyboard.getHeight());
mExtensionPopup.setAnimationStyle(-1);
getLocationInWindow(windowLocation);
// TODO: Fix the "- 30".
mExtension.setPopupOffset(0, -windowLocation[1] - 30);
mExtensionPopup.showAtLocation(this, 0, 0, -keyboard.getHeight()
+ windowLocation[1]);
} else {
mExtension.setVisibility(VISIBLE);
}
}
@Override
public void closing() {
super.closing();
if (mExtensionPopup != null && mExtensionPopup.isShowing()) {
mExtensionPopup.dismiss();
mExtensionPopup = null;
}
}
private void closeExtension() {
mExtension.closing();
mExtension.setVisibility(INVISIBLE);
mExtensionVisible = false;
}
private static class ExtensionKeyboardListener implements OnKeyboardActionListener {
private OnKeyboardActionListener mTarget;
ExtensionKeyboardListener(OnKeyboardActionListener target) {
mTarget = target;
}
public void onKey(int primaryCode, int[] keyCodes, int x, int y) {
mTarget.onKey(primaryCode, keyCodes, x, y);
}
public void onPress(int primaryCode) {
mTarget.onPress(primaryCode);
}
public void onRelease(int primaryCode) {
mTarget.onRelease(primaryCode);
}
public void onText(CharSequence text) {
mTarget.onText(text);
}
public void onCancel() {
mTarget.onCancel();
}
public void swipeDown() {
// Don't pass through
}
public void swipeLeft() {
// Don't pass through
}
public void swipeRight() {
// Don't pass through
}
public void swipeUp() {
// Don't pass through
}
}
/**************************** INSTRUMENTATION *******************************/
static final boolean DEBUG_AUTO_PLAY = false;
static final boolean DEBUG_LINE = false;
private static final int MSG_TOUCH_DOWN = 1;
private static final int MSG_TOUCH_UP = 2;
Handler mHandler2;
private String mStringToPlay;
private int mStringIndex;
private boolean mDownDelivered;
private Key[] mAsciiKeys = new Key[256];
private boolean mPlaying;
private int mLastX;
private int mLastY;
private Paint mPaint;
private void setKeyboardLocal(Keyboard k) {
if (DEBUG_AUTO_PLAY) {
findKeys();
if (mHandler2 == null) {
mHandler2 = new Handler() {
@Override
public void handleMessage(Message msg) {
removeMessages(MSG_TOUCH_DOWN);
removeMessages(MSG_TOUCH_UP);
if (mPlaying == false) return;
switch (msg.what) {
case MSG_TOUCH_DOWN:
if (mStringIndex >= mStringToPlay.length()) {
mPlaying = false;
return;
}
char c = mStringToPlay.charAt(mStringIndex);
while (c > 255 || mAsciiKeys[c] == null) {
mStringIndex++;
if (mStringIndex >= mStringToPlay.length()) {
mPlaying = false;
return;
}
c = mStringToPlay.charAt(mStringIndex);
}
int x = mAsciiKeys[c].x + 10;
int y = mAsciiKeys[c].y + 26;
MotionEvent me = MotionEvent.obtain(SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(),
MotionEvent.ACTION_DOWN, x, y, 0);
LatinKeyboardView.this.dispatchTouchEvent(me);
me.recycle();
sendEmptyMessageDelayed(MSG_TOUCH_UP, 500); // Deliver up in 500ms if nothing else
// happens
mDownDelivered = true;
break;
case MSG_TOUCH_UP:
char cUp = mStringToPlay.charAt(mStringIndex);
int x2 = mAsciiKeys[cUp].x + 10;
int y2 = mAsciiKeys[cUp].y + 26;
mStringIndex++;
MotionEvent me2 = MotionEvent.obtain(SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(),
MotionEvent.ACTION_UP, x2, y2, 0);
LatinKeyboardView.this.dispatchTouchEvent(me2);
me2.recycle();
sendEmptyMessageDelayed(MSG_TOUCH_DOWN, 500); // Deliver up in 500ms if nothing else
// happens
mDownDelivered = false;
break;
}
}
};
}
}
}
private void findKeys() {
List<Key> keys = getKeyboard().getKeys();
// Get the keys on this keyboard
for (int i = 0; i < keys.size(); i++) {
int code = keys.get(i).codes[0];
if (code >= 0 && code <= 255) {
mAsciiKeys[code] = keys.get(i);
}
}
}
public void startPlaying(String s) {
if (DEBUG_AUTO_PLAY) {
if (s == null) return;
mStringToPlay = s.toLowerCase();
mPlaying = true;
mDownDelivered = false;
mStringIndex = 0;
mHandler2.sendEmptyMessageDelayed(MSG_TOUCH_DOWN, 10);
}
}
@Override
public void draw(Canvas c) {
LatinIMEUtil.GCUtils.getInstance().reset();
boolean tryGC = true;
for (int i = 0; i < LatinIMEUtil.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) {
try {
super.draw(c);
tryGC = false;
} catch (OutOfMemoryError e) {
tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait("LatinKeyboardView", e);
}
}
if (DEBUG_AUTO_PLAY) {
if (mPlaying) {
mHandler2.removeMessages(MSG_TOUCH_DOWN);
mHandler2.removeMessages(MSG_TOUCH_UP);
if (mDownDelivered) {
mHandler2.sendEmptyMessageDelayed(MSG_TOUCH_UP, 20);
} else {
mHandler2.sendEmptyMessageDelayed(MSG_TOUCH_DOWN, 20);
}
}
}
if (DEBUG_LINE) {
if (mPaint == null) {
mPaint = new Paint();
mPaint.setColor(0x80FFFFFF);
mPaint.setAntiAlias(false);
}
c.drawLine(mLastX, 0, mLastX, getHeight(), mPaint);
c.drawLine(0, mLastY, getWidth(), mLastY, mPaint);
}
}
}
| true | true | public boolean onTouchEvent(MotionEvent me) {
LatinKeyboard keyboard = (LatinKeyboard) getKeyboard();
if (DEBUG_LINE) {
mLastX = (int) me.getX();
mLastY = (int) me.getY();
invalidate();
}
// If an extension keyboard is visible or this is an extension keyboard, don't look
// for sudden jumps. Otherwise, if there was a sudden jump, return without processing the
// actual motion event.
if (!mExtensionVisible && !mIsExtensionType
&& handleSuddenJump(me)) return true;
// Reset any bounding box controls in the keyboard
if (me.getAction() == MotionEvent.ACTION_DOWN) {
keyboard.keyReleased();
}
if (me.getAction() == MotionEvent.ACTION_UP) {
int languageDirection = keyboard.getLanguageChangeDirection();
if (languageDirection != 0) {
getOnKeyboardActionListener().onKey(
languageDirection == 1 ? KEYCODE_NEXT_LANGUAGE : KEYCODE_PREV_LANGUAGE,
null, mLastX, mLastY);
me.setAction(MotionEvent.ACTION_CANCEL);
keyboard.keyReleased();
return super.onTouchEvent(me);
}
}
// If we don't have an extension keyboard, don't go any further.
if (keyboard.getExtension() == 0) {
return super.onTouchEvent(me);
}
// If the motion event is above the keyboard and it's not an UP event coming
// even before the first MOVE event into the extension area
if (me.getY() < 0 && (mExtensionVisible || me.getAction() != MotionEvent.ACTION_UP)) {
if (mExtensionVisible) {
int action = me.getAction();
if (mFirstEvent) action = MotionEvent.ACTION_DOWN;
mFirstEvent = false;
MotionEvent translated = MotionEvent.obtain(me.getEventTime(), me.getEventTime(),
action,
me.getX(), me.getY() + mExtension.getHeight(), me.getMetaState());
boolean result = mExtension.onTouchEvent(translated);
translated.recycle();
if (me.getAction() == MotionEvent.ACTION_UP
|| me.getAction() == MotionEvent.ACTION_CANCEL) {
closeExtension();
}
return result;
} else {
if (openExtension()) {
MotionEvent cancel = MotionEvent.obtain(me.getDownTime(), me.getEventTime(),
MotionEvent.ACTION_CANCEL, me.getX() - 100, me.getY() - 100, 0);
super.onTouchEvent(cancel);
cancel.recycle();
if (mExtension.getHeight() > 0) {
MotionEvent translated = MotionEvent.obtain(me.getEventTime(),
me.getEventTime(),
MotionEvent.ACTION_DOWN,
me.getX(), me.getY() + mExtension.getHeight(),
me.getMetaState());
mExtension.onTouchEvent(translated);
translated.recycle();
} else {
mFirstEvent = true;
}
// Stop processing multi-touch errors
mDisableDisambiguation = true;
}
return true;
}
} else if (mExtensionVisible) {
closeExtension();
// Send a down event into the main keyboard first
MotionEvent down = MotionEvent.obtain(me.getEventTime(), me.getEventTime(),
MotionEvent.ACTION_DOWN,
me.getX(), me.getY(), me.getMetaState());
super.onTouchEvent(down);
down.recycle();
// Send the actual event
return super.onTouchEvent(me);
} else {
return super.onTouchEvent(me);
}
}
| public boolean onTouchEvent(MotionEvent me) {
LatinKeyboard keyboard = (LatinKeyboard) getKeyboard();
if (DEBUG_LINE) {
mLastX = (int) me.getX();
mLastY = (int) me.getY();
invalidate();
}
// If an extension keyboard is visible or this is an extension keyboard, don't look
// for sudden jumps. Otherwise, if there was a sudden jump, return without processing the
// actual motion event.
if (!mExtensionVisible && !mIsExtensionType
&& handleSuddenJump(me)) return true;
// Reset any bounding box controls in the keyboard
if (me.getAction() == MotionEvent.ACTION_DOWN) {
keyboard.keyReleased();
}
if (me.getAction() == MotionEvent.ACTION_UP) {
int languageDirection = keyboard.getLanguageChangeDirection();
if (languageDirection != 0) {
getOnKeyboardActionListener().onKey(
languageDirection == 1 ? KEYCODE_NEXT_LANGUAGE : KEYCODE_PREV_LANGUAGE,
null, mLastX, mLastY);
me.setAction(MotionEvent.ACTION_CANCEL);
keyboard.keyReleased();
return super.onTouchEvent(me);
}
}
// If we don't have an extension keyboard, don't go any further.
if (keyboard.getExtension() == 0) {
return super.onTouchEvent(me);
}
// If the motion event is above the keyboard and it's not an UP event coming
// even before the first MOVE event into the extension area
if (me.getY() < 0 && (mExtensionVisible || me.getAction() != MotionEvent.ACTION_UP)) {
if (mExtensionVisible) {
int action = me.getAction();
if (mFirstEvent) action = MotionEvent.ACTION_DOWN;
mFirstEvent = false;
MotionEvent translated = MotionEvent.obtain(me.getEventTime(), me.getEventTime(),
action,
me.getX(), me.getY() + mExtension.getHeight(), me.getMetaState());
if (me.getActionIndex() > 0)
return true; // ignore second touches to avoid "pointerIndex out of range"
boolean result = mExtension.onTouchEvent(translated);
translated.recycle();
if (me.getAction() == MotionEvent.ACTION_UP
|| me.getAction() == MotionEvent.ACTION_CANCEL) {
closeExtension();
}
return result;
} else {
if (openExtension()) {
MotionEvent cancel = MotionEvent.obtain(me.getDownTime(), me.getEventTime(),
MotionEvent.ACTION_CANCEL, me.getX() - 100, me.getY() - 100, 0);
super.onTouchEvent(cancel);
cancel.recycle();
if (mExtension.getHeight() > 0) {
MotionEvent translated = MotionEvent.obtain(me.getEventTime(),
me.getEventTime(),
MotionEvent.ACTION_DOWN,
me.getX(), me.getY() + mExtension.getHeight(),
me.getMetaState());
mExtension.onTouchEvent(translated);
translated.recycle();
} else {
mFirstEvent = true;
}
// Stop processing multi-touch errors
mDisableDisambiguation = true;
}
return true;
}
} else if (mExtensionVisible) {
closeExtension();
// Send a down event into the main keyboard first
MotionEvent down = MotionEvent.obtain(me.getEventTime(), me.getEventTime(),
MotionEvent.ACTION_DOWN,
me.getX(), me.getY(), me.getMetaState());
super.onTouchEvent(down);
down.recycle();
// Send the actual event
return super.onTouchEvent(me);
} else {
return super.onTouchEvent(me);
}
}
|
diff --git a/src/mud/Main.java b/src/mud/Main.java
index a7244ef..909c4be 100644
--- a/src/mud/Main.java
+++ b/src/mud/Main.java
@@ -1,54 +1,54 @@
package mud;
import java.io.IOException;
import java.net.UnknownHostException;
import mud.network.client.ClientFrame;
import mud.network.client.GameClient;
import mud.network.client.GameClient.ConnectionChoice;
import mud.network.server.GameServer;
/**
* The main plain, brain.
*
* @author Japhez
*/
public class Main {
/**
* Starts the server on a new thread and listens for client connections.
*
* @throws IOException
*/
public static void startServer(boolean localOnly) throws IOException {
GameServer gameServer = new GameServer(GameServer.DEFAULT_PORT, localOnly);
new Thread(gameServer).start();
}
/**
* Attempts to create and connect the client application, then starts a
* server and connects it if necessary.
*
* @throws UnknownHostException
* @throws IOException
*/
public static void connectClient() throws UnknownHostException, IOException {
ClientFrame clientFrame = new ClientFrame();
GameClient gameClient = new GameClient(clientFrame.getjTextArea1(), clientFrame.getjTextField1());
clientFrame.setVisible(true);
//Block until the connection choice is determined
ConnectionChoice connectionChoice = gameClient.getConnectionChoice();
//Check for local only play
if (connectionChoice.equals(ConnectionChoice.LOCAL_SOLO)) {
startServer(true);
}
//Check for local hosting
if (connectionChoice.equals(ConnectionChoice.LOCAL_CO_OP)) {
- startServer(true);
+ startServer(false);
}
//Otherwise the connection is remote, no need for server
}
public static void main(String[] args) throws IOException {
connectClient();
}
}
| true | true | public static void connectClient() throws UnknownHostException, IOException {
ClientFrame clientFrame = new ClientFrame();
GameClient gameClient = new GameClient(clientFrame.getjTextArea1(), clientFrame.getjTextField1());
clientFrame.setVisible(true);
//Block until the connection choice is determined
ConnectionChoice connectionChoice = gameClient.getConnectionChoice();
//Check for local only play
if (connectionChoice.equals(ConnectionChoice.LOCAL_SOLO)) {
startServer(true);
}
//Check for local hosting
if (connectionChoice.equals(ConnectionChoice.LOCAL_CO_OP)) {
startServer(true);
}
//Otherwise the connection is remote, no need for server
}
| public static void connectClient() throws UnknownHostException, IOException {
ClientFrame clientFrame = new ClientFrame();
GameClient gameClient = new GameClient(clientFrame.getjTextArea1(), clientFrame.getjTextField1());
clientFrame.setVisible(true);
//Block until the connection choice is determined
ConnectionChoice connectionChoice = gameClient.getConnectionChoice();
//Check for local only play
if (connectionChoice.equals(ConnectionChoice.LOCAL_SOLO)) {
startServer(true);
}
//Check for local hosting
if (connectionChoice.equals(ConnectionChoice.LOCAL_CO_OP)) {
startServer(false);
}
//Otherwise the connection is remote, no need for server
}
|
diff --git a/tubular-core/src/test/java/org/trancecode/xproc/XProcTestSuiteReportBuilder.java b/tubular-core/src/test/java/org/trancecode/xproc/XProcTestSuiteReportBuilder.java
index 10ff3c9c..9c975f31 100644
--- a/tubular-core/src/test/java/org/trancecode/xproc/XProcTestSuiteReportBuilder.java
+++ b/tubular-core/src/test/java/org/trancecode/xproc/XProcTestSuiteReportBuilder.java
@@ -1,210 +1,210 @@
/*
* Copyright (C) 2010 TranceCode Software
*
* 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 org.trancecode.xproc;
import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.io.Closeables;
import java.io.File;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.Serializer;
import net.sf.saxon.s9api.Serializer.Property;
import org.trancecode.io.Files;
import org.trancecode.xml.saxon.SaxonBuilder;
import org.trancecode.xproc.XProcTestReportXmlModel.Attributes;
import org.trancecode.xproc.XProcTestReportXmlModel.Elements;
/**
* @author Herve Quiroz
*/
public final class XProcTestSuiteReportBuilder
{
private final Multimap<String, TestResult> results = ArrayListMultimap.create();
private static final class TestResult
{
private final XProcTestCase test;
private final QName actualError;
private final String message;
public TestResult(final XProcTestCase test, final QName actualError, final String message)
{
this.test = Preconditions.checkNotNull(test);
this.actualError = actualError;
this.message = message;
}
public boolean failed()
{
return actualError != null && !actualError.equals(test.getError());
}
}
private static void writeProcessorInformation(final SaxonBuilder builder)
{
builder.startElement(Elements.PROCESSOR);
builder.startElement(Elements.NAME);
builder.text("Tubular");
builder.endElement();
builder.startElement(Elements.VENDOR);
builder.text("TranceCode");
builder.endElement();
builder.startElement(Elements.VENDOR_URI);
builder.text("http://code.google.com/p/tubular/");
builder.endElement();
builder.startElement(Elements.VERSION);
builder.text(Tubular.version());
builder.endElement();
builder.startElement(Elements.LANGUAGE);
builder.text("en_US");
builder.endElement();
builder.startElement(Elements.XPROC_VERSION);
builder.text(Tubular.xprocVersion());
builder.endElement();
builder.startElement(Elements.XPATH_VERSION);
builder.text(Tubular.xpathVersion());
builder.endElement();
builder.startElement(Elements.PSVI_SUPPORTED);
builder.text("false");
builder.endElement();
builder.endElement();
}
public void pass(final XProcTestCase test, final String message)
{
if (test.testSuite() != null)
{
results.put(test.testSuite(), new TestResult(test, null, message));
}
}
public void fail(final XProcTestCase test, final QName actualError, final String message)
{
if (test.testSuite() != null)
{
results.put(test.testSuite(), new TestResult(test, actualError, message));
}
}
public void write(final File file)
{
final Processor processor = new Processor(false);
final SaxonBuilder builder = new SaxonBuilder(processor.getUnderlyingConfiguration());
builder.startDocument();
builder.startElement(Elements.TEST_REPORT);
builder.startElement(Elements.TITLE);
builder.text("XProc Test Results for Tubular");
builder.endElement();
builder.startElement(Elements.DATE);
builder.text(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));
builder.endElement();
writeProcessorInformation(builder);
for (final String testSuite : results.keySet())
{
builder.startElement(Elements.TEST_SUITE);
builder.startElement(Elements.TITLE);
builder.text(testSuite);
builder.endElement();
for (final TestResult result : results.get(testSuite))
{
assert result.test.testSuite().equals(testSuite);
if (result.failed())
{
builder.startElement(Elements.FAIL);
}
else
{
builder.startElement(Elements.PASS);
}
builder.attribute(Attributes.URI, result.test.url().toString());
builder.startElement(Elements.TITLE);
builder.text(result.test.getTitle());
builder.endElement();
if (result.actualError != null)
{
builder.startElement(Elements.ERROR);
if (result.test.getError() != null)
{
builder.attribute(Attributes.EXPECTED, result.test.getError().toString());
}
- builder.text(result.actualError.toString());
+ builder.text(result.actualError.getClarkName());
builder.endElement();
}
if (result.message != null)
{
builder.startElement(Elements.MESSAGE);
builder.text(result.message);
builder.endElement();
}
builder.endElement();
}
builder.endElement();
}
builder.endElement();
builder.endDocument();
// Write report to file
final OutputStream reportOut = Files.newFileOutputStream(file);
final Serializer serializer = new Serializer();
serializer.setOutputStream(reportOut);
serializer.setOutputProperty(Property.INDENT, "yes");
try
{
processor.writeXdmValue(builder.getNode(), serializer);
}
catch (final SaxonApiException e)
{
throw new IllegalStateException(e);
}
finally
{
Closeables.closeQuietly(reportOut);
}
}
}
| true | true | public void write(final File file)
{
final Processor processor = new Processor(false);
final SaxonBuilder builder = new SaxonBuilder(processor.getUnderlyingConfiguration());
builder.startDocument();
builder.startElement(Elements.TEST_REPORT);
builder.startElement(Elements.TITLE);
builder.text("XProc Test Results for Tubular");
builder.endElement();
builder.startElement(Elements.DATE);
builder.text(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));
builder.endElement();
writeProcessorInformation(builder);
for (final String testSuite : results.keySet())
{
builder.startElement(Elements.TEST_SUITE);
builder.startElement(Elements.TITLE);
builder.text(testSuite);
builder.endElement();
for (final TestResult result : results.get(testSuite))
{
assert result.test.testSuite().equals(testSuite);
if (result.failed())
{
builder.startElement(Elements.FAIL);
}
else
{
builder.startElement(Elements.PASS);
}
builder.attribute(Attributes.URI, result.test.url().toString());
builder.startElement(Elements.TITLE);
builder.text(result.test.getTitle());
builder.endElement();
if (result.actualError != null)
{
builder.startElement(Elements.ERROR);
if (result.test.getError() != null)
{
builder.attribute(Attributes.EXPECTED, result.test.getError().toString());
}
builder.text(result.actualError.toString());
builder.endElement();
}
if (result.message != null)
{
builder.startElement(Elements.MESSAGE);
builder.text(result.message);
builder.endElement();
}
builder.endElement();
}
builder.endElement();
}
builder.endElement();
builder.endDocument();
// Write report to file
final OutputStream reportOut = Files.newFileOutputStream(file);
final Serializer serializer = new Serializer();
serializer.setOutputStream(reportOut);
serializer.setOutputProperty(Property.INDENT, "yes");
try
{
processor.writeXdmValue(builder.getNode(), serializer);
}
catch (final SaxonApiException e)
{
throw new IllegalStateException(e);
}
finally
{
Closeables.closeQuietly(reportOut);
}
}
| public void write(final File file)
{
final Processor processor = new Processor(false);
final SaxonBuilder builder = new SaxonBuilder(processor.getUnderlyingConfiguration());
builder.startDocument();
builder.startElement(Elements.TEST_REPORT);
builder.startElement(Elements.TITLE);
builder.text("XProc Test Results for Tubular");
builder.endElement();
builder.startElement(Elements.DATE);
builder.text(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));
builder.endElement();
writeProcessorInformation(builder);
for (final String testSuite : results.keySet())
{
builder.startElement(Elements.TEST_SUITE);
builder.startElement(Elements.TITLE);
builder.text(testSuite);
builder.endElement();
for (final TestResult result : results.get(testSuite))
{
assert result.test.testSuite().equals(testSuite);
if (result.failed())
{
builder.startElement(Elements.FAIL);
}
else
{
builder.startElement(Elements.PASS);
}
builder.attribute(Attributes.URI, result.test.url().toString());
builder.startElement(Elements.TITLE);
builder.text(result.test.getTitle());
builder.endElement();
if (result.actualError != null)
{
builder.startElement(Elements.ERROR);
if (result.test.getError() != null)
{
builder.attribute(Attributes.EXPECTED, result.test.getError().toString());
}
builder.text(result.actualError.getClarkName());
builder.endElement();
}
if (result.message != null)
{
builder.startElement(Elements.MESSAGE);
builder.text(result.message);
builder.endElement();
}
builder.endElement();
}
builder.endElement();
}
builder.endElement();
builder.endDocument();
// Write report to file
final OutputStream reportOut = Files.newFileOutputStream(file);
final Serializer serializer = new Serializer();
serializer.setOutputStream(reportOut);
serializer.setOutputProperty(Property.INDENT, "yes");
try
{
processor.writeXdmValue(builder.getNode(), serializer);
}
catch (final SaxonApiException e)
{
throw new IllegalStateException(e);
}
finally
{
Closeables.closeQuietly(reportOut);
}
}
|
diff --git a/src/logic/CheckEditorBoardDifficulty.java b/src/logic/CheckEditorBoardDifficulty.java
index 4488d73..ae4d6ce 100644
--- a/src/logic/CheckEditorBoardDifficulty.java
+++ b/src/logic/CheckEditorBoardDifficulty.java
@@ -1,931 +1,934 @@
/**
*
*/
package logic;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ImageIcon;
import gui.GuiElementField;
import gui.GuiElementField.eStates;
/**
* Die CheckEditorBoardDifficulty Klasse dient dazu, um die Schwirigkeit des Boards auszugeben
* Durch set und get Methoden k�nnen die Daten des Board gesetzt und ausgegeben werden.
*
* @author Fabian, Mats, Eren, Daniel, Andreas, Anatoli
* @version 0.1
*
*/
public class CheckEditorBoardDifficulty
{
/**
* Dekleration der Variabeln f�r die Klasse
*/
final static public String BOARD_DIFFICULTY_EASY = "einfach";
final static public String BOARD_DIFFICULTY_MEDIUM = "mittel";
final static public String BOARD_DIFFICULTY_HARD = "schwer";
final static public String BOARD_DIFFICULTY_NOT_SOLVABLE = "unl�sbar";
Board _oBoard = null;
eStatesDiff[][] _tmpDiff = null;
protected Map<Integer, HashMap<Integer, Integer>> _unsolvableStars = null;
/**
* Ein Enum wird hier deklariert
*/
public static enum eStatesDiff
{
BLOCKED,
ISSTAR,
}
/**
* Konstruktor der Klasse CheckEditorBoardDifficulty
* Das Editor Board wird nach der Schwirigkeit gepr�ft
* @param Board - Hier wird das Editor Board angegeben
*/
public CheckEditorBoardDifficulty(Board oBoard)
{
_oBoard = oBoard;
}
/**
* Konstruktor der Klasse CheckEditorBoardDifficulty
* Das Editor Board wird nach der Schwirigkeit gepr�ft
* @return BOARD_DIFFICULTY_EASY = "einfach" - Hier wird angegeben, dass das Board die Schwirigkeit leicht hat
* @return BOARD_DIFFICULTY_MEDIUM = Hier wird angegeben, dass das Board die Schwirigkeit mittel hat
* @return BOARD_DIFFICULTY_HARD = Hier wird angegeben, dass das Board die Schwirigkeit schwer hat
* @return BOARD_DIFFICULTY_NOT_SOLVABLE = Hier wird angegeben, dass das Board die Schwirigkeit unl�sbar hat
*/
public String checkDifficulty()
{
/**
* Dekleration der Variabeln f�r die Funktion checkDifficulty
*/
_tmpDiff = new eStatesDiff[_oBoard.getHeight()][_oBoard.getWidth()];
boolean isSolvable = false;
boolean doMediumSearch = false;
boolean doHardSearch = false;
boolean isSolved = false;
boolean hasChanged = true;
int tmpStarCount = 0;
int tmpEmptyFields = 0;
int counter = 0;
boolean foundEmptySpot = false;
int foundSpotX = -1;
int foundSpotY = -1;
int adder = 0;
// go through logicuntil game is solved or stop when no changes were made in last run
while (!isSolved &&
hasChanged)
{
hasChanged = false;
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
int rowStars = getCalculatedRowStars(iY, doMediumSearch);
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
int columnStars = getCalculatedColumnStars(iX, doMediumSearch);
Field oField = _oBoard.getField(iY, iX);
if (0 == columnStars ||
0 == rowStars ||
isArrow(oField.getState()))
{
boolean tmpChanged = updateTmpFields(iY, iX, eStatesDiff.BLOCKED);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
if (!isArrowPointingAtField(iY, iX))
{
boolean tmpChanged = updateTmpFields(iY, iX, eStatesDiff.BLOCKED);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
}
tmpEmptyFields = 0;
for (int iX2 = 0; iX2 < _oBoard.getWidth(); iX2++)
{
if (_tmpDiff[iY][iX2] != eStatesDiff.BLOCKED && _tmpDiff[iY][iX2] != eStatesDiff.ISSTAR)
{
tmpEmptyFields++;
}
}
if (tmpEmptyFields == rowStars)
{
for (int iX2 = 0; iX2 < _oBoard.getWidth(); iX2++)
{
if (_tmpDiff[iY][iX2] != eStatesDiff.BLOCKED)
{
boolean tmpChanged = updateTmpFields(iY, iX2, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
}
}
}
tmpEmptyFields = 0;
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
tmpEmptyFields = 0;
int columnStars = getCalculatedColumnStars(iX, doMediumSearch);
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
if (_tmpDiff[iY][iX] != eStatesDiff.BLOCKED && _tmpDiff[iY][iX] != eStatesDiff.ISSTAR)
{
tmpEmptyFields++;
}
}
if (tmpEmptyFields == columnStars)
{
for (int iY2 = 0; iY2 < _oBoard.getWidth(); iY2++)
{
if (_tmpDiff[iY2][iX] != eStatesDiff.BLOCKED)
{
boolean tmpChanged = updateTmpFields(iY2, iX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
}
}
}
// cross calculation
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
tmpEmptyFields = 0;
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
foundEmptySpot = false;
foundSpotX = -1;
foundSpotY = -1;
Field oField = _oBoard.getField(iY, iX);
if (oField.getState() == eStates.ARROW_SW)
{
adder = 1;
while (((iY + adder) < _oBoard.getHeight()) && ((iX - adder) >= 0))
{
if (_tmpDiff[iY + adder][iX - adder] != eStatesDiff.BLOCKED && _tmpDiff[iY + adder][iX - adder] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX - adder;
foundSpotY = iY + adder;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
adder++;
}
}
else if (oField.getState() == eStates.ARROW_SE)
{
adder = 1;
while (((iY + adder) < _oBoard.getHeight()) && ((iX + adder) < _oBoard.getWidth()))
{
if (_tmpDiff[iY + adder][iX + adder] != eStatesDiff.BLOCKED && _tmpDiff[iY + adder][iX + adder] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX + adder;
foundSpotY = iY + adder;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
adder++;
}
}
else if (oField.getState() == eStates.ARROW_NW)
{
adder = 1;
while (((iY - adder) >= 0) && ((iX - adder) >= 0))
{
if (_tmpDiff[iY - adder][iX - adder] != eStatesDiff.BLOCKED && _tmpDiff[iY - adder][iX - adder] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX - adder;
foundSpotY = iY - adder;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
adder++;
}
}
else if (oField.getState() == eStates.ARROW_NE)
{
adder = 1;
while (((iY - adder) >= 0) && ((iX + adder) < _oBoard.getWidth()))
{
if (_tmpDiff[iY - adder][iX + adder] != eStatesDiff.BLOCKED && _tmpDiff[iY - adder][iX + adder] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX + adder;
foundSpotY = iY - adder;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
adder++;
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
if (doHardSearch)
{
boolean upCheckDone = false;
boolean downCheckDone = false;
foundEmptySpot = false;
foundSpotX = -1;
foundSpotY = -1;
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
upCheckDone = false;
downCheckDone = false;
int columnStars = getCalculatedColumnStars(iX, doHardSearch);
if (1 <= columnStars)
{
// up check
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
foundEmptySpot = false;
Field oField = _oBoard.getField(iY, iX);
if (!upCheckDone && oField.getState() == eStates.ARROW_N)
{
upCheckDone = true;
for (int iTmpY = 0; iTmpY < iY; iTmpY++)
{
if (_tmpDiff[iTmpY][iX] != eStatesDiff.BLOCKED && _tmpDiff[iTmpY][iX] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX;
foundSpotY = iTmpY;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
// down check
for (int iY = _oBoard.getHeight()-1; iY >= 0; iY--)
{
foundEmptySpot = false;
Field oField = _oBoard.getField(iY, iX);
if (!downCheckDone && oField.getState() == eStates.ARROW_S)
{
downCheckDone = true;
for (int iTmpY = iY+1; iTmpY < _oBoard.getHeight(); iTmpY++)
{
if (_tmpDiff[iTmpY][iX] != eStatesDiff.BLOCKED && _tmpDiff[iTmpY][iX] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX;
foundSpotY = iTmpY;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
}
}
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
upCheckDone = false;
downCheckDone = false;
int rowStars = getCalculatedRowStars(iY, doHardSearch);
if (1 <= rowStars)
{
// up check
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
foundEmptySpot = false;
Field oField = _oBoard.getField(iY, iX);
if (!upCheckDone && oField.getState() == eStates.ARROW_W)
{
upCheckDone = true;
for (int iTmpX = 0; iTmpX < iX; iTmpX++)
{
if (_tmpDiff[iY][iTmpX] != eStatesDiff.BLOCKED && _tmpDiff[iY][iTmpX] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iTmpX;
foundSpotY = iY;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
// up check
for (int iX = _oBoard.getWidth()-1; iX >= 0; iX--)
{
foundEmptySpot = false;
Field oField = _oBoard.getField(iY, iX);
if (!downCheckDone && oField.getState() == eStates.ARROW_E)
{
downCheckDone = true;
for (int iTmpX = iX+1; iTmpX < _oBoard.getWidth(); iTmpX++)
{
if (_tmpDiff[iY][iTmpX] != eStatesDiff.BLOCKED && _tmpDiff[iY][iTmpX] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iTmpX;
foundSpotY = iY;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
}
}
- boolean tmpChanged = blockSpecialAlgorigthm();
if (!hasChanged)
{
- hasChanged = tmpChanged;
+ boolean tmpChanged = blockSpecialAlgorigthm();
+ if (!hasChanged)
+ {
+ hasChanged = tmpChanged;
+ }
}
}
isSolved = isSolved();
counter++;
if (!isSolved && !doMediumSearch &&
(counter > 1 || !hasChanged))
{
// its medium
doMediumSearch = true;
hasChanged = true;
}
if (!isSolved && doMediumSearch && !doHardSearch &&
- (counter > 4 || !hasChanged))
+ (counter > 5 || !hasChanged))
{
// its medium
doHardSearch = true;
hasChanged = true;
}
}
if (isSolved && !doMediumSearch && counter <2)
{
return BOARD_DIFFICULTY_EASY;
}
- else if(isSolved && counter < 4 && !doHardSearch)
+ else if(isSolved && counter < 6)
{
return BOARD_DIFFICULTY_MEDIUM;
}
else if(isSolved)
{
return BOARD_DIFFICULTY_HARD;
}
else
{
calculatedUnsolvableStars();
return BOARD_DIFFICULTY_NOT_SOLVABLE;
}
}
public boolean isArrow(eStates state)
{
if (state == eStates.ARROW_E ||
state == eStates.ARROW_N ||
state == eStates.ARROW_NE ||
state == eStates.ARROW_NW ||
state == eStates.ARROW_S ||
state == eStates.ARROW_SE ||
state == eStates.ARROW_SW ||
state == eStates.ARROW_W)
{
return true;
}
return false;
}
public boolean isArrowPointingAtField(int yPos, int xPos)
{
int adder = 0;
// is there a north arrow pointing at me?
for (int iY = yPos+1; iY < _oBoard.getHeight(); iY++)
{
if (_oBoard.getField(iY, xPos).getState() == eStates.ARROW_N)
{
return true;
}
}
// is there a south arrow pointing at me?
for (int iY = 0; iY < yPos; iY++)
{
if (_oBoard.getField(iY, xPos).getState() == eStates.ARROW_S)
{
return true;
}
}
// is there a west arrow pointing at me?
for (int iX = xPos+1; iX < _oBoard.getWidth(); iX++)
{
if (_oBoard.getField(yPos, iX).getState() == eStates.ARROW_W)
{
return true;
}
}
// is there a east arrow pointing at me?
for (int iX = 0; iX < xPos; iX++)
{
if (_oBoard.getField(yPos, iX).getState() == eStates.ARROW_E)
{
return true;
}
}
// is there a northeast arrow pointing at me?
adder = 1;
while (((yPos - adder) >= 0) && ((xPos + adder) < _oBoard.getWidth()))
{
if (_oBoard.getField((yPos - adder), (xPos + adder)).getState() == eStates.ARROW_SW)
{
return true;
}
adder++;
}
// is there a southeast arrow pointing at me?
adder = 1;
while (((yPos + adder) < _oBoard.getHeight()) && ((xPos + adder) < _oBoard.getWidth()))
{
if (_oBoard.getField((yPos + adder), (xPos + adder)).getState() == eStates.ARROW_NW)
{
return true;
}
adder++;
}
// is there a northwest arrow pointing at me?
adder = 1;
while (((yPos - adder) >= 0) && ((xPos - adder) >= 0))
{
if (_oBoard.getField((yPos - adder), (xPos - adder)).getState() == eStates.ARROW_SE)
{
return true;
}
adder++;
}
// is there a southwest arrow pointing at me?
adder = 1;
while (((yPos + adder) < _oBoard.getHeight()) && ((xPos - adder) >= 0))
{
if (_oBoard.getField((yPos + adder), (xPos - adder)).getState() == eStates.ARROW_NE)
{
return true;
}
adder++;
}
return false;
}
private boolean blockSpecialAlgorigthm()
{
boolean hasChanged = false;
boolean containsUpwardArrow = false;
boolean containsDownwardArrow = false;
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
System.out.println("1");
int columnStars = getCalculatedColumnStars(iX, true);
if (1 == columnStars)
{
containsUpwardArrow = false;
containsDownwardArrow = false;
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
System.out.println("2");
Field oField = _oBoard.getField(iY, iX);
if (oField.getState() == eStates.ARROW_N)
{
containsDownwardArrow = true;
}
if (oField.getState() == eStates.ARROW_S)
{
containsUpwardArrow = true;
}
}
if (containsUpwardArrow)
{
// collect Fields that are Pointed by Arrow
for (int iY = _oBoard.getHeight() -1; iY >= 0; iY--)
{
System.out.println("3");
Field oField = _oBoard.getField(iY, iX);
if (oField.getState() == eStates.ARROW_S)
{
for (int iY2 = iY; iY2 >= 0; iY2--)
{
System.out.println("4");
boolean tmpChanged = updateTmpFields(iY2, iX, eStatesDiff.BLOCKED);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
break;
}
}
}
if (containsDownwardArrow)
{
// collect Fields that are Pointed by Arrow
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
System.out.println("5");
Field oField = _oBoard.getField(iY, iX);
if (oField.getState() == eStates.ARROW_N)
{
for (int iY2 = iY; iY2 < _oBoard.getHeight(); iY2++)
{
System.out.println("6");
boolean tmpChanged = updateTmpFields(iY2, iX, eStatesDiff.BLOCKED);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
break;
}
}
}
}
}
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
int rowStars = getCalculatedColumnStars(iY, true);
if (1 == rowStars)
{
containsUpwardArrow = false;
containsDownwardArrow = false;
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
Field oField = _oBoard.getField(iY, iX);
if (oField.getState() == eStates.ARROW_W)
{
containsDownwardArrow = true;
}
if (oField.getState() == eStates.ARROW_E)
{
containsUpwardArrow = true;
}
}
if (containsUpwardArrow)
{
// collect Fields that are Pointed by Arrow
for (int iX = _oBoard.getWidth() -1; iX >= 0; iX--)
{
Field oField = _oBoard.getField(iY, iX);
if (oField.getState() == eStates.ARROW_E)
{
for (int iX2 = iX; iX2 >= 0; iX2--)
{
boolean tmpChanged = updateTmpFields(iY, iX2, eStatesDiff.BLOCKED);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
break;
}
}
}
if (containsDownwardArrow)
{
// collect Fields that are Pointed by Arrow
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
Field oField = _oBoard.getField(iY, iX);
if (oField.getState() == eStates.ARROW_W)
{
for (int iX2 = iX; iX2 < _oBoard.getHeight(); iX2++)
{
boolean tmpChanged = updateTmpFields(iY, iX2, eStatesDiff.BLOCKED);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
break;
}
}
}
}
}
return hasChanged;
}
/**
* Gibt an ob das Board gel�st ist
* @return solved - Enth�lt den Status ob das Editor Board gel�st ist
*/
public boolean isSolved()
{
boolean solved = true;
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
if (_tmpDiff[iY][iX] != eStatesDiff.BLOCKED &&
_tmpDiff[iY][iX] != eStatesDiff.ISSTAR)
{
return false;
}
}
}
return solved;
}
/**
* Die tempor�ren Felder werden hier geupdatet
* @param iY - Hier wird die Positon des Feldes auf der Y Achse angegeben
* @param iX - Hier wird die Positon des Feldes auf der X Achse angegeben
* @param state - Hier wird der Status des Feldes angegeben
* @return boolean - Hier wird zur�ckgegeben ob die tempor�ren Felder geupdatet wurden
*/
public boolean updateTmpFields(int iY, int iX, eStatesDiff state)
{
if (_tmpDiff[iY][iX] != eStatesDiff.BLOCKED &&
_tmpDiff[iY][iX] != eStatesDiff.ISSTAR)
{
_tmpDiff[iY][iX] = state;
return true;
}
return false;
}
/**
* Die Anzahl der Sterne f�r die Zeile werden hier zur�ckgegeben
* @param iY - Hier wird die Positon des Feldes auf der Zeile angegeben
* @param isMedium - Hier wird angegeben ob die Schwirigkeit mittel ist
* @return stars - Die anzahl der ausgerechneten Sterne f�r die Zeile wird hier zur�ckgegeben
*/
public int getCalculatedRowStars(int iY, boolean isMedium)
{
int stars = _oBoard.getCountStarsForRow(iY);
if (isMedium)
{
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
if (_tmpDiff[iY][iX] == eStatesDiff.ISSTAR)
{
stars--;
}
}
}
return stars;
}
/**
* Die Anzahl der Sterne f�r die Spalte werden hier zur�ckgegeben
* @param iX - Hier wird die Positon des Feldes f�r Die Spalte angegeben
* @param isMedium - Hier wird angegeben ob die Schwirigkeit mittel ist
* @return stars - Die anzahl der ausgerechneten Sterne f�r die Spalte wird hier zur�ckgegeben
*/
public int getCalculatedColumnStars(int iX, boolean isMedium)
{
int stars = _oBoard.getCountStarsForColumn(iX);
if (isMedium)
{
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
if (_tmpDiff[iY][iX] == eStatesDiff.ISSTAR)
{
stars--;
}
}
}
return stars;
}
/**
* Die Sterne die unl�sbar sind werden hier in eine HashMap eingetragen
*/
public void calculatedUnsolvableStars()
{
HashMap<Integer, Integer> unsolvableStar = null;
_unsolvableStars = new HashMap<Integer, HashMap<Integer, Integer>>();
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
unsolvableStar = new HashMap<Integer, Integer>();
Field oField = _oBoard.getField(iY, iX);
if (oField.getState() == eStates.STAR &&
_tmpDiff[iY][iX] != eStatesDiff.ISSTAR)
{
unsolvableStar.put(iY, iX);
_unsolvableStars.put(_unsolvableStars.size(), unsolvableStar);
}
}
}
}
/**
* Die Sterne die unl�sbar sind werden hier in eine HashMap eingetragen
* @param _unsolvableStars.size()- Hier wird die Anzahl der Sterne �bergeben die unl�sboar sind
* @param unsolvableStar - Hier wird das Stern �bergeben das unl�sbar ist
* @return _unsolvableStars - Hier werden die Sterne z�r�ckgegben die unl�sbar sind
*/
public Map<Integer, HashMap<Integer, Integer>> getUnsolvableStars()
{
return _unsolvableStars;
}
}
| false | true | public String checkDifficulty()
{
/**
* Dekleration der Variabeln f�r die Funktion checkDifficulty
*/
_tmpDiff = new eStatesDiff[_oBoard.getHeight()][_oBoard.getWidth()];
boolean isSolvable = false;
boolean doMediumSearch = false;
boolean doHardSearch = false;
boolean isSolved = false;
boolean hasChanged = true;
int tmpStarCount = 0;
int tmpEmptyFields = 0;
int counter = 0;
boolean foundEmptySpot = false;
int foundSpotX = -1;
int foundSpotY = -1;
int adder = 0;
// go through logicuntil game is solved or stop when no changes were made in last run
while (!isSolved &&
hasChanged)
{
hasChanged = false;
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
int rowStars = getCalculatedRowStars(iY, doMediumSearch);
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
int columnStars = getCalculatedColumnStars(iX, doMediumSearch);
Field oField = _oBoard.getField(iY, iX);
if (0 == columnStars ||
0 == rowStars ||
isArrow(oField.getState()))
{
boolean tmpChanged = updateTmpFields(iY, iX, eStatesDiff.BLOCKED);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
if (!isArrowPointingAtField(iY, iX))
{
boolean tmpChanged = updateTmpFields(iY, iX, eStatesDiff.BLOCKED);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
}
tmpEmptyFields = 0;
for (int iX2 = 0; iX2 < _oBoard.getWidth(); iX2++)
{
if (_tmpDiff[iY][iX2] != eStatesDiff.BLOCKED && _tmpDiff[iY][iX2] != eStatesDiff.ISSTAR)
{
tmpEmptyFields++;
}
}
if (tmpEmptyFields == rowStars)
{
for (int iX2 = 0; iX2 < _oBoard.getWidth(); iX2++)
{
if (_tmpDiff[iY][iX2] != eStatesDiff.BLOCKED)
{
boolean tmpChanged = updateTmpFields(iY, iX2, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
}
}
}
tmpEmptyFields = 0;
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
tmpEmptyFields = 0;
int columnStars = getCalculatedColumnStars(iX, doMediumSearch);
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
if (_tmpDiff[iY][iX] != eStatesDiff.BLOCKED && _tmpDiff[iY][iX] != eStatesDiff.ISSTAR)
{
tmpEmptyFields++;
}
}
if (tmpEmptyFields == columnStars)
{
for (int iY2 = 0; iY2 < _oBoard.getWidth(); iY2++)
{
if (_tmpDiff[iY2][iX] != eStatesDiff.BLOCKED)
{
boolean tmpChanged = updateTmpFields(iY2, iX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
}
}
}
// cross calculation
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
tmpEmptyFields = 0;
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
foundEmptySpot = false;
foundSpotX = -1;
foundSpotY = -1;
Field oField = _oBoard.getField(iY, iX);
if (oField.getState() == eStates.ARROW_SW)
{
adder = 1;
while (((iY + adder) < _oBoard.getHeight()) && ((iX - adder) >= 0))
{
if (_tmpDiff[iY + adder][iX - adder] != eStatesDiff.BLOCKED && _tmpDiff[iY + adder][iX - adder] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX - adder;
foundSpotY = iY + adder;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
adder++;
}
}
else if (oField.getState() == eStates.ARROW_SE)
{
adder = 1;
while (((iY + adder) < _oBoard.getHeight()) && ((iX + adder) < _oBoard.getWidth()))
{
if (_tmpDiff[iY + adder][iX + adder] != eStatesDiff.BLOCKED && _tmpDiff[iY + adder][iX + adder] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX + adder;
foundSpotY = iY + adder;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
adder++;
}
}
else if (oField.getState() == eStates.ARROW_NW)
{
adder = 1;
while (((iY - adder) >= 0) && ((iX - adder) >= 0))
{
if (_tmpDiff[iY - adder][iX - adder] != eStatesDiff.BLOCKED && _tmpDiff[iY - adder][iX - adder] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX - adder;
foundSpotY = iY - adder;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
adder++;
}
}
else if (oField.getState() == eStates.ARROW_NE)
{
adder = 1;
while (((iY - adder) >= 0) && ((iX + adder) < _oBoard.getWidth()))
{
if (_tmpDiff[iY - adder][iX + adder] != eStatesDiff.BLOCKED && _tmpDiff[iY - adder][iX + adder] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX + adder;
foundSpotY = iY - adder;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
adder++;
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
if (doHardSearch)
{
boolean upCheckDone = false;
boolean downCheckDone = false;
foundEmptySpot = false;
foundSpotX = -1;
foundSpotY = -1;
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
upCheckDone = false;
downCheckDone = false;
int columnStars = getCalculatedColumnStars(iX, doHardSearch);
if (1 <= columnStars)
{
// up check
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
foundEmptySpot = false;
Field oField = _oBoard.getField(iY, iX);
if (!upCheckDone && oField.getState() == eStates.ARROW_N)
{
upCheckDone = true;
for (int iTmpY = 0; iTmpY < iY; iTmpY++)
{
if (_tmpDiff[iTmpY][iX] != eStatesDiff.BLOCKED && _tmpDiff[iTmpY][iX] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX;
foundSpotY = iTmpY;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
// down check
for (int iY = _oBoard.getHeight()-1; iY >= 0; iY--)
{
foundEmptySpot = false;
Field oField = _oBoard.getField(iY, iX);
if (!downCheckDone && oField.getState() == eStates.ARROW_S)
{
downCheckDone = true;
for (int iTmpY = iY+1; iTmpY < _oBoard.getHeight(); iTmpY++)
{
if (_tmpDiff[iTmpY][iX] != eStatesDiff.BLOCKED && _tmpDiff[iTmpY][iX] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX;
foundSpotY = iTmpY;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
}
}
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
upCheckDone = false;
downCheckDone = false;
int rowStars = getCalculatedRowStars(iY, doHardSearch);
if (1 <= rowStars)
{
// up check
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
foundEmptySpot = false;
Field oField = _oBoard.getField(iY, iX);
if (!upCheckDone && oField.getState() == eStates.ARROW_W)
{
upCheckDone = true;
for (int iTmpX = 0; iTmpX < iX; iTmpX++)
{
if (_tmpDiff[iY][iTmpX] != eStatesDiff.BLOCKED && _tmpDiff[iY][iTmpX] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iTmpX;
foundSpotY = iY;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
// up check
for (int iX = _oBoard.getWidth()-1; iX >= 0; iX--)
{
foundEmptySpot = false;
Field oField = _oBoard.getField(iY, iX);
if (!downCheckDone && oField.getState() == eStates.ARROW_E)
{
downCheckDone = true;
for (int iTmpX = iX+1; iTmpX < _oBoard.getWidth(); iTmpX++)
{
if (_tmpDiff[iY][iTmpX] != eStatesDiff.BLOCKED && _tmpDiff[iY][iTmpX] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iTmpX;
foundSpotY = iY;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
}
}
boolean tmpChanged = blockSpecialAlgorigthm();
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
isSolved = isSolved();
counter++;
if (!isSolved && !doMediumSearch &&
(counter > 1 || !hasChanged))
{
// its medium
doMediumSearch = true;
hasChanged = true;
}
if (!isSolved && doMediumSearch && !doHardSearch &&
(counter > 4 || !hasChanged))
{
// its medium
doHardSearch = true;
hasChanged = true;
}
}
if (isSolved && !doMediumSearch && counter <2)
{
return BOARD_DIFFICULTY_EASY;
}
else if(isSolved && counter < 4 && !doHardSearch)
{
return BOARD_DIFFICULTY_MEDIUM;
}
else if(isSolved)
{
return BOARD_DIFFICULTY_HARD;
}
else
{
calculatedUnsolvableStars();
return BOARD_DIFFICULTY_NOT_SOLVABLE;
}
}
| public String checkDifficulty()
{
/**
* Dekleration der Variabeln f�r die Funktion checkDifficulty
*/
_tmpDiff = new eStatesDiff[_oBoard.getHeight()][_oBoard.getWidth()];
boolean isSolvable = false;
boolean doMediumSearch = false;
boolean doHardSearch = false;
boolean isSolved = false;
boolean hasChanged = true;
int tmpStarCount = 0;
int tmpEmptyFields = 0;
int counter = 0;
boolean foundEmptySpot = false;
int foundSpotX = -1;
int foundSpotY = -1;
int adder = 0;
// go through logicuntil game is solved or stop when no changes were made in last run
while (!isSolved &&
hasChanged)
{
hasChanged = false;
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
int rowStars = getCalculatedRowStars(iY, doMediumSearch);
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
int columnStars = getCalculatedColumnStars(iX, doMediumSearch);
Field oField = _oBoard.getField(iY, iX);
if (0 == columnStars ||
0 == rowStars ||
isArrow(oField.getState()))
{
boolean tmpChanged = updateTmpFields(iY, iX, eStatesDiff.BLOCKED);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
if (!isArrowPointingAtField(iY, iX))
{
boolean tmpChanged = updateTmpFields(iY, iX, eStatesDiff.BLOCKED);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
}
tmpEmptyFields = 0;
for (int iX2 = 0; iX2 < _oBoard.getWidth(); iX2++)
{
if (_tmpDiff[iY][iX2] != eStatesDiff.BLOCKED && _tmpDiff[iY][iX2] != eStatesDiff.ISSTAR)
{
tmpEmptyFields++;
}
}
if (tmpEmptyFields == rowStars)
{
for (int iX2 = 0; iX2 < _oBoard.getWidth(); iX2++)
{
if (_tmpDiff[iY][iX2] != eStatesDiff.BLOCKED)
{
boolean tmpChanged = updateTmpFields(iY, iX2, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
}
}
}
tmpEmptyFields = 0;
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
tmpEmptyFields = 0;
int columnStars = getCalculatedColumnStars(iX, doMediumSearch);
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
if (_tmpDiff[iY][iX] != eStatesDiff.BLOCKED && _tmpDiff[iY][iX] != eStatesDiff.ISSTAR)
{
tmpEmptyFields++;
}
}
if (tmpEmptyFields == columnStars)
{
for (int iY2 = 0; iY2 < _oBoard.getWidth(); iY2++)
{
if (_tmpDiff[iY2][iX] != eStatesDiff.BLOCKED)
{
boolean tmpChanged = updateTmpFields(iY2, iX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
}
}
}
// cross calculation
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
tmpEmptyFields = 0;
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
foundEmptySpot = false;
foundSpotX = -1;
foundSpotY = -1;
Field oField = _oBoard.getField(iY, iX);
if (oField.getState() == eStates.ARROW_SW)
{
adder = 1;
while (((iY + adder) < _oBoard.getHeight()) && ((iX - adder) >= 0))
{
if (_tmpDiff[iY + adder][iX - adder] != eStatesDiff.BLOCKED && _tmpDiff[iY + adder][iX - adder] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX - adder;
foundSpotY = iY + adder;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
adder++;
}
}
else if (oField.getState() == eStates.ARROW_SE)
{
adder = 1;
while (((iY + adder) < _oBoard.getHeight()) && ((iX + adder) < _oBoard.getWidth()))
{
if (_tmpDiff[iY + adder][iX + adder] != eStatesDiff.BLOCKED && _tmpDiff[iY + adder][iX + adder] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX + adder;
foundSpotY = iY + adder;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
adder++;
}
}
else if (oField.getState() == eStates.ARROW_NW)
{
adder = 1;
while (((iY - adder) >= 0) && ((iX - adder) >= 0))
{
if (_tmpDiff[iY - adder][iX - adder] != eStatesDiff.BLOCKED && _tmpDiff[iY - adder][iX - adder] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX - adder;
foundSpotY = iY - adder;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
adder++;
}
}
else if (oField.getState() == eStates.ARROW_NE)
{
adder = 1;
while (((iY - adder) >= 0) && ((iX + adder) < _oBoard.getWidth()))
{
if (_tmpDiff[iY - adder][iX + adder] != eStatesDiff.BLOCKED && _tmpDiff[iY - adder][iX + adder] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX + adder;
foundSpotY = iY - adder;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
adder++;
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
if (doHardSearch)
{
boolean upCheckDone = false;
boolean downCheckDone = false;
foundEmptySpot = false;
foundSpotX = -1;
foundSpotY = -1;
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
upCheckDone = false;
downCheckDone = false;
int columnStars = getCalculatedColumnStars(iX, doHardSearch);
if (1 <= columnStars)
{
// up check
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
foundEmptySpot = false;
Field oField = _oBoard.getField(iY, iX);
if (!upCheckDone && oField.getState() == eStates.ARROW_N)
{
upCheckDone = true;
for (int iTmpY = 0; iTmpY < iY; iTmpY++)
{
if (_tmpDiff[iTmpY][iX] != eStatesDiff.BLOCKED && _tmpDiff[iTmpY][iX] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX;
foundSpotY = iTmpY;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
// down check
for (int iY = _oBoard.getHeight()-1; iY >= 0; iY--)
{
foundEmptySpot = false;
Field oField = _oBoard.getField(iY, iX);
if (!downCheckDone && oField.getState() == eStates.ARROW_S)
{
downCheckDone = true;
for (int iTmpY = iY+1; iTmpY < _oBoard.getHeight(); iTmpY++)
{
if (_tmpDiff[iTmpY][iX] != eStatesDiff.BLOCKED && _tmpDiff[iTmpY][iX] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iX;
foundSpotY = iTmpY;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
}
}
for (int iY = 0; iY < _oBoard.getHeight(); iY++)
{
upCheckDone = false;
downCheckDone = false;
int rowStars = getCalculatedRowStars(iY, doHardSearch);
if (1 <= rowStars)
{
// up check
for (int iX = 0; iX < _oBoard.getWidth(); iX++)
{
foundEmptySpot = false;
Field oField = _oBoard.getField(iY, iX);
if (!upCheckDone && oField.getState() == eStates.ARROW_W)
{
upCheckDone = true;
for (int iTmpX = 0; iTmpX < iX; iTmpX++)
{
if (_tmpDiff[iY][iTmpX] != eStatesDiff.BLOCKED && _tmpDiff[iY][iTmpX] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iTmpX;
foundSpotY = iY;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
// up check
for (int iX = _oBoard.getWidth()-1; iX >= 0; iX--)
{
foundEmptySpot = false;
Field oField = _oBoard.getField(iY, iX);
if (!downCheckDone && oField.getState() == eStates.ARROW_E)
{
downCheckDone = true;
for (int iTmpX = iX+1; iTmpX < _oBoard.getWidth(); iTmpX++)
{
if (_tmpDiff[iY][iTmpX] != eStatesDiff.BLOCKED && _tmpDiff[iY][iTmpX] != eStatesDiff.ISSTAR)
{
if (!foundEmptySpot)
{
foundSpotX = iTmpX;
foundSpotY = iY;
foundEmptySpot = true;
}
else
{
foundSpotX = -1;
foundSpotY = -1;
foundEmptySpot = false;
break;
}
}
}
if (foundEmptySpot)
{
boolean tmpChanged = updateTmpFields(foundSpotY, foundSpotX, eStatesDiff.ISSTAR);
if (!hasChanged)
{
hasChanged = tmpChanged;
}
foundSpotX = -1;
foundSpotY = -1;
}
}
}
}
}
if (!hasChanged)
{
boolean tmpChanged = blockSpecialAlgorigthm();
if (!hasChanged)
{
hasChanged = tmpChanged;
}
}
}
isSolved = isSolved();
counter++;
if (!isSolved && !doMediumSearch &&
(counter > 1 || !hasChanged))
{
// its medium
doMediumSearch = true;
hasChanged = true;
}
if (!isSolved && doMediumSearch && !doHardSearch &&
(counter > 5 || !hasChanged))
{
// its medium
doHardSearch = true;
hasChanged = true;
}
}
if (isSolved && !doMediumSearch && counter <2)
{
return BOARD_DIFFICULTY_EASY;
}
else if(isSolved && counter < 6)
{
return BOARD_DIFFICULTY_MEDIUM;
}
else if(isSolved)
{
return BOARD_DIFFICULTY_HARD;
}
else
{
calculatedUnsolvableStars();
return BOARD_DIFFICULTY_NOT_SOLVABLE;
}
}
|
diff --git a/src/com/jpmiii/Realmscraft/RealmscraftListener.java b/src/com/jpmiii/Realmscraft/RealmscraftListener.java
index 519ffad..59d7d81 100644
--- a/src/com/jpmiii/Realmscraft/RealmscraftListener.java
+++ b/src/com/jpmiii/Realmscraft/RealmscraftListener.java
@@ -1,114 +1,114 @@
package com.jpmiii.Realmscraft;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.bukkit.event.Listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import com.jpmiii.Realmscraft.Realmscraft;
public class RealmscraftListener implements Listener {
private Realmscraft plugin;
public RealmscraftListener(Realmscraft plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.MONITOR)
public void normalLogin(PlayerLoginEvent event) {
try {
Realmscraft.dbm.loadPlayer(event.getPlayer());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
event.getPlayer().setCompassTarget(plugin.portalLoc);
}
@EventHandler(priority = EventPriority.MONITOR)
public void portalStep(PlayerInteractEvent event) {
if (event.getAction() == Action.PHYSICAL && !plugin.getConfig().getString("portalServer").isEmpty()) {
//plugin.portalLoc = new Location(event.getPlayer().getWorld(),0,61, 0) ;
if (event.getClickedBlock().getLocation().distance(plugin.portalLoc) <= 5 && !plugin.hotPlayers.containsKey(event.getPlayer().getName())){
- if(plugin.perms.has(event.getPlayer(), "realmscraft.portal")) {
- event.getPlayer().saveData();
+ if(plugin.perms.has(event.getPlayer().getPlayer(), "realmscraft.portal")) {
+ plugin.getServer().getPlayer(event.getPlayer().getName()).updateInventory();
Realmscraft.dbm.savePlayer(event.getPlayer());
plugin.hotPlayers.put(event.getPlayer().getName(), System.currentTimeMillis( ));
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b);
try {
out.writeUTF("Connect");
out.writeUTF(plugin.getConfig().getString("portalServer")); // Target Server
} catch (IOException e) {
// Can never happen
}
event.getPlayer().sendPluginMessage(this.plugin, "BungeeCord", b.toByteArray());
this.plugin.getLogger().info(event.getClickedBlock().getLocation().toString());
Realmscraft.dbm.savePlayer(event.getPlayer());
}
}
}
}
@EventHandler
public void PlayerBed(PlayerBedEnterEvent event) {
if (plugin.perms.has(event.getPlayer(), "realmscraft.sleep") && !plugin.getConfig().getString("sleepServer").isEmpty()) {
String[] msg = {"Would you like to goto", "Dream Land?"};
event.getPlayer().sendMessage(msg);
}
}
@EventHandler
public void PlayerYes(AsyncPlayerChatEvent event) {
if (plugin.perms.has(event.getPlayer(), "realmscraft.sleep") && !plugin.getConfig().getString("sleepServer").isEmpty()) {
//plugin.getLogger().info(event.getPlayer().getName() + " has permission");
if (event.getPlayer().isSleeping()) {
//plugin.getLogger().info(event.getPlayer().getName() + " has said" + event.getMessage());
if(event.getMessage().equalsIgnoreCase("yes")) {
plugin.combatApi.untagPlayer(event.getPlayer().getName());
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b);
try {
out.writeUTF("Connect");
out.writeUTF(plugin.getConfig().getString("sleepServer")); // Target Server
} catch (IOException e) {
// Can never happen
}
event.getPlayer().sendPluginMessage(this.plugin, "BungeeCord", b.toByteArray());
}
}
}
}
}
| true | true | public void portalStep(PlayerInteractEvent event) {
if (event.getAction() == Action.PHYSICAL && !plugin.getConfig().getString("portalServer").isEmpty()) {
//plugin.portalLoc = new Location(event.getPlayer().getWorld(),0,61, 0) ;
if (event.getClickedBlock().getLocation().distance(plugin.portalLoc) <= 5 && !plugin.hotPlayers.containsKey(event.getPlayer().getName())){
if(plugin.perms.has(event.getPlayer(), "realmscraft.portal")) {
event.getPlayer().saveData();
Realmscraft.dbm.savePlayer(event.getPlayer());
plugin.hotPlayers.put(event.getPlayer().getName(), System.currentTimeMillis( ));
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b);
try {
out.writeUTF("Connect");
out.writeUTF(plugin.getConfig().getString("portalServer")); // Target Server
} catch (IOException e) {
// Can never happen
}
event.getPlayer().sendPluginMessage(this.plugin, "BungeeCord", b.toByteArray());
this.plugin.getLogger().info(event.getClickedBlock().getLocation().toString());
Realmscraft.dbm.savePlayer(event.getPlayer());
}
}
}
}
| public void portalStep(PlayerInteractEvent event) {
if (event.getAction() == Action.PHYSICAL && !plugin.getConfig().getString("portalServer").isEmpty()) {
//plugin.portalLoc = new Location(event.getPlayer().getWorld(),0,61, 0) ;
if (event.getClickedBlock().getLocation().distance(plugin.portalLoc) <= 5 && !plugin.hotPlayers.containsKey(event.getPlayer().getName())){
if(plugin.perms.has(event.getPlayer().getPlayer(), "realmscraft.portal")) {
plugin.getServer().getPlayer(event.getPlayer().getName()).updateInventory();
Realmscraft.dbm.savePlayer(event.getPlayer());
plugin.hotPlayers.put(event.getPlayer().getName(), System.currentTimeMillis( ));
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b);
try {
out.writeUTF("Connect");
out.writeUTF(plugin.getConfig().getString("portalServer")); // Target Server
} catch (IOException e) {
// Can never happen
}
event.getPlayer().sendPluginMessage(this.plugin, "BungeeCord", b.toByteArray());
this.plugin.getLogger().info(event.getClickedBlock().getLocation().toString());
Realmscraft.dbm.savePlayer(event.getPlayer());
}
}
}
}
|
diff --git a/src/main/java/it/unito/geosummly/Main.java b/src/main/java/it/unito/geosummly/Main.java
index e784c9e..612ce32 100644
--- a/src/main/java/it/unito/geosummly/Main.java
+++ b/src/main/java/it/unito/geosummly/Main.java
@@ -1,157 +1,157 @@
package it.unito.geosummly;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import com.google.gson.Gson;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
import fi.foyt.foursquare.api.FoursquareApiException;
public class Main {
public static Logger logger = Logger.getLogger(Main.class.toString());
public static void main(String[] args) throws FoursquareApiException, UnknownHostException{
/***************************************************************************************/
/******************************CREATE THE BOUNDING BOX**********************************/
/***************************************************************************************/
double north=45.057; //north coordinate of the bounding box
double south=45.0390186;
double west=7.6600;
double east=7.6854548;
int cells_number=20; //Number N of cells
BoundingBox bbox=new BoundingBox(north, south, west, east); //Initialize the bounding box
ArrayList<BoundingBox> data=new ArrayList<BoundingBox>(); //Data structure
//Create a N*N grid based on the bounding box
Grid grid=new Grid();
grid.setCellsNumber(cells_number);
grid.setBbox(bbox);
grid.setStructure(data);
grid.createCells();
/***************************************************************************************/
/****************************COLLECT ALL THE GEOPOINTS AND******************************/
/****************************CREATE THE TRANSFORMATION MATRIX***************************/
/***************************************************************************************/
//Initialize a MongoDB instance
MongoClient mongoClient=new MongoClient("localhost");
DB db=mongoClient.getDB("VenueDB");
DBCollection coll=db.getCollection("ResultVenues");
//Initialize a Gson instance and declare the document which will contain the JSON results for MongoDB
Gson gson=new Gson();
BasicDBObject doc;
//Initialize the transformation matrix and its parameters
ArrayList<ArrayList<Double>> matrix=new ArrayList<ArrayList<Double>>();
HashMap<String, Integer> map=new HashMap<String, Integer>(); //HashMap of all the distinct categories
ArrayList<String> header=new ArrayList<String>(); //Sorted list of the distinct category (related to the hash map)
- TransformationMatrix t_matrix=new TransformationMatrix();
- t_matrix.setMatrix(matrix);
- t_matrix.setMap(map);
- t_matrix.setHeader(header);
+ TransformationMatrix tm=new TransformationMatrix();
+ tm.setMatrix(matrix);
+ tm.setMap(map);
+ tm.setHeader(header);
ArrayList<Double> row_of_matrix; //row of the transformation matrix (one for each cell);
//Support variables for transformation matrix task
int cat_num=0; //total number of categories of a single cell
int tot_num=0; //overall number of categories
double norm_lat=0; //normalized value in [0,1] of latitude
double norm_lng=0;
ArrayList<String> distinct_list; //list of all the distinct categories for a single cell
ArrayList<Integer> occurrences_list; //list of the occurrences of the distinct categories for a single cell
//Download venues informations
FoursquareSearchVenues fsv=new FoursquareSearchVenues();
ArrayList<FoursquareDataObject> venueInfo;
for(BoundingBox b: data){
logger.log(Level.INFO, "Fetching 4square metadata of the cell: " + b.toString());
//Venues of a single cell
venueInfo=fsv.searchVenues(b.getRow(), b.getColumn(), b.getNorth(), b.getSouth(), b.getWest(), b.getEast());
for(FoursquareDataObject fdo: venueInfo){
//Serialize with Gson
String obj=gson.toJson(fdo);
//Initialize the document which will contain the JSON result parsed for MongoDB and insert this document into MongoDB collection
doc= (BasicDBObject) JSON.parse(obj);
coll.insert(doc);
}
//Transformation matrix task
cat_num=fsv.getCategoriesNumber(venueInfo);//set the total number of categories of the cell
distinct_list=fsv.createCategoryList(venueInfo);
occurrences_list=fsv.getCategoryOccurences(venueInfo, distinct_list);
- t_matrix.updateMap(distinct_list);//update the hash map
- norm_lat=t_matrix.normalizeCoordinate(-90, 90, b.getCenterLat()); //get the normalized value of latitude coordinate
- norm_lng=t_matrix.normalizeCoordinate(-180, 180, b.getCenterLng());
- row_of_matrix=t_matrix.fillRow(occurrences_list, distinct_list, cat_num, norm_lat, norm_lng, b.getArea()); //create a consistent row (related to the categories)
- if(tot_num < row_of_matrix.size()-2)
- tot_num=row_of_matrix.size()-2; //update the overall number of categories
- t_matrix.addRow(row_of_matrix);
+ tm.updateMap(distinct_list);//update the hash map
+ norm_lat=tm.normalizeCoordinate(-90, 90, b.getCenterLat()); //get the normalized value of latitude coordinate
+ norm_lng=tm.normalizeCoordinate(-180, 180, b.getCenterLng());
+ row_of_matrix=tm.fillRow(occurrences_list, distinct_list, cat_num, norm_lat, norm_lng, b.getArea()); //create a consistent row (related to the categories)
+ if(tot_num < row_of_matrix.size())
+ tot_num=row_of_matrix.size(); //update the overall number of categories
+ tm.addRow(row_of_matrix);
}
- t_matrix.fixRowsLength(tot_num); //update rows length for consistency
+ tm.fixRowsLength(tot_num); //update rows length for consistency
// write down the transformation matrix to a file
ByteArrayOutputStream bout = new ByteArrayOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(bout);
try {
CSVPrinter csv = new CSVPrinter(osw, CSVFormat.DEFAULT);
// write the header of the matrix
- ArrayList<String> hdr=t_matrix.getHeader();
+ ArrayList<String> hdr=tm.getHeader();
for(String s: hdr) {
csv.print(s);
}
csv.println();
// iterate per each row of the matrix
- ArrayList<ArrayList<Double>> tm=t_matrix.getMatrix();
- for(ArrayList<Double> a: tm) {
+ ArrayList<ArrayList<Double>> m=tm.getMatrix();
+ for(ArrayList<Double> a: m) {
for(Double d: a) {
csv.print(d);
}
csv.println();
}
csv.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream ("output/matrix.csv");
bout.writeTo(outputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Print JSON files (just for debug)
/*DBCursor cursorDocJSON = coll.find();
while (cursorDocJSON.hasNext()) {
System.out.println(cursorDocJSON.next());
}*/
}
}
| false | true | public static void main(String[] args) throws FoursquareApiException, UnknownHostException{
/***************************************************************************************/
/******************************CREATE THE BOUNDING BOX**********************************/
/***************************************************************************************/
double north=45.057; //north coordinate of the bounding box
double south=45.0390186;
double west=7.6600;
double east=7.6854548;
int cells_number=20; //Number N of cells
BoundingBox bbox=new BoundingBox(north, south, west, east); //Initialize the bounding box
ArrayList<BoundingBox> data=new ArrayList<BoundingBox>(); //Data structure
//Create a N*N grid based on the bounding box
Grid grid=new Grid();
grid.setCellsNumber(cells_number);
grid.setBbox(bbox);
grid.setStructure(data);
grid.createCells();
/***************************************************************************************/
/****************************COLLECT ALL THE GEOPOINTS AND******************************/
/****************************CREATE THE TRANSFORMATION MATRIX***************************/
/***************************************************************************************/
//Initialize a MongoDB instance
MongoClient mongoClient=new MongoClient("localhost");
DB db=mongoClient.getDB("VenueDB");
DBCollection coll=db.getCollection("ResultVenues");
//Initialize a Gson instance and declare the document which will contain the JSON results for MongoDB
Gson gson=new Gson();
BasicDBObject doc;
//Initialize the transformation matrix and its parameters
ArrayList<ArrayList<Double>> matrix=new ArrayList<ArrayList<Double>>();
HashMap<String, Integer> map=new HashMap<String, Integer>(); //HashMap of all the distinct categories
ArrayList<String> header=new ArrayList<String>(); //Sorted list of the distinct category (related to the hash map)
TransformationMatrix t_matrix=new TransformationMatrix();
t_matrix.setMatrix(matrix);
t_matrix.setMap(map);
t_matrix.setHeader(header);
ArrayList<Double> row_of_matrix; //row of the transformation matrix (one for each cell);
//Support variables for transformation matrix task
int cat_num=0; //total number of categories of a single cell
int tot_num=0; //overall number of categories
double norm_lat=0; //normalized value in [0,1] of latitude
double norm_lng=0;
ArrayList<String> distinct_list; //list of all the distinct categories for a single cell
ArrayList<Integer> occurrences_list; //list of the occurrences of the distinct categories for a single cell
//Download venues informations
FoursquareSearchVenues fsv=new FoursquareSearchVenues();
ArrayList<FoursquareDataObject> venueInfo;
for(BoundingBox b: data){
logger.log(Level.INFO, "Fetching 4square metadata of the cell: " + b.toString());
//Venues of a single cell
venueInfo=fsv.searchVenues(b.getRow(), b.getColumn(), b.getNorth(), b.getSouth(), b.getWest(), b.getEast());
for(FoursquareDataObject fdo: venueInfo){
//Serialize with Gson
String obj=gson.toJson(fdo);
//Initialize the document which will contain the JSON result parsed for MongoDB and insert this document into MongoDB collection
doc= (BasicDBObject) JSON.parse(obj);
coll.insert(doc);
}
//Transformation matrix task
cat_num=fsv.getCategoriesNumber(venueInfo);//set the total number of categories of the cell
distinct_list=fsv.createCategoryList(venueInfo);
occurrences_list=fsv.getCategoryOccurences(venueInfo, distinct_list);
t_matrix.updateMap(distinct_list);//update the hash map
norm_lat=t_matrix.normalizeCoordinate(-90, 90, b.getCenterLat()); //get the normalized value of latitude coordinate
norm_lng=t_matrix.normalizeCoordinate(-180, 180, b.getCenterLng());
row_of_matrix=t_matrix.fillRow(occurrences_list, distinct_list, cat_num, norm_lat, norm_lng, b.getArea()); //create a consistent row (related to the categories)
if(tot_num < row_of_matrix.size()-2)
tot_num=row_of_matrix.size()-2; //update the overall number of categories
t_matrix.addRow(row_of_matrix);
}
t_matrix.fixRowsLength(tot_num); //update rows length for consistency
// write down the transformation matrix to a file
ByteArrayOutputStream bout = new ByteArrayOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(bout);
try {
CSVPrinter csv = new CSVPrinter(osw, CSVFormat.DEFAULT);
// write the header of the matrix
ArrayList<String> hdr=t_matrix.getHeader();
for(String s: hdr) {
csv.print(s);
}
csv.println();
// iterate per each row of the matrix
ArrayList<ArrayList<Double>> tm=t_matrix.getMatrix();
for(ArrayList<Double> a: tm) {
for(Double d: a) {
csv.print(d);
}
csv.println();
}
csv.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream ("output/matrix.csv");
bout.writeTo(outputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Print JSON files (just for debug)
/*DBCursor cursorDocJSON = coll.find();
while (cursorDocJSON.hasNext()) {
System.out.println(cursorDocJSON.next());
}*/
}
| public static void main(String[] args) throws FoursquareApiException, UnknownHostException{
/***************************************************************************************/
/******************************CREATE THE BOUNDING BOX**********************************/
/***************************************************************************************/
double north=45.057; //north coordinate of the bounding box
double south=45.0390186;
double west=7.6600;
double east=7.6854548;
int cells_number=20; //Number N of cells
BoundingBox bbox=new BoundingBox(north, south, west, east); //Initialize the bounding box
ArrayList<BoundingBox> data=new ArrayList<BoundingBox>(); //Data structure
//Create a N*N grid based on the bounding box
Grid grid=new Grid();
grid.setCellsNumber(cells_number);
grid.setBbox(bbox);
grid.setStructure(data);
grid.createCells();
/***************************************************************************************/
/****************************COLLECT ALL THE GEOPOINTS AND******************************/
/****************************CREATE THE TRANSFORMATION MATRIX***************************/
/***************************************************************************************/
//Initialize a MongoDB instance
MongoClient mongoClient=new MongoClient("localhost");
DB db=mongoClient.getDB("VenueDB");
DBCollection coll=db.getCollection("ResultVenues");
//Initialize a Gson instance and declare the document which will contain the JSON results for MongoDB
Gson gson=new Gson();
BasicDBObject doc;
//Initialize the transformation matrix and its parameters
ArrayList<ArrayList<Double>> matrix=new ArrayList<ArrayList<Double>>();
HashMap<String, Integer> map=new HashMap<String, Integer>(); //HashMap of all the distinct categories
ArrayList<String> header=new ArrayList<String>(); //Sorted list of the distinct category (related to the hash map)
TransformationMatrix tm=new TransformationMatrix();
tm.setMatrix(matrix);
tm.setMap(map);
tm.setHeader(header);
ArrayList<Double> row_of_matrix; //row of the transformation matrix (one for each cell);
//Support variables for transformation matrix task
int cat_num=0; //total number of categories of a single cell
int tot_num=0; //overall number of categories
double norm_lat=0; //normalized value in [0,1] of latitude
double norm_lng=0;
ArrayList<String> distinct_list; //list of all the distinct categories for a single cell
ArrayList<Integer> occurrences_list; //list of the occurrences of the distinct categories for a single cell
//Download venues informations
FoursquareSearchVenues fsv=new FoursquareSearchVenues();
ArrayList<FoursquareDataObject> venueInfo;
for(BoundingBox b: data){
logger.log(Level.INFO, "Fetching 4square metadata of the cell: " + b.toString());
//Venues of a single cell
venueInfo=fsv.searchVenues(b.getRow(), b.getColumn(), b.getNorth(), b.getSouth(), b.getWest(), b.getEast());
for(FoursquareDataObject fdo: venueInfo){
//Serialize with Gson
String obj=gson.toJson(fdo);
//Initialize the document which will contain the JSON result parsed for MongoDB and insert this document into MongoDB collection
doc= (BasicDBObject) JSON.parse(obj);
coll.insert(doc);
}
//Transformation matrix task
cat_num=fsv.getCategoriesNumber(venueInfo);//set the total number of categories of the cell
distinct_list=fsv.createCategoryList(venueInfo);
occurrences_list=fsv.getCategoryOccurences(venueInfo, distinct_list);
tm.updateMap(distinct_list);//update the hash map
norm_lat=tm.normalizeCoordinate(-90, 90, b.getCenterLat()); //get the normalized value of latitude coordinate
norm_lng=tm.normalizeCoordinate(-180, 180, b.getCenterLng());
row_of_matrix=tm.fillRow(occurrences_list, distinct_list, cat_num, norm_lat, norm_lng, b.getArea()); //create a consistent row (related to the categories)
if(tot_num < row_of_matrix.size())
tot_num=row_of_matrix.size(); //update the overall number of categories
tm.addRow(row_of_matrix);
}
tm.fixRowsLength(tot_num); //update rows length for consistency
// write down the transformation matrix to a file
ByteArrayOutputStream bout = new ByteArrayOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(bout);
try {
CSVPrinter csv = new CSVPrinter(osw, CSVFormat.DEFAULT);
// write the header of the matrix
ArrayList<String> hdr=tm.getHeader();
for(String s: hdr) {
csv.print(s);
}
csv.println();
// iterate per each row of the matrix
ArrayList<ArrayList<Double>> m=tm.getMatrix();
for(ArrayList<Double> a: m) {
for(Double d: a) {
csv.print(d);
}
csv.println();
}
csv.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream ("output/matrix.csv");
bout.writeTo(outputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Print JSON files (just for debug)
/*DBCursor cursorDocJSON = coll.find();
while (cursorDocJSON.hasNext()) {
System.out.println(cursorDocJSON.next());
}*/
}
|
diff --git a/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java b/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java
index 9dcbc6065..ceca1ba3f 100644
--- a/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java
+++ b/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java
@@ -1,1282 +1,1285 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.adapter;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicReference;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Html.TagHandler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.timsu.astrid.R;
import com.todoroo.andlib.data.Property;
import com.todoroo.andlib.data.Property.IntegerProperty;
import com.todoroo.andlib.data.Property.LongProperty;
import com.todoroo.andlib.data.Property.StringProperty;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.utility.AndroidUtilities;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.andlib.utility.Pair;
import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.activity.TaskListFragment;
import com.todoroo.astrid.api.AstridApiConstants;
import com.todoroo.astrid.api.TaskAction;
import com.todoroo.astrid.api.TaskDecoration;
import com.todoroo.astrid.api.TaskDecorationExposer;
import com.todoroo.astrid.core.LinkActionExposer;
import com.todoroo.astrid.data.Metadata;
import com.todoroo.astrid.data.RemoteModel;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.data.TaskAttachment;
import com.todoroo.astrid.data.User;
import com.todoroo.astrid.files.FilesAction;
import com.todoroo.astrid.files.FilesControlSet;
import com.todoroo.astrid.helper.AsyncImageView;
import com.todoroo.astrid.helper.TaskAdapterAddOnManager;
import com.todoroo.astrid.notes.NotesAction;
import com.todoroo.astrid.notes.NotesDecorationExposer;
import com.todoroo.astrid.service.TaskService;
import com.todoroo.astrid.service.ThemeService;
import com.todoroo.astrid.tags.TaskToTagMetadata;
import com.todoroo.astrid.timers.TimerDecorationExposer;
import com.todoroo.astrid.ui.CheckableImageView;
import com.todoroo.astrid.utility.Constants;
import com.todoroo.astrid.utility.ResourceDrawableCache;
/**
* Adapter for displaying a user's tasks as a list
*
* @author Tim Su <[email protected]>
*
*/
public class TaskAdapter extends CursorAdapter implements Filterable {
public interface OnCompletedTaskListener {
public void onCompletedTask(Task item, boolean newState);
}
public static final String DETAIL_SEPARATOR = " | "; //$NON-NLS-1$
public static final String BROADCAST_EXTRA_TASK = "model"; //$NON-NLS-1$
@SuppressWarnings("nls")
private static final LongProperty TASK_RABBIT_ID = Metadata.ID.cloneAs(TaskListFragment.TR_METADATA_JOIN, "taskRabId");
@SuppressWarnings("nls")
private static final StringProperty TAGS = new StringProperty(null, "group_concat(" + TaskListFragment.TAGS_METADATA_JOIN + "." + TaskToTagMetadata.TAG_NAME.name + ", ' | ')").as("tags");
@SuppressWarnings("nls")
private static final LongProperty FILE_ID_PROPERTY = TaskAttachment.ID.cloneAs(TaskListFragment.FILE_METADATA_JOIN, "fileId");
@SuppressWarnings("nls")
private static final IntegerProperty HAS_NOTES_PROPERTY = new IntegerProperty(null, "length(" + Task.NOTES + ") > 0").as("hasNotes");
private static final StringProperty PICTURE = User.PICTURE.cloneAs(TaskListFragment.USER_IMAGE_JOIN, null);
// --- other constants
/** Properties that need to be read from the action item */
public static final Property<?>[] PROPERTIES = new Property<?>[] {
Task.ID,
Task.UUID,
Task.TITLE,
Task.IS_READONLY,
Task.IS_PUBLIC,
Task.IMPORTANCE,
Task.DUE_DATE,
Task.COMPLETION_DATE,
Task.MODIFICATION_DATE,
Task.HIDE_UNTIL,
Task.DELETION_DATE,
Task.DETAILS,
Task.ELAPSED_SECONDS,
Task.TIMER_START,
Task.RECURRENCE,
Task.USER_ID,
Task.USER,
Task.REMINDER_LAST,
Task.SOCIAL_REMINDER,
PICTURE,
HAS_NOTES_PROPERTY, // Whether or not the task has notes
TASK_RABBIT_ID, // Task rabbit metadata id (non-zero means it exists)
TAGS, // Concatenated list of tags
FILE_ID_PROPERTY // File id
};
public static final Property<?>[] BASIC_PROPERTIES = new Property<?>[] {
Task.ID,
Task.UUID,
Task.TITLE,
Task.IS_READONLY,
Task.IS_PUBLIC,
Task.IMPORTANCE,
Task.RECURRENCE,
Task.COMPLETION_DATE,
Task.HIDE_UNTIL,
Task.DELETION_DATE
};
public static final int[] IMPORTANCE_RESOURCES = new int[] {
R.drawable.check_box_1,
R.drawable.check_box_2,
R.drawable.check_box_3,
R.drawable.check_box_4,
};
public static final int[] IMPORTANCE_RESOURCES_CHECKED = new int[] {
R.drawable.check_box_checked_1,
R.drawable.check_box_checked_2,
R.drawable.check_box_checked_3,
R.drawable.check_box_checked_4,
};
public static final int[] IMPORTANCE_RESOURCES_LARGE = new int[] {
R.drawable.check_box_large_1,
R.drawable.check_box_large_2,
R.drawable.check_box_large_3,
R.drawable.check_box_large_4,
};
public static final int[] IMPORTANCE_REPEAT_RESOURCES = new int[] {
R.drawable.check_box_repeat_1,
R.drawable.check_box_repeat_2,
R.drawable.check_box_repeat_3,
R.drawable.check_box_repeat_4,
};
public static final int[] IMPORTANCE_REPEAT_RESOURCES_CHECKED = new int[] {
R.drawable.check_box_repeat_checked_1,
R.drawable.check_box_repeat_checked_2,
R.drawable.check_box_repeat_checked_3,
R.drawable.check_box_repeat_checked_4,
};
private static final Drawable[] IMPORTANCE_DRAWABLES = new Drawable[IMPORTANCE_RESOURCES.length];
private static final Drawable[] IMPORTANCE_DRAWABLES_CHECKED = new Drawable[IMPORTANCE_RESOURCES_CHECKED.length];
private static final Drawable[] IMPORTANCE_DRAWABLES_LARGE = new Drawable[IMPORTANCE_RESOURCES_LARGE.length];
private static final Drawable[] IMPORTANCE_REPEAT_DRAWABLES = new Drawable[IMPORTANCE_REPEAT_RESOURCES.length];
private static final Drawable[] IMPORTANCE_REPEAT_DRAWABLES_CHECKED = new Drawable[IMPORTANCE_REPEAT_RESOURCES_CHECKED.length];
// --- instance variables
@Autowired
protected TaskService taskService;
public static int APPLY_LISTENERS_PARENT = 0;
public static int APPLY_LISTENERS_ROW_BODY= 1;
public static int APPLY_LISTENERS_NONE = 2;
protected final Context context;
protected final TaskListFragment fragment;
protected final Resources resources;
protected final HashMap<Object, Boolean> completedItems = new HashMap<Object, Boolean>(0);
protected OnCompletedTaskListener onCompletedTaskListener = null;
public boolean isFling = false;
protected final int resource;
protected final LayoutInflater inflater;
private DetailLoaderThread detailLoader;
private int fontSize;
protected int applyListeners = APPLY_LISTENERS_PARENT;
private long mostRecentlyMade = -1;
private final ScaleAnimation scaleAnimation;
private final int readonlyBackground;
private final AtomicReference<String> query;
// measure utilities
protected final Paint paint;
protected final DisplayMetrics displayMetrics;
private final boolean simpleLayout;
private final boolean titleOnlyLayout;
protected final int minRowHeight;
// --- task detail and decoration soft caches
public final DecorationManager decorationManager;
private final Map<Long, TaskAction> taskActionLoader = Collections.synchronizedMap(new HashMap<Long, TaskAction>());
/**
* Constructor
*
* @param fragment
* @param resource
* layout resource to inflate
* @param c
* database cursor
* @param autoRequery
* whether cursor is automatically re-queried on changes
* @param onCompletedTaskListener
* task listener. can be null
*/
public TaskAdapter(TaskListFragment fragment, int resource,
Cursor c, AtomicReference<String> query, boolean autoRequery,
OnCompletedTaskListener onCompletedTaskListener) {
super(ContextManager.getContext(), c, autoRequery);
DependencyInjectionService.getInstance().inject(this);
this.context = ContextManager.getContext();
this.query = query;
this.resource = resource;
this.titleOnlyLayout = resource == R.layout.task_adapter_row_title_only;
this.fragment = fragment;
this.resources = fragment.getResources();
this.onCompletedTaskListener = onCompletedTaskListener;
inflater = (LayoutInflater) fragment.getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
fontSize = Preferences.getIntegerFromString(R.string.p_fontSize, 18);
paint = new Paint();
displayMetrics = new DisplayMetrics();
fragment.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
this.simpleLayout = (resource == R.layout.task_adapter_row_simple);
this.minRowHeight = computeMinRowHeight();
startDetailThread();
decorationManager = new DecorationManager();
scaleAnimation = new ScaleAnimation(1.4f, 1.0f, 1.4f, 1.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnimation.setDuration(100);
TypedValue readonlyBg = new TypedValue();
fragment.getActivity().getTheme().resolveAttribute(R.attr.asReadonlyTaskBackground, readonlyBg, false);
readonlyBackground = readonlyBg.data;
preloadDrawables(IMPORTANCE_RESOURCES, IMPORTANCE_DRAWABLES);
preloadDrawables(IMPORTANCE_RESOURCES_CHECKED, IMPORTANCE_DRAWABLES_CHECKED);
preloadDrawables(IMPORTANCE_RESOURCES_LARGE, IMPORTANCE_DRAWABLES_LARGE);
preloadDrawables(IMPORTANCE_REPEAT_RESOURCES, IMPORTANCE_REPEAT_DRAWABLES);
preloadDrawables(IMPORTANCE_REPEAT_RESOURCES_CHECKED, IMPORTANCE_REPEAT_DRAWABLES_CHECKED);
}
private void preloadDrawables(int[] resourceIds, Drawable[] drawables) {
for (int i = 0; i < resourceIds.length; i++) {
drawables[i] = resources.getDrawable(resourceIds[i]);
}
}
protected int computeMinRowHeight() {
DisplayMetrics metrics = resources.getDisplayMetrics();
if (simpleLayout || titleOnlyLayout) {
return (int) (metrics.density * 40);
} else {
return (int) (metrics.density * 45);
}
}
public int computeFullRowHeight() {
DisplayMetrics metrics = resources.getDisplayMetrics();
if (fontSize < 16) {
return (int) (39 * metrics.density);
} else {
return minRowHeight + (int) (10 * metrics.density);
}
}
private void startDetailThread() {
if (Preferences.getBoolean(R.string.p_showNotes, false) && !simpleLayout && !titleOnlyLayout) {
detailLoader = new DetailLoaderThread();
detailLoader.start();
}
}
/* ======================================================================
* =========================================================== filterable
* ====================================================================== */
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
if (getFilterQueryProvider() != null) {
return getFilterQueryProvider().runQuery(constraint);
}
// perform query
TodorooCursor<Task> newCursor = taskService.fetchFiltered(
query.get(), constraint, fragment.taskProperties());
return newCursor;
}
public String getQuery() {
return query.get();
}
/* ======================================================================
* =========================================================== view setup
* ====================================================================== */
/** Creates a new view for use in the list view */
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ViewGroup view = (ViewGroup)inflater.inflate(resource, parent, false);
// create view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.task = new Task();
viewHolder.view = view;
viewHolder.rowBody = (ViewGroup)view.findViewById(R.id.rowBody);
viewHolder.nameView = (TextView)view.findViewById(R.id.title);
viewHolder.picture = (AsyncImageView)view.findViewById(R.id.picture);
viewHolder.pictureBorder = (ImageView)view.findViewById(R.id.pictureBorder);
viewHolder.completeBox = (CheckableImageView)view.findViewById(R.id.completeBox);
viewHolder.dueDate = (TextView)view.findViewById(R.id.dueDate);
viewHolder.tagsView = (TextView)view.findViewById(R.id.tagsDisplay);
viewHolder.details1 = (TextView)view.findViewById(R.id.details1);
viewHolder.details2 = (TextView)view.findViewById(R.id.details2);
viewHolder.taskRow = (LinearLayout)view.findViewById(R.id.task_row);
viewHolder.taskActionContainer = view.findViewById(R.id.taskActionContainer);
viewHolder.taskActionIcon = (ImageView)view.findViewById(R.id.taskActionIcon);
boolean showFullTaskTitle = Preferences.getBoolean(R.string.p_fullTaskTitle, false);
boolean showNotes = Preferences.getBoolean(R.string.p_showNotes, false);
if (showFullTaskTitle && !titleOnlyLayout) {
viewHolder.nameView.setMaxLines(Integer.MAX_VALUE);
viewHolder.nameView.setSingleLine(false);
viewHolder.nameView.setEllipsize(null);
} else if (titleOnlyLayout) {
viewHolder.nameView.setMaxLines(1);
viewHolder.nameView.setSingleLine(true);
viewHolder.nameView.setEllipsize(TruncateAt.END);
}
if (showNotes && !simpleLayout && !titleOnlyLayout) {
RelativeLayout.LayoutParams taskRowParams = (RelativeLayout.LayoutParams)viewHolder.taskRow.getLayoutParams();
taskRowParams.addRule(RelativeLayout.CENTER_VERTICAL, 0);
}
view.setTag(viewHolder);
for(int i = 0; i < view.getChildCount(); i++)
view.getChildAt(i).setTag(viewHolder);
if(viewHolder.details1 != null)
viewHolder.details1.setTag(viewHolder);
// add UI component listeners
addListeners(view);
return view;
}
/** Populates a view with content */
@Override
public void bindView(View view, Context context, Cursor c) {
TodorooCursor<Task> cursor = (TodorooCursor<Task>)c;
ViewHolder viewHolder = ((ViewHolder)view.getTag());
if (!titleOnlyLayout) {
viewHolder.isTaskRabbit = (cursor.get(TASK_RABBIT_ID) > 0);
viewHolder.tagsString = cursor.get(TAGS);
viewHolder.imageUrl = RemoteModel.PictureHelper.getPictureUrlFromCursor(cursor, PICTURE, RemoteModel.PICTURE_THUMB);
viewHolder.hasFiles = cursor.get(FILE_ID_PROPERTY) > 0;
viewHolder.hasNotes = cursor.get(HAS_NOTES_PROPERTY) > 0;
}
Task task = viewHolder.task;
task.clear();
task.readFromCursor(cursor);
setFieldContentsAndVisibility(view);
setTaskAppearance(viewHolder, task);
}
public String getItemUuid(int position) {
TodorooCursor<Task> c = (TodorooCursor<Task>) getCursor();
if (c != null) {
if (c.moveToPosition(position)) {
return c.get(Task.UUID);
} else {
return RemoteModel.NO_UUID;
}
} else {
return RemoteModel.NO_UUID;
}
}
/**
* View Holder saves a lot of findViewById lookups.
*
* @author Tim Su <[email protected]>
*
*/
public static class ViewHolder {
public Task task;
public ViewGroup view;
public ViewGroup rowBody;
public TextView nameView;
public CheckableImageView completeBox;
public AsyncImageView picture;
public ImageView pictureBorder;
public TextView dueDate;
public TextView tagsView;
public TextView details1, details2;
public LinearLayout taskRow;
public View taskActionContainer;
public ImageView taskActionIcon;
public boolean isTaskRabbit; // From join query, not part of the task model
public String tagsString; // From join query, not part of the task model
public String imageUrl; // From join query, not part of the task model
public boolean hasFiles; // From join query, not part of the task model
public boolean hasNotes;
public View[] decorations;
}
/** Helper method to set the contents and visibility of each field */
public synchronized void setFieldContentsAndVisibility(View view) {
ViewHolder viewHolder = (ViewHolder)view.getTag();
Task task = viewHolder.task;
if (fontSize < 16 || titleOnlyLayout) {
viewHolder.rowBody.setMinimumHeight(0);
viewHolder.completeBox.setMinimumHeight(0);
} else {
viewHolder.rowBody.setMinimumHeight(minRowHeight);
viewHolder.completeBox.setMinimumHeight(minRowHeight);
}
if (task.isEditable())
viewHolder.view.setBackgroundColor(resources.getColor(android.R.color.transparent));
else
viewHolder.view.setBackgroundColor(readonlyBackground);
// name
final TextView nameView = viewHolder.nameView; {
String nameValue = task.getValue(Task.TITLE);
long hiddenUntil = task.getValue(Task.HIDE_UNTIL);
if(task.getValue(Task.DELETION_DATE) > 0)
nameValue = resources.getString(R.string.TAd_deletedFormat, nameValue);
if(hiddenUntil > DateUtilities.now())
nameValue = resources.getString(R.string.TAd_hiddenFormat, nameValue);
nameView.setText(nameValue);
}
if (titleOnlyLayout) {
return;
}
float dueDateTextWidth = setupDueDateAndTags(viewHolder, task);
String details;
if(viewHolder.details1 != null) {
if(taskDetailLoader.containsKey(task.getId()))
details = taskDetailLoader.get(task.getId()).toString();
else
details = task.getValue(Task.DETAILS);
if(TextUtils.isEmpty(details) || DETAIL_SEPARATOR.equals(details) || task.isCompleted()) {
viewHolder.details1.setVisibility(View.GONE);
viewHolder.details2.setVisibility(View.GONE);
} else if (Preferences.getBoolean(R.string.p_showNotes, false)) {
viewHolder.details1.setVisibility(View.VISIBLE);
if (details.startsWith(DETAIL_SEPARATOR)) {
StringBuffer buffer = new StringBuffer(details);
int length = DETAIL_SEPARATOR.length();
while(buffer.lastIndexOf(DETAIL_SEPARATOR, length) == 0)
buffer.delete(0, length);
details = buffer.toString(); //details.substring(DETAIL_SEPARATOR.length());
}
drawDetails(viewHolder, details, dueDateTextWidth);
}
}
// Task action
ImageView taskAction = viewHolder.taskActionIcon;
if (taskAction != null) {
TaskAction action = getTaskAction(task, viewHolder.hasFiles, viewHolder.hasNotes);
if (action != null) {
taskAction.setVisibility(View.VISIBLE);
taskAction.setImageDrawable(action.icon);
taskAction.setTag(action);
} else {
taskAction.setVisibility(View.GONE);
taskAction.setTag(null);
}
}
if(Math.abs(DateUtilities.now() - task.getValue(Task.MODIFICATION_DATE)) < 2000L)
mostRecentlyMade = task.getId();
}
private TaskAction getTaskAction(Task task, boolean hasFiles, boolean hasNotes) {
if (titleOnlyLayout || task.isCompleted() || !task.isEditable())
return null;
if (taskActionLoader.containsKey(task.getId())) {
return taskActionLoader.get(task.getId());
} else {
TaskAction action = LinkActionExposer.getActionsForTask(context, task, hasFiles, hasNotes);
taskActionLoader.put(task.getId(), action);
return action;
}
}
@SuppressWarnings("nls")
private void drawDetails(ViewHolder viewHolder, String details, float rightWidth) {
SpannableStringBuilder prospective = new SpannableStringBuilder();
SpannableStringBuilder actual = new SpannableStringBuilder();
details = details.trim().replace("\n", "<br>");
String[] splitDetails = details.split("\\|");
viewHolder.completeBox.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
rightWidth = rightWidth + viewHolder.dueDate.getPaddingRight();
float left = viewHolder.completeBox.getMeasuredWidth() +
((MarginLayoutParams)viewHolder.completeBox.getLayoutParams()).leftMargin;
int availableWidth = (int) (displayMetrics.widthPixels - left - (rightWidth + 16) * displayMetrics.density);
int i = 0;
for(; i < splitDetails.length; i++) {
Spanned spanned = convertToHtml(splitDetails[i] + " ", detailImageGetter, null);
prospective.insert(prospective.length(), spanned);
viewHolder.details1.setText(prospective);
viewHolder.details1.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
if(rightWidth > 0 && viewHolder.details1.getMeasuredWidth() > availableWidth)
break;
actual.insert(actual.length(), spanned);
}
viewHolder.details1.setText(actual);
actual.clear();
if(i >= splitDetails.length) {
viewHolder.details2.setVisibility(View.GONE);
return;
} else {
viewHolder.details2.setVisibility(View.VISIBLE);
}
for(; i < splitDetails.length; i++)
actual.insert(actual.length(), convertToHtml(splitDetails[i] + " ", detailImageGetter, null));
viewHolder.details2.setText(actual);
}
protected TaskRowListener listener = new TaskRowListener();
private Pair<Float, Float> lastTouchYRawY = new Pair<Float, Float>(0f, 0f);
/**
* Set listeners for this view. This is called once per view when it is
* created.
*/
protected void addListeners(final View container) {
final ViewHolder viewHolder = (ViewHolder)container.getTag();
// check box listener
OnTouchListener otl = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
lastTouchYRawY = new Pair<Float, Float>(event.getY(), event.getRawY());
return false;
}
};
viewHolder.completeBox.setOnTouchListener(otl);
viewHolder.completeBox.setOnClickListener(completeBoxListener);
if (viewHolder.picture != null) {
viewHolder.picture.setOnTouchListener(otl);
viewHolder.picture.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
viewHolder.completeBox.performClick();
}
});
}
if (viewHolder.taskActionContainer != null) {
viewHolder.taskActionContainer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TaskAction action = (TaskAction) viewHolder.taskActionIcon.getTag();
if (action instanceof NotesAction) {
showEditNotesDialog(viewHolder.task);
} else if (action instanceof FilesAction) {
showFilesDialog(viewHolder.task);
} else if (action != null) {
try {
action.intent.send();
} catch (CanceledException e) {
// Oh well
}
}
}
});
}
}
private void showEditNotesDialog(final Task task) {
String notes = null;
Task t = taskService.fetchById(task.getId(), Task.NOTES);
if (t != null)
notes = t.getValue(Task.NOTES);
if (TextUtils.isEmpty(notes))
return;
int theme = ThemeService.getEditDialogTheme();
final Dialog dialog = new Dialog(fragment.getActivity(), theme);
dialog.setTitle(R.string.TEA_note_label);
View notesView = LayoutInflater.from(fragment.getActivity()).inflate(R.layout.notes_view_dialog, null);
dialog.setContentView(notesView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
notesView.findViewById(R.id.edit_dlg_ok).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
final TextView notesField = (TextView) notesView.findViewById(R.id.notes);
notesField.setText(notes);
LayoutParams params = dialog.getWindow().getAttributes();
params.width = LayoutParams.FILL_PARENT;
params.height = LayoutParams.WRAP_CONTENT;
Configuration config = fragment.getResources().getConfiguration();
int size = config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
if (AndroidUtilities.getSdkVersion() >= 9 && size == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
DisplayMetrics metrics = fragment.getResources().getDisplayMetrics();
params.width = metrics.widthPixels / 2;
}
dialog.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
dialog.show();
}
private void showFilesDialog(Task task) {
FilesControlSet filesControlSet = new FilesControlSet(fragment.getActivity(), R.layout.control_set_files,
R.layout.control_set_files_display, R.string.TEA_control_files);
filesControlSet.readFromTask(task);
filesControlSet.getDisplayView().performClick();
}
/* ======================================================================
* ============================================================== details
* ====================================================================== */
private final HashMap<String, Spanned> htmlCache = new HashMap<String, Spanned>(8);
private Spanned convertToHtml(String string, ImageGetter imageGetter, TagHandler tagHandler) {
if(!htmlCache.containsKey(string)) {
Spanned html;
try {
html = Html.fromHtml(string, imageGetter, tagHandler);
} catch (RuntimeException e) {
html = Spannable.Factory.getInstance().newSpannable(string);
}
htmlCache.put(string, html);
return html;
}
return htmlCache.get(string);
}
private final HashMap<Long, String> dateCache = new HashMap<Long, String>(8);
@SuppressWarnings("nls")
private String formatDate(long date) {
if(dateCache.containsKey(date))
return dateCache.get(date);
String formatString = "%s" + (simpleLayout ? " " : "\n") + "%s";
String string = DateUtilities.getRelativeDay(fragment.getActivity(), date);
if(Task.hasDueTime(date))
string = String.format(formatString, string, //$NON-NLS-1$
DateUtilities.getTimeString(fragment.getActivity(), new Date(date)));
dateCache.put(date, string);
return string;
}
// implementation note: this map is really costly if users have
// a large number of tasks to load, since it all goes into memory.
// it's best to do this, though, in order to append details to each other
private final Map<Long, StringBuilder> taskDetailLoader = Collections.synchronizedMap(new HashMap<Long, StringBuilder>(0));
public class DetailLoaderThread extends Thread {
@Override
public void run() {
// for all of the tasks returned by our cursor, verify details
AndroidUtilities.sleepDeep(500L);
TodorooCursor<Task> fetchCursor = taskService.fetchFiltered(
query.get(), null, Task.ID, Task.TITLE, Task.DETAILS, Task.DETAILS_DATE,
Task.MODIFICATION_DATE, Task.COMPLETION_DATE);
try {
Random random = new Random();
Task task = new Task();
for(fetchCursor.moveToFirst(); !fetchCursor.isAfterLast(); fetchCursor.moveToNext()) {
task.clear();
task.readFromCursor(fetchCursor);
if(task.isCompleted())
continue;
if(detailsAreRecentAndUpToDate(task)) {
// even if we are up to date, randomly load a fraction
if(random.nextFloat() < 0.1) {
taskDetailLoader.put(task.getId(),
new StringBuilder(task.getValue(Task.DETAILS)));
requestNewDetails(task);
if(Constants.DEBUG)
System.err.println("Refreshing details: " + task.getId()); //$NON-NLS-1$
}
continue;
} else if(Constants.DEBUG) {
System.err.println("Forced loading of details: " + task.getId() + //$NON-NLS-1$
"\n details: " + new Date(task.getValue(Task.DETAILS_DATE)) + //$NON-NLS-1$
"\n modified: " + new Date(task.getValue(Task.MODIFICATION_DATE))); //$NON-NLS-1$
}
addTaskToLoadingArray(task);
task.setValue(Task.DETAILS, DETAIL_SEPARATOR);
task.setValue(Task.DETAILS_DATE, DateUtilities.now());
taskService.save(task);
requestNewDetails(task);
}
if(taskDetailLoader.size() > 0) {
Activity activity = fragment.getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
}
}
} catch (Exception e) {
// suppress silently
} finally {
fetchCursor.close();
}
}
private boolean detailsAreRecentAndUpToDate(Task task) {
return task.getValue(Task.DETAILS_DATE) >= task.getValue(Task.MODIFICATION_DATE) &&
!TextUtils.isEmpty(task.getValue(Task.DETAILS));
}
private void addTaskToLoadingArray(Task task) {
StringBuilder detailStringBuilder = new StringBuilder();
taskDetailLoader.put(task.getId(), detailStringBuilder);
}
private void requestNewDetails(Task task) {
Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_REQUEST_DETAILS);
broadcastIntent.putExtra(AstridApiConstants.EXTRAS_TASK_ID, task.getId());
Activity activity = fragment.getActivity();
if (activity != null)
activity.sendOrderedBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ);
}
}
/**
* Add detail to a task
*
* @param id
* @param detail
*/
public void addDetails(long id, String detail) {
final StringBuilder details = taskDetailLoader.get(id);
if(details == null)
return;
synchronized(details) {
if(details.toString().contains(detail))
return;
if(details.length() > 0)
details.append(DETAIL_SEPARATOR);
details.append(detail);
Task task = new Task();
task.setId(id);
task.setValue(Task.DETAILS, details.toString());
task.setValue(Task.DETAILS_DATE, DateUtilities.now());
taskService.save(task);
}
Activity activity = fragment.getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
}
}
private final ImageGetter detailImageGetter = new ImageGetter() {
private final HashMap<Integer, Drawable> cache =
new HashMap<Integer, Drawable>(3);
@SuppressWarnings("nls")
public Drawable getDrawable(String source) {
int drawable = 0;
if(source.equals("silk_clock"))
drawable = R.drawable.details_alarm;
else if(source.equals("silk_tag_pink"))
drawable = R.drawable.details_tag;
else if(source.equals("silk_date"))
drawable = R.drawable.details_repeat;
else if(source.equals("silk_note"))
drawable = R.drawable.details_note;
if (drawable == 0)
drawable = resources.getIdentifier("drawable/" + source, null, Constants.PACKAGE);
if(drawable == 0)
return null;
Drawable d;
if(!cache.containsKey(drawable)) {
d = resources.getDrawable(drawable);
d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());
cache.put(drawable, d);
} else
d = cache.get(drawable);
return d;
}
};
/* ======================================================================
* ============================================================== add-ons
* ====================================================================== */
/**
* Called to tell the cache to be cleared
*/
public void flushCaches() {
completedItems.clear();
decorationManager.clearCache();
taskDetailLoader.clear();
startDetailThread();
}
public HashMap<Object, Boolean> getCompletedItems() {
return completedItems;
}
/**
* AddOnManager for TaskDecorations
*
* @author Tim Su <[email protected]>
*
*/
public class DecorationManager extends TaskAdapterAddOnManager<TaskDecoration> {
public DecorationManager() {
super(fragment);
}
private final TaskDecorationExposer[] exposers = new TaskDecorationExposer[] {
new TimerDecorationExposer(),
new NotesDecorationExposer()
};
/**
* Request add-ons for the given task
* @return true if cache miss, false if cache hit
*/
@Override
public boolean request(ViewHolder viewHolder) {
long taskId = viewHolder.task.getId();
Collection<TaskDecoration> list = initialize(taskId);
if(list != null) {
draw(viewHolder, taskId, list);
return false;
}
// request details
draw(viewHolder, taskId, get(taskId));
for(TaskDecorationExposer exposer : exposers) {
TaskDecoration deco = exposer.expose(viewHolder.task);
if(deco != null) {
addNew(viewHolder.task.getId(), exposer.getAddon(), deco, viewHolder);
}
}
return true;
}
@Override
protected void draw(ViewHolder viewHolder, long taskId, Collection<TaskDecoration> decorations) {
if(decorations == null || viewHolder.task.getId() != taskId)
return;
reset(viewHolder, taskId);
if(decorations.size() == 0)
return;
int i = 0;
boolean colorSet = false;
if(viewHolder.decorations == null || viewHolder.decorations.length != decorations.size())
viewHolder.decorations = new View[decorations.size()];
for(TaskDecoration decoration : decorations) {
if(decoration.color != 0 && !colorSet) {
colorSet = true;
viewHolder.view.setBackgroundColor(decoration.color);
}
if(decoration.decoration != null) {
View view = decoration.decoration.apply(fragment.getActivity(), viewHolder.taskRow);
viewHolder.decorations[i] = view;
switch(decoration.position) {
case TaskDecoration.POSITION_LEFT: {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, R.id.completeBox);
view.setLayoutParams(params);
viewHolder.rowBody.addView(view);
break;
}
case TaskDecoration.POSITION_RIGHT:
viewHolder.taskRow.addView(view, viewHolder.taskRow.getChildCount());
}
}
i++;
}
}
@Override
protected void reset(ViewHolder viewHolder, long taskId) {
if(viewHolder.decorations != null) {
for(View view : viewHolder.decorations) {
viewHolder.rowBody.removeView(view);
viewHolder.taskRow.removeView(view);
}
viewHolder.decorations = null;
}
if(viewHolder.task.getId() == mostRecentlyMade)
viewHolder.view.setBackgroundColor(Color.argb(30, 150, 150, 150));
else
viewHolder.view.setBackgroundResource(android.R.drawable.list_selector_background);
}
@Override
protected Intent createBroadcastIntent(Task task) {
return null;
}
}
/* ======================================================================
* ======================================================= event handlers
* ====================================================================== */
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
fontSize = Preferences.getIntegerFromString(R.string.p_fontSize, 18);
}
protected final View.OnClickListener completeBoxListener = new View.OnClickListener() {
public void onClick(View v) {
int[] location = new int[2];
v.getLocationOnScreen(location);
ViewHolder viewHolder = getTagFromCheckBox(v);
if(Math.abs(location[1] + lastTouchYRawY.getLeft() - lastTouchYRawY.getRight()) > 10) {
viewHolder.completeBox.setChecked(!viewHolder.completeBox.isChecked());
return;
}
Task task = viewHolder.task;
completeTask(task, viewHolder.completeBox.isChecked());
// set check box to actual action item state
setTaskAppearance(viewHolder, task);
if (viewHolder.completeBox.getVisibility() == View.VISIBLE)
viewHolder.completeBox.startAnimation(scaleAnimation);
}
};
protected ViewHolder getTagFromCheckBox(View v) {
return (ViewHolder)((View)v.getParent()).getTag();
}
public class TaskRowListener implements OnClickListener {
@Override
public void onClick(View v) {
// expand view (unless deleted)
final ViewHolder viewHolder = (ViewHolder)v.getTag();
if(viewHolder.task.isDeleted())
return;
long taskId = viewHolder.task.getId();
fragment.onTaskListItemClicked(taskId, viewHolder.task.isEditable());
}
}
/**
* Call me when the parent presses trackpad
*/
public void onTrackpadPressed(View container) {
if(container == null)
return;
final CheckBox completeBox = ((CheckBox)container.findViewById(R.id.completeBox));
completeBox.performClick();
}
/** Helper method to adjust a tasks' appearance if the task is completed or
* uncompleted.
*
* @param actionItem
* @param name
* @param progress
*/
void setTaskAppearance(ViewHolder viewHolder, Task task) {
Activity activity = fragment.getActivity();
if (activity == null)
return;
// show item as completed if it was recently checked
- if(completedItems.get(task.getUuid()) != null || completedItems.get(task.getId()) != null) {
+ Boolean value = completedItems.get(task.getUuid());
+ if (value == null)
+ value = completedItems.get(task.getId());
+ if(value != null) {
task.setValue(Task.COMPLETION_DATE,
- completedItems.get(task.getId()) ? DateUtilities.now() : 0);
+ value ? DateUtilities.now() : 0);
}
boolean state = task.isCompleted();
TextView name = viewHolder.nameView;
if(state) {
name.setPaintFlags(name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
name.setTextAppearance(activity, R.style.TextAppearance_TAd_ItemTitle_Completed);
} else {
name.setPaintFlags(name.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
name.setTextAppearance(activity, R.style.TextAppearance_TAd_ItemTitle);
}
name.setTextSize(fontSize);
if (!titleOnlyLayout) {
setupDueDateAndTags(viewHolder, task);
float detailTextSize = Math.max(10, fontSize * 14 / 20);
if(viewHolder.details1 != null)
viewHolder.details1.setTextSize(detailTextSize);
if(viewHolder.details2 != null)
viewHolder.details2.setTextSize(detailTextSize);
if(viewHolder.dueDate != null) {
viewHolder.dueDate.setTextSize(detailTextSize);
if (simpleLayout)
viewHolder.dueDate.setTypeface(null, 0);
}
if (viewHolder.tagsView != null) {
viewHolder.tagsView.setTextSize(detailTextSize);
if (simpleLayout)
viewHolder.tagsView.setTypeface(null, 0);
}
paint.setTextSize(detailTextSize);
// image view
final AsyncImageView pictureView = viewHolder.picture; {
if (pictureView != null) {
if(Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID)) && !viewHolder.isTaskRabbit) {
pictureView.setVisibility(View.GONE);
if (viewHolder.pictureBorder != null)
viewHolder.pictureBorder.setVisibility(View.GONE);
} else {
pictureView.setVisibility(View.VISIBLE);
if (viewHolder.pictureBorder != null)
viewHolder.pictureBorder.setVisibility(View.VISIBLE);
pictureView.setUrl(null);
if (viewHolder.isTaskRabbit) {
pictureView.setDefaultImageResource(R.drawable.task_rabbit_image);
} else if (Task.USER_ID_UNASSIGNED.equals(task.getValue(Task.USER_ID)))
pictureView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_anyone_transparent));
else {
pictureView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_default_person_image));
if (!TextUtils.isEmpty(viewHolder.imageUrl)) {
pictureView.setUrl(viewHolder.imageUrl);
} else if (!TextUtils.isEmpty(task.getValue(Task.USER))) {
try {
JSONObject user = new JSONObject(task.getValue(Task.USER));
pictureView.setUrl(user.optString("picture")); //$NON-NLS-1$
} catch (JSONException e) {
//
}
}
}
}
}
}
}
setupCompleteBox(viewHolder);
}
private void setupCompleteBox(ViewHolder viewHolder) {
// complete box
final Task task = viewHolder.task;
final AsyncImageView pictureView = viewHolder.picture;
final CheckableImageView checkBoxView = viewHolder.completeBox; {
boolean completed = task.isCompleted();
checkBoxView.setChecked(completed);
// disable checkbox if task is readonly
checkBoxView.setEnabled(viewHolder.task.isEditable());
int value = task.getValue(Task.IMPORTANCE);
if (value >= IMPORTANCE_RESOURCES.length)
value = IMPORTANCE_RESOURCES.length - 1;
Drawable[] boxes = IMPORTANCE_DRAWABLES;
if (!TextUtils.isEmpty(task.getValue(Task.RECURRENCE))) {
boxes = completed ? IMPORTANCE_REPEAT_DRAWABLES_CHECKED : IMPORTANCE_REPEAT_DRAWABLES;
} else {
boxes = completed ? IMPORTANCE_DRAWABLES_CHECKED : IMPORTANCE_DRAWABLES;
}
checkBoxView.setImageDrawable(boxes[value]);
if (titleOnlyLayout)
return;
if (checkBoxView.isChecked()) {
if (pictureView != null)
pictureView.setVisibility(View.GONE);
if (viewHolder.pictureBorder != null)
viewHolder.pictureBorder.setVisibility(View.GONE);
}
if (pictureView != null && pictureView.getVisibility() == View.VISIBLE) {
checkBoxView.setVisibility(View.INVISIBLE);
if (viewHolder.pictureBorder != null)
viewHolder.pictureBorder.setBackgroundDrawable(IMPORTANCE_DRAWABLES_LARGE[value]);
} else {
checkBoxView.setVisibility(View.VISIBLE);
}
}
}
// Returns due date text width
private float setupDueDateAndTags(ViewHolder viewHolder, Task task) {
// due date / completion date
float dueDateTextWidth = 0;
final TextView dueDateView = viewHolder.dueDate; {
Activity activity = fragment.getActivity();
if (activity != null) {
if(!task.isCompleted() && task.hasDueDate()) {
long dueDate = task.getValue(Task.DUE_DATE);
if(task.isOverdue())
dueDateView.setTextAppearance(activity, R.style.TextAppearance_TAd_ItemDueDate_Overdue);
else
dueDateView.setTextAppearance(activity, R.style.TextAppearance_TAd_ItemDueDate);
String dateValue = formatDate(dueDate);
dueDateView.setText(dateValue);
dueDateTextWidth = paint.measureText(dateValue);
dueDateView.setVisibility(View.VISIBLE);
} else if(task.isCompleted()) {
String dateValue = formatDate(task.getValue(Task.COMPLETION_DATE));
dueDateView.setText(resources.getString(R.string.TAd_completed, dateValue));
dueDateView.setTextAppearance(activity, R.style.TextAppearance_TAd_ItemDueDate_Completed);
dueDateTextWidth = paint.measureText(dateValue);
dueDateView.setVisibility(View.VISIBLE);
} else {
dueDateView.setVisibility(View.GONE);
}
if (viewHolder.tagsView != null) {
String tags = viewHolder.tagsString;
if (tags != null && task.hasDueDate())
tags = " | " + tags; //$NON-NLS-1$
if (!task.isCompleted()) {
viewHolder.tagsView.setText(tags);
viewHolder.tagsView.setVisibility(TextUtils.isEmpty(tags) ? View.GONE : View.VISIBLE);
} else {
viewHolder.tagsView.setText(""); //$NON-NLS-1$
viewHolder.tagsView.setVisibility(View.GONE);
}
}
}
}
return dueDateTextWidth;
}
/**
* This method is called when user completes a task via check box or other
* means
*
* @param container
* container for the action item
* @param newState
* state that this task should be set to
* @param completeBox
* the box that was clicked. can be null
*/
protected void completeTask(final Task task, final boolean newState) {
if(task == null)
return;
if (newState != task.isCompleted()) {
if(onCompletedTaskListener != null)
onCompletedTaskListener.onCompletedTask(task, newState);
completedItems.put(task.getUuid(), newState);
taskService.setComplete(task, newState);
}
}
/**
* Add a new listener
* @param newListener
*/
public void addOnCompletedTaskListener(final OnCompletedTaskListener newListener) {
if(this.onCompletedTaskListener == null)
this.onCompletedTaskListener = newListener;
else {
final OnCompletedTaskListener old = this.onCompletedTaskListener;
this.onCompletedTaskListener = new OnCompletedTaskListener() {
@Override
public void onCompletedTask(Task item, boolean newState) {
old.onCompletedTask(item, newState);
newListener.onCompletedTask(item, newState);
}
};
}
}
}
| false | true | void setTaskAppearance(ViewHolder viewHolder, Task task) {
Activity activity = fragment.getActivity();
if (activity == null)
return;
// show item as completed if it was recently checked
if(completedItems.get(task.getUuid()) != null || completedItems.get(task.getId()) != null) {
task.setValue(Task.COMPLETION_DATE,
completedItems.get(task.getId()) ? DateUtilities.now() : 0);
}
boolean state = task.isCompleted();
TextView name = viewHolder.nameView;
if(state) {
name.setPaintFlags(name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
name.setTextAppearance(activity, R.style.TextAppearance_TAd_ItemTitle_Completed);
} else {
name.setPaintFlags(name.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
name.setTextAppearance(activity, R.style.TextAppearance_TAd_ItemTitle);
}
name.setTextSize(fontSize);
if (!titleOnlyLayout) {
setupDueDateAndTags(viewHolder, task);
float detailTextSize = Math.max(10, fontSize * 14 / 20);
if(viewHolder.details1 != null)
viewHolder.details1.setTextSize(detailTextSize);
if(viewHolder.details2 != null)
viewHolder.details2.setTextSize(detailTextSize);
if(viewHolder.dueDate != null) {
viewHolder.dueDate.setTextSize(detailTextSize);
if (simpleLayout)
viewHolder.dueDate.setTypeface(null, 0);
}
if (viewHolder.tagsView != null) {
viewHolder.tagsView.setTextSize(detailTextSize);
if (simpleLayout)
viewHolder.tagsView.setTypeface(null, 0);
}
paint.setTextSize(detailTextSize);
// image view
final AsyncImageView pictureView = viewHolder.picture; {
if (pictureView != null) {
if(Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID)) && !viewHolder.isTaskRabbit) {
pictureView.setVisibility(View.GONE);
if (viewHolder.pictureBorder != null)
viewHolder.pictureBorder.setVisibility(View.GONE);
} else {
pictureView.setVisibility(View.VISIBLE);
if (viewHolder.pictureBorder != null)
viewHolder.pictureBorder.setVisibility(View.VISIBLE);
pictureView.setUrl(null);
if (viewHolder.isTaskRabbit) {
pictureView.setDefaultImageResource(R.drawable.task_rabbit_image);
} else if (Task.USER_ID_UNASSIGNED.equals(task.getValue(Task.USER_ID)))
pictureView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_anyone_transparent));
else {
pictureView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_default_person_image));
if (!TextUtils.isEmpty(viewHolder.imageUrl)) {
pictureView.setUrl(viewHolder.imageUrl);
} else if (!TextUtils.isEmpty(task.getValue(Task.USER))) {
try {
JSONObject user = new JSONObject(task.getValue(Task.USER));
pictureView.setUrl(user.optString("picture")); //$NON-NLS-1$
} catch (JSONException e) {
//
}
}
}
}
}
}
}
setupCompleteBox(viewHolder);
}
| void setTaskAppearance(ViewHolder viewHolder, Task task) {
Activity activity = fragment.getActivity();
if (activity == null)
return;
// show item as completed if it was recently checked
Boolean value = completedItems.get(task.getUuid());
if (value == null)
value = completedItems.get(task.getId());
if(value != null) {
task.setValue(Task.COMPLETION_DATE,
value ? DateUtilities.now() : 0);
}
boolean state = task.isCompleted();
TextView name = viewHolder.nameView;
if(state) {
name.setPaintFlags(name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
name.setTextAppearance(activity, R.style.TextAppearance_TAd_ItemTitle_Completed);
} else {
name.setPaintFlags(name.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
name.setTextAppearance(activity, R.style.TextAppearance_TAd_ItemTitle);
}
name.setTextSize(fontSize);
if (!titleOnlyLayout) {
setupDueDateAndTags(viewHolder, task);
float detailTextSize = Math.max(10, fontSize * 14 / 20);
if(viewHolder.details1 != null)
viewHolder.details1.setTextSize(detailTextSize);
if(viewHolder.details2 != null)
viewHolder.details2.setTextSize(detailTextSize);
if(viewHolder.dueDate != null) {
viewHolder.dueDate.setTextSize(detailTextSize);
if (simpleLayout)
viewHolder.dueDate.setTypeface(null, 0);
}
if (viewHolder.tagsView != null) {
viewHolder.tagsView.setTextSize(detailTextSize);
if (simpleLayout)
viewHolder.tagsView.setTypeface(null, 0);
}
paint.setTextSize(detailTextSize);
// image view
final AsyncImageView pictureView = viewHolder.picture; {
if (pictureView != null) {
if(Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID)) && !viewHolder.isTaskRabbit) {
pictureView.setVisibility(View.GONE);
if (viewHolder.pictureBorder != null)
viewHolder.pictureBorder.setVisibility(View.GONE);
} else {
pictureView.setVisibility(View.VISIBLE);
if (viewHolder.pictureBorder != null)
viewHolder.pictureBorder.setVisibility(View.VISIBLE);
pictureView.setUrl(null);
if (viewHolder.isTaskRabbit) {
pictureView.setDefaultImageResource(R.drawable.task_rabbit_image);
} else if (Task.USER_ID_UNASSIGNED.equals(task.getValue(Task.USER_ID)))
pictureView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_anyone_transparent));
else {
pictureView.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_default_person_image));
if (!TextUtils.isEmpty(viewHolder.imageUrl)) {
pictureView.setUrl(viewHolder.imageUrl);
} else if (!TextUtils.isEmpty(task.getValue(Task.USER))) {
try {
JSONObject user = new JSONObject(task.getValue(Task.USER));
pictureView.setUrl(user.optString("picture")); //$NON-NLS-1$
} catch (JSONException e) {
//
}
}
}
}
}
}
}
setupCompleteBox(viewHolder);
}
|
diff --git a/uk.ac.gda.common/src/uk/ac/gda/ClientManager.java b/uk.ac.gda.common/src/uk/ac/gda/ClientManager.java
index 28760fd..e2b70cc 100644
--- a/uk.ac.gda.common/src/uk/ac/gda/ClientManager.java
+++ b/uk.ac.gda.common/src/uk/ac/gda/ClientManager.java
@@ -1,52 +1,52 @@
/*-
* Copyright © 2009 Diamond Light Source Ltd.
*
* This file is part of GDA.
*
* GDA 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.
*
* GDA 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 GDA. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.ac.gda;
/**
* A class which holds information about the testing framework state.
*/
public class ClientManager {
private static boolean testingMode = false;
/**
* @return Returns the testingMode.
*/
public static boolean isTestingMode() {
return testingMode;
}
/**
* @param testingMode The testingMode to set.
*/
public static void setTestingMode(boolean testingMode) {
ClientManager.testingMode = testingMode;
}
/**
* @return In testing mode this returns false and in gda client mode, true
*/
public static boolean isClient() {
// TODO Make test more appropriate
- if (System.getProperty("gda.root")==null || System.getProperty("gda.config")==null) {
+ if (System.getProperty("gda.config")==null) {
return false;
}
return true;
}
}
| true | true | public static boolean isClient() {
// TODO Make test more appropriate
if (System.getProperty("gda.root")==null || System.getProperty("gda.config")==null) {
return false;
}
return true;
}
| public static boolean isClient() {
// TODO Make test more appropriate
if (System.getProperty("gda.config")==null) {
return false;
}
return true;
}
|
diff --git a/src/com/ramblingwood/minecraft/jsonapi/dynamic/Call.java b/src/com/ramblingwood/minecraft/jsonapi/dynamic/Call.java
index 59425ac..957db79 100644
--- a/src/com/ramblingwood/minecraft/jsonapi/dynamic/Call.java
+++ b/src/com/ramblingwood/minecraft/jsonapi/dynamic/Call.java
@@ -1,233 +1,238 @@
package com.ramblingwood.minecraft.jsonapi.dynamic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.bukkit.Server;
import org.bukkit.plugin.Plugin;
import com.ramblingwood.minecraft.jsonapi.JSONAPI;
public class Call {
private static Server Server = JSONAPI.instance.getServer();
private static APIWrapperMethods APIInstance = APIWrapperMethods.getInstance();
private Class<?>[] signature = new Class<?>[] {};
private ArrayList<Object> stack = new ArrayList<Object>();
private HashMap<Integer, String> defaults = new HashMap<Integer, String>();
public static boolean debug = false;
private int expectedArgs = 0;
public Call (String input, ArgumentList args) {
signature = args.getTypes();
parseString(input);
}
private void debug(String in) {
if(debug) {
System.out.println(in);
}
}
public int getNumberOfExpectedArgs () {
return expectedArgs;
}
public Object call(Object[] params) throws Exception {
int size = stack.size();
ArrayList<Object> oParams = new ArrayList<Object>(Arrays.asList(params));
oParams.ensureCapacity(oParams.size()+defaults.size());
for(Integer i : defaults.keySet()) {
oParams.add(i, defaults.get(i));
}
debug("oParams:"+oParams.toString());
debug("Stack:"+stack);
Object lastResult = null;
for(int i = 0; i < size; i++) {
Object v = stack.get(i);
debug("v:"+v.getClass().getCanonicalName());
if(v instanceof Server || v instanceof APIWrapperMethods || (i == 0 && v instanceof Plugin)) {
lastResult = v;
continue;
}
if(v instanceof SubCall) {
SubCall obj = (SubCall)v;
debug("Calling method: '"+obj.getName()+"' with signature: '"+obj.requiresArgs()+"' '"+Arrays.asList(sigForIndices(obj.requiresArgs()))+"'.");
debug("Last result:"+lastResult.toString());
debug("Invoking method: '"+obj.getName()+"' with args: '"+Arrays.asList(indicies(oParams, obj.requiresArgs()))+"'.");
Object[] args = indicies(oParams, obj.requiresArgs());
Class<?>[] sig = sigForIndices(obj.requiresArgs());
for(int x = 0; x < args.length; x++) {
Object val = args[x];
if((val.getClass().equals(Long.class) || val.getClass().equals(Double.class) || val.getClass().equals(String.class)) && sig[x].equals(Integer.class)) {
args[x] = Integer.valueOf(val.toString());
val = args[x];
}
if((val.getClass().equals(Integer.class) || val.getClass().equals(Long.class) || val.getClass().equals(String.class)) && sig[x].equals(Double.class)) {
args[x] = Double.valueOf(val.toString());
val = args[x];
}
if((val.getClass().equals(Integer.class) || val.getClass().equals(Double.class) || val.getClass().equals(String.class)) && sig[x].equals(Long.class)) {
args[x] = Long.valueOf(val.toString());
val = args[x];
}
debug("Arg "+x+": '"+val+"', type: "+val.getClass().getName());
debug("Sig type: "+sig[x].getName());
}
lastResult = lastResult.getClass().getMethod(obj.getName(), sig).invoke(lastResult, args);
debug("New value:"+lastResult);
}
}
return lastResult;
}
public Object[] indicies (ArrayList<Object> o, ArrayList<Integer>i) {
if(i == null) { return new Object[] {}; }
Object[] ret = new Object[i.size()];
for(int y = 0; y < ret.length; y++) {
ret[y] = o.get(i.get(y));
}
return ret;
}
public Class<?>[] sigForIndices (ArrayList<Integer> i) {
if(i == null) { return new Class<?>[]{}; }
Class<?>[] ret = new Class<?>[i.size()];
for(int y = 0; y < ret.length; y++) {
ret[y] = signature[i.get(y)];
}
return ret;
}
public void parseString (String input) {
String[] parts = input.split("\\.");
for(int i = 0; i < parts.length; i++) {
String v = parts[i];
//if(i == 0) {
if(v.equals("Server")) {
stack.add(Server);
}
else if(v.equals("this")) {
stack.add(APIInstance);
}
else if(v.equals("Plugins")) { // handles Plugins.PLUGINNAME.pluginMethod(0,1,2)
String v2 = parts[i+1];
stack.add(Server.getPluginManager().getPlugin(v2));
continue;
}
//}
else {
// no args
if(v.endsWith("()") || !v.endsWith(")")) {
stack.add(new SubCall(v.substring(0, v.length()-2), new ArrayList<Integer>()));
}
// args
else {
// find the position of the args
int startPos = v.lastIndexOf("(");
// take the stuff in the ('s and )'s
String[] argParts = v.substring(startPos+1, v.length() - 1).split(",");
ArrayList<Integer> argPos = new ArrayList<Integer>();
// put all string 0, 1, 2, 3 etc into a int[]
int multiplier = 0;
for(int x = 0; x < argParts.length; x++) {
- if(argParts[x].startsWith("\"") && argParts[x].endsWith("\"")) {
- defaults.put(x, argParts[x].substring(1, argParts[x].length() - 1));
+ if(argParts[x].trim().startsWith("\"") && argParts[x].trim().endsWith("\"")) {
+ defaults.put(x, argParts[x].trim().substring(1, argParts[x].trim().length() - 1));
ArrayList<Class<?>> cc = new ArrayList<Class<?>>(Arrays.asList(signature));
cc.add(x, String.class);
signature = cc.toArray(signature);
if(argPos.size() > 0) {
argPos.add(argPos.get(argPos.size()-1)+1);
}
else {
argPos.add(0);
}
multiplier++;
}
else {
- argPos.add(Integer.parseInt(argParts[x].trim()) + (multiplier));
+ try {
+ argPos.add(Integer.parseInt(argParts[x].trim()) + (multiplier));
+ }
+ catch (NumberFormatException e) {
+ e.printStackTrace();
+ }
}
}
expectedArgs = argPos.size() - multiplier;
// add this "method" onto the stack
stack.add(new SubCall(v.substring(0, startPos), argPos));
}
}
}
}
class SubCall {
private String name;
private ArrayList<Integer> argPos;
public SubCall(String name, ArrayList<Integer> argPos) {
this.name = name;
this.argPos = argPos;
}
public ArrayList<Integer> requiresArgs () {
return (argPos.size() > 0 ? argPos : null);
}
public String getName() {
return name;
}
}
public Object callMethod(String method, String[] signature, Object[] params) throws Exception {
String[] parts = method.split("\\.");
Class<?>[] ps = new Class<?>[signature.length];
for(int i = 0; i< signature.length; i++) {
try {
ps[i] = Class.forName(signature[i]);
}
catch(ClassNotFoundException e) {
ps[i] = Class.forName("java.lang."+signature[i]);
}
}
Class c = Class.forName(parts[0]);
Object lastResult = new Object();
for(int i = 0; i < parts.length; i++) {
if(i == 0) {
lastResult = c.getMethod(parts[i+1], null).invoke(null, null);
}
else if(i == (parts.length - 1)) {
return lastResult;
}
else {
lastResult = lastResult.getClass().getMethod(parts[i+1], ps).invoke(lastResult, params);
}
}
return lastResult;
}
}
| false | true | public void parseString (String input) {
String[] parts = input.split("\\.");
for(int i = 0; i < parts.length; i++) {
String v = parts[i];
//if(i == 0) {
if(v.equals("Server")) {
stack.add(Server);
}
else if(v.equals("this")) {
stack.add(APIInstance);
}
else if(v.equals("Plugins")) { // handles Plugins.PLUGINNAME.pluginMethod(0,1,2)
String v2 = parts[i+1];
stack.add(Server.getPluginManager().getPlugin(v2));
continue;
}
//}
else {
// no args
if(v.endsWith("()") || !v.endsWith(")")) {
stack.add(new SubCall(v.substring(0, v.length()-2), new ArrayList<Integer>()));
}
// args
else {
// find the position of the args
int startPos = v.lastIndexOf("(");
// take the stuff in the ('s and )'s
String[] argParts = v.substring(startPos+1, v.length() - 1).split(",");
ArrayList<Integer> argPos = new ArrayList<Integer>();
// put all string 0, 1, 2, 3 etc into a int[]
int multiplier = 0;
for(int x = 0; x < argParts.length; x++) {
if(argParts[x].startsWith("\"") && argParts[x].endsWith("\"")) {
defaults.put(x, argParts[x].substring(1, argParts[x].length() - 1));
ArrayList<Class<?>> cc = new ArrayList<Class<?>>(Arrays.asList(signature));
cc.add(x, String.class);
signature = cc.toArray(signature);
if(argPos.size() > 0) {
argPos.add(argPos.get(argPos.size()-1)+1);
}
else {
argPos.add(0);
}
multiplier++;
}
else {
argPos.add(Integer.parseInt(argParts[x].trim()) + (multiplier));
}
}
expectedArgs = argPos.size() - multiplier;
// add this "method" onto the stack
stack.add(new SubCall(v.substring(0, startPos), argPos));
}
}
}
}
| public void parseString (String input) {
String[] parts = input.split("\\.");
for(int i = 0; i < parts.length; i++) {
String v = parts[i];
//if(i == 0) {
if(v.equals("Server")) {
stack.add(Server);
}
else if(v.equals("this")) {
stack.add(APIInstance);
}
else if(v.equals("Plugins")) { // handles Plugins.PLUGINNAME.pluginMethod(0,1,2)
String v2 = parts[i+1];
stack.add(Server.getPluginManager().getPlugin(v2));
continue;
}
//}
else {
// no args
if(v.endsWith("()") || !v.endsWith(")")) {
stack.add(new SubCall(v.substring(0, v.length()-2), new ArrayList<Integer>()));
}
// args
else {
// find the position of the args
int startPos = v.lastIndexOf("(");
// take the stuff in the ('s and )'s
String[] argParts = v.substring(startPos+1, v.length() - 1).split(",");
ArrayList<Integer> argPos = new ArrayList<Integer>();
// put all string 0, 1, 2, 3 etc into a int[]
int multiplier = 0;
for(int x = 0; x < argParts.length; x++) {
if(argParts[x].trim().startsWith("\"") && argParts[x].trim().endsWith("\"")) {
defaults.put(x, argParts[x].trim().substring(1, argParts[x].trim().length() - 1));
ArrayList<Class<?>> cc = new ArrayList<Class<?>>(Arrays.asList(signature));
cc.add(x, String.class);
signature = cc.toArray(signature);
if(argPos.size() > 0) {
argPos.add(argPos.get(argPos.size()-1)+1);
}
else {
argPos.add(0);
}
multiplier++;
}
else {
try {
argPos.add(Integer.parseInt(argParts[x].trim()) + (multiplier));
}
catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
expectedArgs = argPos.size() - multiplier;
// add this "method" onto the stack
stack.add(new SubCall(v.substring(0, startPos), argPos));
}
}
}
}
|
diff --git a/src/au/gov/naa/digipres/xena/util/SourceURIParser.java b/src/au/gov/naa/digipres/xena/util/SourceURIParser.java
index a5453507..8fc010bf 100644
--- a/src/au/gov/naa/digipres/xena/util/SourceURIParser.java
+++ b/src/au/gov/naa/digipres/xena/util/SourceURIParser.java
@@ -1,112 +1,112 @@
/**
* This file is part of Xena.
*
* Xena 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.
*
* Xena 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 Xena; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* @author Andrew Keeling
* @author Chris Bitmead
* @author Justin Waddell
*/
/*
* Created on 26/04/2006 andrek24
*
*/
package au.gov.naa.digipres.xena.util;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import org.xml.sax.SAXException;
import au.gov.naa.digipres.xena.javatools.FileName;
import au.gov.naa.digipres.xena.kernel.XenaInputSource;
import au.gov.naa.digipres.xena.kernel.plugin.PluginManager;
public class SourceURIParser {
/**
* Return the relative system Id for a given XenaInputSource. This assumes that
* the base path has been set in the meta data wrapper by which all local system
* id should be resolved from.
*
* TODO: aak - SourceURIParser - better description required please...
*
* @param xis
* @param pluginManager
* @return String - the relative path and name of the file relative to the base path set in
* the meta data wrapper, or, if that is not able to be resolved (ie base path is not set or
* the XIS URI has nothing to do with the base path) then the entire URI of the XIS.
* @throws SAXException - In the event that the URI from the XIS cannot be encoded.
*/
public static String getRelativeSystemId(XenaInputSource xis, PluginManager pluginManager) throws SAXException {
String xisRelativeSystemId = "";
try {
java.net.URI uri = new java.net.URI(xis.getSystemId());
if (uri.getScheme() != null && "file".equals(uri.getScheme())) {
File inputSourceFile = new File(uri);
String relativePath = null;
File baseDir;
/*
* Get the path location.
*
* First off, see if we can get a path from the filter manager, and get a relative path.
* If no success, then we set the path to be the full path name.
*
*/
if (pluginManager.getMetaDataWrapperManager().getBasePathName() != null) {
try {
baseDir = new File(pluginManager.getMetaDataWrapperManager().getBasePathName());
relativePath = FileName.relativeTo(baseDir, inputSourceFile);
} catch (IOException iox) {
// Nothing to do here as we have another go at setting the base path further down
}
}
if (relativePath == null) {
- relativePath = inputSourceFile.getAbsolutePath();
+ relativePath = inputSourceFile.getName();
}
String encodedPath = null;
try {
encodedPath = au.gov.naa.digipres.xena.util.UrlEncoder.encode(relativePath);
} catch (UnsupportedEncodingException x) {
throw new SAXException(x);
}
xisRelativeSystemId = "file:/" + encodedPath;
} else {
xisRelativeSystemId = xis.getSystemId();
}
} catch (URISyntaxException xe) {
xisRelativeSystemId = xis.getSystemId();
}
return xisRelativeSystemId;
}
/**
* Return only the filename component of the source uri.
* Basically everything after the last '/' and '\'.
*
* TODO: aak - SourceURIParser - better description required please...
*
* @param xis
* @return
*/
public static String getFileNameComponent(XenaInputSource xis) {
String systemId = xis.getSystemId();
int backslashIndex = systemId.lastIndexOf("\\");
int slashIndex = systemId.lastIndexOf("/");
int lastIndex = backslashIndex > slashIndex ? backslashIndex : slashIndex;
return systemId.substring(lastIndex + 1);
}
}
| true | true | public static String getRelativeSystemId(XenaInputSource xis, PluginManager pluginManager) throws SAXException {
String xisRelativeSystemId = "";
try {
java.net.URI uri = new java.net.URI(xis.getSystemId());
if (uri.getScheme() != null && "file".equals(uri.getScheme())) {
File inputSourceFile = new File(uri);
String relativePath = null;
File baseDir;
/*
* Get the path location.
*
* First off, see if we can get a path from the filter manager, and get a relative path.
* If no success, then we set the path to be the full path name.
*
*/
if (pluginManager.getMetaDataWrapperManager().getBasePathName() != null) {
try {
baseDir = new File(pluginManager.getMetaDataWrapperManager().getBasePathName());
relativePath = FileName.relativeTo(baseDir, inputSourceFile);
} catch (IOException iox) {
// Nothing to do here as we have another go at setting the base path further down
}
}
if (relativePath == null) {
relativePath = inputSourceFile.getAbsolutePath();
}
String encodedPath = null;
try {
encodedPath = au.gov.naa.digipres.xena.util.UrlEncoder.encode(relativePath);
} catch (UnsupportedEncodingException x) {
throw new SAXException(x);
}
xisRelativeSystemId = "file:/" + encodedPath;
} else {
xisRelativeSystemId = xis.getSystemId();
}
} catch (URISyntaxException xe) {
xisRelativeSystemId = xis.getSystemId();
}
return xisRelativeSystemId;
}
| public static String getRelativeSystemId(XenaInputSource xis, PluginManager pluginManager) throws SAXException {
String xisRelativeSystemId = "";
try {
java.net.URI uri = new java.net.URI(xis.getSystemId());
if (uri.getScheme() != null && "file".equals(uri.getScheme())) {
File inputSourceFile = new File(uri);
String relativePath = null;
File baseDir;
/*
* Get the path location.
*
* First off, see if we can get a path from the filter manager, and get a relative path.
* If no success, then we set the path to be the full path name.
*
*/
if (pluginManager.getMetaDataWrapperManager().getBasePathName() != null) {
try {
baseDir = new File(pluginManager.getMetaDataWrapperManager().getBasePathName());
relativePath = FileName.relativeTo(baseDir, inputSourceFile);
} catch (IOException iox) {
// Nothing to do here as we have another go at setting the base path further down
}
}
if (relativePath == null) {
relativePath = inputSourceFile.getName();
}
String encodedPath = null;
try {
encodedPath = au.gov.naa.digipres.xena.util.UrlEncoder.encode(relativePath);
} catch (UnsupportedEncodingException x) {
throw new SAXException(x);
}
xisRelativeSystemId = "file:/" + encodedPath;
} else {
xisRelativeSystemId = xis.getSystemId();
}
} catch (URISyntaxException xe) {
xisRelativeSystemId = xis.getSystemId();
}
return xisRelativeSystemId;
}
|
diff --git a/Meteor/testcases/test/nchelp/meteor/SAMLAssertionTest.java b/Meteor/testcases/test/nchelp/meteor/SAMLAssertionTest.java
index eaa285f1..b69fe9d3 100755
--- a/Meteor/testcases/test/nchelp/meteor/SAMLAssertionTest.java
+++ b/Meteor/testcases/test/nchelp/meteor/SAMLAssertionTest.java
@@ -1,156 +1,156 @@
/**
*
* Copyright 2002 NCHELP
*
* Author: Tim Bornholtz, Priority Technologies, Inc.
*
*
* This code is part of the Meteor system as defined and specified
* by the National Council of Higher Education Loan Programs, Inc.
* (NCHELP) and the Meteor Sponsors, and developed by Priority
* Technologies, Inc. (PTI).
*
*
* 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 test.nchelp.meteor;
import java.net.UnknownHostException;
import java.util.Date;
import junit.framework.TestCase;
import junit.textui.TestRunner;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nchelp.meteor.security.SecurityToken;
import org.nchelp.meteor.security.saml.Assertion;
import org.nchelp.meteor.security.saml.AssertionFactory;
import org.nchelp.meteor.security.saml.AttributeStatement;
import org.nchelp.meteor.security.saml.NameIdentifier;
import org.nchelp.meteor.security.saml.SAMLUtil;
import org.nchelp.meteor.security.saml.Subject;
import org.nchelp.meteor.util.XMLParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class SAMLAssertionTest extends TestCase {
private final Log log = LogFactory.getLog(this.getClass());
public SAMLAssertionTest(String name) {
super(name);
}
public static void main(String args[]) {
TestRunner.run(SAMLAssertionTest.class);
}
public void testSaml() {
String userid = "ED.303";
try {
Assertion aa = AssertionFactory.newInstance(
- new String( new Long(System.currentTimeMillis()).toString() ),
+ Long.toString(System.currentTimeMillis()) ,
"nchelp.org/meteor",
new Date(),
userid,
"nchelp.org/meteor",
"http://nchelp.org",
new Date(),
java.net.InetAddress.getLocalHost().getHostAddress(),
java.net.InetAddress.getLocalHost().getHostName()
);
NameIdentifier ni = new NameIdentifier();
ni.setSecurityDomain("nchelp.org/meteor");
ni.setName(userid);
Subject subject = new Subject();
subject.setNameIdentifier(ni);
AttributeStatement as = new AttributeStatement();
as.setSubject(subject);
as.addAttribute("Role", "nchelp.org/meteor", SecurityToken.roleFAA);
aa.addStatement(as);
aa.setAttributeValue("Level", "nchelp.org/meteor", "3");
Document doc = SAMLUtil.newDocument();
Element e = doc.createElement("AssertionSpecifier");
doc.appendChild(e);
aa.serialize(e);
System.out.println(XMLParser.xmlToString(doc));
} catch(UnknownHostException e) {
e.printStackTrace();
fail();
}
}
public void testSamlDeserialization(){
String saml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><AssertionSpecifier> <saml:Assertion AssertionID=\"1017033169855\" IssueInstant=\"2002-03-24T11:12:49CST\" Issuer=\"nchelp.org/meteor\" MajorVersion=\"1\" MinorVersion=\"0\" xmlns:saml=\"http://www.oasis-open.org/committees/security/docs/draft-sstc-schema-assertion-27.xsd\"> <saml:AuthenticationStatement AuthenticationInstant=\"2002-03-24T11:12:49CST\" AuthenticationMethod=\"http://nchelp.org\"> <saml:Subject> <saml:NameIdentifier Name=\"ED.303\" SecurityDomain=\"nchelp.org/meteor\"/> </saml:Subject> <saml:AuthenticationLocality DNSAddress=\"GERTRUDE\" IPAddress=\"127.0.0.1\"/> </saml:AuthenticationStatement> <saml:AttributeStatement> <saml:Subject> <saml:NameIdentifier Name=\"ED.303\" SecurityDomain=\"nchelp.org/meteor\"/> </saml:Subject> <saml:Attribute AttributeName=\"Role\" AttributeNamespace=\"nchelp.org/meteor\"> <saml:AttributeValue>FAA</saml:AttributeValue> </saml:Attribute> </saml:AttributeStatement> </saml:Assertion></AssertionSpecifier>";
Assertion a = new Assertion();
try {
Document doc1 = XMLParser.parseXML(saml);
Element rootNode = doc1.getDocumentElement();
NodeList nl = rootNode.getChildNodes();
for(int n = 0; n < nl.getLength(); n++){
Node node = nl.item(n);
if(node.getNodeType() == Node.ELEMENT_NODE){
if("Assertion".equals(node.getLocalName())){
a.deserialize((Element)node);
}
}
}
} catch(Exception e) {
e.printStackTrace();
fail();
}
System.out.println("Role: " + a.getAttributeValue("Role", "nchelp.org/meteor"));
Document doc2 = SAMLUtil.newDocument();
Element e = doc2.createElement("AssertionSpecifier");
doc2.appendChild(e);
a.serialize(e);
System.out.println(XMLParser.xmlToString(doc2));
}
}
| true | true | public void testSaml() {
String userid = "ED.303";
try {
Assertion aa = AssertionFactory.newInstance(
new String( new Long(System.currentTimeMillis()).toString() ),
"nchelp.org/meteor",
new Date(),
userid,
"nchelp.org/meteor",
"http://nchelp.org",
new Date(),
java.net.InetAddress.getLocalHost().getHostAddress(),
java.net.InetAddress.getLocalHost().getHostName()
);
NameIdentifier ni = new NameIdentifier();
ni.setSecurityDomain("nchelp.org/meteor");
ni.setName(userid);
Subject subject = new Subject();
subject.setNameIdentifier(ni);
AttributeStatement as = new AttributeStatement();
as.setSubject(subject);
as.addAttribute("Role", "nchelp.org/meteor", SecurityToken.roleFAA);
aa.addStatement(as);
aa.setAttributeValue("Level", "nchelp.org/meteor", "3");
Document doc = SAMLUtil.newDocument();
Element e = doc.createElement("AssertionSpecifier");
doc.appendChild(e);
aa.serialize(e);
System.out.println(XMLParser.xmlToString(doc));
} catch(UnknownHostException e) {
e.printStackTrace();
fail();
}
}
| public void testSaml() {
String userid = "ED.303";
try {
Assertion aa = AssertionFactory.newInstance(
Long.toString(System.currentTimeMillis()) ,
"nchelp.org/meteor",
new Date(),
userid,
"nchelp.org/meteor",
"http://nchelp.org",
new Date(),
java.net.InetAddress.getLocalHost().getHostAddress(),
java.net.InetAddress.getLocalHost().getHostName()
);
NameIdentifier ni = new NameIdentifier();
ni.setSecurityDomain("nchelp.org/meteor");
ni.setName(userid);
Subject subject = new Subject();
subject.setNameIdentifier(ni);
AttributeStatement as = new AttributeStatement();
as.setSubject(subject);
as.addAttribute("Role", "nchelp.org/meteor", SecurityToken.roleFAA);
aa.addStatement(as);
aa.setAttributeValue("Level", "nchelp.org/meteor", "3");
Document doc = SAMLUtil.newDocument();
Element e = doc.createElement("AssertionSpecifier");
doc.appendChild(e);
aa.serialize(e);
System.out.println(XMLParser.xmlToString(doc));
} catch(UnknownHostException e) {
e.printStackTrace();
fail();
}
}
|
diff --git a/src/main/java/org/devtcg/five/meta/FileCrawler.java b/src/main/java/org/devtcg/five/meta/FileCrawler.java
index e54e443..62fec03 100644
--- a/src/main/java/org/devtcg/five/meta/FileCrawler.java
+++ b/src/main/java/org/devtcg/five/meta/FileCrawler.java
@@ -1,559 +1,559 @@
/*
* Copyright (C) 2009 Josh Guilfoyle <[email protected]>
*
* 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, 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.
*/
package org.devtcg.five.meta;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.devtcg.five.meta.dao.AlbumDAO;
import org.devtcg.five.meta.dao.ArtistDAO;
import org.devtcg.five.meta.dao.PlaylistDAO;
import org.devtcg.five.meta.dao.SongDAO;
import org.devtcg.five.meta.dao.PlaylistDAO.Playlist;
import org.devtcg.five.meta.dao.PlaylistDAO.PlaylistEntryDAO;
import org.devtcg.five.persistence.Configuration;
import org.devtcg.five.util.CancelableExecutor;
import org.devtcg.five.util.CancelableThread;
import org.devtcg.five.util.FileUtils;
import org.devtcg.five.util.StringUtils;
import entagged.audioformats.AudioFile;
import entagged.audioformats.AudioFileIO;
import entagged.audioformats.Tag;
import entagged.audioformats.exceptions.CannotReadException;
public class FileCrawler
{
private static final Log LOG = LogFactory.getLog(FileCrawler.class);
private static FileCrawler INSTANCE;
private CrawlerThread mThread;
private List<String> mPaths;
private Listener mListener;
public interface Listener
{
public void onStart();
public void onProgress(int scannedSoFar);
public void onFinished(boolean canceled);
}
private FileCrawler()
{
try {
setPaths(Configuration.getInstance().getLibraryPaths());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public static synchronized FileCrawler getInstance()
{
if (INSTANCE == null)
INSTANCE = new FileCrawler();
return INSTANCE;
}
private void setPaths(List<String> paths)
{
mPaths = paths;
}
public void setListener(Listener l)
{
mListener = l;
}
public synchronized void startScan()
{
if (mThread == null)
{
mThread = new CrawlerThread(MetaProvider.getInstance());
mThread.start();
}
}
public synchronized void stopAbruptly()
{
if (mThread != null)
{
mThread.requestCancelAndWait();
/* Should have been set to null by the thread itself. */
assert mThread == null;
}
}
public synchronized boolean isActive()
{
return mThread != null;
}
private class CrawlerThread extends CancelableThread
{
/**
* Used to execute network tasks which will collect extra meta data
* than is available on the filesystem. Currently uses both MusicBrainz
* and Last.fm.
*/
private final CancelableExecutor mNetworkMetaExecutor =
new CancelableExecutor(new LinkedBlockingQueue<FutureTask<?>>());
private final MetaProvider mProvider;
private int mFilesScanned = 0;
public CrawlerThread(MetaProvider provider)
{
setName("FileCrawler");
setPriority(Thread.MIN_PRIORITY);
mProvider = provider;
}
private boolean isPlaylist(File file, String ext)
{
if (ext == null)
return false;
if (ext.equalsIgnoreCase("pls") == true)
return true;
if (ext.equalsIgnoreCase("m3u") == true)
return true;
return false;
}
private boolean isSong(File file, String ext)
{
/* TODO: Inspect the file, do not rely on file extension. */
if (ext == null)
return false;
if (ext.equalsIgnoreCase("mp3") == true)
return true;
// if (ext.equalsIgnoreCase("ogg") == true)
// return true;
//
// if (ext.equalsIgnoreCase("wma") == true)
// return true;
//
// if (ext.equalsIgnoreCase("flac") == true)
// return true;
//
// if (ext.equalsIgnoreCase("m4a") == true)
// return true;
return false;
}
private long processPlaylistSong(PlaylistEntryDAO existing, Playlist playlistBuf,
File entry) throws SQLException
{
if (entry.exists() == false || isSong(entry, FileUtils.getExtension(entry)) == false)
return -1;
/*
* Make sure we have this song in our database to send to clients.
* Duplicates will be prevented by the normal filesystem logic.
*/
long songId = handleFileSong(entry);
if (songId == -1)
return -1;
/*
* Try to detect if an existing playlist has any songs deleted or
* changed positions. This will trigger an updated sync time which
* will then communicate the entire new playlist to the client on
* sync.
*/
if (existing != null && playlistBuf.hasChanges == false)
{
long songAtPos = mProvider.getPlaylistSongDAO().getSongAtPosition(existing.getId(),
playlistBuf.songs.size());
if (songAtPos != songId)
playlistBuf.hasChanges = true;
}
playlistBuf.songs.add(songId);
return songId;
}
private long handlePlaylistPls(File file) throws SQLException
{
try {
BufferedReader reader = new BufferedReader(new FileReader(file), 1024);
/* Sanity check. */
String firstLine = reader.readLine();
if (firstLine == null || firstLine.trim().equalsIgnoreCase("[playlist]") == false)
return -1;
PlaylistDAO.PlaylistEntryDAO existingPlaylist =
mProvider.getPlaylistDAO().getPlaylist(file.getAbsolutePath());
/*
* Temporary container used to buffer all playlist entries in
* order to effectively detect changes before we commit to the
* database.
*/
PlaylistDAO.Playlist playlistBuf =
mProvider.getPlaylistDAO().newPlaylist();
String line;
while ((line = reader.readLine()) != null)
{
line = line.trim();
if (line.startsWith("File"))
{
String[] keyPair = line.split("=", 2);
if (keyPair.length < 2)
continue;
File entry;
try {
URL entryUrl = new URL(URLDecoder.decode(keyPair[1], "UTF-8"));
entry = new File(entryUrl.getFile());
} catch (MalformedURLException e) {
entry = new File(keyPair[1]);
if (!entry.isAbsolute()) {
- entry = entry.getAbsoluteFile();
+ entry = new File(file.getAbsoluteFile().getParent(), keyPair[1]);
}
}
System.out.println("entry=" + entry);
processPlaylistSong(existingPlaylist, playlistBuf, entry);
}
}
/*
* Couldn't parse any of the playlist entries, or it contained
* none.
*/
if (playlistBuf.songs.isEmpty())
{
if (existingPlaylist == null)
return -1;
else
throw new UnsupportedOperationException("Need to delete, but not implemented.");
}
long id;
if (existingPlaylist == null)
{
id = mProvider.getPlaylistDAO().insert(file.getAbsolutePath(),
FileUtils.removeExtension(file.getName()), System.currentTimeMillis());
}
else
{
id = existingPlaylist.getId();
mProvider.getPlaylistDAO().unmark(id);
}
if (existingPlaylist == null || playlistBuf.hasChanges)
{
if (existingPlaylist != null)
mProvider.getPlaylistSongDAO().deleteByPlaylist(id);
int pos = 0;
for (long songId: playlistBuf.songs)
mProvider.getPlaylistSongDAO().insert(id, pos++, songId);
}
return id;
} catch (IOException e) {
return -1;
}
}
private long handlePlaylistM3u(File file) throws SQLException
{
return -1;
}
private long handleFilePlaylist(File file) throws SQLException
{
String ext = FileUtils.getExtension(file);
long id = -1;
if (ext != null)
{
if (ext.equalsIgnoreCase("m3u") == true)
id = handlePlaylistM3u(file);
else if (ext.equalsIgnoreCase("pls") == true)
id = handlePlaylistPls(file);
}
if (id == -1)
{
if (LOG.isWarnEnabled())
LOG.warn("Can't handle playlist file " + file.getAbsolutePath());
}
return id;
}
private String stringTagValue(List<?> tagValue, String prefixHack, String defaultValue)
{
if (tagValue == null || tagValue.size() == 0)
return defaultValue;
String value = tagValue.get(0).toString();
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
/*
* For some reason entagged prepends a prefix like "ARTIST : " on
* id3v1 records. Seems like a bug, but I don't have the energy to
* fix it upstream at the moment.
*/
if (prefixHack != null && value.startsWith(prefixHack))
return value.substring(prefixHack.length());
else
return value;
}
private int intTagValue(List<?> tagValue, int defaultValue)
{
String value = stringTagValue(tagValue, null, null);
if (value == null)
return defaultValue;
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
return defaultValue;
}
}
private long getArtistId(String artist) throws SQLException
{
String nameMatch = StringUtils.getNameMatch(artist);
ArtistDAO.ArtistEntryDAO artistEntry =
mProvider.getArtistDAO().getArtist(nameMatch);
if (artistEntry == null)
{
long id = mProvider.getArtistDAO().insert(artist);
mNetworkMetaExecutor.execute(new LastfmArtistPhotoTask(mProvider,
id, artist).getTask());
return id;
}
try {
return artistEntry.getId();
} finally {
artistEntry.close();
}
}
private long getAlbumId(long artistId, String album) throws SQLException
{
String nameMatch = StringUtils.getNameMatch(album);
AlbumDAO.AlbumEntryDAO albumEntry =
mProvider.getAlbumDAO().getAlbum(artistId, nameMatch);
if (albumEntry == null)
{
ArtistDAO.ArtistEntryDAO artistEntry =
mProvider.getArtistDAO().getArtist(artistId);
long id = mProvider.getAlbumDAO().insert(artistId, album);
mNetworkMetaExecutor.execute(new LastfmAlbumArtworkTask(mProvider,
id, artistEntry.getName(), album).getTask());
return id;
}
try {
return albumEntry.getId();
} finally {
albumEntry.close();
}
}
private long handleFileSong(File file) throws SQLException
{
SongDAO.SongEntryDAO existingEntry =
mProvider.getSongDAO().getSong(file.getAbsolutePath());
/* Typical case; no data needs to be updated. */
try {
if (existingEntry != null &&
existingEntry.getMtime() == file.lastModified())
{
mProvider.getSongDAO().unmark(existingEntry.getId());
return existingEntry.getId();
}
else
{
/*
* This file is either new or has been updated since the last time
* we scanned. Re-parse.
*/
return handleFileNewOrUpdatedSong(file, existingEntry);
}
} finally {
if (existingEntry != null)
existingEntry.close();
}
}
private long handleFileNewOrUpdatedSong(File file, SongDAO.SongEntryDAO existingEntry)
throws SQLException
{
try {
AudioFile audioFile = AudioFileIO.read(file);
Tag tag = audioFile.getTag();
String artist = stringTagValue(tag.getArtist(), "ARTIST : ", "<Unknown>");
String album = stringTagValue(tag.getAlbum(), "ALBUM : ", "<Unknown>");
String title = stringTagValue(tag.getTitle(), "TITLE : ", null);
int bitrate = audioFile.getBitrate();
int length = audioFile.getLength();
int track = intTagValue(tag.getTrack(), -1);
/* Title is actually the only property we strictly require. */
if (title == null)
throw new CannotReadException("No title property set");
long artistId = getArtistId(artist);
long albumId = getAlbumId(artistId, album);
SongDAO.Song song = mProvider.getSongDAO().newSong(file,
artistId, albumId, title, bitrate, length, track);
if (existingEntry != null)
return mProvider.getSongDAO().update(existingEntry.getId(), song);
else
return mProvider.getSongDAO().insert(song);
} catch (CannotReadException e) {
if (LOG.isWarnEnabled())
LOG.warn(file + ": unable to parse song: " + e);
return -1;
}
}
private boolean handleFile(File file) throws SQLException
{
String ext = FileUtils.getExtension(file);
if (isPlaylist(file, ext) == true)
return handleFilePlaylist(file) != -1;
else if (isSong(file, ext) == true)
return handleFileSong(file) != -1;
return false;
}
/**
* Recursively scan a given path, inserting any entries into the
* temporary provider.
*/
private void traverse(File path) throws SQLException
{
File[] files = path.listFiles();
if (files == null)
return;
for (File file : files)
{
if (hasCanceled() == true)
return;
if (file.isDirectory() == true)
traverse(file);
else if (file.isFile() == true)
{
if (handleFile(file))
{
mFilesScanned++;
if (mListener != null)
mListener.onProgress(mFilesScanned);
}
}
}
}
private void deleteAllMarked() throws SQLException
{
/* TODO */
}
private void crawlImpl() throws SQLException
{
mProvider.getSongDAO().markAll();
for (String path : mPaths)
traverse(new File(path));
/* Delete every entry that hasn't been unmarked during traversal. */
deleteAllMarked();
/* Will work whether we were canceled or not. */
mNetworkMetaExecutor.shutdownAndWait();
}
public void run()
{
if (mListener != null)
mListener.onStart();
try {
crawlImpl();
} catch (SQLException e) {
/* TODO */
e.printStackTrace();
} finally {
synchronized (FileCrawler.this) {
mThread = null;
}
if (mListener != null)
mListener.onFinished(hasCanceled());
}
}
@Override
protected void onRequestCancel()
{
interrupt();
mNetworkMetaExecutor.requestCancel();
}
}
}
| true | true | private long handlePlaylistPls(File file) throws SQLException
{
try {
BufferedReader reader = new BufferedReader(new FileReader(file), 1024);
/* Sanity check. */
String firstLine = reader.readLine();
if (firstLine == null || firstLine.trim().equalsIgnoreCase("[playlist]") == false)
return -1;
PlaylistDAO.PlaylistEntryDAO existingPlaylist =
mProvider.getPlaylistDAO().getPlaylist(file.getAbsolutePath());
/*
* Temporary container used to buffer all playlist entries in
* order to effectively detect changes before we commit to the
* database.
*/
PlaylistDAO.Playlist playlistBuf =
mProvider.getPlaylistDAO().newPlaylist();
String line;
while ((line = reader.readLine()) != null)
{
line = line.trim();
if (line.startsWith("File"))
{
String[] keyPair = line.split("=", 2);
if (keyPair.length < 2)
continue;
File entry;
try {
URL entryUrl = new URL(URLDecoder.decode(keyPair[1], "UTF-8"));
entry = new File(entryUrl.getFile());
} catch (MalformedURLException e) {
entry = new File(keyPair[1]);
if (!entry.isAbsolute()) {
entry = entry.getAbsoluteFile();
}
}
System.out.println("entry=" + entry);
processPlaylistSong(existingPlaylist, playlistBuf, entry);
}
}
/*
* Couldn't parse any of the playlist entries, or it contained
* none.
*/
if (playlistBuf.songs.isEmpty())
{
if (existingPlaylist == null)
return -1;
else
throw new UnsupportedOperationException("Need to delete, but not implemented.");
}
long id;
if (existingPlaylist == null)
{
id = mProvider.getPlaylistDAO().insert(file.getAbsolutePath(),
FileUtils.removeExtension(file.getName()), System.currentTimeMillis());
}
else
{
id = existingPlaylist.getId();
mProvider.getPlaylistDAO().unmark(id);
}
if (existingPlaylist == null || playlistBuf.hasChanges)
{
if (existingPlaylist != null)
mProvider.getPlaylistSongDAO().deleteByPlaylist(id);
int pos = 0;
for (long songId: playlistBuf.songs)
mProvider.getPlaylistSongDAO().insert(id, pos++, songId);
}
return id;
} catch (IOException e) {
return -1;
}
}
| private long handlePlaylistPls(File file) throws SQLException
{
try {
BufferedReader reader = new BufferedReader(new FileReader(file), 1024);
/* Sanity check. */
String firstLine = reader.readLine();
if (firstLine == null || firstLine.trim().equalsIgnoreCase("[playlist]") == false)
return -1;
PlaylistDAO.PlaylistEntryDAO existingPlaylist =
mProvider.getPlaylistDAO().getPlaylist(file.getAbsolutePath());
/*
* Temporary container used to buffer all playlist entries in
* order to effectively detect changes before we commit to the
* database.
*/
PlaylistDAO.Playlist playlistBuf =
mProvider.getPlaylistDAO().newPlaylist();
String line;
while ((line = reader.readLine()) != null)
{
line = line.trim();
if (line.startsWith("File"))
{
String[] keyPair = line.split("=", 2);
if (keyPair.length < 2)
continue;
File entry;
try {
URL entryUrl = new URL(URLDecoder.decode(keyPair[1], "UTF-8"));
entry = new File(entryUrl.getFile());
} catch (MalformedURLException e) {
entry = new File(keyPair[1]);
if (!entry.isAbsolute()) {
entry = new File(file.getAbsoluteFile().getParent(), keyPair[1]);
}
}
System.out.println("entry=" + entry);
processPlaylistSong(existingPlaylist, playlistBuf, entry);
}
}
/*
* Couldn't parse any of the playlist entries, or it contained
* none.
*/
if (playlistBuf.songs.isEmpty())
{
if (existingPlaylist == null)
return -1;
else
throw new UnsupportedOperationException("Need to delete, but not implemented.");
}
long id;
if (existingPlaylist == null)
{
id = mProvider.getPlaylistDAO().insert(file.getAbsolutePath(),
FileUtils.removeExtension(file.getName()), System.currentTimeMillis());
}
else
{
id = existingPlaylist.getId();
mProvider.getPlaylistDAO().unmark(id);
}
if (existingPlaylist == null || playlistBuf.hasChanges)
{
if (existingPlaylist != null)
mProvider.getPlaylistSongDAO().deleteByPlaylist(id);
int pos = 0;
for (long songId: playlistBuf.songs)
mProvider.getPlaylistSongDAO().insert(id, pos++, songId);
}
return id;
} catch (IOException e) {
return -1;
}
}
|
diff --git a/src/org/apache/xerces/impl/dv/dtd/ListDatatypeValidator.java b/src/org/apache/xerces/impl/dv/dtd/ListDatatypeValidator.java
index f05f80677..6a38f40c6 100644
--- a/src/org/apache/xerces/impl/dv/dtd/ListDatatypeValidator.java
+++ b/src/org/apache/xerces/impl/dv/dtd/ListDatatypeValidator.java
@@ -1,105 +1,105 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.impl.dv.dtd;
import org.apache.xerces.impl.dv.*;
import java.util.StringTokenizer;
/**
* For list types: ENTITIES, IDREFS, NMTOKENS.
*
* @author Jeffrey Rodriguez, IBM
* @author Sandy Gao, IBM
*
* @version $Id$
*/
public class ListDatatypeValidator implements DatatypeValidator {
// the type of items in the list
DatatypeValidator fItemValidator;
// construct a list datatype validator
public ListDatatypeValidator(DatatypeValidator itemDV) {
fItemValidator = itemDV;
}
/**
* Checks that "content" string is valid.
* If invalid a Datatype validation exception is thrown.
*
* @param content the string value that needs to be validated
* @param context the validation context
* @throws InvalidDatatypeException if the content is
* invalid according to the rules for the validators
* @see InvalidDatatypeValueException
*/
public void validate(String content, ValidationContext context) throws InvalidDatatypeValueException {
- StringTokenizer parsedList = new StringTokenizer(content);
+ StringTokenizer parsedList = new StringTokenizer(content," ");
int numberOfTokens = parsedList.countTokens();
if (numberOfTokens == 0) {
throw new InvalidDatatypeValueException("EmptyList", null);
}
//Check each token in list against base type
while (parsedList.hasMoreTokens()) {
this.fItemValidator.validate(parsedList.nextToken(), context);
}
}
}
| true | true | public void validate(String content, ValidationContext context) throws InvalidDatatypeValueException {
StringTokenizer parsedList = new StringTokenizer(content);
int numberOfTokens = parsedList.countTokens();
if (numberOfTokens == 0) {
throw new InvalidDatatypeValueException("EmptyList", null);
}
//Check each token in list against base type
while (parsedList.hasMoreTokens()) {
this.fItemValidator.validate(parsedList.nextToken(), context);
}
}
| public void validate(String content, ValidationContext context) throws InvalidDatatypeValueException {
StringTokenizer parsedList = new StringTokenizer(content," ");
int numberOfTokens = parsedList.countTokens();
if (numberOfTokens == 0) {
throw new InvalidDatatypeValueException("EmptyList", null);
}
//Check each token in list against base type
while (parsedList.hasMoreTokens()) {
this.fItemValidator.validate(parsedList.nextToken(), context);
}
}
|
diff --git a/src/se/bthstudent/sis/afk/GLaDOS/ConfigurationApparatus.java b/src/se/bthstudent/sis/afk/GLaDOS/ConfigurationApparatus.java
index a6916d3..9ff7a82 100644
--- a/src/se/bthstudent/sis/afk/GLaDOS/ConfigurationApparatus.java
+++ b/src/se/bthstudent/sis/afk/GLaDOS/ConfigurationApparatus.java
@@ -1,73 +1,73 @@
package se.bthstudent.sis.afk.GLaDOS;
import java.io.*;
public class ConfigurationApparatus {
private String[] channels;
private TestSubject[] admins;
private String password;
private String server;
public ConfigurationApparatus() {
this.channels = new String[0];
this.admins = new TestSubject[0];
this.password = "gasegvioaejrgioajwetg4iojhawergjaweiprgjse89gjaejkrgawjg8jawopjhmae0gb";
this.server = "";
}
public void readConfig() {
String location = ".GLaDOS.conf";
try {
BufferedReader in = new BufferedReader(new FileReader(location));
String read = in.readLine();
while (read != null) {
if (!read.equals("")) {
String[] parts = read.split(" ");
if (parts[0].equals("channels:")) {
this.channels = new String[parts.length - 1];
System.arraycopy(parts, 1, this.channels, 0,
this.channels.length);
} else if (parts[0].equals("password:")) {
this.password = parts[1];
} else if (parts[0].equals("admins:")) {
this.admins = new TestSubject[parts.length - 1];
for (int i = 0; i < this.admins.length; i++) {
String[] temp = { parts[i + 1] };
this.admins[i] = new TestSubject(temp[0], temp,
TestSubject.Mode.NONE, true);
}
} else if (parts[0].equals("server:")) {
this.server = parts[1];
}
}
read = in.readLine();
}
} catch (IOException e) {
System.out
- .println(".GLaDOS.rc doesn't exist, please create before running GLaDOS");
+ .println(".GLaDOS.conf doesn't exist, please create before running GLaDOS");
System.exit(0);
}
}
public String[] getChannels() {
return this.channels;
}
public TestSubject[] getAdmins() {
return this.admins;
}
public String getPassword() {
return this.password;
}
public String getServer() {
return this.server;
}
}
| true | true | public void readConfig() {
String location = ".GLaDOS.conf";
try {
BufferedReader in = new BufferedReader(new FileReader(location));
String read = in.readLine();
while (read != null) {
if (!read.equals("")) {
String[] parts = read.split(" ");
if (parts[0].equals("channels:")) {
this.channels = new String[parts.length - 1];
System.arraycopy(parts, 1, this.channels, 0,
this.channels.length);
} else if (parts[0].equals("password:")) {
this.password = parts[1];
} else if (parts[0].equals("admins:")) {
this.admins = new TestSubject[parts.length - 1];
for (int i = 0; i < this.admins.length; i++) {
String[] temp = { parts[i + 1] };
this.admins[i] = new TestSubject(temp[0], temp,
TestSubject.Mode.NONE, true);
}
} else if (parts[0].equals("server:")) {
this.server = parts[1];
}
}
read = in.readLine();
}
} catch (IOException e) {
System.out
.println(".GLaDOS.rc doesn't exist, please create before running GLaDOS");
System.exit(0);
}
}
| public void readConfig() {
String location = ".GLaDOS.conf";
try {
BufferedReader in = new BufferedReader(new FileReader(location));
String read = in.readLine();
while (read != null) {
if (!read.equals("")) {
String[] parts = read.split(" ");
if (parts[0].equals("channels:")) {
this.channels = new String[parts.length - 1];
System.arraycopy(parts, 1, this.channels, 0,
this.channels.length);
} else if (parts[0].equals("password:")) {
this.password = parts[1];
} else if (parts[0].equals("admins:")) {
this.admins = new TestSubject[parts.length - 1];
for (int i = 0; i < this.admins.length; i++) {
String[] temp = { parts[i + 1] };
this.admins[i] = new TestSubject(temp[0], temp,
TestSubject.Mode.NONE, true);
}
} else if (parts[0].equals("server:")) {
this.server = parts[1];
}
}
read = in.readLine();
}
} catch (IOException e) {
System.out
.println(".GLaDOS.conf doesn't exist, please create before running GLaDOS");
System.exit(0);
}
}
|
diff --git a/src/test/java/org/spout/api/util/cuboid/CuboidNibbleLightBufferTest.java b/src/test/java/org/spout/api/util/cuboid/CuboidNibbleLightBufferTest.java
index 7d1d095d5..a54cded46 100644
--- a/src/test/java/org/spout/api/util/cuboid/CuboidNibbleLightBufferTest.java
+++ b/src/test/java/org/spout/api/util/cuboid/CuboidNibbleLightBufferTest.java
@@ -1,131 +1,131 @@
/*
* This file is part of SpoutAPI.
*
* Copyright (c) 2011-2012, Spout LLC <http://www.spout.org/>
* SpoutAPI is licensed under the Spout License Version 1.
*
* SpoutAPI 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.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the Spout License Version 1.
*
* SpoutAPI 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,
* the MIT license and the Spout License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://spout.in/licensev1> for the full license, including
* the MIT license.
*/
package org.spout.api.util.cuboid;
import static org.junit.Assert.assertTrue;
import java.util.Random;
import org.junit.Test;
public class CuboidNibbleLightBufferTest {
private final int SIZE = 16;
private final int HALF_SIZE = 16;
private final int LOOPS = 10;
@Test
public void copyTest() {
Random r = new Random();
for (int c = 0; c < LOOPS; c++) {
int bx = r.nextInt();
int by = r.nextInt();
int bz = r.nextInt();
int sx = r.nextInt(SIZE) + SIZE;
int sy = r.nextInt(SIZE) + SIZE;
int sz = r.nextInt(SIZE) + SIZE;
int vol = sx * sy * sz;
if ((vol | 1) == vol) {
sx = sx & (~1);
}
short destId = (short) r.nextInt();
- CuboidNibbleLightBuffer dest = new CuboidNibbleLightBuffer(destId, bx, by, bz, sx, sy, sz);
+ CuboidNibbleLightBuffer dest = new CuboidNibbleLightBuffer(null, destId, bx, by, bz, sx, sy, sz);
assertTrue("Id not set correctly", destId == dest.getManagerId());
int bx2 = bx + r.nextInt(HALF_SIZE);
int by2 = by + r.nextInt(HALF_SIZE);
int bz2 = bz + r.nextInt(HALF_SIZE);
int sx2 = r.nextInt(HALF_SIZE) + HALF_SIZE;
int sy2 = r.nextInt(HALF_SIZE) + HALF_SIZE;
int sz2 = r.nextInt(HALF_SIZE) + HALF_SIZE;
int vol2 = sx2 * sy2 * sz2;
if ((vol2 | 1) == vol2) {
sx2 = sx2 & (~1);
}
short srcId = (short) r.nextInt();
- CuboidNibbleLightBuffer src = new CuboidNibbleLightBuffer(srcId, bx2, by2, bz2, sx2, sy2, sz2);
+ CuboidNibbleLightBuffer src = new CuboidNibbleLightBuffer(null, srcId, bx2, by2, bz2, sx2, sy2, sz2);
assertTrue("Id not set correctly", srcId == src.getManagerId());
byte[][][] values = new byte[sx2][sy2][sz2];
for (int x = bx2; x < bx2 + sx2; x++) {
for (int y = by2; y < by2 + sy2; y++) {
for (int z = bz2; z < bz2 + sz2; z++) {
byte value = (byte) (r.nextInt() & 0xf);
values[x - bx2][y - by2][z - bz2] = value;
src.set(x, y, z, value);
}
}
}
for (int x = bx2; x < bx2 + sx2; x++) {
for (int y = by2; y < by2 + sy2; y++) {
for (int z = bz2; z < bz2 + sz2; z++) {
byte value = values[x - bx2][y - by2][z - bz2];
assertTrue("value mismatch in setting up src buffer " + (x - bx2) + ", " + (y - by2) + ", " + (z - bz2) + ", got " + src.get(x, y, z) + ", exp " + value, value == src.get(x, y, z));
}
}
}
dest.write(src);
for (int x = bx2; x < bx2 + sx2; x++) {
for (int y = by2; y < by2 + sy2; y++) {
for (int z = bz2; z < bz2 + sz2; z++) {
if (x >= (bx + sx) || y >= (by + sy) || z >= (bz + sz)) {
continue;
}
byte value = values[x - bx2][y - by2][z - bz2];
assertTrue("value mismatch after copy " + (x - bx2) + ", " + (y - by2) + ", " + (z - bz2) + ", got " + dest.get(x, y, z) + ", exp " + value, value == dest.get(x, y, z));
}
}
}
for (int x = bx; x < bx + sx; x++) {
for (int y = by; y < by + sy; y++) {
for (int z = bz; z < bz + sz; z++) {
if (x < (bx2 + sx2) && x >= bx2 && y < (by2 + sy2) && y >= by2 && z < (bz2 + sz2) && z >= bz2) {
continue;
}
assertTrue("Dest buffer changed outside source buffer " + (x - bx) + ", " + (y - by) + ", " + (z - bz) + ", got " + dest.get(x, y, z) + ", exp " + 0, 0 == dest.get(x, y, z));
}
}
}
}
}
}
| false | true | public void copyTest() {
Random r = new Random();
for (int c = 0; c < LOOPS; c++) {
int bx = r.nextInt();
int by = r.nextInt();
int bz = r.nextInt();
int sx = r.nextInt(SIZE) + SIZE;
int sy = r.nextInt(SIZE) + SIZE;
int sz = r.nextInt(SIZE) + SIZE;
int vol = sx * sy * sz;
if ((vol | 1) == vol) {
sx = sx & (~1);
}
short destId = (short) r.nextInt();
CuboidNibbleLightBuffer dest = new CuboidNibbleLightBuffer(destId, bx, by, bz, sx, sy, sz);
assertTrue("Id not set correctly", destId == dest.getManagerId());
int bx2 = bx + r.nextInt(HALF_SIZE);
int by2 = by + r.nextInt(HALF_SIZE);
int bz2 = bz + r.nextInt(HALF_SIZE);
int sx2 = r.nextInt(HALF_SIZE) + HALF_SIZE;
int sy2 = r.nextInt(HALF_SIZE) + HALF_SIZE;
int sz2 = r.nextInt(HALF_SIZE) + HALF_SIZE;
int vol2 = sx2 * sy2 * sz2;
if ((vol2 | 1) == vol2) {
sx2 = sx2 & (~1);
}
short srcId = (short) r.nextInt();
CuboidNibbleLightBuffer src = new CuboidNibbleLightBuffer(srcId, bx2, by2, bz2, sx2, sy2, sz2);
assertTrue("Id not set correctly", srcId == src.getManagerId());
byte[][][] values = new byte[sx2][sy2][sz2];
for (int x = bx2; x < bx2 + sx2; x++) {
for (int y = by2; y < by2 + sy2; y++) {
for (int z = bz2; z < bz2 + sz2; z++) {
byte value = (byte) (r.nextInt() & 0xf);
values[x - bx2][y - by2][z - bz2] = value;
src.set(x, y, z, value);
}
}
}
for (int x = bx2; x < bx2 + sx2; x++) {
for (int y = by2; y < by2 + sy2; y++) {
for (int z = bz2; z < bz2 + sz2; z++) {
byte value = values[x - bx2][y - by2][z - bz2];
assertTrue("value mismatch in setting up src buffer " + (x - bx2) + ", " + (y - by2) + ", " + (z - bz2) + ", got " + src.get(x, y, z) + ", exp " + value, value == src.get(x, y, z));
}
}
}
dest.write(src);
for (int x = bx2; x < bx2 + sx2; x++) {
for (int y = by2; y < by2 + sy2; y++) {
for (int z = bz2; z < bz2 + sz2; z++) {
if (x >= (bx + sx) || y >= (by + sy) || z >= (bz + sz)) {
continue;
}
byte value = values[x - bx2][y - by2][z - bz2];
assertTrue("value mismatch after copy " + (x - bx2) + ", " + (y - by2) + ", " + (z - bz2) + ", got " + dest.get(x, y, z) + ", exp " + value, value == dest.get(x, y, z));
}
}
}
for (int x = bx; x < bx + sx; x++) {
for (int y = by; y < by + sy; y++) {
for (int z = bz; z < bz + sz; z++) {
if (x < (bx2 + sx2) && x >= bx2 && y < (by2 + sy2) && y >= by2 && z < (bz2 + sz2) && z >= bz2) {
continue;
}
assertTrue("Dest buffer changed outside source buffer " + (x - bx) + ", " + (y - by) + ", " + (z - bz) + ", got " + dest.get(x, y, z) + ", exp " + 0, 0 == dest.get(x, y, z));
}
}
}
}
}
| public void copyTest() {
Random r = new Random();
for (int c = 0; c < LOOPS; c++) {
int bx = r.nextInt();
int by = r.nextInt();
int bz = r.nextInt();
int sx = r.nextInt(SIZE) + SIZE;
int sy = r.nextInt(SIZE) + SIZE;
int sz = r.nextInt(SIZE) + SIZE;
int vol = sx * sy * sz;
if ((vol | 1) == vol) {
sx = sx & (~1);
}
short destId = (short) r.nextInt();
CuboidNibbleLightBuffer dest = new CuboidNibbleLightBuffer(null, destId, bx, by, bz, sx, sy, sz);
assertTrue("Id not set correctly", destId == dest.getManagerId());
int bx2 = bx + r.nextInt(HALF_SIZE);
int by2 = by + r.nextInt(HALF_SIZE);
int bz2 = bz + r.nextInt(HALF_SIZE);
int sx2 = r.nextInt(HALF_SIZE) + HALF_SIZE;
int sy2 = r.nextInt(HALF_SIZE) + HALF_SIZE;
int sz2 = r.nextInt(HALF_SIZE) + HALF_SIZE;
int vol2 = sx2 * sy2 * sz2;
if ((vol2 | 1) == vol2) {
sx2 = sx2 & (~1);
}
short srcId = (short) r.nextInt();
CuboidNibbleLightBuffer src = new CuboidNibbleLightBuffer(null, srcId, bx2, by2, bz2, sx2, sy2, sz2);
assertTrue("Id not set correctly", srcId == src.getManagerId());
byte[][][] values = new byte[sx2][sy2][sz2];
for (int x = bx2; x < bx2 + sx2; x++) {
for (int y = by2; y < by2 + sy2; y++) {
for (int z = bz2; z < bz2 + sz2; z++) {
byte value = (byte) (r.nextInt() & 0xf);
values[x - bx2][y - by2][z - bz2] = value;
src.set(x, y, z, value);
}
}
}
for (int x = bx2; x < bx2 + sx2; x++) {
for (int y = by2; y < by2 + sy2; y++) {
for (int z = bz2; z < bz2 + sz2; z++) {
byte value = values[x - bx2][y - by2][z - bz2];
assertTrue("value mismatch in setting up src buffer " + (x - bx2) + ", " + (y - by2) + ", " + (z - bz2) + ", got " + src.get(x, y, z) + ", exp " + value, value == src.get(x, y, z));
}
}
}
dest.write(src);
for (int x = bx2; x < bx2 + sx2; x++) {
for (int y = by2; y < by2 + sy2; y++) {
for (int z = bz2; z < bz2 + sz2; z++) {
if (x >= (bx + sx) || y >= (by + sy) || z >= (bz + sz)) {
continue;
}
byte value = values[x - bx2][y - by2][z - bz2];
assertTrue("value mismatch after copy " + (x - bx2) + ", " + (y - by2) + ", " + (z - bz2) + ", got " + dest.get(x, y, z) + ", exp " + value, value == dest.get(x, y, z));
}
}
}
for (int x = bx; x < bx + sx; x++) {
for (int y = by; y < by + sy; y++) {
for (int z = bz; z < bz + sz; z++) {
if (x < (bx2 + sx2) && x >= bx2 && y < (by2 + sy2) && y >= by2 && z < (bz2 + sz2) && z >= bz2) {
continue;
}
assertTrue("Dest buffer changed outside source buffer " + (x - bx) + ", " + (y - by) + ", " + (z - bz) + ", got " + dest.get(x, y, z) + ", exp " + 0, 0 == dest.get(x, y, z));
}
}
}
}
}
|
diff --git a/src/com/github/MrTwiggy/OreGin/OreGinManager.java b/src/com/github/MrTwiggy/OreGin/OreGinManager.java
index ffb3d8f..0c22184 100644
--- a/src/com/github/MrTwiggy/OreGin/OreGinManager.java
+++ b/src/com/github/MrTwiggy/OreGin/OreGinManager.java
@@ -1,140 +1,140 @@
package com.github.MrTwiggy.OreGin;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
/**
* OreGinManager.java
* Purpose: Manages the maintenance, creation, and destruction of OreGins
*
* @author MrTwiggy
* @version 0.1 1/08/13
*/
public class OreGinManager implements Listener
{
List<OreGin> oreGins; //List of current OreGins
public OreGinPlugin plugin; //OreGinPlugin object
/**
* Constructor
*/
public OreGinManager(OreGinPlugin plugin)
{
this.plugin = plugin;
oreGins = new ArrayList<OreGin>();
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override
public void run() {
UpdateOreGins();
}
}, 0L, OreGinPlugin.UPDATE_CYCLE);
}
/**
* Updates all the OreGins
*/
public void UpdateOreGins()
{
for (OreGin oreGin : oreGins)
{
oreGin.Update();
}
}
/**
* Attempts to create an OreGin at the location
*/
public boolean CreateOreGin(Location machineLocation)
{
//Add logic for attempting to create an OreGin
if (!OreGinExistsAt(machineLocation) && OreGin.ValidUpgrade(machineLocation, 1))
{
oreGins.add(new OreGin(machineLocation));
plugin.getLogger().info("New OreGin created!");
return true;
}
return false;
}
/**
* Attempts to create an OreGin of given OreGin data
*/
public boolean CreateOreGin(OreGin oreGin)
{
if(oreGin.GetLocation().getBlock().getType().equals(Material.DISPENSER) && !OreGinExistsAt(oreGin.GetLocation()))
{
oreGins.add(oreGin);
plugin.getLogger().info("New OreGin created!");
return true;
}
else
{
return false;
}
}
/**
* Returns the OreGin with a matching Location, if any
*/
public OreGin GetOreGin(Location machineLocation)
{
for (OreGin oreGin : oreGins)
{
if (oreGin.GetLocation().equals(machineLocation))
return oreGin;
}
return null;
}
/**
* Returns whether an OreGin exists at the given Location
*/
public boolean OreGinExistsAt(Location machineLocation)
{
return (GetOreGin(machineLocation) != null);
}
/**
* Returns whether item is an OreGin
*/
public boolean IsOreGin(ItemStack item)
{
boolean result = false;
if (item.getItemMeta().getDisplayName() == null)
return false;
- for(int i = 0; i < OreGinPlugin.MAX_TIERS; i++)
+ for(int i = 1; i <= OreGinPlugin.MAX_TIERS; i++)
{
if (item.getItemMeta().getDisplayName().equalsIgnoreCase("T" + i + " OreGin"))
{
result = true;
break;
}
}
return result;
}
/**
* Returns whether location contains an OreGin light
*/
public boolean OreGinLightExistsAt(Location lightLocation)
{
return (OreGinExistsAt(lightLocation.getBlock().getRelative(BlockFace.DOWN).getLocation())
&& (lightLocation.getBlock().getType().equals(OreGinPlugin.LIGHT_OFF)
|| lightLocation.getBlock().getType().equals(OreGinPlugin.LIGHT_ON)));
}
}
| true | true | public boolean IsOreGin(ItemStack item)
{
boolean result = false;
if (item.getItemMeta().getDisplayName() == null)
return false;
for(int i = 0; i < OreGinPlugin.MAX_TIERS; i++)
{
if (item.getItemMeta().getDisplayName().equalsIgnoreCase("T" + i + " OreGin"))
{
result = true;
break;
}
}
return result;
}
| public boolean IsOreGin(ItemStack item)
{
boolean result = false;
if (item.getItemMeta().getDisplayName() == null)
return false;
for(int i = 1; i <= OreGinPlugin.MAX_TIERS; i++)
{
if (item.getItemMeta().getDisplayName().equalsIgnoreCase("T" + i + " OreGin"))
{
result = true;
break;
}
}
return result;
}
|
diff --git a/src/me/libraryaddict/Hungergames/Types/Gamer.java b/src/me/libraryaddict/Hungergames/Types/Gamer.java
index 6203fed..977f0b9 100644
--- a/src/me/libraryaddict/Hungergames/Types/Gamer.java
+++ b/src/me/libraryaddict/Hungergames/Types/Gamer.java
@@ -1,314 +1,314 @@
package me.libraryaddict.Hungergames.Types;
import java.util.ArrayList;
import java.util.List;
import me.libraryaddict.Hungergames.Hungergames;
import me.libraryaddict.Hungergames.Managers.PlayerManager;
import me.libraryaddict.Hungergames.Managers.ScoreboardManager;
import net.milkbowl.vault.economy.Economy;
import net.minecraft.server.v1_5_R3.EntityPlayer;
import net.minecraft.server.v1_5_R3.Packet201PlayerInfo;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_5_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.scoreboard.DisplaySlot;
public class Gamer {
private static Economy economy = null;
private static Hungergames hg = HungergamesApi.getHungergames();
private static PlayerManager pm = HungergamesApi.getPlayerManager();
private boolean build = false;
private boolean canRide = false;
private long cooldown = 0;
private int kills = 0;
private Player player;
/**
* True when the game hasn't started. If he wants to see other players. False when the game has started if he wants to see
* other players
*/
private boolean seeInvis = true;
private boolean spectating = false;
public void setAlive(boolean alive) {
String name = ChatColor.DARK_GRAY + player.getName() + ChatColor.RESET;
- if (alive && !isAlive()) {
- setSpectating(!alive);
+ if (alive) {
+ setSpectating(false);
setHuman();
show();
player.setFallDistance(0F);
player.setAllowFlight(false);
updateSelfToOthers();
if (player.getDisplayName().equals(name))
player.setDisplayName(player.getName());
- } else if (!alive && isAlive()) {
- setSpectating(!alive);
+ } else if (!alive) {
+ setSpectating(true);
setGhost();
hide();
player.setAllowFlight(true);
player.setFlying(true);
updateSelfToOthers();
player.setFoodLevel(20);
player.setHealth(20);
player.setFireTicks(0);
if (player.getDisplayName().equals(player.getName()))
player.setDisplayName(name);
}
}
public Gamer(Player player) {
this.player = player;
if (hg.currentTime >= 0) {
seeInvis = false;
spectating = true;
}
setupEconomy();
}
public void addBalance(long newBalance) {
if (economy != null) {
if (newBalance > 0)
economy.depositPlayer(getName(), newBalance);
else
economy.withdrawPlayer(getName(), -newBalance);
}
}
public void addKill() {
kills++;
ScoreboardManager.makeScore("Main", DisplaySlot.PLAYER_LIST, getPlayer().getPlayerListName(), getKills());
}
/**
* Can this player interact with the world regardless of being a spectator
*/
public boolean canBuild() {
return build;
}
/**
* Can this player interact with the world
*/
public boolean canInteract() {
if (build || (hg.currentTime >= 0 && !spectating))
return true;
return false;
}
public boolean canRide() {
return canRide;
}
/**
* If this player can see that gamer
*/
public boolean canSee(Gamer gamer) {
return seeInvis || gamer.isAlive();
}
/**
* Clears his inventory and returns it
*
* @return
*/
public void clearInventory() {
getPlayer().getInventory().setArmorContents(new ItemStack[4]);
getPlayer().getInventory().clear();
getPlayer().setItemOnCursor(new ItemStack(0));
}
public long getBalance() {
if (economy == null)
return 0;
return (long) economy.getBalance(getName());
}
public long getChunkCooldown() {
return this.cooldown;
}
public List<ItemStack> getInventory() {
List<ItemStack> items = new ArrayList<ItemStack>();
for (ItemStack item : getPlayer().getInventory().getContents())
if (item != null && item.getType() != Material.AIR)
items.add(item.clone());
for (ItemStack item : getPlayer().getInventory().getArmorContents())
if (item != null && item.getType() != Material.AIR)
items.add(item.clone());
if (getPlayer().getItemOnCursor() != null && getPlayer().getItemOnCursor().getType() != Material.AIR)
items.add(getPlayer().getItemOnCursor().clone());
return items;
}
public int getKills() {
return kills;
}
/**
* @return Player name
*/
public String getName() {
return player.getName();
}
/**
* @return Player
*/
public Player getPlayer() {
return player;
}
/**
* Hides the player to everyone in the game
*/
public void hide() {
for (Gamer gamer : pm.getGamers())
gamer.hide(getPlayer());
}
/**
* Hides the player from this gamer
*
* @param hider
*/
public void hide(Player hider) {
Packet201PlayerInfo packet = new Packet201PlayerInfo(hider.getPlayerListName(), false, 9999);
if (hider != null)
if (getPlayer().canSee(hider)) {
getPlayer().hidePlayer(hider);
((CraftPlayer) getPlayer()).getHandle().playerConnection.sendPacket(packet);
}
}
public boolean isAlive() {
return !isSpectator() && hg.currentTime >= 0;
}
/**
* Is this player op
*/
public boolean isOp() {
return getPlayer().isOp();
}
/**
* Is this player spectating
*/
public boolean isSpectator() {
return spectating;
}
/**
* Set them to view invis?
*/
public void seeInvis(boolean seeInvis) {
this.seeInvis = seeInvis;
}
/**
* Set if he can build regardless of spectating
*/
public void setBuild(boolean buildMode) {
this.build = buildMode;
}
public void setChunkCooldown(long newCool) {
this.cooldown = newCool;
}
/**
* Set their width and length to 0, Makes arrows move through them
*/
public void setGhost() {
EntityPlayer p = ((CraftPlayer) getPlayer()).getHandle();
p.width = 0;
p.length = 0;
}
/**
* Restore their width and length. Makes arrows hit them
*/
public void setHuman() {
EntityPlayer p = ((CraftPlayer) getPlayer()).getHandle();
p.width = 0.6F;
p.length = 1.8F;
}
public void setRiding(boolean ride) {
this.canRide = ride;
}
/**
* Set them to spectating
*/
public void setSpectating(boolean spectating) {
this.spectating = spectating;
}
private void setupEconomy() {
if (!(economy == null && Bukkit.getPluginManager().getPlugin("Vault") != null))
return;
RegisteredServiceProvider<Economy> economyProvider = Bukkit.getServer().getServicesManager()
.getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
}
}
/**
* Shows the player to everyone in the game
*/
public void show() {
for (Gamer gamer : pm.getGamers())
gamer.show(getPlayer());
}
/**
* Shows the player to this gamer
*/
public void show(Player hider) {
Packet201PlayerInfo packet = new Packet201PlayerInfo(hider.getPlayerListName(), true, 0);
if (hider != null)
if (!getPlayer().canSee(hider)) {
getPlayer().showPlayer(hider);
((CraftPlayer) getPlayer()).getHandle().playerConnection.sendPacket(packet);
}
}
/**
* Updates the invis for this player to see everyone else
*/
public void updateOthersToSelf() {
for (Gamer gamer : pm.getGamers())
if (gamer != this)
if (canSee(gamer))
show(gamer.getPlayer());
else
hide(gamer.getPlayer());
}
/**
* Updates the invis for everyone if they can see this player or not
*/
public void updateSelfToOthers() {
for (Gamer gamer : pm.getGamers())
if (gamer != this)
if (gamer.canSee(this))
gamer.show(getPlayer());
else
gamer.hide(getPlayer());
}
/**
* Can this player see people or not see.
*/
public boolean viewPlayers() {
return seeInvis;
}
}
| false | true | public void setAlive(boolean alive) {
String name = ChatColor.DARK_GRAY + player.getName() + ChatColor.RESET;
if (alive && !isAlive()) {
setSpectating(!alive);
setHuman();
show();
player.setFallDistance(0F);
player.setAllowFlight(false);
updateSelfToOthers();
if (player.getDisplayName().equals(name))
player.setDisplayName(player.getName());
} else if (!alive && isAlive()) {
setSpectating(!alive);
setGhost();
hide();
player.setAllowFlight(true);
player.setFlying(true);
updateSelfToOthers();
player.setFoodLevel(20);
player.setHealth(20);
player.setFireTicks(0);
if (player.getDisplayName().equals(player.getName()))
player.setDisplayName(name);
}
}
| public void setAlive(boolean alive) {
String name = ChatColor.DARK_GRAY + player.getName() + ChatColor.RESET;
if (alive) {
setSpectating(false);
setHuman();
show();
player.setFallDistance(0F);
player.setAllowFlight(false);
updateSelfToOthers();
if (player.getDisplayName().equals(name))
player.setDisplayName(player.getName());
} else if (!alive) {
setSpectating(true);
setGhost();
hide();
player.setAllowFlight(true);
player.setFlying(true);
updateSelfToOthers();
player.setFoodLevel(20);
player.setHealth(20);
player.setFireTicks(0);
if (player.getDisplayName().equals(player.getName()))
player.setDisplayName(name);
}
}
|
diff --git a/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/RuntimeProcessFactory.java b/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/RuntimeProcessFactory.java
index 8b1e0c371..e64db7115 100644
--- a/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/RuntimeProcessFactory.java
+++ b/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/RuntimeProcessFactory.java
@@ -1,484 +1,485 @@
/*******************************************************************************
* Copyright (c) 2011 IBM 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:
* Otavio Busatto Pontes <[email protected]> - initial API and implementation
*******************************************************************************/
package org.eclipse.linuxtools.tools.launch.core.factory;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.linuxtools.profiling.launch.IRemoteCommandLauncher;
import org.eclipse.linuxtools.profiling.launch.IRemoteFileProxy;
import org.eclipse.linuxtools.profiling.launch.RemoteProxyManager;
/*
* Create process using Runtime.getRuntime().exec and prepends the
* 'Linux tools path' project property to the environment PATH.
* Use this factory instead of Runtime.getRuntime().exec if the command you
* are running may be in the linux tools path selected in the project property
* page.
*/
public class RuntimeProcessFactory extends LinuxtoolsProcessFactory {
private static RuntimeProcessFactory instance = null;
private static final String WHICH_CMD = "which"; //$NON-NLS-1$
private String[] tokenizeCommand(String command) {
StringTokenizer tokenizer = new StringTokenizer(command);
String[] cmdarray = new String[tokenizer.countTokens()];
for (int i = 0; tokenizer.hasMoreElements(); i++)
cmdarray[i] = tokenizer.nextToken();
return cmdarray;
}
private String[] fillPathCommand(String[] cmdarray, IProject project) throws IOException {
cmdarray[0] = whichCommand(cmdarray[0], project);
return cmdarray;
}
/**
* @deprecated
*
* Use {@link RuntimeProcessFactory#fillPathCommand(String[], IProject)} instead.
*/
@Deprecated
private String[] fillPathCommand(String[] cmdarray, String[] envp) throws IOException {
cmdarray[0] = whichCommand(cmdarray[0], envp);
return cmdarray;
}
/**
* @deprecated
*
* Use {@link RuntimeProcessFactory#fillPathSudoCommand(String[], IProject)} instead.
*/
@Deprecated
private String[] fillPathSudoCommand(String[] cmdarray, String[] envp) throws IOException {
cmdarray[2] = whichCommand(cmdarray[2], envp);
return cmdarray;
}
private String[] fillPathSudoCommand(String[] cmdarray, IProject project) throws IOException {
cmdarray[1] = whichCommand(cmdarray[1], project);
return cmdarray;
}
/**
* @deprecated
*
* Use {@link RuntimeProcessFactory#whichCommand(String, IProject)} instead.
*/
@Deprecated
public String whichCommand(String command, String[] envp) throws IOException {
Process p = Runtime.getRuntime().exec(new String[] {WHICH_CMD, command}, envp);
try {
if (p.waitFor() == 0) {
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
command = reader.readLine();
} else {
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
throw new IOException(reader.readLine());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return command;
}
/**
* Used to get the full command path. It will look for the command in the
* system path and in the path selected in 'Linux Tools Path' preference page
* in the informed project.
*
* @param command The desired command
* @param project The current project. If null, only system path will be
* used to look for the command.
* @return The full command path if command was found or the command if
* command was not found.
*
* @since 1.1
*/
public String whichCommand(String command, IProject project) throws IOException {
if (project != null) {
String[] envp = updateEnvironment(null, project);
try {
IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project);
URI whichUri = URI.create(WHICH_CMD);
IPath whichPath = new Path(proxy.toPath(whichUri));
IRemoteCommandLauncher launcher = RemoteProxyManager.getInstance().getLauncher(project);
Process pProxy = launcher.execute(whichPath, new String[]{command}, envp, null, new NullProgressMonitor());
if (pProxy != null){
BufferedReader error = new BufferedReader(new InputStreamReader(pProxy.getErrorStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(pProxy.getInputStream()));
- if(error.readLine() != null){
- throw new IOException(error.readLine());
+ String errorLine;
+ if((errorLine = error.readLine()) != null){
+ throw new IOException(errorLine);
}
error.close();
String readLine = reader.readLine();
ArrayList<String> lines = new ArrayList<String>();
while (readLine != null) {
lines.add(readLine);
readLine = reader.readLine();
}
reader.close();
if (project.getLocationURI()!=null) {
if(project.getLocationURI().toString().startsWith("rse:")) { //$NON-NLS-1$
// RSE output
command = lines.get(lines.size()-2);
} else {
// Remotetools output
command = lines.get(0);
}
} else {
// Local output
command = lines.get(0);
}
}
} catch (CoreException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException e) {
// Executable cannot be found in system path.
e.printStackTrace();
}
}
return command;
}
/**
* @return The default instance of the RuntimeProcessFactory.
*/
public static RuntimeProcessFactory getFactory() {
if (instance == null)
instance = new RuntimeProcessFactory();
return instance;
}
/**
* Execute one command using the path selected in 'Linux Tools Path' preference page
* in the informed project.
* @param cmd The desired command
* @param project The current project. If null, only system path will be
* used to look for the command.
* @return The process started by exec.
*/
public Process exec(String cmd, IProject project) throws IOException {
return exec(cmd, null, (IFileStore)null, project);
}
/**
* Execute one command using the path selected in 'Linux Tools Path' preference page
* in the informed project.
* @param cmdarray An array with the command to be executed and its params.
* @param project The current project. If null, only system path will be
* used to look for the command.
* @return The process started by exec.
*/
public Process exec(String[] cmdarray, IProject project) throws IOException {
return exec(cmdarray, null, project);
}
/**
* Execute one command using the path selected in 'Linux Tools Path' preference page
* in the informed project.
* @param cmdarray An array with the command to be executed and its params.
* @param envp An array with extra enviroment variables to be used when running
* the command
* @param project The current project. If null, only system path will be
* used to look for the command.
* @return The process started by exec.
*/
public Process exec(String[] cmdarray, String[] envp, IProject project) throws IOException {
return exec(cmdarray, envp, (IFileStore)null, project);
}
/**
* Execute one command using the path selected in 'Linux Tools Path' preference page
* in the informed project.
* @param cmd The desired command
* @param envp An array with extra enviroment variables to be used when running
* the command
* @param project The current project. If null, only system path will be
* used to look for the command.
* @return The process started by exec.
*/
public Process exec(String cmd, String[] envp, IProject project) throws IOException {
return exec(cmd, envp, (IFileStore)null, project);
}
/**
* @deprecated
*
* Use {@link RuntimeProcessFactory#exec(String, String[], IFileStore, IProject)} instead.
*/
@Deprecated
public Process exec(String cmd, String[] envp, File dir, IProject project)
throws IOException {
return exec(tokenizeCommand(cmd), envp, dir, project);
}
/**
* Execute one command using the path selected in 'Linux Tools Path' preference page
* in the informed project.
* @param cmd The desired command
* @param envp An array with extra enviroment variables to be used when running
* the command
* @param dir The directory used as current directory to run the command.
* @param project The current project. If null, only system path will be
* used to look for the command.
* @return The process started by exec.
*
* @since 1.1
*/
public Process exec(String cmd, String[] envp, IFileStore dir, IProject project)
throws IOException {
return exec(tokenizeCommand(cmd), envp, dir, project);
}
/**
* @deprecated
*
* Use {@link RuntimeProcessFactory#exec(String[], String[], IFileStore, IProject)} instead.
*/
@Deprecated
public Process exec(String cmdarray[], String[] envp, File dir, IProject project)
throws IOException {
envp = updateEnvironment(envp, project);
cmdarray = fillPathCommand(cmdarray, envp);
return Runtime.getRuntime().exec(cmdarray, envp, dir);
}
/**
* Execute one command using the path selected in 'Linux Tools Path' preference page
* in the informed project.
* @param cmdarray An array with the command to be executed and its params.
* @param envp An array with extra enviroment variables to be used when running
* the command
* @param dir The directory used as current directory to run the command.
* @param project The current project. If null, only system path will be
* used to look for the command.
* @return The process started by exec.
*
* @since 1.1
*/
public Process exec(String cmdarray[], String[] envp, IFileStore dir, IProject project)
throws IOException {
Process p = null;
try {
cmdarray = fillPathCommand(cmdarray, project);
String command = cmdarray[0];
URI uri = URI.create(command);
IPath changeToDir = null;
IPath path;
IRemoteCommandLauncher launcher;
if (project != null) {
IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project);
path = new Path(proxy.toPath(uri));
launcher = RemoteProxyManager.getInstance().getLauncher(project);
envp = updateEnvironment(envp, project);
if (dir != null)
changeToDir = new Path(proxy.toPath(dir.toURI()));
} else {
path = new Path(uri.getPath());
launcher = RemoteProxyManager.getInstance().getLauncher(uri);
if (dir != null)
changeToDir = new Path(dir.toURI().getPath());
}
List<String> cmdlist = new ArrayList<String>(Arrays.asList(cmdarray));
cmdlist.remove(0);
cmdlist.toArray(cmdarray);
cmdarray = cmdlist.toArray(new String[0]);
p = launcher.execute(path, cmdarray, envp, changeToDir , new NullProgressMonitor());
} catch (CoreException e) {
e.printStackTrace();
}
return p;
}
/**
* Execute one command, as root, using the path selected in 'Linux Tools Path'
* preference page in the informed project.
* @param cmd The desired command
* @param project The current project. If null, only system path will be
* used to look for the command.
* @return The process started by sudoExec
*/
public Process sudoExec(String cmd, IProject project) throws IOException {
return sudoExec(cmd, null, (IFileStore)null, project);
}
/**
* Execute one command, as root, using the path selected in 'Linux Tools Path'
* preference page in the informed project.
* @param cmd The desired command
* @param envp An array with extra enviroment variables to be used when running
* the command
* @param project The current project. If null, only system path will be
* used to look for the command.
* @return The process started by sudoExec
*/
public Process sudoExec(String cmd, String[] envp, IProject project) throws IOException {
return exec(cmd, envp, (IFileStore)null, project);
}
/**
* @deprecated
*
* Use {@link RuntimeProcessFactory#sudoExec(String, String[], IFileStore, IProject)} instead.
*/
@Deprecated
public Process sudoExec(String cmd, String[] envp, File dir, IProject project)
throws IOException {
return sudoExec(tokenizeCommand(cmd), envp, dir, project);
}
/**
* Execute one command, as root, using the path selected in 'Linux Tools Path'
* preference page in the informed project.
* @param cmd The desired command
* @param envp An array with extra enviroment variables to be used when running
* the command
* @param dir The directory used as current directory to run the command.
* @param project The current project. If null, only system path will be
* used to look for the command.
* @return The process started by sudoExec
*
* @since 1.1
*/
public Process sudoExec(String cmd, String[] envp, IFileStore dir, IProject project)
throws IOException {
return sudoExec(tokenizeCommand(cmd), envp, dir, project);
}
/**
* Execute one command, as root, using the path selected in 'Linux Tools Path'
* preference page in the informed project.
* @param cmdarray An array with the command to be executed and its params.
* @param project The current project. If null, only system path will be
* used to look for the command.
* @return The process started by sudoExec
*/
public Process sudoExec(String[] cmdarray, IProject project) throws IOException {
return sudoExec(cmdarray, null, project);
}
/**
* Execute one command, as root, using the path selected in 'Linux Tools Path'
* preference page in the informed project.
* @param cmdarray An array with the command to be executed and its params.
* @param envp An array with extra enviroment variables to be used when running
* the command
* @param project The current project. If null, only system path will be
* used to look for the command.
* @return The process started by sudoExec
*/
public Process sudoExec(String[] cmdarray, String[] envp, IProject project) throws IOException {
return sudoExec(cmdarray, envp, (IFileStore)null, project);
}
/**
* @deprecated
*
* Use {@link RuntimeProcessFactory#sudoExec(String[], String[], IFileStore, IProject)} instead.
*/
@Deprecated
public Process sudoExec(String[] cmdarray, String[] envp, File dir, IProject project) throws IOException {
List<String> cmdList = Arrays.asList(cmdarray);
ArrayList<String> cmdArrayList = new ArrayList<String>(cmdList);
cmdArrayList.add(0, "sudo"); //$NON-NLS-1$
cmdArrayList.add(1, "-n"); //$NON-NLS-1$
String[] cmdArraySudo = new String[cmdArrayList.size()];
cmdArrayList.toArray(cmdArraySudo);
envp = updateEnvironment(envp, project);
cmdArraySudo = fillPathSudoCommand(cmdArraySudo, envp);
return Runtime.getRuntime().exec(cmdArraySudo, envp, dir);
}
/**
* Execute one command, as root, using the path selected in 'Linux Tools Path'
* preference page in the informed project.
* @param cmdarray An array with the command to be executed and its params.
* @param envp An array with extra enviroment variables to be used when running
* the command
* @param dir The directory used as current directory to run the command.
* @param project The current project. If null, only system path will be
* used to look for the command.
* @return The process started by sudoExec
*
* @since 1.1
*/
public Process sudoExec(String[] cmdarray, String[] envp, IFileStore dir, IProject project) throws IOException {
URI uri = URI.create("sudo"); //$NON-NLS-1$
List<String> cmdList = Arrays.asList(cmdarray);
ArrayList<String> cmdArrayList = new ArrayList<String>(cmdList);
cmdArrayList.add(0, "-n"); //$NON-NLS-1$
String[] cmdArraySudo = new String[cmdArrayList.size()];
cmdArrayList.toArray(cmdArraySudo);
Process p = null;
try {
cmdArraySudo = fillPathSudoCommand(cmdArraySudo, project);
IRemoteCommandLauncher launcher;
IPath changeToDir = null, path;
if (project != null) {
IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project);
path = new Path(proxy.toPath(uri));
launcher = RemoteProxyManager.getInstance().getLauncher(project);
envp = updateEnvironment(envp, project);
if (dir != null)
changeToDir = new Path(proxy.toPath(dir.toURI()));
} else {
launcher = RemoteProxyManager.getInstance().getLauncher(uri);
path = new Path(uri.getPath());
if (dir != null)
changeToDir = new Path(dir.toURI().getPath());
}
List<String> cmdlist = new ArrayList<String>(Arrays.asList(cmdArraySudo));
cmdlist.remove(0);
cmdlist.toArray(cmdArraySudo);
cmdArraySudo = cmdlist.toArray(new String[0]);
p = launcher.execute(path, cmdArraySudo, envp, changeToDir , new NullProgressMonitor());
} catch (CoreException e) {
e.printStackTrace();
}
return p;
}
}
| true | true | public String whichCommand(String command, IProject project) throws IOException {
if (project != null) {
String[] envp = updateEnvironment(null, project);
try {
IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project);
URI whichUri = URI.create(WHICH_CMD);
IPath whichPath = new Path(proxy.toPath(whichUri));
IRemoteCommandLauncher launcher = RemoteProxyManager.getInstance().getLauncher(project);
Process pProxy = launcher.execute(whichPath, new String[]{command}, envp, null, new NullProgressMonitor());
if (pProxy != null){
BufferedReader error = new BufferedReader(new InputStreamReader(pProxy.getErrorStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(pProxy.getInputStream()));
if(error.readLine() != null){
throw new IOException(error.readLine());
}
error.close();
String readLine = reader.readLine();
ArrayList<String> lines = new ArrayList<String>();
while (readLine != null) {
lines.add(readLine);
readLine = reader.readLine();
}
reader.close();
if (project.getLocationURI()!=null) {
if(project.getLocationURI().toString().startsWith("rse:")) { //$NON-NLS-1$
// RSE output
command = lines.get(lines.size()-2);
} else {
// Remotetools output
command = lines.get(0);
}
} else {
// Local output
command = lines.get(0);
}
}
} catch (CoreException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException e) {
// Executable cannot be found in system path.
e.printStackTrace();
}
}
return command;
}
| public String whichCommand(String command, IProject project) throws IOException {
if (project != null) {
String[] envp = updateEnvironment(null, project);
try {
IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project);
URI whichUri = URI.create(WHICH_CMD);
IPath whichPath = new Path(proxy.toPath(whichUri));
IRemoteCommandLauncher launcher = RemoteProxyManager.getInstance().getLauncher(project);
Process pProxy = launcher.execute(whichPath, new String[]{command}, envp, null, new NullProgressMonitor());
if (pProxy != null){
BufferedReader error = new BufferedReader(new InputStreamReader(pProxy.getErrorStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(pProxy.getInputStream()));
String errorLine;
if((errorLine = error.readLine()) != null){
throw new IOException(errorLine);
}
error.close();
String readLine = reader.readLine();
ArrayList<String> lines = new ArrayList<String>();
while (readLine != null) {
lines.add(readLine);
readLine = reader.readLine();
}
reader.close();
if (project.getLocationURI()!=null) {
if(project.getLocationURI().toString().startsWith("rse:")) { //$NON-NLS-1$
// RSE output
command = lines.get(lines.size()-2);
} else {
// Remotetools output
command = lines.get(0);
}
} else {
// Local output
command = lines.get(0);
}
}
} catch (CoreException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException e) {
// Executable cannot be found in system path.
e.printStackTrace();
}
}
return command;
}
|
diff --git a/java/tools/src/com/jopdesign/wcet/WCETAnalysis.java b/java/tools/src/com/jopdesign/wcet/WCETAnalysis.java
index edf1d622..693d6733 100644
--- a/java/tools/src/com/jopdesign/wcet/WCETAnalysis.java
+++ b/java/tools/src/com/jopdesign/wcet/WCETAnalysis.java
@@ -1,220 +1,221 @@
/*
This file is part of JOP, the Java Optimized Processor
see <http://www.jopdesign.com/>
Copyright (C) 2006-2008, Martin Schoeberl ([email protected])
Copyright (C) 2008-2009, Benedikt Huber ([email protected])
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/>.
*/
/* Notes: WCET times reported by JOP (noted if JopSIM+cache-timing differs)
* Method.java: 12039
* StartKfl.java: 3048-11200
* StartLift.java: 4638-4772 (JopSIM: 4636-4774)
*/
package com.jopdesign.wcet;
import org.apache.log4j.Logger;
import com.jopdesign.build.MethodInfo;
import com.jopdesign.wcet.analysis.GlobalAnalysis;
import com.jopdesign.wcet.analysis.RecursiveAnalysis;
import com.jopdesign.wcet.analysis.UppaalAnalysis;
import com.jopdesign.wcet.analysis.WcetCost;
import com.jopdesign.wcet.analysis.RecursiveAnalysis.RecursiveWCETStrategy;
import com.jopdesign.wcet.config.Config;
import com.jopdesign.wcet.config.Option;
import com.jopdesign.wcet.graphutils.MiscUtils;
import com.jopdesign.wcet.ipet.LpSolveWrapper;
import com.jopdesign.wcet.jop.CacheConfig;
import com.jopdesign.wcet.jop.CacheConfig.StaticCacheApproximation;
import com.jopdesign.wcet.report.Report;
import com.jopdesign.wcet.report.ReportConfig;
import com.jopdesign.wcet.uppaal.UppAalConfig;
import static com.jopdesign.wcet.ExecHelper.timeDiff;
/**
* WCET Analysis for JOP - Executable
*/
public class WCETAnalysis {
private static final String CONFIG_FILE_PROP = "config";
public static final String VERSION = "1.0.0";
private static final Logger tlLogger = Logger.getLogger(WCETAnalysis.class);
public static Option<?>[][] options = {
ProjectConfig.projectOptions,
CacheConfig.cacheOptions,
UppAalConfig.uppaalOptions,
ReportConfig.options,
};
public static void main(String[] args) {
Config config = Config.instance();
config.addOptions(options);
ExecHelper exec = new ExecHelper(WCETAnalysis.class,VERSION,tlLogger,CONFIG_FILE_PROP);
exec.initTopLevelLogger(); /* Console logging for top level messages */
exec.loadConfig(args); /* Load config */
WCETAnalysis inst = new WCETAnalysis(config);
/* run */
if(! inst.run(exec)) exec.bail("WCET Analysis failed");
tlLogger.info("WCET Analysis finished.");
}
private Config config;
private Project project;
public WCETAnalysis(Config c) {
this.config = c;
}
private boolean run(ExecHelper exec) {
project = null;
ProjectConfig pConfig = new ProjectConfig(config);
/* Initialize */
try {
project = new Project(pConfig);
project.setTopLevelLooger(tlLogger);
Report.initVelocity(config); /* Initialize velocity engine */
tlLogger.info("Loading project");
project.load();
MethodInfo largestMethod = project.getProcessorModel().getMethodCache().checkCache();
- int minWords = MiscUtils.bytesToWords(largestMethod.getCode().getLength());
+ int minWords = MiscUtils.bytesToWords(largestMethod.getCode().getCode().length);
System.out.println("Minimal Cache Size for target method(words): "
+ minWords
+ " because of "+largestMethod.getFQMethodName());
project.recordMetric("min-cache-size",largestMethod.getFQMethodName(),minWords);
} catch (Exception e) {
exec.logException("Loading project", e);
return false;
}
/* Perf-Test */
// for(int i = 0; i < 50; i++) {
// RecursiveAnalysis<StaticCacheApproximation> an =
// new RecursiveAnalysis<StaticCacheApproximation>(project,new RecursiveAnalysis.LocalIPETStrategy());
// an.computeWCET(project.getTargetMethod(),StaticCacheApproximation.ALWAYS_HIT);
// }
// System.err.println("Total solver time (50): "+LpSolveWrapper.getSolverTime());
// System.exit(1);
+ // new ETMCExport(project).export(project.getOutFile("Spec_"+project.getProjectName()+".txt"));
/* Run */
boolean succeed = false;
try {
/* Analysis */
project.setGenerateWCETReport(false); /* generate reports later */
tlLogger.info("Cyclomatic complexity: "+project.computeCyclomaticComplexity(project.getTargetMethod()));
WcetCost mincachecost, ah, am, wcet;
/* Perform a few standard analysis (MIN_CACHE_COST, ALWAYS_HIT, ALWAYS_MISS) */
{
long start,stop;
/* always hit */
RecursiveAnalysis<StaticCacheApproximation> an =
new RecursiveAnalysis<StaticCacheApproximation>(project,new RecursiveAnalysis.LocalIPETStrategy());
LpSolveWrapper.resetSolverTime();
start = System.nanoTime();
ah = an.computeWCET(project.getTargetMethod(),StaticCacheApproximation.ALWAYS_HIT);
stop = System.nanoTime();
reportSpecial("always-hit",ah,start,stop,LpSolveWrapper.getSolverTime());
/* always miss */
/* FIXME: We don't have report generation for UPPAAL and global analysis yet */
if( project.getProjectConfig().useUppaal()
|| project.getConfig().getOption(CacheConfig.STATIC_CACHE_APPROX).needsInterProcIPET()) {
project.setGenerateWCETReport(true);
}
am = an.computeWCET(project.getTargetMethod(),StaticCacheApproximation.ALWAYS_MISS);
reportSpecial("always-miss",am,0,0,0);
project.setGenerateWCETReport(false);
/* minimal cache cost */
boolean missOnceOnInvoke = config.getOption(CacheConfig.ASSUME_MISS_ONCE_ON_INVOKE);
config.setOption(CacheConfig.ASSUME_MISS_ONCE_ON_INVOKE, true);
GlobalAnalysis gb = new GlobalAnalysis(project);
LpSolveWrapper.resetSolverTime();
start = System.nanoTime();
mincachecost = gb.computeWCET(project.getTargetMethod(), StaticCacheApproximation.ALL_FIT);
stop = System.nanoTime();
reportSpecial("min-cache-cost",mincachecost, start, stop, LpSolveWrapper.getSolverTime());
config.setOption(CacheConfig.ASSUME_MISS_ONCE_ON_INVOKE, missOnceOnInvoke);
}
tlLogger.info("Starting precise WCET analysis");
project.setGenerateWCETReport(true);
if(project.getProjectConfig().useUppaal()) {
UppaalAnalysis an = new UppaalAnalysis(tlLogger,project,project.getOutDir("uppaal"));
config.checkPresent(UppAalConfig.UPPAAL_VERIFYTA_BINARY);
long start = System.nanoTime();
wcet = an.computeWCET(project.getTargetMethod(),am.getCost());
long stop = System.nanoTime();
reportUppaal(wcet,start,stop,an.getSearchtime(),an.getSolvertimemax());
} else {
StaticCacheApproximation staticCacheApprox =
config.getOption(CacheConfig.STATIC_CACHE_APPROX);
RecursiveWCETStrategy<StaticCacheApproximation> recStrategy;
if(staticCacheApprox == StaticCacheApproximation.ALL_FIT) {
recStrategy = new GlobalAnalysis.GlobalIPETStrategy();
} else {
recStrategy = new RecursiveAnalysis.LocalIPETStrategy();
}
RecursiveAnalysis<StaticCacheApproximation> an =
new RecursiveAnalysis<StaticCacheApproximation>(project,recStrategy);
LpSolveWrapper.resetSolverTime();
long start = System.nanoTime();
wcet = an.computeWCET(project.getTargetMethod(),config.getOption(CacheConfig.STATIC_CACHE_APPROX));
long stop = System.nanoTime();
report(wcet,start,stop,LpSolveWrapper.getSolverTime());
}
tlLogger.info("WCET analysis finsihed: "+wcet);
succeed = true;
} catch (Exception e) {
exec.logException("analysis", e);
}
if(! project.doWriteReport()) {
tlLogger.info("Ommiting HTML report");
return succeed;
}
try {
/* Report */
tlLogger.info("Generating info pages");
project.getReport().generateInfoPages();
tlLogger.info("Generating result document");
project.writeReport();
tlLogger.info("Generated files are in "+pConfig.getOutDir());
} catch (Exception e) {
exec.logException("Report generation", e);
return false;
}
return succeed;
}
private void report(WcetCost wcet, long start, long stop,double solverTime) {
String key = "wcet";
System.out.println(key+": "+wcet);
System.out.println(key+".time: " + timeDiff(start,stop));
System.out.println(key+".solvertime: " + solverTime);
project.recordResult(wcet,timeDiff(start,stop),solverTime);
project.getReport().addStat(key, wcet.toString());
}
private void reportUppaal(WcetCost wcet, long start, long stop, double searchtime, double solvertimemax) {
String key = "wcet";
System.out.println(key+": "+wcet);
System.out.println(key+".time: " + timeDiff(start,stop));
System.out.println(key+".searchtime: " + searchtime);
System.out.println(key+".solvertimemax: " + solvertimemax);
project.recordResultUppaal(wcet,timeDiff(start,stop),searchtime,solvertimemax);
project.getReport().addStat(key, wcet.toString());
}
private void reportSpecial(String metric, WcetCost cost, long start, long stop, double solverTime) {
String key = "wcet."+metric;
System.out.println(key+": "+cost);
if(start != stop) System.out.println(key+".time: " + timeDiff(start,stop));
if(solverTime != 0) System.out.println(key+".solvertime: " + solverTime);
project.recordSpecialResult(metric,cost);
project.getReport().addStat(key, cost.toString());
}
}
| false | true | private boolean run(ExecHelper exec) {
project = null;
ProjectConfig pConfig = new ProjectConfig(config);
/* Initialize */
try {
project = new Project(pConfig);
project.setTopLevelLooger(tlLogger);
Report.initVelocity(config); /* Initialize velocity engine */
tlLogger.info("Loading project");
project.load();
MethodInfo largestMethod = project.getProcessorModel().getMethodCache().checkCache();
int minWords = MiscUtils.bytesToWords(largestMethod.getCode().getLength());
System.out.println("Minimal Cache Size for target method(words): "
+ minWords
+ " because of "+largestMethod.getFQMethodName());
project.recordMetric("min-cache-size",largestMethod.getFQMethodName(),minWords);
} catch (Exception e) {
exec.logException("Loading project", e);
return false;
}
/* Perf-Test */
// for(int i = 0; i < 50; i++) {
// RecursiveAnalysis<StaticCacheApproximation> an =
// new RecursiveAnalysis<StaticCacheApproximation>(project,new RecursiveAnalysis.LocalIPETStrategy());
// an.computeWCET(project.getTargetMethod(),StaticCacheApproximation.ALWAYS_HIT);
// }
// System.err.println("Total solver time (50): "+LpSolveWrapper.getSolverTime());
// System.exit(1);
/* Run */
boolean succeed = false;
try {
/* Analysis */
project.setGenerateWCETReport(false); /* generate reports later */
tlLogger.info("Cyclomatic complexity: "+project.computeCyclomaticComplexity(project.getTargetMethod()));
WcetCost mincachecost, ah, am, wcet;
/* Perform a few standard analysis (MIN_CACHE_COST, ALWAYS_HIT, ALWAYS_MISS) */
{
long start,stop;
/* always hit */
RecursiveAnalysis<StaticCacheApproximation> an =
new RecursiveAnalysis<StaticCacheApproximation>(project,new RecursiveAnalysis.LocalIPETStrategy());
LpSolveWrapper.resetSolverTime();
start = System.nanoTime();
ah = an.computeWCET(project.getTargetMethod(),StaticCacheApproximation.ALWAYS_HIT);
stop = System.nanoTime();
reportSpecial("always-hit",ah,start,stop,LpSolveWrapper.getSolverTime());
/* always miss */
/* FIXME: We don't have report generation for UPPAAL and global analysis yet */
if( project.getProjectConfig().useUppaal()
|| project.getConfig().getOption(CacheConfig.STATIC_CACHE_APPROX).needsInterProcIPET()) {
project.setGenerateWCETReport(true);
}
am = an.computeWCET(project.getTargetMethod(),StaticCacheApproximation.ALWAYS_MISS);
reportSpecial("always-miss",am,0,0,0);
project.setGenerateWCETReport(false);
/* minimal cache cost */
boolean missOnceOnInvoke = config.getOption(CacheConfig.ASSUME_MISS_ONCE_ON_INVOKE);
config.setOption(CacheConfig.ASSUME_MISS_ONCE_ON_INVOKE, true);
GlobalAnalysis gb = new GlobalAnalysis(project);
LpSolveWrapper.resetSolverTime();
start = System.nanoTime();
mincachecost = gb.computeWCET(project.getTargetMethod(), StaticCacheApproximation.ALL_FIT);
stop = System.nanoTime();
reportSpecial("min-cache-cost",mincachecost, start, stop, LpSolveWrapper.getSolverTime());
config.setOption(CacheConfig.ASSUME_MISS_ONCE_ON_INVOKE, missOnceOnInvoke);
}
tlLogger.info("Starting precise WCET analysis");
project.setGenerateWCETReport(true);
if(project.getProjectConfig().useUppaal()) {
UppaalAnalysis an = new UppaalAnalysis(tlLogger,project,project.getOutDir("uppaal"));
config.checkPresent(UppAalConfig.UPPAAL_VERIFYTA_BINARY);
long start = System.nanoTime();
wcet = an.computeWCET(project.getTargetMethod(),am.getCost());
long stop = System.nanoTime();
reportUppaal(wcet,start,stop,an.getSearchtime(),an.getSolvertimemax());
} else {
StaticCacheApproximation staticCacheApprox =
config.getOption(CacheConfig.STATIC_CACHE_APPROX);
RecursiveWCETStrategy<StaticCacheApproximation> recStrategy;
if(staticCacheApprox == StaticCacheApproximation.ALL_FIT) {
recStrategy = new GlobalAnalysis.GlobalIPETStrategy();
} else {
recStrategy = new RecursiveAnalysis.LocalIPETStrategy();
}
RecursiveAnalysis<StaticCacheApproximation> an =
new RecursiveAnalysis<StaticCacheApproximation>(project,recStrategy);
LpSolveWrapper.resetSolverTime();
long start = System.nanoTime();
wcet = an.computeWCET(project.getTargetMethod(),config.getOption(CacheConfig.STATIC_CACHE_APPROX));
long stop = System.nanoTime();
report(wcet,start,stop,LpSolveWrapper.getSolverTime());
}
tlLogger.info("WCET analysis finsihed: "+wcet);
succeed = true;
} catch (Exception e) {
exec.logException("analysis", e);
}
if(! project.doWriteReport()) {
tlLogger.info("Ommiting HTML report");
return succeed;
}
try {
/* Report */
tlLogger.info("Generating info pages");
project.getReport().generateInfoPages();
tlLogger.info("Generating result document");
project.writeReport();
tlLogger.info("Generated files are in "+pConfig.getOutDir());
} catch (Exception e) {
exec.logException("Report generation", e);
return false;
}
return succeed;
}
| private boolean run(ExecHelper exec) {
project = null;
ProjectConfig pConfig = new ProjectConfig(config);
/* Initialize */
try {
project = new Project(pConfig);
project.setTopLevelLooger(tlLogger);
Report.initVelocity(config); /* Initialize velocity engine */
tlLogger.info("Loading project");
project.load();
MethodInfo largestMethod = project.getProcessorModel().getMethodCache().checkCache();
int minWords = MiscUtils.bytesToWords(largestMethod.getCode().getCode().length);
System.out.println("Minimal Cache Size for target method(words): "
+ minWords
+ " because of "+largestMethod.getFQMethodName());
project.recordMetric("min-cache-size",largestMethod.getFQMethodName(),minWords);
} catch (Exception e) {
exec.logException("Loading project", e);
return false;
}
/* Perf-Test */
// for(int i = 0; i < 50; i++) {
// RecursiveAnalysis<StaticCacheApproximation> an =
// new RecursiveAnalysis<StaticCacheApproximation>(project,new RecursiveAnalysis.LocalIPETStrategy());
// an.computeWCET(project.getTargetMethod(),StaticCacheApproximation.ALWAYS_HIT);
// }
// System.err.println("Total solver time (50): "+LpSolveWrapper.getSolverTime());
// System.exit(1);
// new ETMCExport(project).export(project.getOutFile("Spec_"+project.getProjectName()+".txt"));
/* Run */
boolean succeed = false;
try {
/* Analysis */
project.setGenerateWCETReport(false); /* generate reports later */
tlLogger.info("Cyclomatic complexity: "+project.computeCyclomaticComplexity(project.getTargetMethod()));
WcetCost mincachecost, ah, am, wcet;
/* Perform a few standard analysis (MIN_CACHE_COST, ALWAYS_HIT, ALWAYS_MISS) */
{
long start,stop;
/* always hit */
RecursiveAnalysis<StaticCacheApproximation> an =
new RecursiveAnalysis<StaticCacheApproximation>(project,new RecursiveAnalysis.LocalIPETStrategy());
LpSolveWrapper.resetSolverTime();
start = System.nanoTime();
ah = an.computeWCET(project.getTargetMethod(),StaticCacheApproximation.ALWAYS_HIT);
stop = System.nanoTime();
reportSpecial("always-hit",ah,start,stop,LpSolveWrapper.getSolverTime());
/* always miss */
/* FIXME: We don't have report generation for UPPAAL and global analysis yet */
if( project.getProjectConfig().useUppaal()
|| project.getConfig().getOption(CacheConfig.STATIC_CACHE_APPROX).needsInterProcIPET()) {
project.setGenerateWCETReport(true);
}
am = an.computeWCET(project.getTargetMethod(),StaticCacheApproximation.ALWAYS_MISS);
reportSpecial("always-miss",am,0,0,0);
project.setGenerateWCETReport(false);
/* minimal cache cost */
boolean missOnceOnInvoke = config.getOption(CacheConfig.ASSUME_MISS_ONCE_ON_INVOKE);
config.setOption(CacheConfig.ASSUME_MISS_ONCE_ON_INVOKE, true);
GlobalAnalysis gb = new GlobalAnalysis(project);
LpSolveWrapper.resetSolverTime();
start = System.nanoTime();
mincachecost = gb.computeWCET(project.getTargetMethod(), StaticCacheApproximation.ALL_FIT);
stop = System.nanoTime();
reportSpecial("min-cache-cost",mincachecost, start, stop, LpSolveWrapper.getSolverTime());
config.setOption(CacheConfig.ASSUME_MISS_ONCE_ON_INVOKE, missOnceOnInvoke);
}
tlLogger.info("Starting precise WCET analysis");
project.setGenerateWCETReport(true);
if(project.getProjectConfig().useUppaal()) {
UppaalAnalysis an = new UppaalAnalysis(tlLogger,project,project.getOutDir("uppaal"));
config.checkPresent(UppAalConfig.UPPAAL_VERIFYTA_BINARY);
long start = System.nanoTime();
wcet = an.computeWCET(project.getTargetMethod(),am.getCost());
long stop = System.nanoTime();
reportUppaal(wcet,start,stop,an.getSearchtime(),an.getSolvertimemax());
} else {
StaticCacheApproximation staticCacheApprox =
config.getOption(CacheConfig.STATIC_CACHE_APPROX);
RecursiveWCETStrategy<StaticCacheApproximation> recStrategy;
if(staticCacheApprox == StaticCacheApproximation.ALL_FIT) {
recStrategy = new GlobalAnalysis.GlobalIPETStrategy();
} else {
recStrategy = new RecursiveAnalysis.LocalIPETStrategy();
}
RecursiveAnalysis<StaticCacheApproximation> an =
new RecursiveAnalysis<StaticCacheApproximation>(project,recStrategy);
LpSolveWrapper.resetSolverTime();
long start = System.nanoTime();
wcet = an.computeWCET(project.getTargetMethod(),config.getOption(CacheConfig.STATIC_CACHE_APPROX));
long stop = System.nanoTime();
report(wcet,start,stop,LpSolveWrapper.getSolverTime());
}
tlLogger.info("WCET analysis finsihed: "+wcet);
succeed = true;
} catch (Exception e) {
exec.logException("analysis", e);
}
if(! project.doWriteReport()) {
tlLogger.info("Ommiting HTML report");
return succeed;
}
try {
/* Report */
tlLogger.info("Generating info pages");
project.getReport().generateInfoPages();
tlLogger.info("Generating result document");
project.writeReport();
tlLogger.info("Generated files are in "+pConfig.getOutDir());
} catch (Exception e) {
exec.logException("Report generation", e);
return false;
}
return succeed;
}
|
diff --git a/seam/plugins/org.jboss.tools.seam.text.ext/src/org/jboss/tools/seam/text/ext/hyperlink/SeamComponentHyperlinkDetector.java b/seam/plugins/org.jboss.tools.seam.text.ext/src/org/jboss/tools/seam/text/ext/hyperlink/SeamComponentHyperlinkDetector.java
index 1ba0c4a68..81b5a6936 100644
--- a/seam/plugins/org.jboss.tools.seam.text.ext/src/org/jboss/tools/seam/text/ext/hyperlink/SeamComponentHyperlinkDetector.java
+++ b/seam/plugins/org.jboss.tools.seam.text.ext/src/org/jboss/tools/seam/text/ext/hyperlink/SeamComponentHyperlinkDetector.java
@@ -1,217 +1,217 @@
/*******************************************************************************
* Copyright (c) 2009 Exadel, Inc. and Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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:
* Exadel, Inc. and Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.seam.text.ext.hyperlink;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.jdt.core.IAnnotatable;
import org.eclipse.jdt.core.IAnnotation;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMemberValuePair;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.text.JavaWordFinder;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.hyperlink.AbstractHyperlinkDetector;
import org.eclipse.jface.text.hyperlink.IHyperlink;
import org.eclipse.ui.texteditor.ITextEditor;
import org.jboss.tools.seam.core.IBijectedAttribute;
import org.jboss.tools.seam.core.IRole;
import org.jboss.tools.seam.core.ISeamComponent;
import org.jboss.tools.seam.core.ISeamComponentDeclaration;
import org.jboss.tools.seam.core.ISeamContextShortVariable;
import org.jboss.tools.seam.core.ISeamContextVariable;
import org.jboss.tools.seam.core.ISeamProject;
import org.jboss.tools.seam.core.ISeamXmlFactory;
import org.jboss.tools.seam.core.SeamCorePlugin;
import org.jboss.tools.seam.internal.core.el.SeamELCompletionEngine;
import org.jboss.tools.seam.text.ext.SeamExtPlugin;
/**
*
* @author Victor Rubezhny
*
*/
public class SeamComponentHyperlinkDetector extends AbstractHyperlinkDetector {
/*
* If the hyperlink is performed on the field name that is annotated as @In then
* the hyperlink will open a correspondent Seam component
*
* (non-Javadoc)
* @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion, boolean)
*/
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
ITextEditor textEditor= (ITextEditor)getAdapter(ITextEditor.class);
if (region == null ||
// canShowMultipleHyperlinks ||
!(textEditor instanceof JavaEditor))
return null;
int offset= region.getOffset();
IJavaElement input= EditorUtility.getEditorInputJavaElement(textEditor, false);
if (input == null)
return null;
if (input.getResource() == null || input.getResource().getProject() == null)
return null;
ISeamProject seamProject = SeamCorePlugin.getSeamProject(input.getResource().getProject(), true);
if(seamProject == null) {
return null;
}
SeamELCompletionEngine engine = new SeamELCompletionEngine();
IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
IRegion wordRegion= JavaWordFinder.findWord(document, offset);
if (wordRegion == null)
return null;
IFile file = null;
try {
IResource resource = input.getCorrespondingResource();
if (resource instanceof IFile)
file = (IFile) resource;
} catch (JavaModelException e) {
// It is probably because of Java element's resource is not found
SeamExtPlugin.getDefault().logError(e);
}
int[] range = new int[]{wordRegion.getOffset(), wordRegion.getOffset() + wordRegion.getLength()};
IJavaElement[] elements = null;
try {
elements = ((ICodeAssist)input).codeSelect(wordRegion.getOffset(), wordRegion.getLength());
if (elements == null)
return null;
ArrayList<IHyperlink> hyperlinks = new ArrayList<IHyperlink>();
for (IJavaElement element : elements) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable = (IAnnotatable)element;
IAnnotation annotation = annotatable.getAnnotation("In");
- if (annotation == null)
+ if (annotation == null || !annotation.exists())
continue;
String nameToSearch = element.getElementName();
IMemberValuePair[] mvPairs = annotation.getMemberValuePairs();
if (mvPairs != null) {
for (IMemberValuePair mvPair : mvPairs) {
if ("value".equals(mvPair.getMemberName()) && mvPair.getValue() != null) {
String name = mvPair.getValue().toString();
if (name != null && name.trim().length() != 0) {
nameToSearch = name;
break;
}
}
}
}
if (nameToSearch == null && nameToSearch.trim().length() == 0)
continue;
Set<ISeamContextVariable> vars = seamProject.getVariables(true);
if (vars != null) {
for (ISeamContextVariable var : vars) {
if (nameToSearch.equals(var.getName())){
while (var instanceof ISeamContextShortVariable) {
var = ((ISeamContextShortVariable)var).getOriginal();
}
if (var == null)
continue;
if (var instanceof ISeamXmlFactory) {
ISeamXmlFactory xmlFactory = (ISeamXmlFactory)var;
String value = xmlFactory.getValue();
if (value == null || value.trim().length() == 0) {
value = xmlFactory.getMethod();
}
if (value == null || value.trim().length() == 0)
continue;
List<IJavaElement> javaElements = null;
try {
javaElements = engine.getJavaElementsForExpression(
seamProject, file, value);
} catch (StringIndexOutOfBoundsException e) {
SeamExtPlugin.getDefault().logError(e);
} catch (BadLocationException e) {
SeamExtPlugin.getDefault().logError(e);
}
if (javaElements != null) {
for (IJavaElement javaElement : javaElements) {
String resourceName = null;
if (javaElement.getResource() != null) {
resourceName=javaElement.getResource().getName();
}
hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName, javaElement, nameToSearch));
}
}
} else if (var instanceof ISeamComponent) {
String resourceName = null;
ISeamComponent comp = (ISeamComponent)var;
Set<ISeamComponentDeclaration> decls = comp.getAllDeclarations();
for (ISeamComponentDeclaration decl : decls) {
if (decl.getResource() != null) {
resourceName = decl.getResource().getName();
break;
}
}
hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName, (ISeamComponent)var, nameToSearch));
} else if (var instanceof IRole) {
String resourceName = null;
if (var.getResource() != null) {
resourceName = var.getResource().getName();
}
hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName, (IRole)var, nameToSearch));
} else if (var instanceof IBijectedAttribute) {
String resourceName = null;
if (var.getResource() != null) {
resourceName = var.getResource().getName();
}
IBijectedAttribute attr = (IBijectedAttribute)var;
if (attr.getSourceMember() != null) {
hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName, (IBijectedAttribute)var, nameToSearch));
}
}
}
}
}
}
}
if (hyperlinks != null && !hyperlinks.isEmpty()) {
return (IHyperlink[])hyperlinks.toArray(new IHyperlink[hyperlinks.size()]);
}
} catch (JavaModelException jme) {
SeamExtPlugin.getDefault().logError(jme);
}
return null;
}
}
| true | true | public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
ITextEditor textEditor= (ITextEditor)getAdapter(ITextEditor.class);
if (region == null ||
// canShowMultipleHyperlinks ||
!(textEditor instanceof JavaEditor))
return null;
int offset= region.getOffset();
IJavaElement input= EditorUtility.getEditorInputJavaElement(textEditor, false);
if (input == null)
return null;
if (input.getResource() == null || input.getResource().getProject() == null)
return null;
ISeamProject seamProject = SeamCorePlugin.getSeamProject(input.getResource().getProject(), true);
if(seamProject == null) {
return null;
}
SeamELCompletionEngine engine = new SeamELCompletionEngine();
IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
IRegion wordRegion= JavaWordFinder.findWord(document, offset);
if (wordRegion == null)
return null;
IFile file = null;
try {
IResource resource = input.getCorrespondingResource();
if (resource instanceof IFile)
file = (IFile) resource;
} catch (JavaModelException e) {
// It is probably because of Java element's resource is not found
SeamExtPlugin.getDefault().logError(e);
}
int[] range = new int[]{wordRegion.getOffset(), wordRegion.getOffset() + wordRegion.getLength()};
IJavaElement[] elements = null;
try {
elements = ((ICodeAssist)input).codeSelect(wordRegion.getOffset(), wordRegion.getLength());
if (elements == null)
return null;
ArrayList<IHyperlink> hyperlinks = new ArrayList<IHyperlink>();
for (IJavaElement element : elements) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable = (IAnnotatable)element;
IAnnotation annotation = annotatable.getAnnotation("In");
if (annotation == null)
continue;
String nameToSearch = element.getElementName();
IMemberValuePair[] mvPairs = annotation.getMemberValuePairs();
if (mvPairs != null) {
for (IMemberValuePair mvPair : mvPairs) {
if ("value".equals(mvPair.getMemberName()) && mvPair.getValue() != null) {
String name = mvPair.getValue().toString();
if (name != null && name.trim().length() != 0) {
nameToSearch = name;
break;
}
}
}
}
if (nameToSearch == null && nameToSearch.trim().length() == 0)
continue;
Set<ISeamContextVariable> vars = seamProject.getVariables(true);
if (vars != null) {
for (ISeamContextVariable var : vars) {
if (nameToSearch.equals(var.getName())){
while (var instanceof ISeamContextShortVariable) {
var = ((ISeamContextShortVariable)var).getOriginal();
}
if (var == null)
continue;
if (var instanceof ISeamXmlFactory) {
ISeamXmlFactory xmlFactory = (ISeamXmlFactory)var;
String value = xmlFactory.getValue();
if (value == null || value.trim().length() == 0) {
value = xmlFactory.getMethod();
}
if (value == null || value.trim().length() == 0)
continue;
List<IJavaElement> javaElements = null;
try {
javaElements = engine.getJavaElementsForExpression(
seamProject, file, value);
} catch (StringIndexOutOfBoundsException e) {
SeamExtPlugin.getDefault().logError(e);
} catch (BadLocationException e) {
SeamExtPlugin.getDefault().logError(e);
}
if (javaElements != null) {
for (IJavaElement javaElement : javaElements) {
String resourceName = null;
if (javaElement.getResource() != null) {
resourceName=javaElement.getResource().getName();
}
hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName, javaElement, nameToSearch));
}
}
} else if (var instanceof ISeamComponent) {
String resourceName = null;
ISeamComponent comp = (ISeamComponent)var;
Set<ISeamComponentDeclaration> decls = comp.getAllDeclarations();
for (ISeamComponentDeclaration decl : decls) {
if (decl.getResource() != null) {
resourceName = decl.getResource().getName();
break;
}
}
hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName, (ISeamComponent)var, nameToSearch));
} else if (var instanceof IRole) {
String resourceName = null;
if (var.getResource() != null) {
resourceName = var.getResource().getName();
}
hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName, (IRole)var, nameToSearch));
} else if (var instanceof IBijectedAttribute) {
String resourceName = null;
if (var.getResource() != null) {
resourceName = var.getResource().getName();
}
IBijectedAttribute attr = (IBijectedAttribute)var;
if (attr.getSourceMember() != null) {
hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName, (IBijectedAttribute)var, nameToSearch));
}
}
}
}
}
}
}
if (hyperlinks != null && !hyperlinks.isEmpty()) {
return (IHyperlink[])hyperlinks.toArray(new IHyperlink[hyperlinks.size()]);
}
} catch (JavaModelException jme) {
SeamExtPlugin.getDefault().logError(jme);
}
return null;
}
| public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
ITextEditor textEditor= (ITextEditor)getAdapter(ITextEditor.class);
if (region == null ||
// canShowMultipleHyperlinks ||
!(textEditor instanceof JavaEditor))
return null;
int offset= region.getOffset();
IJavaElement input= EditorUtility.getEditorInputJavaElement(textEditor, false);
if (input == null)
return null;
if (input.getResource() == null || input.getResource().getProject() == null)
return null;
ISeamProject seamProject = SeamCorePlugin.getSeamProject(input.getResource().getProject(), true);
if(seamProject == null) {
return null;
}
SeamELCompletionEngine engine = new SeamELCompletionEngine();
IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
IRegion wordRegion= JavaWordFinder.findWord(document, offset);
if (wordRegion == null)
return null;
IFile file = null;
try {
IResource resource = input.getCorrespondingResource();
if (resource instanceof IFile)
file = (IFile) resource;
} catch (JavaModelException e) {
// It is probably because of Java element's resource is not found
SeamExtPlugin.getDefault().logError(e);
}
int[] range = new int[]{wordRegion.getOffset(), wordRegion.getOffset() + wordRegion.getLength()};
IJavaElement[] elements = null;
try {
elements = ((ICodeAssist)input).codeSelect(wordRegion.getOffset(), wordRegion.getLength());
if (elements == null)
return null;
ArrayList<IHyperlink> hyperlinks = new ArrayList<IHyperlink>();
for (IJavaElement element : elements) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable = (IAnnotatable)element;
IAnnotation annotation = annotatable.getAnnotation("In");
if (annotation == null || !annotation.exists())
continue;
String nameToSearch = element.getElementName();
IMemberValuePair[] mvPairs = annotation.getMemberValuePairs();
if (mvPairs != null) {
for (IMemberValuePair mvPair : mvPairs) {
if ("value".equals(mvPair.getMemberName()) && mvPair.getValue() != null) {
String name = mvPair.getValue().toString();
if (name != null && name.trim().length() != 0) {
nameToSearch = name;
break;
}
}
}
}
if (nameToSearch == null && nameToSearch.trim().length() == 0)
continue;
Set<ISeamContextVariable> vars = seamProject.getVariables(true);
if (vars != null) {
for (ISeamContextVariable var : vars) {
if (nameToSearch.equals(var.getName())){
while (var instanceof ISeamContextShortVariable) {
var = ((ISeamContextShortVariable)var).getOriginal();
}
if (var == null)
continue;
if (var instanceof ISeamXmlFactory) {
ISeamXmlFactory xmlFactory = (ISeamXmlFactory)var;
String value = xmlFactory.getValue();
if (value == null || value.trim().length() == 0) {
value = xmlFactory.getMethod();
}
if (value == null || value.trim().length() == 0)
continue;
List<IJavaElement> javaElements = null;
try {
javaElements = engine.getJavaElementsForExpression(
seamProject, file, value);
} catch (StringIndexOutOfBoundsException e) {
SeamExtPlugin.getDefault().logError(e);
} catch (BadLocationException e) {
SeamExtPlugin.getDefault().logError(e);
}
if (javaElements != null) {
for (IJavaElement javaElement : javaElements) {
String resourceName = null;
if (javaElement.getResource() != null) {
resourceName=javaElement.getResource().getName();
}
hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName, javaElement, nameToSearch));
}
}
} else if (var instanceof ISeamComponent) {
String resourceName = null;
ISeamComponent comp = (ISeamComponent)var;
Set<ISeamComponentDeclaration> decls = comp.getAllDeclarations();
for (ISeamComponentDeclaration decl : decls) {
if (decl.getResource() != null) {
resourceName = decl.getResource().getName();
break;
}
}
hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName, (ISeamComponent)var, nameToSearch));
} else if (var instanceof IRole) {
String resourceName = null;
if (var.getResource() != null) {
resourceName = var.getResource().getName();
}
hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName, (IRole)var, nameToSearch));
} else if (var instanceof IBijectedAttribute) {
String resourceName = null;
if (var.getResource() != null) {
resourceName = var.getResource().getName();
}
IBijectedAttribute attr = (IBijectedAttribute)var;
if (attr.getSourceMember() != null) {
hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName, (IBijectedAttribute)var, nameToSearch));
}
}
}
}
}
}
}
if (hyperlinks != null && !hyperlinks.isEmpty()) {
return (IHyperlink[])hyperlinks.toArray(new IHyperlink[hyperlinks.size()]);
}
} catch (JavaModelException jme) {
SeamExtPlugin.getDefault().logError(jme);
}
return null;
}
|
diff --git a/src/nl/rutgerkok/BetterEnderChest/BetterEnderChest.java b/src/nl/rutgerkok/BetterEnderChest/BetterEnderChest.java
index 51364f2..2be177d 100644
--- a/src/nl/rutgerkok/BetterEnderChest/BetterEnderChest.java
+++ b/src/nl/rutgerkok/BetterEnderChest/BetterEnderChest.java
@@ -1,312 +1,312 @@
package nl.rutgerkok.BetterEnderChest;
import java.util.logging.Logger;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class BetterEnderChest extends JavaPlugin
{
private EnderHandler enderHandler;
private EnderCommands commandHandler;
private EnderStorage enderStorage;
private Material chestMaterial;
private Bridge protectionBridge;
private int chestRows, publicChestRows;
private boolean usePermissions, enablePublicChests;
private String chestDrop, chestDropSilkTouch;
public static final String publicChestName = "--publicchest";
public static String publicChestDisplayName;
public void onEnable()
{
//ProtectionBridge
if(initBridge())
{
logThis("Linked to "+protectionBridge.getBridgeName());
}
else
{
logThis("Not linked to a block protection plugin like Lockette or LWC.");
}
//Chests storage
enderStorage = new EnderStorage(this);
//EventHandler
enderHandler = new EnderHandler(this,protectionBridge);
getServer().getPluginManager().registerEvents(enderHandler, this);
//CommandHandler
commandHandler = new EnderCommands(this);
getCommand("betterenderchest").setExecutor(commandHandler);
//AutoSave
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable()
{
public void run()
{
enderHandler.onSave();
}
}, 20*300, 20*300);
//Configuration
initConfig();
logThis("Enabled.");
}
public void onDisable()
{
if(enderHandler!=null)
{
enderHandler.onSave();
logThis("Disabling...");
}
}
//PUBLIC FUNCTIONS
/**
* Gets the current chest material
* @return The current chest material
*/
public Material getChestMaterial()
{
return chestMaterial;
}
/**
* Gets the rows in the chest
* @return The rows in the chest
*/
public int getChestRows()
{
return chestRows;
}
/**
* Gets the string of the chest drop. See documentation online.
* @param silkTouch - whether to use Silk Touch
* @return String of the chest drop
*/
public String getChestDropString(boolean silkTouch)
{
if(silkTouch)
return chestDropSilkTouch;
return chestDrop;
}
/**
* Gets a class to load/modify/save Ender Chests
* @return
*/
public EnderStorage getEnderChests()
{
return enderStorage;
}
/**
* Gets whether a public chest must be shown when a unprotected chest is opened
* @return
*/
public boolean getPublicChestsEnabled()
{
return enablePublicChests;
}
/**
* Gets the rows in the public chest
* @return The rows in the chest
*/
public int getPublicChestRows()
{
return publicChestRows;
}
/**
* Gets whether the string is a valid chest drop
* @param drop
* @return
*/
public boolean isValidChestDrop(String drop)
{
if(drop.equals("OBSIDIAN")) return true;
if(drop.equals("OBSIDIAN_WITH_EYE_OF_ENDER")) return true;
if(drop.equals("OBSIDIAN_WITH_ENDER_PEARL")) return true;
if(drop.equals("EYE_OF_ENDER")) return true;
if(drop.equals("ENDER_PEARL")) return true;
if(drop.equals("ITSELF")) return true;
if(drop.equals("NOTHING")) return true;
return false;
}
private void initConfig()
{
if(!getConfig().getString("enderBlock","NOT_FOUND").equals("NOT_FOUND"))
{ //we have a 0.1-0.3 config here!
convertConfig();
}
//Chestmaterial
String chestBlock = getConfig().getString("EnderChest.block", "BOOKSHELF");
chestMaterial = Material.matchMaterial(chestBlock);
if(chestMaterial==null)
{ //gebruik standaardoptie
chestMaterial = Material.BOOKSHELF;
getConfig().set("EnderChest.block", "BOOKSHELF");
logThis("Cannot load chest material, defaulting to BOOKSHELF.","WARNING");
}
else
{
logThis("Using material "+chestMaterial);
}
if(!(protectionBridge instanceof NoBridge))
{ //reminder to add to custom blocks list
logThis("Make sure to add "+chestMaterial.getId()+" to the "+protectionBridge.getBridgeName()+" custom blocks list");
}
getConfig().set("EnderChest.block", chestMaterial.toString());
//Chestrows
chestRows = getConfig().getInt("EnderChest.rows", 3);
if(chestRows<1||chestRows>20)
{
logThis("The number of rows in the private chest was "+chestRows+"...","WARNING");
logThis("Changed it to 3.","WARNING");
chestRows=3;
}
- getConfig().set("EnderChest.rows", 3);
+ getConfig().set("EnderChest.rows", chestRows);
//Chestdrop
chestDrop = getConfig().getString("EnderChest.drop","OBSIDIAN");
chestDrop = chestDrop.toUpperCase();
if(!isValidChestDrop(chestDrop))
{ //cannot understand value
logThis("Could not understand the drop "+chestDrop+", defaulting to OBSIDIAN","WARNING");
chestDrop = "OBSIDIAN";
}
getConfig().set("EnderChest.drop",chestDrop);
//ChestSilkTouchDrop
chestDropSilkTouch = getConfig().getString("EnderChest.dropSilkTouch","ITSELF");
chestDropSilkTouch = chestDropSilkTouch.toUpperCase();
if(!isValidChestDrop(chestDropSilkTouch))
{ //cannot understand value
logThis("Could not understand the Silk Touch drop "+chestDropSilkTouch+", defaulting to ITSELF","WARNING");
chestDropSilkTouch = "ITSELF";
}
getConfig().set("EnderChest.dropSilkTouch",chestDropSilkTouch);
//Permissions
usePermissions = getConfig().getBoolean("Permissions.enabled", false);
getConfig().set("Permissions.enabled", usePermissions);
//Public chests
//enabled?
enablePublicChests = getConfig().getBoolean("PublicChest.enabled", true);
getConfig().set("PublicChest.enabled", enablePublicChests);
//display name?
BetterEnderChest.publicChestDisplayName = getConfig().getString("PublicChest.name", "Public Chest");
getConfig().set("PublicChest.name", BetterEnderChest.publicChestDisplayName);
//rows?
publicChestRows = getConfig().getInt("PublicChest.rows", chestRows);
if(publicChestRows<1||publicChestRows>20)
{
logThis("The number of rows in the private chest was "+chestRows+"...","WARNING");
logThis("Changed it to 3.","WARNING");
publicChestRows=3;
}
getConfig().set("PublicChest.rows", publicChestRows);
//Save everything
saveConfig();
}
private void convertConfig()
{ //doesn't save automatically!
//convert old options
getConfig().set("EnderChest.block",getConfig().getString("enderBlock", "BOOKSHELF"));
getConfig().set("EnderChest.rows",getConfig().getInt("rowsInChest", 0));
getConfig().set("Permissions.enabled",getConfig().getBoolean("usePermissions", false));
//remove old options
getConfig().set("enderBlock", null);
getConfig().set("rowsInChest", null);
getConfig().set("usePermissions", null);
}
/**
* If usePermissions is true, it returns whether the player has the permission. Otherwise it will return fallBack.
* @param player
* @param permission The permissions to check
* @param fallBack Return this if permissions are disabled and the player is not a op
* @return If usePermissions is true, it returns whether the player has the permission. Otherwise it will return fallBack
*/
public boolean hasPermission(Player player, String permission, boolean fallBack)
{
if(!usePermissions)
{
if(player.isOp()) return true;
return fallBack;
}
return player.hasPermission(permission);
}
private boolean initBridge()
{
if(getServer().getPluginManager().isPluginEnabled("Lockette"))
{
protectionBridge = new LocketteBridge();
return true;
}
//Disabled Deadbolt. Is has no custom block support..
//if(getServer().getPluginManager().isPluginEnabled("Deadbolt"))
//{
// protectionBridge = new DeadboltBridge();
// return true;
//}
if(getServer().getPluginManager().isPluginEnabled("LWC"))
{
protectionBridge = new LWCBridge();
return true;
}
//No bridge found
protectionBridge = new NoBridge();
return false;
}
/**
* Logs a message.
* @param message
*/
public void logThis(String message)
{
logThis(message,"info");
}
/**
* Logs a message.
* @param message
* @param type - WARNING, LOG or SEVERE
*/
public void logThis(String message, String type)
{
Logger log = Logger.getLogger("Minecraft");
if(type.equalsIgnoreCase("info")) log.info("["+this.getDescription().getName()+"] "+message);
if(type.equalsIgnoreCase("warning")) log.warning("["+this.getDescription().getName()+"] "+message);
if(type.equalsIgnoreCase("severe")) log.severe("["+this.getDescription().getName()+"] "+message);
}
}
| true | true | private void initConfig()
{
if(!getConfig().getString("enderBlock","NOT_FOUND").equals("NOT_FOUND"))
{ //we have a 0.1-0.3 config here!
convertConfig();
}
//Chestmaterial
String chestBlock = getConfig().getString("EnderChest.block", "BOOKSHELF");
chestMaterial = Material.matchMaterial(chestBlock);
if(chestMaterial==null)
{ //gebruik standaardoptie
chestMaterial = Material.BOOKSHELF;
getConfig().set("EnderChest.block", "BOOKSHELF");
logThis("Cannot load chest material, defaulting to BOOKSHELF.","WARNING");
}
else
{
logThis("Using material "+chestMaterial);
}
if(!(protectionBridge instanceof NoBridge))
{ //reminder to add to custom blocks list
logThis("Make sure to add "+chestMaterial.getId()+" to the "+protectionBridge.getBridgeName()+" custom blocks list");
}
getConfig().set("EnderChest.block", chestMaterial.toString());
//Chestrows
chestRows = getConfig().getInt("EnderChest.rows", 3);
if(chestRows<1||chestRows>20)
{
logThis("The number of rows in the private chest was "+chestRows+"...","WARNING");
logThis("Changed it to 3.","WARNING");
chestRows=3;
}
getConfig().set("EnderChest.rows", 3);
//Chestdrop
chestDrop = getConfig().getString("EnderChest.drop","OBSIDIAN");
chestDrop = chestDrop.toUpperCase();
if(!isValidChestDrop(chestDrop))
{ //cannot understand value
logThis("Could not understand the drop "+chestDrop+", defaulting to OBSIDIAN","WARNING");
chestDrop = "OBSIDIAN";
}
getConfig().set("EnderChest.drop",chestDrop);
//ChestSilkTouchDrop
chestDropSilkTouch = getConfig().getString("EnderChest.dropSilkTouch","ITSELF");
chestDropSilkTouch = chestDropSilkTouch.toUpperCase();
if(!isValidChestDrop(chestDropSilkTouch))
{ //cannot understand value
logThis("Could not understand the Silk Touch drop "+chestDropSilkTouch+", defaulting to ITSELF","WARNING");
chestDropSilkTouch = "ITSELF";
}
getConfig().set("EnderChest.dropSilkTouch",chestDropSilkTouch);
//Permissions
usePermissions = getConfig().getBoolean("Permissions.enabled", false);
getConfig().set("Permissions.enabled", usePermissions);
//Public chests
//enabled?
enablePublicChests = getConfig().getBoolean("PublicChest.enabled", true);
getConfig().set("PublicChest.enabled", enablePublicChests);
//display name?
BetterEnderChest.publicChestDisplayName = getConfig().getString("PublicChest.name", "Public Chest");
getConfig().set("PublicChest.name", BetterEnderChest.publicChestDisplayName);
//rows?
publicChestRows = getConfig().getInt("PublicChest.rows", chestRows);
if(publicChestRows<1||publicChestRows>20)
{
logThis("The number of rows in the private chest was "+chestRows+"...","WARNING");
logThis("Changed it to 3.","WARNING");
publicChestRows=3;
}
getConfig().set("PublicChest.rows", publicChestRows);
//Save everything
saveConfig();
}
| private void initConfig()
{
if(!getConfig().getString("enderBlock","NOT_FOUND").equals("NOT_FOUND"))
{ //we have a 0.1-0.3 config here!
convertConfig();
}
//Chestmaterial
String chestBlock = getConfig().getString("EnderChest.block", "BOOKSHELF");
chestMaterial = Material.matchMaterial(chestBlock);
if(chestMaterial==null)
{ //gebruik standaardoptie
chestMaterial = Material.BOOKSHELF;
getConfig().set("EnderChest.block", "BOOKSHELF");
logThis("Cannot load chest material, defaulting to BOOKSHELF.","WARNING");
}
else
{
logThis("Using material "+chestMaterial);
}
if(!(protectionBridge instanceof NoBridge))
{ //reminder to add to custom blocks list
logThis("Make sure to add "+chestMaterial.getId()+" to the "+protectionBridge.getBridgeName()+" custom blocks list");
}
getConfig().set("EnderChest.block", chestMaterial.toString());
//Chestrows
chestRows = getConfig().getInt("EnderChest.rows", 3);
if(chestRows<1||chestRows>20)
{
logThis("The number of rows in the private chest was "+chestRows+"...","WARNING");
logThis("Changed it to 3.","WARNING");
chestRows=3;
}
getConfig().set("EnderChest.rows", chestRows);
//Chestdrop
chestDrop = getConfig().getString("EnderChest.drop","OBSIDIAN");
chestDrop = chestDrop.toUpperCase();
if(!isValidChestDrop(chestDrop))
{ //cannot understand value
logThis("Could not understand the drop "+chestDrop+", defaulting to OBSIDIAN","WARNING");
chestDrop = "OBSIDIAN";
}
getConfig().set("EnderChest.drop",chestDrop);
//ChestSilkTouchDrop
chestDropSilkTouch = getConfig().getString("EnderChest.dropSilkTouch","ITSELF");
chestDropSilkTouch = chestDropSilkTouch.toUpperCase();
if(!isValidChestDrop(chestDropSilkTouch))
{ //cannot understand value
logThis("Could not understand the Silk Touch drop "+chestDropSilkTouch+", defaulting to ITSELF","WARNING");
chestDropSilkTouch = "ITSELF";
}
getConfig().set("EnderChest.dropSilkTouch",chestDropSilkTouch);
//Permissions
usePermissions = getConfig().getBoolean("Permissions.enabled", false);
getConfig().set("Permissions.enabled", usePermissions);
//Public chests
//enabled?
enablePublicChests = getConfig().getBoolean("PublicChest.enabled", true);
getConfig().set("PublicChest.enabled", enablePublicChests);
//display name?
BetterEnderChest.publicChestDisplayName = getConfig().getString("PublicChest.name", "Public Chest");
getConfig().set("PublicChest.name", BetterEnderChest.publicChestDisplayName);
//rows?
publicChestRows = getConfig().getInt("PublicChest.rows", chestRows);
if(publicChestRows<1||publicChestRows>20)
{
logThis("The number of rows in the private chest was "+chestRows+"...","WARNING");
logThis("Changed it to 3.","WARNING");
publicChestRows=3;
}
getConfig().set("PublicChest.rows", publicChestRows);
//Save everything
saveConfig();
}
|
diff --git a/src/main/java/com/nateriver/app/cracking/Q21.java b/src/main/java/com/nateriver/app/cracking/Q21.java
index 4839b80..b20bb82 100644
--- a/src/main/java/com/nateriver/app/cracking/Q21.java
+++ b/src/main/java/com/nateriver/app/cracking/Q21.java
@@ -1,81 +1,81 @@
package com.nateriver.app.cracking;
import com.nateriver.app.models.SingleLink;
import com.nateriver.app.utils.PrintUtil;
import java.util.HashMap;
/**
* Write code to remove duplicates from an unsorted linked list.
* FOLLOW UP
* How would you solve this problem if a temporary buffer is not allowed?
*/
public class Q21 {
/**
* Use a hash map to mark value
*/
public static void removeDuplicateLink(SingleLink head){
if(head == null || head.next == null)
return;
SingleLink node = head;
HashMap<String,Integer> map = new HashMap<String, Integer>();
while (node != null && node.next != null){
SingleLink nextNode = node.next;
if(map.containsKey(nextNode.value)){
//remove node
node.next = nextNode.next;
nextNode.next = null;
}
else{
map.put(nextNode.value,1);
- node = node.next;
}
+ node = node.next;
}
}
/**
* use two link to traverse
* complexity would be O(n2)
*/
public static void removeDuplicateLink1(SingleLink head){
if(head == null || head.next == null)
return;
SingleLink nodeFirst = head;
SingleLink nodeSecond;
while (nodeFirst.next != null){
nodeSecond = nodeFirst.next;
while (nodeSecond != null && nodeSecond.next != null){
SingleLink nextSecondNode = nodeSecond.next;
if(nextSecondNode.value.equals(nodeFirst.next.value)){
nodeSecond.next = nextSecondNode.next;
nextSecondNode.next = null;
}
nodeSecond = nodeSecond.next;
}
nodeFirst = nodeFirst.next;
}
}
public static void main(String[] args) {
SingleLink head = new SingleLink();
SingleLink node = head;
String[] values = new String[]{"a","b","c","c","a","d","a"};
for(String value : values ){
SingleLink tempNode = new SingleLink();
tempNode.value = value;
node.next = tempNode;
node = node.next;
node.next = null;
}
PrintUtil.printSingleLink(head);
removeDuplicateLink1(head);
PrintUtil.printSingleLink(head);
}
}
| false | true | public static void removeDuplicateLink(SingleLink head){
if(head == null || head.next == null)
return;
SingleLink node = head;
HashMap<String,Integer> map = new HashMap<String, Integer>();
while (node != null && node.next != null){
SingleLink nextNode = node.next;
if(map.containsKey(nextNode.value)){
//remove node
node.next = nextNode.next;
nextNode.next = null;
}
else{
map.put(nextNode.value,1);
node = node.next;
}
}
}
| public static void removeDuplicateLink(SingleLink head){
if(head == null || head.next == null)
return;
SingleLink node = head;
HashMap<String,Integer> map = new HashMap<String, Integer>();
while (node != null && node.next != null){
SingleLink nextNode = node.next;
if(map.containsKey(nextNode.value)){
//remove node
node.next = nextNode.next;
nextNode.next = null;
}
else{
map.put(nextNode.value,1);
}
node = node.next;
}
}
|
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/TargetBound.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/TargetBound.java
index 992b31e99..68ed44dbd 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/TargetBound.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/TargetBound.java
@@ -1,375 +1,375 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.routing.impl.raptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.opentripplanner.common.geometry.DistanceLibrary;
import org.opentripplanner.common.geometry.SphericalDistanceLibrary;
import org.opentripplanner.routing.algorithm.strategies.RemainingWeightHeuristic;
import org.opentripplanner.routing.algorithm.strategies.SearchTerminationStrategy;
import org.opentripplanner.routing.algorithm.strategies.SkipTraverseResultStrategy;
import org.opentripplanner.routing.algorithm.strategies.TransitLocalStreetService;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.edgetype.PreAlightEdge;
import org.opentripplanner.routing.edgetype.PreBoardEdge;
import org.opentripplanner.routing.edgetype.StreetEdge;
import org.opentripplanner.routing.edgetype.TransitBoardAlight;
import org.opentripplanner.routing.graph.AbstractVertex;
import org.opentripplanner.routing.graph.Edge;
import org.opentripplanner.routing.graph.Vertex;
import org.opentripplanner.routing.spt.ArrayMultiShortestPathTree;
import org.opentripplanner.routing.spt.ShortestPathTree;
import org.opentripplanner.routing.spt.ShortestPathTreeFactory;
import org.opentripplanner.routing.vertextype.TransitStop;
import com.vividsolutions.jts.geom.Coordinate;
public class TargetBound implements SearchTerminationStrategy, SkipTraverseResultStrategy, RemainingWeightHeuristic, ShortestPathTreeFactory {
private static final long serialVersionUID = -5296036164138922096L;
private static final long WORST_TIME_DIFFERENCE = 3600;
private static final double WORST_WEIGHT_DIFFERENCE_FACTOR = 1.3;
List<State> bounders;
private Vertex realTarget;
private DistanceLibrary distanceLibrary = SphericalDistanceLibrary.getInstance();
private Coordinate realTargetCoordinate;
private double distanceToNearestTransitStop;
private TransitLocalStreetService transitLocalStreets;
private double speedUpperBound;
//this is saved so that it can be reused in various skipping functions
private double targetDistance;
private double speedWeight;
/**
* How much longer the worst path can be than the best in terms of time.
* Setting this lower will cut off some less-walking more-time paths.
* Setting it higher will slow down the search a lot.
*/
private double timeBoundFactor = 2;
private List<Integer> previousArrivalTime = new ArrayList<Integer>();
private RoutingRequest options;
public ShortestPathTree spt = new ArrayMultiShortestPathTree(options);
double[] distance = new double[AbstractVertex.getMaxIndex()];
public double bestTargetDistance = Double.POSITIVE_INFINITY;
public List<State> removedBoundingStates = new ArrayList<State>();
private List<State> transitStopsVisited = new ArrayList<State>();
public TargetBound(RoutingRequest options) {
this.options = options;
if (options.rctx.target != null) {
this.realTarget = options.rctx.target;
this.realTargetCoordinate = realTarget.getCoordinate();
this.distanceToNearestTransitStop = realTarget.getDistanceToNearestTransitStop();
bounders = new ArrayList<State>();
transitLocalStreets = options.rctx.graph.getService(TransitLocalStreetService.class);
speedUpperBound = options.getSpeedUpperBound();
this.speedWeight = options.getWalkReluctance() / speedUpperBound;
}
}
@Override
public boolean shouldSearchContinue(Vertex origin, Vertex target, State current,
ShortestPathTree spt, RoutingRequest traverseOptions) {
final Vertex vertex = current.getVertex();
if (vertex instanceof TransitStop) {
transitStopsVisited.add(current);
}
if (vertex == realTarget) {
addBounder(current);
}
return true;
}
public void addBounder(State bounder) {
for (Iterator<State> it = bounders.iterator(); it.hasNext(); ) {
State old = it.next();
if (bounder.dominates(old)) {
it.remove();
removedBoundingStates.add(old);
} else if (bounder.getNumBoardings() <= old.getNumBoardings() && options.arriveBy ? (
bounder.getTime() - WORST_TIME_DIFFERENCE > old.getTime())
: (bounder.getTime() + WORST_TIME_DIFFERENCE < old.getTime())) {
it.remove();
removedBoundingStates.add(old);
}
}
bounders.add(bounder);
RaptorState state = (RaptorState) bounder.getExtension("raptorParent");
if (state == null) {
previousArrivalTime.add(-1);
return;
}
RaptorStop stop = state.stop;
//get previous alight at stop
if (options.isArriveBy()) {
final int nextDepartTime = getNextDepartTime(options, (state.arrivalTime - options.getBoardSlack()) - 2, stop.stopVertex);
previousArrivalTime.add((int) ((nextDepartTime - options.getAlightSlack()) - bounder.getElapsedTime()));
} else {
final int previousArriveTime = getPreviousArriveTime(options, state.arrivalTime - options.getAlightSlack() + 2, stop.stopVertex);
previousArrivalTime.add((int) (previousArriveTime + options.getAlightSlack() + bounder.getElapsedTime()));
}
}
@Override
public boolean shouldSkipTraversalResult(Vertex origin, Vertex target, State parent,
State current, ShortestPathTree spt, RoutingRequest traverseOptions) {
if (realTarget == null)
return false;
final Vertex vertex = current.getVertex();
int vertexIndex = vertex.getIndex();
if (vertexIndex < distance.length) {
if (distance[vertexIndex] > 0.0) {
targetDistance = distance[vertexIndex];
} else {
targetDistance = distanceLibrary.fastDistance(realTargetCoordinate.y, realTargetCoordinate.x,
vertex.getY(), vertex.getX());
distance[vertexIndex] = targetDistance;
if (vertex instanceof TransitStop && targetDistance < bestTargetDistance) {
bestTargetDistance = targetDistance;
}
}
} else {
targetDistance = distanceLibrary.fastDistance(realTargetCoordinate.y, realTargetCoordinate.x,
vertex.getY(), vertex.getX());
}
final double remainingWalk = traverseOptions.maxWalkDistance
- current.getWalkDistance();
final double minWalk;
double minTime = 0;
if (targetDistance > remainingWalk) {
// then we must have some transit + some walk.
minWalk = this.distanceToNearestTransitStop + vertex.getDistanceToNearestTransitStop();
minTime = options.isArriveBy() ? traverseOptions.getAlightSlack() : traverseOptions.getBoardSlack();
if (current.getBackEdge() instanceof StreetEdge && transitLocalStreets != null && !transitLocalStreets.transferrable(vertex)) {
return true;
}
} else {
// could walk directly to destination
if (targetDistance < distanceToNearestTransitStop || transitLocalStreets == null || !transitLocalStreets.transferrable(vertex))
minWalk = targetDistance;
else
minWalk = distanceToNearestTransitStop;
}
if (minWalk > remainingWalk)
return true;
final double optimisticDistance = current.getWalkDistance() + minWalk;
final double walkTime = minWalk
/ speedUpperBound;
minTime += (targetDistance - minWalk) / Raptor.MAX_TRANSIT_SPEED + walkTime;
double stateTime = current.getOptimizedElapsedTime() + minTime;
int i = 0;
boolean prevBounded = !bounders.isEmpty();
for (State bounder : bounders) {
if (current.getWeight() + minTime + walkTime * (options.getWalkReluctance() - 1) > bounder.getWeight() * WORST_WEIGHT_DIFFERENCE_FACTOR) {
return true;
}
int prevTime = previousArrivalTime.get(i++);
if (optimisticDistance * 1.1 > bounder.getWalkDistance()
&& current.getNumBoardings() >= bounder.getNumBoardings()) {
if (current.getElapsedTime() + minTime > bounder.getElapsedTime()) {
return true;
- } else if (prevTime < 0 && (options.arriveBy ? (current.getTime() + minTime <= prevTime) : ((current.getTime() - minTime) >= prevTime))) {
+ } else if (prevTime > 0 && (options.arriveBy ? (current.getTime() - minTime >= prevTime) : ((current.getTime() + minTime) <= prevTime))) {
prevBounded = false;
}
} else {
prevBounded = false;
}
//check that the new path is not much longer in time than the bounding path
if (bounder.getOptimizedElapsedTime() * timeBoundFactor < stateTime) {
return true;
}
}
return prevBounded;
}
public static int getNextDepartTime(RoutingRequest request, int departureTime, Vertex stopVertex) {
int bestArrivalTime = Integer.MAX_VALUE;
request.arriveBy = false;
// find the boards
for (Edge preboard : stopVertex.getOutgoing()) {
if (preboard instanceof PreBoardEdge) {
Vertex departure = preboard.getToVertex(); // this is the departure vertex
for (Edge board : departure.getOutgoing()) {
if (board instanceof TransitBoardAlight) {
State state = new State(board.getFromVertex(), departureTime, request);
State result = board.traverse(state);
if (result == null)
continue;
int time = (int) result.getTime();
if (time < bestArrivalTime) {
bestArrivalTime = time;
}
}
}
}
}
request.arriveBy = true;
return bestArrivalTime;
}
public static int getPreviousArriveTime(RoutingRequest request, int arrivalTime, Vertex stopVertex) {
int bestArrivalTime = -1;
request.arriveBy = true;
// find the alights
for (Edge prealight : stopVertex.getIncoming()) {
if (prealight instanceof PreAlightEdge) {
Vertex arrival = prealight.getFromVertex(); // this is the arrival vertex
for (Edge alight : arrival.getIncoming()) {
if (alight instanceof TransitBoardAlight) {
State state = new State(alight.getToVertex(), arrivalTime, request);
State result = alight.traverse(state);
if (result == null)
continue;
int time = (int) result.getTime();
if (time > bestArrivalTime) {
bestArrivalTime = time;
}
}
}
}
}
request.arriveBy = false;
return bestArrivalTime;
}
@Override
public double computeInitialWeight(State s, Vertex target) {
return computeForwardWeight(s, target);
}
/**
* This actually does have to be admissible, since when we find the target, it used to bound the rest of the search.
*/
@Override
public double computeForwardWeight(State s, Vertex target) {
return targetDistance * speedWeight;
}
@Override
public double computeReverseWeight(State s, Vertex target) {
return computeForwardWeight(s, target);
}
/** Reset the heuristic */
@Override
public void reset() {
}
public double getTimeBoundFactor() {
return timeBoundFactor;
}
public void setTimeBoundFactor(double timeBoundFactor) {
this.timeBoundFactor = timeBoundFactor;
}
@Override
public ShortestPathTree create(RoutingRequest options) {
return spt;
}
public void addSptStates(List<MaxWalkState> states) {
for (MaxWalkState state : states) {
if (state.getVertex() instanceof TransitStop) {
transitStopsVisited.add(state);
}
spt.add(state);
}
}
public double getTargetDistance(Vertex vertex) {
int vertexIndex = vertex.getIndex();
if (vertexIndex < distance.length) {
if (distance[vertexIndex] > 0.0) {
return distance[vertexIndex];
} else {
double d = distanceLibrary.fastDistance(realTargetCoordinate.y,
realTargetCoordinate.x, vertex.getY(), vertex.getX());
distance[vertexIndex] = d;
return d;
}
} else {
return distanceLibrary.fastDistance(realTargetCoordinate.y, realTargetCoordinate.x,
vertex.getY(), vertex.getX());
}
}
public List<State> getTransitStopsVisited() {
return transitStopsVisited;
}
public void prepareForSearch() {
transitStopsVisited.clear();
}
public void reset(RoutingRequest options) {
this.options = options;
if (realTarget != options.rctx.target) {
this.realTarget = options.rctx.target;
this.realTargetCoordinate = realTarget.getCoordinate();
this.distanceToNearestTransitStop = realTarget.getDistanceToNearestTransitStop();
bounders = new ArrayList<State>();
Arrays.fill(distance, -1);
}
spt = new ArrayMultiShortestPathTree(options);
transitLocalStreets = options.rctx.graph.getService(TransitLocalStreetService.class);
speedUpperBound = options.getSpeedUpperBound();
this.speedWeight = options.getWalkReluctance() / speedUpperBound;
}
}
| true | true | public boolean shouldSkipTraversalResult(Vertex origin, Vertex target, State parent,
State current, ShortestPathTree spt, RoutingRequest traverseOptions) {
if (realTarget == null)
return false;
final Vertex vertex = current.getVertex();
int vertexIndex = vertex.getIndex();
if (vertexIndex < distance.length) {
if (distance[vertexIndex] > 0.0) {
targetDistance = distance[vertexIndex];
} else {
targetDistance = distanceLibrary.fastDistance(realTargetCoordinate.y, realTargetCoordinate.x,
vertex.getY(), vertex.getX());
distance[vertexIndex] = targetDistance;
if (vertex instanceof TransitStop && targetDistance < bestTargetDistance) {
bestTargetDistance = targetDistance;
}
}
} else {
targetDistance = distanceLibrary.fastDistance(realTargetCoordinate.y, realTargetCoordinate.x,
vertex.getY(), vertex.getX());
}
final double remainingWalk = traverseOptions.maxWalkDistance
- current.getWalkDistance();
final double minWalk;
double minTime = 0;
if (targetDistance > remainingWalk) {
// then we must have some transit + some walk.
minWalk = this.distanceToNearestTransitStop + vertex.getDistanceToNearestTransitStop();
minTime = options.isArriveBy() ? traverseOptions.getAlightSlack() : traverseOptions.getBoardSlack();
if (current.getBackEdge() instanceof StreetEdge && transitLocalStreets != null && !transitLocalStreets.transferrable(vertex)) {
return true;
}
} else {
// could walk directly to destination
if (targetDistance < distanceToNearestTransitStop || transitLocalStreets == null || !transitLocalStreets.transferrable(vertex))
minWalk = targetDistance;
else
minWalk = distanceToNearestTransitStop;
}
if (minWalk > remainingWalk)
return true;
final double optimisticDistance = current.getWalkDistance() + minWalk;
final double walkTime = minWalk
/ speedUpperBound;
minTime += (targetDistance - minWalk) / Raptor.MAX_TRANSIT_SPEED + walkTime;
double stateTime = current.getOptimizedElapsedTime() + minTime;
int i = 0;
boolean prevBounded = !bounders.isEmpty();
for (State bounder : bounders) {
if (current.getWeight() + minTime + walkTime * (options.getWalkReluctance() - 1) > bounder.getWeight() * WORST_WEIGHT_DIFFERENCE_FACTOR) {
return true;
}
int prevTime = previousArrivalTime.get(i++);
if (optimisticDistance * 1.1 > bounder.getWalkDistance()
&& current.getNumBoardings() >= bounder.getNumBoardings()) {
if (current.getElapsedTime() + minTime > bounder.getElapsedTime()) {
return true;
} else if (prevTime < 0 && (options.arriveBy ? (current.getTime() + minTime <= prevTime) : ((current.getTime() - minTime) >= prevTime))) {
prevBounded = false;
}
} else {
prevBounded = false;
}
//check that the new path is not much longer in time than the bounding path
if (bounder.getOptimizedElapsedTime() * timeBoundFactor < stateTime) {
return true;
}
}
return prevBounded;
}
| public boolean shouldSkipTraversalResult(Vertex origin, Vertex target, State parent,
State current, ShortestPathTree spt, RoutingRequest traverseOptions) {
if (realTarget == null)
return false;
final Vertex vertex = current.getVertex();
int vertexIndex = vertex.getIndex();
if (vertexIndex < distance.length) {
if (distance[vertexIndex] > 0.0) {
targetDistance = distance[vertexIndex];
} else {
targetDistance = distanceLibrary.fastDistance(realTargetCoordinate.y, realTargetCoordinate.x,
vertex.getY(), vertex.getX());
distance[vertexIndex] = targetDistance;
if (vertex instanceof TransitStop && targetDistance < bestTargetDistance) {
bestTargetDistance = targetDistance;
}
}
} else {
targetDistance = distanceLibrary.fastDistance(realTargetCoordinate.y, realTargetCoordinate.x,
vertex.getY(), vertex.getX());
}
final double remainingWalk = traverseOptions.maxWalkDistance
- current.getWalkDistance();
final double minWalk;
double minTime = 0;
if (targetDistance > remainingWalk) {
// then we must have some transit + some walk.
minWalk = this.distanceToNearestTransitStop + vertex.getDistanceToNearestTransitStop();
minTime = options.isArriveBy() ? traverseOptions.getAlightSlack() : traverseOptions.getBoardSlack();
if (current.getBackEdge() instanceof StreetEdge && transitLocalStreets != null && !transitLocalStreets.transferrable(vertex)) {
return true;
}
} else {
// could walk directly to destination
if (targetDistance < distanceToNearestTransitStop || transitLocalStreets == null || !transitLocalStreets.transferrable(vertex))
minWalk = targetDistance;
else
minWalk = distanceToNearestTransitStop;
}
if (minWalk > remainingWalk)
return true;
final double optimisticDistance = current.getWalkDistance() + minWalk;
final double walkTime = minWalk
/ speedUpperBound;
minTime += (targetDistance - minWalk) / Raptor.MAX_TRANSIT_SPEED + walkTime;
double stateTime = current.getOptimizedElapsedTime() + minTime;
int i = 0;
boolean prevBounded = !bounders.isEmpty();
for (State bounder : bounders) {
if (current.getWeight() + minTime + walkTime * (options.getWalkReluctance() - 1) > bounder.getWeight() * WORST_WEIGHT_DIFFERENCE_FACTOR) {
return true;
}
int prevTime = previousArrivalTime.get(i++);
if (optimisticDistance * 1.1 > bounder.getWalkDistance()
&& current.getNumBoardings() >= bounder.getNumBoardings()) {
if (current.getElapsedTime() + minTime > bounder.getElapsedTime()) {
return true;
} else if (prevTime > 0 && (options.arriveBy ? (current.getTime() - minTime >= prevTime) : ((current.getTime() + minTime) <= prevTime))) {
prevBounded = false;
}
} else {
prevBounded = false;
}
//check that the new path is not much longer in time than the bounding path
if (bounder.getOptimizedElapsedTime() * timeBoundFactor < stateTime) {
return true;
}
}
return prevBounded;
}
|
diff --git a/src/com/csipsimple/service/DeviceStateReceiver.java b/src/com/csipsimple/service/DeviceStateReceiver.java
index 1d0e2e14..122a5f7a 100644
--- a/src/com/csipsimple/service/DeviceStateReceiver.java
+++ b/src/com/csipsimple/service/DeviceStateReceiver.java
@@ -1,116 +1,116 @@
/**
* Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple 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.
* If you own a pjsip commercial license you can also redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as an android library.
*
* CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.csipsimple.service;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import com.csipsimple.api.SipManager;
import com.csipsimple.api.SipProfile;
import com.csipsimple.utils.CallHandlerPlugin;
import com.csipsimple.utils.ExtraPlugins;
import com.csipsimple.utils.Log;
import com.csipsimple.utils.NightlyUpdater;
import com.csipsimple.utils.PhoneCapabilityTester;
import com.csipsimple.utils.PreferencesProviderWrapper;
import com.csipsimple.utils.RewriterPlugin;
public class DeviceStateReceiver extends BroadcastReceiver {
//private static final String ACTION_DATA_STATE_CHANGED = "android.intent.action.ANY_DATA_STATE";
private static final String THIS_FILE = "Device State";
public static final String APPLY_NIGHTLY_UPLOAD = "com.csipsimple.action.APPLY_NIGHTLY";
@Override
public void onReceive(Context context, Intent intent) {
PreferencesProviderWrapper prefWrapper = new PreferencesProviderWrapper(context);
String intentAction = intent.getAction();
//
// ACTION_DATA_STATE_CHANGED
// Data state change is used to detect changes in the mobile
// network such as a switch of network type (GPRS, EDGE, 3G)
// which are not detected by the Connectivity changed broadcast.
//
//
// ACTION_CONNECTIVITY_CHANGED
// Connectivity change is used to detect changes in the overall
// data network status as well as a switch between wifi and mobile
// networks.
//
if (/*intentAction.equals(ACTION_DATA_STATE_CHANGED) ||*/
intentAction.equals(ConnectivityManager.CONNECTIVITY_ACTION) ||
intentAction.equals(Intent.ACTION_BOOT_COMPLETED)) {
if (prefWrapper.isValidConnectionForIncoming()
&&
!prefWrapper
.getPreferenceBooleanValue(PreferencesProviderWrapper.HAS_BEEN_QUIT)) {
Log.d(THIS_FILE, "Try to start service if not already started");
Intent sip_service_intent = new Intent(context, SipService.class);
context.startService(sip_service_intent);
}
} else if (intentAction.equals(SipManager.INTENT_SIP_ACCOUNT_ACTIVATE)) {
context.enforceCallingOrSelfPermission(SipManager.PERMISSION_CONFIGURE_SIP, null);
long accId;
accId = intent.getLongExtra(SipProfile.FIELD_ID, SipProfile.INVALID_ID);
if (accId == SipProfile.INVALID_ID) {
// allow remote side to send us integers.
// previous call will warn, but that's fine, no worries
- accId = intent.getLongExtra(SipProfile.FIELD_ID, SipProfile.INVALID_ID);
+ accId = intent.getIntExtra(SipProfile.FIELD_ID, (int) SipProfile.INVALID_ID);
}
if (accId != SipProfile.INVALID_ID) {
boolean active = intent.getBooleanExtra(SipProfile.FIELD_ACTIVE, true);
ContentValues cv = new ContentValues();
cv.put(SipProfile.FIELD_ACTIVE, active);
int done = context.getContentResolver().update(
ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, accId), cv,
null, null);
if (done > 0) {
if (prefWrapper.isValidConnectionForIncoming()) {
Intent sipServiceIntent = new Intent(context, SipService.class);
context.startService(sipServiceIntent);
}
}
}
} else if (Intent.ACTION_PACKAGE_ADDED.equalsIgnoreCase(intentAction) ||
Intent.ACTION_PACKAGE_REMOVED.equalsIgnoreCase(intentAction)) {
CallHandlerPlugin.clearAvailableCallHandlers();
RewriterPlugin.clearAvailableRewriters();
ExtraPlugins.clearDynPlugins();
PhoneCapabilityTester.deinit();
} else if (APPLY_NIGHTLY_UPLOAD.equals(intentAction)) {
NightlyUpdater nu = new NightlyUpdater(context);
nu.applyUpdate(intent);
}
}
}
| true | true | public void onReceive(Context context, Intent intent) {
PreferencesProviderWrapper prefWrapper = new PreferencesProviderWrapper(context);
String intentAction = intent.getAction();
//
// ACTION_DATA_STATE_CHANGED
// Data state change is used to detect changes in the mobile
// network such as a switch of network type (GPRS, EDGE, 3G)
// which are not detected by the Connectivity changed broadcast.
//
//
// ACTION_CONNECTIVITY_CHANGED
// Connectivity change is used to detect changes in the overall
// data network status as well as a switch between wifi and mobile
// networks.
//
if (/*intentAction.equals(ACTION_DATA_STATE_CHANGED) ||*/
intentAction.equals(ConnectivityManager.CONNECTIVITY_ACTION) ||
intentAction.equals(Intent.ACTION_BOOT_COMPLETED)) {
if (prefWrapper.isValidConnectionForIncoming()
&&
!prefWrapper
.getPreferenceBooleanValue(PreferencesProviderWrapper.HAS_BEEN_QUIT)) {
Log.d(THIS_FILE, "Try to start service if not already started");
Intent sip_service_intent = new Intent(context, SipService.class);
context.startService(sip_service_intent);
}
} else if (intentAction.equals(SipManager.INTENT_SIP_ACCOUNT_ACTIVATE)) {
context.enforceCallingOrSelfPermission(SipManager.PERMISSION_CONFIGURE_SIP, null);
long accId;
accId = intent.getLongExtra(SipProfile.FIELD_ID, SipProfile.INVALID_ID);
if (accId == SipProfile.INVALID_ID) {
// allow remote side to send us integers.
// previous call will warn, but that's fine, no worries
accId = intent.getLongExtra(SipProfile.FIELD_ID, SipProfile.INVALID_ID);
}
if (accId != SipProfile.INVALID_ID) {
boolean active = intent.getBooleanExtra(SipProfile.FIELD_ACTIVE, true);
ContentValues cv = new ContentValues();
cv.put(SipProfile.FIELD_ACTIVE, active);
int done = context.getContentResolver().update(
ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, accId), cv,
null, null);
if (done > 0) {
if (prefWrapper.isValidConnectionForIncoming()) {
Intent sipServiceIntent = new Intent(context, SipService.class);
context.startService(sipServiceIntent);
}
}
}
} else if (Intent.ACTION_PACKAGE_ADDED.equalsIgnoreCase(intentAction) ||
Intent.ACTION_PACKAGE_REMOVED.equalsIgnoreCase(intentAction)) {
CallHandlerPlugin.clearAvailableCallHandlers();
RewriterPlugin.clearAvailableRewriters();
ExtraPlugins.clearDynPlugins();
PhoneCapabilityTester.deinit();
} else if (APPLY_NIGHTLY_UPLOAD.equals(intentAction)) {
NightlyUpdater nu = new NightlyUpdater(context);
nu.applyUpdate(intent);
}
}
| public void onReceive(Context context, Intent intent) {
PreferencesProviderWrapper prefWrapper = new PreferencesProviderWrapper(context);
String intentAction = intent.getAction();
//
// ACTION_DATA_STATE_CHANGED
// Data state change is used to detect changes in the mobile
// network such as a switch of network type (GPRS, EDGE, 3G)
// which are not detected by the Connectivity changed broadcast.
//
//
// ACTION_CONNECTIVITY_CHANGED
// Connectivity change is used to detect changes in the overall
// data network status as well as a switch between wifi and mobile
// networks.
//
if (/*intentAction.equals(ACTION_DATA_STATE_CHANGED) ||*/
intentAction.equals(ConnectivityManager.CONNECTIVITY_ACTION) ||
intentAction.equals(Intent.ACTION_BOOT_COMPLETED)) {
if (prefWrapper.isValidConnectionForIncoming()
&&
!prefWrapper
.getPreferenceBooleanValue(PreferencesProviderWrapper.HAS_BEEN_QUIT)) {
Log.d(THIS_FILE, "Try to start service if not already started");
Intent sip_service_intent = new Intent(context, SipService.class);
context.startService(sip_service_intent);
}
} else if (intentAction.equals(SipManager.INTENT_SIP_ACCOUNT_ACTIVATE)) {
context.enforceCallingOrSelfPermission(SipManager.PERMISSION_CONFIGURE_SIP, null);
long accId;
accId = intent.getLongExtra(SipProfile.FIELD_ID, SipProfile.INVALID_ID);
if (accId == SipProfile.INVALID_ID) {
// allow remote side to send us integers.
// previous call will warn, but that's fine, no worries
accId = intent.getIntExtra(SipProfile.FIELD_ID, (int) SipProfile.INVALID_ID);
}
if (accId != SipProfile.INVALID_ID) {
boolean active = intent.getBooleanExtra(SipProfile.FIELD_ACTIVE, true);
ContentValues cv = new ContentValues();
cv.put(SipProfile.FIELD_ACTIVE, active);
int done = context.getContentResolver().update(
ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, accId), cv,
null, null);
if (done > 0) {
if (prefWrapper.isValidConnectionForIncoming()) {
Intent sipServiceIntent = new Intent(context, SipService.class);
context.startService(sipServiceIntent);
}
}
}
} else if (Intent.ACTION_PACKAGE_ADDED.equalsIgnoreCase(intentAction) ||
Intent.ACTION_PACKAGE_REMOVED.equalsIgnoreCase(intentAction)) {
CallHandlerPlugin.clearAvailableCallHandlers();
RewriterPlugin.clearAvailableRewriters();
ExtraPlugins.clearDynPlugins();
PhoneCapabilityTester.deinit();
} else if (APPLY_NIGHTLY_UPLOAD.equals(intentAction)) {
NightlyUpdater nu = new NightlyUpdater(context);
nu.applyUpdate(intent);
}
}
|
diff --git a/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/EventView.java b/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/EventView.java
index e8384ca3..6f88f90b 100644
--- a/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/EventView.java
+++ b/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/EventView.java
@@ -1,442 +1,444 @@
package ch.cern.atlas.apvs.client.ui;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.cern.atlas.apvs.client.ClientFactory;
import ch.cern.atlas.apvs.client.event.SelectPtuEvent;
import ch.cern.atlas.apvs.client.event.SelectTabEvent;
import ch.cern.atlas.apvs.client.service.EventServiceAsync;
import ch.cern.atlas.apvs.client.service.SortOrder;
import ch.cern.atlas.apvs.client.widget.ClickableHtmlColumn;
import ch.cern.atlas.apvs.client.widget.ClickableTextColumn;
import ch.cern.atlas.apvs.domain.Event;
import ch.cern.atlas.apvs.domain.Measurement;
import ch.cern.atlas.apvs.ptu.shared.EventChangedEvent;
import ch.cern.atlas.apvs.ptu.shared.MeasurementChangedEvent;
import ch.cern.atlas.apvs.ptu.shared.PtuClientConstants;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.cellview.client.ColumnSortEvent.AsyncHandler;
import com.google.gwt.user.cellview.client.ColumnSortList;
import com.google.gwt.user.cellview.client.ColumnSortList.ColumnSortInfo;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.Range;
import com.google.gwt.view.client.RangeChangeEvent;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.web.bindery.event.shared.EventBus;
public class EventView extends SimplePanel implements Module {
private Logger log = LoggerFactory.getLogger(getClass().getName());
private EventBus cmdBus;
private String ptuId;
private String measurementName;
private DataGrid<Event> table = new DataGrid<Event>();
private String ptuHeader;
private ClickableTextColumn<Event> ptu;
private String nameHeader;
private ClickableHtmlColumn<Event> name;
private Map<String, String> units = new HashMap<String, String>();
private boolean selectable = false;
private boolean sortable = true;
public EventView() {
}
@Override
public boolean configure(Element element, ClientFactory clientFactory, Arguments args) {
String height = args.getArg(0);
if (args.size() > 1) {
cmdBus = clientFactory.getEventBus(args.getArg(1));
}
table.setSize("100%", height);
table.setEmptyTableWidget(new Label("No Events"));
add(table);
AsyncDataProvider<Event> dataProvider = new AsyncDataProvider<Event>() {
@SuppressWarnings("unchecked")
@Override
protected void onRangeChanged(HasData<Event> display) {
EventServiceAsync.Util.getInstance().getRowCount(new AsyncCallback<Integer>() {
@Override
public void onSuccess(Integer result) {
table.setRowCount(result);
}
@Override
public void onFailure(Throwable caught) {
table.setRowCount(0);
}
});
final Range range = display.getVisibleRange();
System.err.println(range);
final ColumnSortList sortList = table.getColumnSortList();
SortOrder[] order = new SortOrder[sortList.size()];
for (int i=0; i<sortList.size(); i++) {
ColumnSortInfo info = sortList.get(i);
// FIXME #88 remove cast
order[i] = new SortOrder(((ClickableTextColumn<Event>)info.getColumn()).getDataStoreName(), info.isAscending());
}
if (order.length == 0) {
order = new SortOrder[1];
- order[0] = new SortOrder("tbl_events.datetime", true);
+ order[0] = new SortOrder("tbl_events.datetime", false);
}
EventServiceAsync.Util.getInstance().getTableData(range, order, new AsyncCallback<List<Event>>() {
@Override
public void onSuccess(List<Event> result) {
System.err.println("RPC DB SUCCESS");
table.setRowData(range.getStart(), result);
}
@Override
public void onFailure(Throwable caught) {
System.err.println("RPC DB FAILED");
table.setRowCount(0);
}
});
}
};
// Table
dataProvider.addDataDisplay(table);
AsyncHandler columnSortHandler = new AsyncHandler(table);
table.addColumnSortHandler(columnSortHandler);
// Subscriptions
EventChangedEvent.subscribe(clientFactory.getRemoteEventBus(),
new EventChangedEvent.Handler() {
@Override
public void onEventChanged(EventChangedEvent e) {
Event event = e.getEvent();
if (event == null)
return;
if (((ptuId == null) || event.getPtuId().equals(ptuId))
&& ((measurementName == null) || event
.getName().equals(measurementName))) {
update();
}
}
});
MeasurementChangedEvent.subscribe(clientFactory.getRemoteEventBus(),
new MeasurementChangedEvent.Handler() {
@Override
public void onMeasurementChanged(
MeasurementChangedEvent event) {
Measurement m = event.getMeasurement();
units.put(unitKey(m.getPtuId(), m.getName()),
m.getUnit());
update();
}
});
if (cmdBus != null) {
SelectPtuEvent.subscribe(cmdBus, new SelectPtuEvent.Handler() {
@Override
public void onPtuSelected(SelectPtuEvent event) {
ptuId = event.getPtuId();
// dataProvider.getList().clear();
update();
}
});
SelectMeasurementEvent.subscribe(cmdBus,
new SelectMeasurementEvent.Handler() {
@Override
public void onSelection(SelectMeasurementEvent event) {
measurementName = event.getName();
// dataProvider.getList().clear();
update();
}
});
// FIXME #189
SelectTabEvent.subscribe(cmdBus, new SelectTabEvent.Handler() {
@Override
public void onTabSelected(SelectTabEvent event) {
if (event.getTab().equals("Summary")) {
update();
}
}
});
}
// DATE and TIME (1)
ClickableTextColumn<Event> date = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return PtuClientConstants.dateFormat.format(object.getDate());
}
@Override
public String getDataStoreName() {
return "tbl_events.datetime";
}
};
date.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
date.setSortable(sortable);
if (selectable) {
date.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(date, "Date / Time");
+ // desc sort, push twice
+ table.getColumnSortList().push(date);
table.getColumnSortList().push(date);
// PtuID (2)
ptu = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getPtuId();
}
@Override
public String getDataStoreName() {
return "tbl_devices.name";
}
};
ptu.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
ptu.setSortable(sortable);
if (selectable) {
ptu.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
ptuHeader = "PTU ID";
table.addColumn(ptu, ptuHeader);
// Name (3)
name = new ClickableHtmlColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getName();
}
@Override
public String getDataStoreName() {
return "tbl_events.sensor";
}
};
name.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
name.setSortable(sortable);
if (selectable) {
name.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
nameHeader = "Name";
table.addColumn(name, nameHeader);
// EventType
ClickableTextColumn<Event> eventType = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getEventType();
}
@Override
public String getDataStoreName() {
return "tbl_events.event_type";
}
};
eventType.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
eventType.setSortable(sortable);
if (selectable) {
eventType.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(eventType, "EventType");
// Value
ClickableTextColumn<Event> value = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getValue().toString();
}
@Override
public String getDataStoreName() {
return "tbl_events.value";
}
};
value.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
value.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(value, "Value");
// Threshold
ClickableTextColumn<Event> threshold = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getTheshold().toString();
}
@Override
public String getDataStoreName() {
return "tbl_events.threshold";
}
};
threshold.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
threshold.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(threshold, "Threshold");
// Unit
ClickableHtmlColumn<Event> unit = new ClickableHtmlColumn<Event>() {
@Override
public String getValue(Event object) {
return units.get(unitKey(object.getPtuId(), object.getName()));
}
};
unit.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
unit.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(unit, "Unit");
// Selection
if (selectable) {
final SingleSelectionModel<Event> selectionModel = new SingleSelectionModel<Event>();
table.setSelectionModel(selectionModel);
selectionModel
.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
Event m = selectionModel.getSelectedObject();
log.info(m + " " + event.getSource());
}
});
}
return true;
}
private void selectEvent(Event event) {
}
private void update() {
// enable / disable columns
if (table.getColumnIndex(ptu) >= 0) {
table.removeColumn(ptu);
}
if (ptuId == null) {
// add Ptu Column
table.insertColumn(1, ptu, ptuHeader);
}
if (table.getColumnIndex(name) >= 0) {
table.removeColumn(name);
}
if (measurementName == null) {
// add Name column
table.insertColumn(2, name, nameHeader);
}
// Re-sort the table
// if (sortable) {
// ColumnSortEvent.fire(table, table.getColumnSortList());
// }
RangeChangeEvent.fire(table, table.getVisibleRange());
table.redraw();
// if (selectable) {
// Event selection = table.getSelectionModel().getSelectedObject();
//
// if ((selection == null) && (dataProvider.getList().size() > 0)) {
// selection = dataProvider.getList().get(0);
//
// selectEvent(selection);
// }
//
// // re-set the selection as the async update may have changed the
// // rendering
// if (selection != null) {
// selectionModel.setSelected(selection, true);
// }
// }
}
private String unitKey(String ptuId, String name) {
return ptuId + ":" + name;
}
}
| false | true | public boolean configure(Element element, ClientFactory clientFactory, Arguments args) {
String height = args.getArg(0);
if (args.size() > 1) {
cmdBus = clientFactory.getEventBus(args.getArg(1));
}
table.setSize("100%", height);
table.setEmptyTableWidget(new Label("No Events"));
add(table);
AsyncDataProvider<Event> dataProvider = new AsyncDataProvider<Event>() {
@SuppressWarnings("unchecked")
@Override
protected void onRangeChanged(HasData<Event> display) {
EventServiceAsync.Util.getInstance().getRowCount(new AsyncCallback<Integer>() {
@Override
public void onSuccess(Integer result) {
table.setRowCount(result);
}
@Override
public void onFailure(Throwable caught) {
table.setRowCount(0);
}
});
final Range range = display.getVisibleRange();
System.err.println(range);
final ColumnSortList sortList = table.getColumnSortList();
SortOrder[] order = new SortOrder[sortList.size()];
for (int i=0; i<sortList.size(); i++) {
ColumnSortInfo info = sortList.get(i);
// FIXME #88 remove cast
order[i] = new SortOrder(((ClickableTextColumn<Event>)info.getColumn()).getDataStoreName(), info.isAscending());
}
if (order.length == 0) {
order = new SortOrder[1];
order[0] = new SortOrder("tbl_events.datetime", true);
}
EventServiceAsync.Util.getInstance().getTableData(range, order, new AsyncCallback<List<Event>>() {
@Override
public void onSuccess(List<Event> result) {
System.err.println("RPC DB SUCCESS");
table.setRowData(range.getStart(), result);
}
@Override
public void onFailure(Throwable caught) {
System.err.println("RPC DB FAILED");
table.setRowCount(0);
}
});
}
};
// Table
dataProvider.addDataDisplay(table);
AsyncHandler columnSortHandler = new AsyncHandler(table);
table.addColumnSortHandler(columnSortHandler);
// Subscriptions
EventChangedEvent.subscribe(clientFactory.getRemoteEventBus(),
new EventChangedEvent.Handler() {
@Override
public void onEventChanged(EventChangedEvent e) {
Event event = e.getEvent();
if (event == null)
return;
if (((ptuId == null) || event.getPtuId().equals(ptuId))
&& ((measurementName == null) || event
.getName().equals(measurementName))) {
update();
}
}
});
MeasurementChangedEvent.subscribe(clientFactory.getRemoteEventBus(),
new MeasurementChangedEvent.Handler() {
@Override
public void onMeasurementChanged(
MeasurementChangedEvent event) {
Measurement m = event.getMeasurement();
units.put(unitKey(m.getPtuId(), m.getName()),
m.getUnit());
update();
}
});
if (cmdBus != null) {
SelectPtuEvent.subscribe(cmdBus, new SelectPtuEvent.Handler() {
@Override
public void onPtuSelected(SelectPtuEvent event) {
ptuId = event.getPtuId();
// dataProvider.getList().clear();
update();
}
});
SelectMeasurementEvent.subscribe(cmdBus,
new SelectMeasurementEvent.Handler() {
@Override
public void onSelection(SelectMeasurementEvent event) {
measurementName = event.getName();
// dataProvider.getList().clear();
update();
}
});
// FIXME #189
SelectTabEvent.subscribe(cmdBus, new SelectTabEvent.Handler() {
@Override
public void onTabSelected(SelectTabEvent event) {
if (event.getTab().equals("Summary")) {
update();
}
}
});
}
// DATE and TIME (1)
ClickableTextColumn<Event> date = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return PtuClientConstants.dateFormat.format(object.getDate());
}
@Override
public String getDataStoreName() {
return "tbl_events.datetime";
}
};
date.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
date.setSortable(sortable);
if (selectable) {
date.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(date, "Date / Time");
table.getColumnSortList().push(date);
// PtuID (2)
ptu = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getPtuId();
}
@Override
public String getDataStoreName() {
return "tbl_devices.name";
}
};
ptu.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
ptu.setSortable(sortable);
if (selectable) {
ptu.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
ptuHeader = "PTU ID";
table.addColumn(ptu, ptuHeader);
// Name (3)
name = new ClickableHtmlColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getName();
}
@Override
public String getDataStoreName() {
return "tbl_events.sensor";
}
};
name.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
name.setSortable(sortable);
if (selectable) {
name.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
nameHeader = "Name";
table.addColumn(name, nameHeader);
// EventType
ClickableTextColumn<Event> eventType = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getEventType();
}
@Override
public String getDataStoreName() {
return "tbl_events.event_type";
}
};
eventType.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
eventType.setSortable(sortable);
if (selectable) {
eventType.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(eventType, "EventType");
// Value
ClickableTextColumn<Event> value = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getValue().toString();
}
@Override
public String getDataStoreName() {
return "tbl_events.value";
}
};
value.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
value.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(value, "Value");
// Threshold
ClickableTextColumn<Event> threshold = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getTheshold().toString();
}
@Override
public String getDataStoreName() {
return "tbl_events.threshold";
}
};
threshold.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
threshold.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(threshold, "Threshold");
// Unit
ClickableHtmlColumn<Event> unit = new ClickableHtmlColumn<Event>() {
@Override
public String getValue(Event object) {
return units.get(unitKey(object.getPtuId(), object.getName()));
}
};
unit.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
unit.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(unit, "Unit");
// Selection
if (selectable) {
final SingleSelectionModel<Event> selectionModel = new SingleSelectionModel<Event>();
table.setSelectionModel(selectionModel);
selectionModel
.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
Event m = selectionModel.getSelectedObject();
log.info(m + " " + event.getSource());
}
});
}
return true;
}
| public boolean configure(Element element, ClientFactory clientFactory, Arguments args) {
String height = args.getArg(0);
if (args.size() > 1) {
cmdBus = clientFactory.getEventBus(args.getArg(1));
}
table.setSize("100%", height);
table.setEmptyTableWidget(new Label("No Events"));
add(table);
AsyncDataProvider<Event> dataProvider = new AsyncDataProvider<Event>() {
@SuppressWarnings("unchecked")
@Override
protected void onRangeChanged(HasData<Event> display) {
EventServiceAsync.Util.getInstance().getRowCount(new AsyncCallback<Integer>() {
@Override
public void onSuccess(Integer result) {
table.setRowCount(result);
}
@Override
public void onFailure(Throwable caught) {
table.setRowCount(0);
}
});
final Range range = display.getVisibleRange();
System.err.println(range);
final ColumnSortList sortList = table.getColumnSortList();
SortOrder[] order = new SortOrder[sortList.size()];
for (int i=0; i<sortList.size(); i++) {
ColumnSortInfo info = sortList.get(i);
// FIXME #88 remove cast
order[i] = new SortOrder(((ClickableTextColumn<Event>)info.getColumn()).getDataStoreName(), info.isAscending());
}
if (order.length == 0) {
order = new SortOrder[1];
order[0] = new SortOrder("tbl_events.datetime", false);
}
EventServiceAsync.Util.getInstance().getTableData(range, order, new AsyncCallback<List<Event>>() {
@Override
public void onSuccess(List<Event> result) {
System.err.println("RPC DB SUCCESS");
table.setRowData(range.getStart(), result);
}
@Override
public void onFailure(Throwable caught) {
System.err.println("RPC DB FAILED");
table.setRowCount(0);
}
});
}
};
// Table
dataProvider.addDataDisplay(table);
AsyncHandler columnSortHandler = new AsyncHandler(table);
table.addColumnSortHandler(columnSortHandler);
// Subscriptions
EventChangedEvent.subscribe(clientFactory.getRemoteEventBus(),
new EventChangedEvent.Handler() {
@Override
public void onEventChanged(EventChangedEvent e) {
Event event = e.getEvent();
if (event == null)
return;
if (((ptuId == null) || event.getPtuId().equals(ptuId))
&& ((measurementName == null) || event
.getName().equals(measurementName))) {
update();
}
}
});
MeasurementChangedEvent.subscribe(clientFactory.getRemoteEventBus(),
new MeasurementChangedEvent.Handler() {
@Override
public void onMeasurementChanged(
MeasurementChangedEvent event) {
Measurement m = event.getMeasurement();
units.put(unitKey(m.getPtuId(), m.getName()),
m.getUnit());
update();
}
});
if (cmdBus != null) {
SelectPtuEvent.subscribe(cmdBus, new SelectPtuEvent.Handler() {
@Override
public void onPtuSelected(SelectPtuEvent event) {
ptuId = event.getPtuId();
// dataProvider.getList().clear();
update();
}
});
SelectMeasurementEvent.subscribe(cmdBus,
new SelectMeasurementEvent.Handler() {
@Override
public void onSelection(SelectMeasurementEvent event) {
measurementName = event.getName();
// dataProvider.getList().clear();
update();
}
});
// FIXME #189
SelectTabEvent.subscribe(cmdBus, new SelectTabEvent.Handler() {
@Override
public void onTabSelected(SelectTabEvent event) {
if (event.getTab().equals("Summary")) {
update();
}
}
});
}
// DATE and TIME (1)
ClickableTextColumn<Event> date = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return PtuClientConstants.dateFormat.format(object.getDate());
}
@Override
public String getDataStoreName() {
return "tbl_events.datetime";
}
};
date.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
date.setSortable(sortable);
if (selectable) {
date.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(date, "Date / Time");
// desc sort, push twice
table.getColumnSortList().push(date);
table.getColumnSortList().push(date);
// PtuID (2)
ptu = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getPtuId();
}
@Override
public String getDataStoreName() {
return "tbl_devices.name";
}
};
ptu.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
ptu.setSortable(sortable);
if (selectable) {
ptu.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
ptuHeader = "PTU ID";
table.addColumn(ptu, ptuHeader);
// Name (3)
name = new ClickableHtmlColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getName();
}
@Override
public String getDataStoreName() {
return "tbl_events.sensor";
}
};
name.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
name.setSortable(sortable);
if (selectable) {
name.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
nameHeader = "Name";
table.addColumn(name, nameHeader);
// EventType
ClickableTextColumn<Event> eventType = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getEventType();
}
@Override
public String getDataStoreName() {
return "tbl_events.event_type";
}
};
eventType.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
eventType.setSortable(sortable);
if (selectable) {
eventType.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(eventType, "EventType");
// Value
ClickableTextColumn<Event> value = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getValue().toString();
}
@Override
public String getDataStoreName() {
return "tbl_events.value";
}
};
value.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
value.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(value, "Value");
// Threshold
ClickableTextColumn<Event> threshold = new ClickableTextColumn<Event>() {
@Override
public String getValue(Event object) {
return object.getTheshold().toString();
}
@Override
public String getDataStoreName() {
return "tbl_events.threshold";
}
};
threshold.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
threshold.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(threshold, "Threshold");
// Unit
ClickableHtmlColumn<Event> unit = new ClickableHtmlColumn<Event>() {
@Override
public String getValue(Event object) {
return units.get(unitKey(object.getPtuId(), object.getName()));
}
};
unit.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
if (selectable) {
unit.setFieldUpdater(new FieldUpdater<Event, String>() {
@Override
public void update(int index, Event object, String value) {
selectEvent(object);
}
});
}
table.addColumn(unit, "Unit");
// Selection
if (selectable) {
final SingleSelectionModel<Event> selectionModel = new SingleSelectionModel<Event>();
table.setSelectionModel(selectionModel);
selectionModel
.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
Event m = selectionModel.getSelectedObject();
log.info(m + " " + event.getSource());
}
});
}
return true;
}
|
diff --git a/apps/SdkSetup/src/com/android/sdksetup/DefaultActivity.java b/apps/SdkSetup/src/com/android/sdksetup/DefaultActivity.java
index db6385ca..56f43a46 100644
--- a/apps/SdkSetup/src/com/android/sdksetup/DefaultActivity.java
+++ b/apps/SdkSetup/src/com/android/sdksetup/DefaultActivity.java
@@ -1,57 +1,55 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.sdksetup;
import android.app.Activity;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
/**
* Entry point for SDK SetupWizard.
*
*/
public class DefaultActivity extends Activity {
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Add a persistent setting to allow other apps to know the device has been provisioned.
Settings.Secure.putInt(getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 1);
// Enable the GPS.
// Not needed since this SDK will contain the Settings app.
- LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
Settings.Secure.putString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED, LocationManager.GPS_PROVIDER);
- locationManager.updateProviders();
// enable install from non market
Settings.Secure.putInt(getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS, 1);
// remove this activity from the package manager.
PackageManager pm = getPackageManager();
ComponentName name = new ComponentName(this, DefaultActivity.class);
pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
// terminate the activity.
finish();
}
}
| false | true | protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Add a persistent setting to allow other apps to know the device has been provisioned.
Settings.Secure.putInt(getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 1);
// Enable the GPS.
// Not needed since this SDK will contain the Settings app.
LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
Settings.Secure.putString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED, LocationManager.GPS_PROVIDER);
locationManager.updateProviders();
// enable install from non market
Settings.Secure.putInt(getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS, 1);
// remove this activity from the package manager.
PackageManager pm = getPackageManager();
ComponentName name = new ComponentName(this, DefaultActivity.class);
pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
// terminate the activity.
finish();
}
| protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Add a persistent setting to allow other apps to know the device has been provisioned.
Settings.Secure.putInt(getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 1);
// Enable the GPS.
// Not needed since this SDK will contain the Settings app.
Settings.Secure.putString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED, LocationManager.GPS_PROVIDER);
// enable install from non market
Settings.Secure.putInt(getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS, 1);
// remove this activity from the package manager.
PackageManager pm = getPackageManager();
ComponentName name = new ComponentName(this, DefaultActivity.class);
pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
// terminate the activity.
finish();
}
|
diff --git a/jamwiki-core/src/main/java/org/jamwiki/parser/TableOfContents.java b/jamwiki-core/src/main/java/org/jamwiki/parser/TableOfContents.java
index a248b5aa..a68228b4 100644
--- a/jamwiki-core/src/main/java/org/jamwiki/parser/TableOfContents.java
+++ b/jamwiki-core/src/main/java/org/jamwiki/parser/TableOfContents.java
@@ -1,293 +1,293 @@
/**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version of the GNU Lesser General
* Public License as published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.parser;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.jamwiki.Environment;
import org.jamwiki.utils.WikiLogger;
import org.jamwiki.utils.Utilities;
/**
* This class is used to generate a table of contents based on values passed in
* through the parser.
*/
public class TableOfContents {
private static final WikiLogger logger = WikiLogger.getLogger(TableOfContents.class.getName());
/**
* Status indicating that this TOC object has not yet been initialized. For the JFlex parser
* this will mean no __TOC__ tag has been added to the document being parsed.
*/
public static final int STATUS_TOC_UNINITIALIZED = 0;
/**
* Status indicating that this TOC object has been initialized. For the JFlex parser this
* will mean a __TOC__ tag has been added to the document being parsed.
*/
public static final int STATUS_TOC_INITIALIZED = 1;
/** Status indicating that the document being parsed does not allow a table of contents. */
public static final int STATUS_NO_TOC = 2;
/** Force a TOC to appear */
private boolean forceTOC = false;
/** It is possible for a user to include more than one "TOC" tag in a document, so keep count. */
private int insertTagCount = 0;
/** Keep track of how many times the parser attempts to insert the TOC (one per "TOC" tag) */
private int insertionAttempt = 0;
/**
* minLevel holds the minimum TOC heading level that is being displayed by the current TOC. For
* example, if the TOC contains only h3 and h4 entries, this value would be 3.
*/
private int minLevel = 4;
private final Map entries = new LinkedHashMap();
private int status = STATUS_TOC_UNINITIALIZED;
/** The minimum number of headings that must be present for a TOC to appear, unless forceTOC is set to true. */
private static final int MINIMUM_HEADINGS = 4;
/**
* Keep track of the TOC prefix to display. This array is initialized with all ones, and each element
* is then incremented as the TOC is displayed.
*/
private int[] tocPrefixes = null;
/**
* Add a new table of contents entry to the table of contents object.
* The entry should contain the name to use in the HTML anchor tag,
* the text to display in the table of contents, and the indentation
* level for the entry within the table of contents.
*
* @param name The name of the entry, to be used in the anchor tag name.
* @param text The text to display for the table of contents entry.
* @param level The level of the entry. If an entry is a sub-heading of
* another entry the value should be 2. If there is a sub-heading of that
* entry then its value would be 3, and so forth.
*/
public void addEntry(String name, String text, int level) {
if (this.status != STATUS_NO_TOC && this.status != STATUS_TOC_INITIALIZED) {
this.setStatus(STATUS_TOC_INITIALIZED);
}
name = this.checkForUniqueName(name);
TableOfContentsEntry entry = new TableOfContentsEntry(name, text, level);
this.entries.put(name, entry);
if (level < minLevel) {
minLevel = level;
}
}
/**
* This method checks to see if a TOC is allowed to be inserted, and if so
* returns an HTML representation of the TOC.
*
* @return An HTML representation of the current table of contents object,
* or an empty string if the table of contents can not be inserted due
* to an inadequate number of entries or some other reason.
*/
public String attemptTOCInsertion() {
this.insertionAttempt++;
if (this.size() == 0 || (this.size() < MINIMUM_HEADINGS && !this.forceTOC)) {
// too few headings
return "";
}
if (this.getStatus() == TableOfContents.STATUS_NO_TOC) {
// TOC disallowed
return "";
}
if (!Environment.getBooleanValue(Environment.PROP_PARSER_TOC)) {
// TOC turned off for the wiki
return "";
}
if (this.insertionAttempt < this.insertTagCount) {
// user specified a TOC location, only insert there
return "";
}
return this.toHTML();
}
/**
* Verify the the TOC name is unique. If it is already in use append
* a numerical suffix onto it.
*
* @param name The name to use in the TOC, unless it is already in use.
* @return A unique name for use in the TOC, of the form "name" or "name_1"
* if "name" is already in use.
*/
public String checkForUniqueName(String name) {
if (StringUtils.isBlank(name)) {
name = "empty";
}
int count = 0;
String candidate = name;
while (count < 1000) {
if (this.entries.get(candidate) == null) {
return candidate;
}
count++;
candidate = name + "_" + count;
}
logger.warning("Unable to find appropriate TOC name after " + count + " iterations for value " + name);
return candidate;
}
/**
* Internal method to close any list tags prior to adding the next entry.
*/
private void closeList(int level, StringBuffer text, int previousLevel) {
for (int i = previousLevel; i > level; i--) {
// close lists to current level
text.append("</li>\n</ul>");
}
}
/**
* Return the current table of contents status, such as "no table of contents
* allowed" or "uninitialized".
*
* @return The current status of this table of contents object.
*/
public int getStatus() {
return this.status;
}
/**
*
*/
private String nextTocPrefix(int depth) {
// initialize the tocPrefixes value for display
int maxDepth = Environment.getIntValue(Environment.PROP_PARSER_TOC_DEPTH);
if (this.tocPrefixes == null) {
// initialize the prefix array
this.tocPrefixes = new int[maxDepth];
for (int i = 0; i < maxDepth; i++) {
this.tocPrefixes[i] = 0;
}
}
// increment current element
this.tocPrefixes[depth] = this.tocPrefixes[depth] + 1;
// clear out all lower elements
for (int i = depth + 1; i < maxDepth; i++) {
this.tocPrefixes[i] = 0;
}
// generate next prefix of the form 1.1.1
String prefix = new Integer(this.tocPrefixes[0]).toString();
for (int i = 1; i <= depth; i++) {
prefix += "." + this.tocPrefixes[i];
}
return prefix;
}
/**
* Internal method to open any list tags prior to adding the next entry.
*/
private void openList(int level, StringBuffer text, int previousLevel) {
if (level <= previousLevel) {
// same or lower level as previous item, close previous and open new
text.append("</li>\n<li>");
return;
}
for (int i = previousLevel; i < level; i++) {
// open lists to current level
text.append("<ul>\n<li>");
}
}
/**
* Force a TOC to appear, even if there are fewer than four headings.
*
* @param forceTOC Set to <code>true</code> if a TOC is being forced
* to appear, false otherwise.
*/
public void setForceTOC(boolean forceTOC) {
this.forceTOC = forceTOC;
}
/**
* Set the current table of contents status, such as "no table of contents
* allowed" or "uninitialized".
*
* @param status The current status of this table of contents object.
*/
public void setStatus(int status) {
if (status == STATUS_TOC_INITIALIZED) {
// keep track of how many TOC insertion tags are present
this.insertTagCount++;
}
this.status = status;
}
/**
* Return the number of entries in this TOC object.
*
* @return The number of entries in this table of contents object.
*/
public int size() {
return this.entries.size();
}
/**
* Return an HTML representation of this table of contents object.
*
* @return An HTML representation of this table of contents object.
*/
public String toHTML() {
StringBuffer text = new StringBuffer();
text.append("<table id=\"toc\">\n<tr>\n<td>\n");
TableOfContentsEntry entry = null;
int adjustedLevel = 0;
int previousLevel = 0;
Iterator tocIterator = this.entries.values().iterator();
while (tocIterator.hasNext()) {
entry = (TableOfContentsEntry)tocIterator.next();
// adjusted level determines how far to indent the list
adjustedLevel = ((entry.level - minLevel) + 1);
// cannot increase TOC indent level more than one level at a time
if (adjustedLevel > (previousLevel + 1)) {
adjustedLevel = previousLevel + 1;
}
if (adjustedLevel <= Environment.getIntValue(Environment.PROP_PARSER_TOC_DEPTH)) {
// only display if not nested deeper than max
closeList(adjustedLevel, text, previousLevel);
openList(adjustedLevel, text, previousLevel);
text.append("<a href=\"#").append(Utilities.encodeAndEscapeTopicName(entry.name)).append("\">");
text.append("<span class=\"tocnumber\">").append(this.nextTocPrefix(adjustedLevel - 1)).append("</span> ");
text.append("<span class=\"toctext\">").append(entry.text).append("</span></a>");
+ previousLevel = adjustedLevel;
}
- previousLevel = adjustedLevel;
}
closeList(0, text, previousLevel);
text.append("\n</td>\n</tr>\n</table>\n");
return text.toString();
}
/**
* Inner class holds TOC entries until they can be processed for display.
*/
class TableOfContentsEntry {
int level;
String name;
String text;
/**
*
*/
TableOfContentsEntry(String name, String text, int level) {
this.name = name;
this.text = text;
this.level = level;
}
}
}
| false | true | public String toHTML() {
StringBuffer text = new StringBuffer();
text.append("<table id=\"toc\">\n<tr>\n<td>\n");
TableOfContentsEntry entry = null;
int adjustedLevel = 0;
int previousLevel = 0;
Iterator tocIterator = this.entries.values().iterator();
while (tocIterator.hasNext()) {
entry = (TableOfContentsEntry)tocIterator.next();
// adjusted level determines how far to indent the list
adjustedLevel = ((entry.level - minLevel) + 1);
// cannot increase TOC indent level more than one level at a time
if (adjustedLevel > (previousLevel + 1)) {
adjustedLevel = previousLevel + 1;
}
if (adjustedLevel <= Environment.getIntValue(Environment.PROP_PARSER_TOC_DEPTH)) {
// only display if not nested deeper than max
closeList(adjustedLevel, text, previousLevel);
openList(adjustedLevel, text, previousLevel);
text.append("<a href=\"#").append(Utilities.encodeAndEscapeTopicName(entry.name)).append("\">");
text.append("<span class=\"tocnumber\">").append(this.nextTocPrefix(adjustedLevel - 1)).append("</span> ");
text.append("<span class=\"toctext\">").append(entry.text).append("</span></a>");
}
previousLevel = adjustedLevel;
}
closeList(0, text, previousLevel);
text.append("\n</td>\n</tr>\n</table>\n");
return text.toString();
}
| public String toHTML() {
StringBuffer text = new StringBuffer();
text.append("<table id=\"toc\">\n<tr>\n<td>\n");
TableOfContentsEntry entry = null;
int adjustedLevel = 0;
int previousLevel = 0;
Iterator tocIterator = this.entries.values().iterator();
while (tocIterator.hasNext()) {
entry = (TableOfContentsEntry)tocIterator.next();
// adjusted level determines how far to indent the list
adjustedLevel = ((entry.level - minLevel) + 1);
// cannot increase TOC indent level more than one level at a time
if (adjustedLevel > (previousLevel + 1)) {
adjustedLevel = previousLevel + 1;
}
if (adjustedLevel <= Environment.getIntValue(Environment.PROP_PARSER_TOC_DEPTH)) {
// only display if not nested deeper than max
closeList(adjustedLevel, text, previousLevel);
openList(adjustedLevel, text, previousLevel);
text.append("<a href=\"#").append(Utilities.encodeAndEscapeTopicName(entry.name)).append("\">");
text.append("<span class=\"tocnumber\">").append(this.nextTocPrefix(adjustedLevel - 1)).append("</span> ");
text.append("<span class=\"toctext\">").append(entry.text).append("</span></a>");
previousLevel = adjustedLevel;
}
}
closeList(0, text, previousLevel);
text.append("\n</td>\n</tr>\n</table>\n");
return text.toString();
}
|
diff --git a/src/de/aidger/model/models/HourlyWage.java b/src/de/aidger/model/models/HourlyWage.java
index cd59b5f8..6fe292f4 100644
--- a/src/de/aidger/model/models/HourlyWage.java
+++ b/src/de/aidger/model/models/HourlyWage.java
@@ -1,195 +1,197 @@
package de.aidger.model.models;
import java.math.BigDecimal;
import de.aidger.model.AbstractModel;
import de.unistuttgart.iste.se.adohive.model.IHourlyWage;
/**
* Represents a single entry in the hourly wage column of the database. Contains
* functions to retrieve and change the data in the database.
*
* @author aidGer Team
*/
public class HourlyWage extends AbstractModel<IHourlyWage> implements
IHourlyWage {
/**
* The qualification needed for the wage
*/
private String qualification;
/**
* The month the wage is valid in.
*/
private byte month;
/**
* The year the wage is valid in.
*/
private short year;
/**
* The wage per hour.
*/
private BigDecimal wage;
/**
* Initializes the HourlyWage class.
*/
public HourlyWage() {
validatePresenceOf(new String[] { "qualification", "wage" });
// TODO: Validate month and year
}
/**
* Initializes the HourlyWage class with the given hourly wage model.
*
* @param h
* the hourly wage model
*/
public HourlyWage(IHourlyWage h) {
setId(h.getId());
setMonth(h.getMonth());
setQualification(h.getQualification());
setWage(h.getWage());
setYear(h.getYear());
}
/**
* Clone the current wage
*/
@Override
public HourlyWage clone() {
HourlyWage h = new HourlyWage();
h.setId(id);
h.setMonth(month);
h.setQualification(qualification);
h.setWage(wage);
h.setYear(year);
return h;
}
/**
* Check if two objects are equal.
*
* @param o
* The other object
* @return True if both are equal
*/
@Override
public boolean equals(Object o) {
if (o instanceof HourlyWage) {
HourlyWage h = (HourlyWage) o;
- return h.id == id
- && h.month == month
+ /* ID is not used anymore because the database table itself doesn't
+ contain one. */
+ return h.month == month
&& h.year == year
&& (qualification == null ? h.qualification == null
: h.qualification.equals(qualification))
- && (wage == null ? h.wage == null : h.wage.equals(wage));
+ && (wage == null ? h.wage == null :
+ wage.subtract(h.wage).doubleValue() <= 0.01);
} else {
return false;
}
}
/**
* Generate a unique hashcode for this instance.
*
* @return The hashcode
*/
@Override
public int hashCode() {
int hash = 7;
hash = 37 * hash
+ (qualification != null ? qualification.hashCode() : 0);
hash = 37 * hash + month;
hash = 37 * hash + year;
hash = 37 * hash + (wage != null ? wage.hashCode() : 0);
return hash;
}
/**
* Get the month the wage is valid in.
*
* @return The month the wage is valid in
*/
@Override
public byte getMonth() {
return month;
}
/**
* Get the qualification needed for the wage.
*
* @return The qualification needed for the wage
*/
@Override
public String getQualification() {
return qualification;
}
/**
* Get the wage per hour.
*
* @return The wage per hour
*/
@Override
public BigDecimal getWage() {
return wage;
}
/**
* Get the year the wage is valid in.
*
* @return The year the wage is valid in
*/
@Override
public short getYear() {
return year;
}
/**
* Set the month the wage is valid in.
*
* @param month
* The month the wage is valid in
*/
@Override
public void setMonth(byte month) {
this.month = month;
}
/**
* Set the qualification needed for the wage.
*
* @param qual
* The qualification needed for the wage
*/
@Override
public void setQualification(String qual) {
qualification = qual;
}
/**
* Set the wage per hour.
*
* @param wage
* The wage per hour
*/
@Override
public void setWage(BigDecimal wage) {
this.wage = wage;
}
/**
* Set the year the wage is valid in.
*
* @param year
* The year the wage is valid in.
*/
@Override
public void setYear(short year) {
this.year = year;
}
}
| false | true | public boolean equals(Object o) {
if (o instanceof HourlyWage) {
HourlyWage h = (HourlyWage) o;
return h.id == id
&& h.month == month
&& h.year == year
&& (qualification == null ? h.qualification == null
: h.qualification.equals(qualification))
&& (wage == null ? h.wage == null : h.wage.equals(wage));
} else {
return false;
}
}
| public boolean equals(Object o) {
if (o instanceof HourlyWage) {
HourlyWage h = (HourlyWage) o;
/* ID is not used anymore because the database table itself doesn't
contain one. */
return h.month == month
&& h.year == year
&& (qualification == null ? h.qualification == null
: h.qualification.equals(qualification))
&& (wage == null ? h.wage == null :
wage.subtract(h.wage).doubleValue() <= 0.01);
} else {
return false;
}
}
|
diff --git a/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/command/checkin/PerforceCheckInCommand.java b/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/command/checkin/PerforceCheckInCommand.java
index f811298d..b04b892d 100644
--- a/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/command/checkin/PerforceCheckInCommand.java
+++ b/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/command/checkin/PerforceCheckInCommand.java
@@ -1,172 +1,172 @@
package org.apache.maven.scm.provider.perforce.command.checkin;
/*
* 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 org.apache.maven.scm.ScmException;
import org.apache.maven.scm.ScmFileSet;
import org.apache.maven.scm.ScmVersion;
import org.apache.maven.scm.command.checkin.AbstractCheckInCommand;
import org.apache.maven.scm.command.checkin.CheckInScmResult;
import org.apache.maven.scm.provider.ScmProviderRepository;
import org.apache.maven.scm.provider.perforce.PerforceScmProvider;
import org.apache.maven.scm.provider.perforce.command.PerforceCommand;
import org.apache.maven.scm.provider.perforce.repository.PerforceScmProviderRepository;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.Commandline;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @todo refactor this & other perforce commands -- most of the invocation and stream
* consumer code could be shared
* @author Mike Perham
* @version $Id$
*/
public class PerforceCheckInCommand
extends AbstractCheckInCommand
implements PerforceCommand
{
/** {@inheritDoc} */
protected CheckInScmResult executeCheckInCommand( ScmProviderRepository repo, ScmFileSet files, String message,
ScmVersion version )
throws ScmException
{
Commandline cl = createCommandLine( (PerforceScmProviderRepository) repo, files.getBasedir() );
PerforceCheckInConsumer consumer = new PerforceCheckInConsumer();
try
{
String jobs = System.getProperty( "maven.scm.jobs" );
getLogger().debug( PerforceScmProvider.clean( "Executing " + cl.toString() ) );
Process proc = cl.execute();
OutputStream out = proc.getOutputStream();
DataOutputStream dos = new DataOutputStream( out );
PerforceScmProviderRepository prepo = (PerforceScmProviderRepository) repo;
String changes = createChangeListSpecification( prepo, files, message, PerforceScmProvider.getRepoPath(
getLogger(), prepo, files.getBasedir() ), jobs );
getLogger().debug( "Sending changelist:\n" + changes );
dos.write( changes.getBytes() );
dos.close();
out.close();
// TODO find & use a less naive InputStream multiplexer
BufferedReader stdout = new BufferedReader( new InputStreamReader( proc.getInputStream() ) );
BufferedReader stderr = new BufferedReader( new InputStreamReader( proc.getErrorStream() ) );
String line;
while ( ( line = stdout.readLine() ) != null )
{
getLogger().debug( "Consuming stdout: " + line );
consumer.consumeLine( line );
}
while ( ( line = stderr.readLine() ) != null )
{
getLogger().debug( "Consuming stderr: " + line );
consumer.consumeLine( line );
}
stderr.close();
stdout.close();
}
catch ( CommandLineException e )
{
getLogger().error( e );
}
catch ( IOException e )
{
getLogger().error( e );
}
return new CheckInScmResult( cl.toString(), consumer.isSuccess() ? "Checkin successful" : "Unable to submit",
consumer.getOutput(), consumer.isSuccess() );
}
public static Commandline createCommandLine( PerforceScmProviderRepository repo, File workingDirectory )
{
Commandline command = PerforceScmProvider.createP4Command( repo, workingDirectory );
command.createArg().setValue( "submit" );
command.createArg().setValue( "-i" );
return command;
}
private static final String NEWLINE = "\r\n";
- static String createChangeListSpecification( PerforceScmProviderRepository repo, ScmFileSet files,
+ public static String createChangeListSpecification( PerforceScmProviderRepository repo, ScmFileSet files,
String msg, String canonicalPath, String jobs )
{
StringBuffer buf = new StringBuffer();
buf.append( "Change: new" ).append( NEWLINE ).append( NEWLINE );
buf.append( "Description:" ).append( NEWLINE ).append( "\t" ).append( msg ).append( NEWLINE ).append( NEWLINE );
if ( jobs != null && jobs.length() != 0 )
{
// Multiple jobs are not handled with this implementation
buf.append( "Jobs:" ).append( NEWLINE ).append( "\t" ).append( jobs ).append( NEWLINE ).append( NEWLINE );
}
buf.append( "Files:" ).append( NEWLINE );
try
{
Set dupes = new HashSet();
File workingDir = files.getBasedir();
String candir = workingDir.getCanonicalPath();
List fs = files.getFileList();
for ( int i = 0; i < fs.size(); i++ )
{
File file = (File) fs.get( i );
// XXX Submit requires the canonical repository path for each
// file.
// It is unclear how to get that from a File object.
// We assume the repo object has the relative prefix
// "//depot/some/project"
// and canfile has the relative path "src/foo.xml" to be added
// to that prefix.
// "//depot/some/project/src/foo.xml"
String canfile = file.getCanonicalPath();
if ( dupes.contains( canfile ) )
{
// XXX I am seeing duplicate files in the ScmFileSet.
// I don't know why this is but we have to weed them out
// or Perforce will barf
System.err.println( "Skipping duplicate file: " + file );
continue;
}
dupes.add( canfile );
if ( canfile.startsWith( candir ) )
{
canfile = canfile.substring( candir.length() + 1 );
}
buf.append( "\t" ).append( canonicalPath ).append( "/" ).append( canfile.replace( '\\', '/' ) )
.append( NEWLINE );
}
}
catch ( IOException e )
{
e.printStackTrace();
}
return buf.toString();
}
}
| true | true | static String createChangeListSpecification( PerforceScmProviderRepository repo, ScmFileSet files,
String msg, String canonicalPath, String jobs )
{
StringBuffer buf = new StringBuffer();
buf.append( "Change: new" ).append( NEWLINE ).append( NEWLINE );
buf.append( "Description:" ).append( NEWLINE ).append( "\t" ).append( msg ).append( NEWLINE ).append( NEWLINE );
if ( jobs != null && jobs.length() != 0 )
{
// Multiple jobs are not handled with this implementation
buf.append( "Jobs:" ).append( NEWLINE ).append( "\t" ).append( jobs ).append( NEWLINE ).append( NEWLINE );
}
buf.append( "Files:" ).append( NEWLINE );
try
{
Set dupes = new HashSet();
File workingDir = files.getBasedir();
String candir = workingDir.getCanonicalPath();
List fs = files.getFileList();
for ( int i = 0; i < fs.size(); i++ )
{
File file = (File) fs.get( i );
// XXX Submit requires the canonical repository path for each
// file.
// It is unclear how to get that from a File object.
// We assume the repo object has the relative prefix
// "//depot/some/project"
// and canfile has the relative path "src/foo.xml" to be added
// to that prefix.
// "//depot/some/project/src/foo.xml"
String canfile = file.getCanonicalPath();
if ( dupes.contains( canfile ) )
{
// XXX I am seeing duplicate files in the ScmFileSet.
// I don't know why this is but we have to weed them out
// or Perforce will barf
System.err.println( "Skipping duplicate file: " + file );
continue;
}
dupes.add( canfile );
if ( canfile.startsWith( candir ) )
{
canfile = canfile.substring( candir.length() + 1 );
}
buf.append( "\t" ).append( canonicalPath ).append( "/" ).append( canfile.replace( '\\', '/' ) )
.append( NEWLINE );
}
}
catch ( IOException e )
{
e.printStackTrace();
}
return buf.toString();
}
| public static String createChangeListSpecification( PerforceScmProviderRepository repo, ScmFileSet files,
String msg, String canonicalPath, String jobs )
{
StringBuffer buf = new StringBuffer();
buf.append( "Change: new" ).append( NEWLINE ).append( NEWLINE );
buf.append( "Description:" ).append( NEWLINE ).append( "\t" ).append( msg ).append( NEWLINE ).append( NEWLINE );
if ( jobs != null && jobs.length() != 0 )
{
// Multiple jobs are not handled with this implementation
buf.append( "Jobs:" ).append( NEWLINE ).append( "\t" ).append( jobs ).append( NEWLINE ).append( NEWLINE );
}
buf.append( "Files:" ).append( NEWLINE );
try
{
Set dupes = new HashSet();
File workingDir = files.getBasedir();
String candir = workingDir.getCanonicalPath();
List fs = files.getFileList();
for ( int i = 0; i < fs.size(); i++ )
{
File file = (File) fs.get( i );
// XXX Submit requires the canonical repository path for each
// file.
// It is unclear how to get that from a File object.
// We assume the repo object has the relative prefix
// "//depot/some/project"
// and canfile has the relative path "src/foo.xml" to be added
// to that prefix.
// "//depot/some/project/src/foo.xml"
String canfile = file.getCanonicalPath();
if ( dupes.contains( canfile ) )
{
// XXX I am seeing duplicate files in the ScmFileSet.
// I don't know why this is but we have to weed them out
// or Perforce will barf
System.err.println( "Skipping duplicate file: " + file );
continue;
}
dupes.add( canfile );
if ( canfile.startsWith( candir ) )
{
canfile = canfile.substring( candir.length() + 1 );
}
buf.append( "\t" ).append( canonicalPath ).append( "/" ).append( canfile.replace( '\\', '/' ) )
.append( NEWLINE );
}
}
catch ( IOException e )
{
e.printStackTrace();
}
return buf.toString();
}
|
diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java
index b351b739e..5508df639 100644
--- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java
+++ b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java
@@ -1,411 +1,411 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 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.equinox.internal.p2.metadata.generator;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.equinox.internal.p2.artifact.repository.ArtifactRepositoryManager;
import org.eclipse.equinox.internal.p2.core.ProvisioningEventBus;
import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper;
import org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager;
import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository;
import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager;
import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException;
import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus;
import org.eclipse.equinox.internal.provisional.p2.core.repository.IRepository;
import org.eclipse.equinox.internal.provisional.p2.metadata.generator.EclipseInstallGeneratorInfoProvider;
import org.eclipse.equinox.internal.provisional.p2.metadata.generator.Generator;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager;
import org.eclipse.osgi.util.NLS;
import org.osgi.framework.ServiceRegistration;
public class EclipseGeneratorApplication implements IApplication {
// The mapping rules for in-place generation need to construct paths into the structure
// of an eclipse installation; in the future the default artifact mapping declared in
// SimpleArtifactRepository may change, for example, to not have a 'bundles' directory
// instead of a 'plugins' directory, so a separate constant is defined and used here.
static final private String[][] INPLACE_MAPPING_RULES = { {"(& (classifier=osgi.bundle) (format=packed)", "${repoUrl}/features/${id}_${version}.jar.pack.gz"}, //$NON-NLS-1$//$NON-NLS-2$
{"(& (classifier=org.eclipse.update.feature))", "${repoUrl}/features/${id}_${version}.jar"}, //$NON-NLS-1$//$NON-NLS-2$
{"(& (classifier=osgi.bundle))", "${repoUrl}/plugins/${id}_${version}.jar"}, //$NON-NLS-1$//$NON-NLS-2$
{"(& (classifier=binary))", "${repoUrl}/binary/${id}_${version}"}}; //$NON-NLS-1$//$NON-NLS-2$
static final public String PUBLISH_PACK_FILES_AS_SIBLINGS = "publishPackFilesAsSiblings"; //$NON-NLS-1$
private ArtifactRepositoryManager defaultArtifactManager;
private ServiceRegistration registrationDefaultArtifactManager;
private MetadataRepositoryManager defaultMetadataManager;
private ServiceRegistration registrationDefaultMetadataManager;
private IProvisioningEventBus bus;
private ServiceRegistration registrationBus;
private Generator.GeneratorResult incrementalResult = null;
private boolean generateRootIU = true;
private String metadataLocation;
private String metadataRepoName;
private String artifactLocation;
private String artifactRepoName;
private String operation;
private String argument;
private String features;
private String bundles;
private String base;
//whether repository xml files should be compressed
private String compress = "false"; //$NON-NLS-1$
private File getExecutableName(String base, EclipseInstallGeneratorInfoProvider provider) {
File location = provider.getExecutableLocation();
if (location == null)
return new File(base, EclipseInstallGeneratorInfoProvider.getDefaultExecutableName(null));
if (location.isAbsolute())
return location;
return new File(base, location.getPath());
}
private void initialize(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
if ("-source".equalsIgnoreCase(operation)) //$NON-NLS-1$
provider.initialize(new File(argument));
else if ("-inplace".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.initialize(new File(argument));
initializeForInplace(provider);
} else if ("-config".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.initialize(new File(argument), new File(argument, "configuration"), getExecutableName(argument, provider), null, null); //$NON-NLS-1$
} else if ("-updateSite".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.setAddDefaultIUs(false);
provider.initialize(new File(argument), null, null, new File[] {new File(argument, "plugins")}, new File(argument, "features")); //$NON-NLS-1$ //$NON-NLS-2$
initializeForInplace(provider);
} else {
if (base != null && bundles != null && features != null)
provider.initialize(new File(base), null, null, new File[] {new File(bundles)}, new File(features));
}
initializeRepositories(provider);
}
private void initializeArtifactRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.context, IArtifactRepositoryManager.class.getName());
URL location;
try {
location = new URL(artifactLocation);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(NLS.bind(Messages.exception_artifactRepoLocationURL, artifactLocation));
}
String repositoryName = artifactRepoName != null ? artifactRepoName : artifactLocation + " - artifacts"; //$NON-NLS-1$
Map properties = new HashMap(1);
properties.put(IRepository.PROP_COMPRESSED, compress);
if (provider.reuseExistingPack200Files())
properties.put(PUBLISH_PACK_FILES_AS_SIBLINGS, Boolean.TRUE.toString());
IArtifactRepository result = null;
try {
result = manager.createRepository(location, repositoryName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties);
provider.setArtifactRepository(result);
// TODO is this needed?
if (artifactRepoName != null)
result.setName(artifactRepoName);
return;
} catch (ProvisionException e) {
//fall through a load existing repo
}
IArtifactRepository repository = manager.loadRepository(location, null);
if (!repository.isModifiable())
throw new IllegalArgumentException(NLS.bind(Messages.exception_artifactRepoNotWritable, location));
provider.setArtifactRepository(repository);
if (provider.reuseExistingPack200Files())
repository.setProperty(PUBLISH_PACK_FILES_AS_SIBLINGS, "true"); //$NON-NLS-1$
if (!provider.append())
repository.removeAll();
return;
}
public void initializeForInplace(EclipseInstallGeneratorInfoProvider provider) {
File location = provider.getBaseLocation();
if (location == null)
location = provider.getBundleLocations()[0];
try {
metadataLocation = location.toURL().toExternalForm();
artifactLocation = location.toURL().toExternalForm();
} catch (MalformedURLException e) {
// ought not happen...
}
provider.setPublishArtifactRepository(true);
provider.setPublishArtifacts(false);
provider.setMappingRules(INPLACE_MAPPING_RULES);
}
private void initializeMetadataRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
URL location;
try {
location = new URL(metadataLocation);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(NLS.bind(Messages.exception_metadataRepoLocationURL, artifactLocation));
}
// First try to create a simple repo, this will fail if one already exists
// We try creating a repo first instead of just loading what is there because we don't want a repo based
// on a site.xml if there is one there.
String repositoryName = metadataRepoName == null ? metadataLocation + " - metadata" : metadataRepoName; //$NON-NLS-1$
Map properties = new HashMap(1);
properties.put(IRepository.PROP_COMPRESSED, compress);
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.context, IMetadataRepositoryManager.class.getName());
try {
- IMetadataRepository result = manager.createRepository(location, repositoryName, IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, null);
+ IMetadataRepository result = manager.createRepository(location, repositoryName, IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties);
manager.addRepository(result.getLocation());
// TODO is this needed?
if (metadataRepoName != null)
result.setName(metadataRepoName);
provider.setMetadataRepository(result);
return;
} catch (ProvisionException e) {
//fall through and load the existing repo
}
IMetadataRepository repository = manager.loadRepository(location, null);
if (repository != null) {
// don't set the compress flag here because we don't want to change the format
// of an already existing repository
if (!repository.isModifiable())
throw new IllegalArgumentException(NLS.bind(Messages.exception_metadataRepoNotWritable, location));
provider.setMetadataRepository(repository);
if (!provider.append())
repository.removeAll();
return;
}
}
private void initializeRepositories(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
initializeArtifactRepository(provider);
initializeMetadataRepository(provider);
}
public void setCompress(String value) {
if (Boolean.valueOf(value).booleanValue())
compress = "true"; //$NON-NLS-1$
}
public void processCommandLineArguments(String[] args, EclipseInstallGeneratorInfoProvider provider) throws Exception {
if (args == null)
return;
for (int i = 0; i < args.length; i++) {
// check for args without parameters (i.e., a flag arg)
if (args[i].equalsIgnoreCase("-publishArtifacts") || args[i].equalsIgnoreCase("-pa")) //$NON-NLS-1$ //$NON-NLS-2$
provider.setPublishArtifacts(true);
if (args[i].equalsIgnoreCase("-publishArtifactRepository") || args[i].equalsIgnoreCase("-par")) //$NON-NLS-1$ //$NON-NLS-2$
provider.setPublishArtifactRepository(true);
if (args[i].equalsIgnoreCase("-append")) //$NON-NLS-1$
provider.setAppend(true);
if (args[i].equalsIgnoreCase("-noDefaultIUs")) //$NON-NLS-1$
provider.setAddDefaultIUs(false);
if (args[i].equalsIgnoreCase("-compress")) //$NON-NLS-1$
compress = "true"; //$NON-NLS-1$
if (args[i].equalsIgnoreCase("-reusePack200Files")) //$NON-NLS-1$
provider.reuseExistingPack200Files(true);
// check for args with parameters. If we are at the last argument or if the next one
// has a '-' as the first character, then we can't have an arg with a parm so continue.
if (i == args.length - 1 || args[i + 1].startsWith("-")) //$NON-NLS-1$
continue;
String arg = args[++i];
if (args[i - 1].equalsIgnoreCase("-source")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-inplace")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-config")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-updateSite")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-exe")) //$NON-NLS-1$
provider.setExecutableLocation(arg);
if (args[i - 1].equalsIgnoreCase("-launcherConfig")) //$NON-NLS-1$
provider.setLauncherConfig(arg);
if (args[i - 1].equalsIgnoreCase("-metadataRepository") || args[i - 1].equalsIgnoreCase("-mr")) //$NON-NLS-1$ //$NON-NLS-2$
metadataLocation = arg;
if (args[i - 1].equalsIgnoreCase("-metadataRepositoryName")) //$NON-NLS-1$
metadataRepoName = arg;
if (args[i - 1].equalsIgnoreCase("-artifactRepository") | args[i - 1].equalsIgnoreCase("-ar")) //$NON-NLS-1$ //$NON-NLS-2$
artifactLocation = arg;
if (args[i - 1].equalsIgnoreCase("-artifactRepositoryName")) //$NON-NLS-1$
artifactRepoName = arg;
if (args[i - 1].equalsIgnoreCase("-flavor")) //$NON-NLS-1$
provider.setFlavor(arg);
if (args[i - 1].equalsIgnoreCase("-productFile")) //$NON-NLS-1$
provider.setProductFile(arg);
if (args[i - 1].equalsIgnoreCase("-features")) //$NON-NLS-1$
features = arg;
if (args[i - 1].equalsIgnoreCase("-bundles")) //$NON-NLS-1$
bundles = arg;
if (args[i - 1].equalsIgnoreCase("-base")) //$NON-NLS-1$
base = arg;
if (args[i - 1].equalsIgnoreCase("-root")) //$NON-NLS-1$
provider.setRootId(arg);
if (args[i - 1].equalsIgnoreCase("-rootVersion")) //$NON-NLS-1$
provider.setRootVersion(arg);
if (args[i - 1].equalsIgnoreCase("-p2.os")) //$NON-NLS-1$
provider.setOS(arg);
if (args[i - 1].equalsIgnoreCase("-site")) //$NON-NLS-1$
provider.setSiteLocation(new URL(arg));
}
}
private void registerDefaultArtifactRepoManager() {
if (ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()) == null) {
defaultArtifactManager = new ArtifactRepositoryManager();
registrationDefaultArtifactManager = Activator.getContext().registerService(IArtifactRepositoryManager.class.getName(), defaultArtifactManager, null);
}
}
private void registerDefaultMetadataRepoManager() {
if (ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()) == null) {
defaultMetadataManager = new MetadataRepositoryManager();
registrationDefaultMetadataManager = Activator.getContext().registerService(IMetadataRepositoryManager.class.getName(), defaultMetadataManager, null);
}
}
private void registerEventBus() {
if (ServiceHelper.getService(Activator.getContext(), IProvisioningEventBus.SERVICE_NAME) == null) {
bus = new ProvisioningEventBus();
registrationBus = Activator.getContext().registerService(IProvisioningEventBus.SERVICE_NAME, bus, null);
}
}
public Object run(String args[]) throws Exception {
EclipseInstallGeneratorInfoProvider provider = new EclipseInstallGeneratorInfoProvider();
processCommandLineArguments(args, provider);
Object result = run(provider);
if (result != IApplication.EXIT_OK)
for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
return result;
}
public Object run(EclipseInstallGeneratorInfoProvider provider) throws Exception {
registerEventBus();
registerDefaultMetadataRepoManager();
registerDefaultArtifactRepoManager();
initialize(provider);
if (provider.getBaseLocation() == null && provider.getProductFile() == null && !generateRootIU) {
System.out.println(Messages.exception_baseLocationNotSpecified);
return new Integer(-1);
}
System.out.println(NLS.bind(Messages.message_generatingMetadata, provider.getBaseLocation()));
long before = System.currentTimeMillis();
Generator generator = new Generator(provider);
if (incrementalResult != null)
generator.setIncrementalResult(incrementalResult);
generator.setGenerateRootIU(generateRootIU);
IStatus result = generator.generate();
incrementalResult = null;
long after = System.currentTimeMillis();
if (result.isOK()) {
System.out.println(NLS.bind(Messages.message_generationCompleted, String.valueOf((after - before) / 1000)));
return IApplication.EXIT_OK;
}
System.out.println(result);
return new Integer(1);
}
public Object start(IApplicationContext context) throws Exception {
return run((String[]) context.getArguments().get("application.args")); //$NON-NLS-1$
}
public void stop() {
if (registrationDefaultMetadataManager != null) {
registrationDefaultMetadataManager.unregister();
registrationDefaultMetadataManager = null;
}
if (registrationDefaultArtifactManager != null) {
registrationDefaultArtifactManager.unregister();
registrationDefaultArtifactManager = null;
}
if (registrationBus != null) {
registrationBus.unregister();
registrationBus = null;
}
}
public void setBase(String base) {
this.base = base;
}
public void setArtifactLocation(String location) {
this.artifactLocation = location;
}
public void setBundles(String bundles) {
this.bundles = bundles;
}
public void setOperation(String operation, String argument) {
this.operation = operation;
this.argument = argument;
}
public void setFeatures(String features) {
this.features = features;
}
public void setMetadataLocation(String location) {
this.metadataLocation = location;
}
public void setIncrementalResult(Generator.GeneratorResult ius) {
this.incrementalResult = ius;
}
public void setGeneratorRootIU(boolean b) {
this.generateRootIU = b;
}
}
| true | true | private void initialize(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
if ("-source".equalsIgnoreCase(operation)) //$NON-NLS-1$
provider.initialize(new File(argument));
else if ("-inplace".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.initialize(new File(argument));
initializeForInplace(provider);
} else if ("-config".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.initialize(new File(argument), new File(argument, "configuration"), getExecutableName(argument, provider), null, null); //$NON-NLS-1$
} else if ("-updateSite".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.setAddDefaultIUs(false);
provider.initialize(new File(argument), null, null, new File[] {new File(argument, "plugins")}, new File(argument, "features")); //$NON-NLS-1$ //$NON-NLS-2$
initializeForInplace(provider);
} else {
if (base != null && bundles != null && features != null)
provider.initialize(new File(base), null, null, new File[] {new File(bundles)}, new File(features));
}
initializeRepositories(provider);
}
private void initializeArtifactRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.context, IArtifactRepositoryManager.class.getName());
URL location;
try {
location = new URL(artifactLocation);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(NLS.bind(Messages.exception_artifactRepoLocationURL, artifactLocation));
}
String repositoryName = artifactRepoName != null ? artifactRepoName : artifactLocation + " - artifacts"; //$NON-NLS-1$
Map properties = new HashMap(1);
properties.put(IRepository.PROP_COMPRESSED, compress);
if (provider.reuseExistingPack200Files())
properties.put(PUBLISH_PACK_FILES_AS_SIBLINGS, Boolean.TRUE.toString());
IArtifactRepository result = null;
try {
result = manager.createRepository(location, repositoryName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties);
provider.setArtifactRepository(result);
// TODO is this needed?
if (artifactRepoName != null)
result.setName(artifactRepoName);
return;
} catch (ProvisionException e) {
//fall through a load existing repo
}
IArtifactRepository repository = manager.loadRepository(location, null);
if (!repository.isModifiable())
throw new IllegalArgumentException(NLS.bind(Messages.exception_artifactRepoNotWritable, location));
provider.setArtifactRepository(repository);
if (provider.reuseExistingPack200Files())
repository.setProperty(PUBLISH_PACK_FILES_AS_SIBLINGS, "true"); //$NON-NLS-1$
if (!provider.append())
repository.removeAll();
return;
}
public void initializeForInplace(EclipseInstallGeneratorInfoProvider provider) {
File location = provider.getBaseLocation();
if (location == null)
location = provider.getBundleLocations()[0];
try {
metadataLocation = location.toURL().toExternalForm();
artifactLocation = location.toURL().toExternalForm();
} catch (MalformedURLException e) {
// ought not happen...
}
provider.setPublishArtifactRepository(true);
provider.setPublishArtifacts(false);
provider.setMappingRules(INPLACE_MAPPING_RULES);
}
private void initializeMetadataRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
URL location;
try {
location = new URL(metadataLocation);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(NLS.bind(Messages.exception_metadataRepoLocationURL, artifactLocation));
}
// First try to create a simple repo, this will fail if one already exists
// We try creating a repo first instead of just loading what is there because we don't want a repo based
// on a site.xml if there is one there.
String repositoryName = metadataRepoName == null ? metadataLocation + " - metadata" : metadataRepoName; //$NON-NLS-1$
Map properties = new HashMap(1);
properties.put(IRepository.PROP_COMPRESSED, compress);
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.context, IMetadataRepositoryManager.class.getName());
try {
IMetadataRepository result = manager.createRepository(location, repositoryName, IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, null);
manager.addRepository(result.getLocation());
// TODO is this needed?
if (metadataRepoName != null)
result.setName(metadataRepoName);
provider.setMetadataRepository(result);
return;
} catch (ProvisionException e) {
//fall through and load the existing repo
}
IMetadataRepository repository = manager.loadRepository(location, null);
if (repository != null) {
// don't set the compress flag here because we don't want to change the format
// of an already existing repository
if (!repository.isModifiable())
throw new IllegalArgumentException(NLS.bind(Messages.exception_metadataRepoNotWritable, location));
provider.setMetadataRepository(repository);
if (!provider.append())
repository.removeAll();
return;
}
}
private void initializeRepositories(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
initializeArtifactRepository(provider);
initializeMetadataRepository(provider);
}
public void setCompress(String value) {
if (Boolean.valueOf(value).booleanValue())
compress = "true"; //$NON-NLS-1$
}
public void processCommandLineArguments(String[] args, EclipseInstallGeneratorInfoProvider provider) throws Exception {
if (args == null)
return;
for (int i = 0; i < args.length; i++) {
// check for args without parameters (i.e., a flag arg)
if (args[i].equalsIgnoreCase("-publishArtifacts") || args[i].equalsIgnoreCase("-pa")) //$NON-NLS-1$ //$NON-NLS-2$
provider.setPublishArtifacts(true);
if (args[i].equalsIgnoreCase("-publishArtifactRepository") || args[i].equalsIgnoreCase("-par")) //$NON-NLS-1$ //$NON-NLS-2$
provider.setPublishArtifactRepository(true);
if (args[i].equalsIgnoreCase("-append")) //$NON-NLS-1$
provider.setAppend(true);
if (args[i].equalsIgnoreCase("-noDefaultIUs")) //$NON-NLS-1$
provider.setAddDefaultIUs(false);
if (args[i].equalsIgnoreCase("-compress")) //$NON-NLS-1$
compress = "true"; //$NON-NLS-1$
if (args[i].equalsIgnoreCase("-reusePack200Files")) //$NON-NLS-1$
provider.reuseExistingPack200Files(true);
// check for args with parameters. If we are at the last argument or if the next one
// has a '-' as the first character, then we can't have an arg with a parm so continue.
if (i == args.length - 1 || args[i + 1].startsWith("-")) //$NON-NLS-1$
continue;
String arg = args[++i];
if (args[i - 1].equalsIgnoreCase("-source")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-inplace")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-config")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-updateSite")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-exe")) //$NON-NLS-1$
provider.setExecutableLocation(arg);
if (args[i - 1].equalsIgnoreCase("-launcherConfig")) //$NON-NLS-1$
provider.setLauncherConfig(arg);
if (args[i - 1].equalsIgnoreCase("-metadataRepository") || args[i - 1].equalsIgnoreCase("-mr")) //$NON-NLS-1$ //$NON-NLS-2$
metadataLocation = arg;
if (args[i - 1].equalsIgnoreCase("-metadataRepositoryName")) //$NON-NLS-1$
metadataRepoName = arg;
if (args[i - 1].equalsIgnoreCase("-artifactRepository") | args[i - 1].equalsIgnoreCase("-ar")) //$NON-NLS-1$ //$NON-NLS-2$
artifactLocation = arg;
if (args[i - 1].equalsIgnoreCase("-artifactRepositoryName")) //$NON-NLS-1$
artifactRepoName = arg;
if (args[i - 1].equalsIgnoreCase("-flavor")) //$NON-NLS-1$
provider.setFlavor(arg);
if (args[i - 1].equalsIgnoreCase("-productFile")) //$NON-NLS-1$
provider.setProductFile(arg);
if (args[i - 1].equalsIgnoreCase("-features")) //$NON-NLS-1$
features = arg;
if (args[i - 1].equalsIgnoreCase("-bundles")) //$NON-NLS-1$
bundles = arg;
if (args[i - 1].equalsIgnoreCase("-base")) //$NON-NLS-1$
base = arg;
if (args[i - 1].equalsIgnoreCase("-root")) //$NON-NLS-1$
provider.setRootId(arg);
if (args[i - 1].equalsIgnoreCase("-rootVersion")) //$NON-NLS-1$
provider.setRootVersion(arg);
if (args[i - 1].equalsIgnoreCase("-p2.os")) //$NON-NLS-1$
provider.setOS(arg);
if (args[i - 1].equalsIgnoreCase("-site")) //$NON-NLS-1$
provider.setSiteLocation(new URL(arg));
}
}
private void registerDefaultArtifactRepoManager() {
if (ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()) == null) {
defaultArtifactManager = new ArtifactRepositoryManager();
registrationDefaultArtifactManager = Activator.getContext().registerService(IArtifactRepositoryManager.class.getName(), defaultArtifactManager, null);
}
}
private void registerDefaultMetadataRepoManager() {
if (ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()) == null) {
defaultMetadataManager = new MetadataRepositoryManager();
registrationDefaultMetadataManager = Activator.getContext().registerService(IMetadataRepositoryManager.class.getName(), defaultMetadataManager, null);
}
}
private void registerEventBus() {
if (ServiceHelper.getService(Activator.getContext(), IProvisioningEventBus.SERVICE_NAME) == null) {
bus = new ProvisioningEventBus();
registrationBus = Activator.getContext().registerService(IProvisioningEventBus.SERVICE_NAME, bus, null);
}
}
public Object run(String args[]) throws Exception {
EclipseInstallGeneratorInfoProvider provider = new EclipseInstallGeneratorInfoProvider();
processCommandLineArguments(args, provider);
Object result = run(provider);
if (result != IApplication.EXIT_OK)
for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
return result;
}
public Object run(EclipseInstallGeneratorInfoProvider provider) throws Exception {
registerEventBus();
registerDefaultMetadataRepoManager();
registerDefaultArtifactRepoManager();
initialize(provider);
if (provider.getBaseLocation() == null && provider.getProductFile() == null && !generateRootIU) {
System.out.println(Messages.exception_baseLocationNotSpecified);
return new Integer(-1);
}
System.out.println(NLS.bind(Messages.message_generatingMetadata, provider.getBaseLocation()));
long before = System.currentTimeMillis();
Generator generator = new Generator(provider);
if (incrementalResult != null)
generator.setIncrementalResult(incrementalResult);
generator.setGenerateRootIU(generateRootIU);
IStatus result = generator.generate();
incrementalResult = null;
long after = System.currentTimeMillis();
if (result.isOK()) {
System.out.println(NLS.bind(Messages.message_generationCompleted, String.valueOf((after - before) / 1000)));
return IApplication.EXIT_OK;
}
System.out.println(result);
return new Integer(1);
}
public Object start(IApplicationContext context) throws Exception {
return run((String[]) context.getArguments().get("application.args")); //$NON-NLS-1$
}
public void stop() {
if (registrationDefaultMetadataManager != null) {
registrationDefaultMetadataManager.unregister();
registrationDefaultMetadataManager = null;
}
if (registrationDefaultArtifactManager != null) {
registrationDefaultArtifactManager.unregister();
registrationDefaultArtifactManager = null;
}
if (registrationBus != null) {
registrationBus.unregister();
registrationBus = null;
}
}
public void setBase(String base) {
this.base = base;
}
public void setArtifactLocation(String location) {
this.artifactLocation = location;
}
public void setBundles(String bundles) {
this.bundles = bundles;
}
public void setOperation(String operation, String argument) {
this.operation = operation;
this.argument = argument;
}
public void setFeatures(String features) {
this.features = features;
}
public void setMetadataLocation(String location) {
this.metadataLocation = location;
}
public void setIncrementalResult(Generator.GeneratorResult ius) {
this.incrementalResult = ius;
}
public void setGeneratorRootIU(boolean b) {
this.generateRootIU = b;
}
}
| private void initialize(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
if ("-source".equalsIgnoreCase(operation)) //$NON-NLS-1$
provider.initialize(new File(argument));
else if ("-inplace".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.initialize(new File(argument));
initializeForInplace(provider);
} else if ("-config".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.initialize(new File(argument), new File(argument, "configuration"), getExecutableName(argument, provider), null, null); //$NON-NLS-1$
} else if ("-updateSite".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.setAddDefaultIUs(false);
provider.initialize(new File(argument), null, null, new File[] {new File(argument, "plugins")}, new File(argument, "features")); //$NON-NLS-1$ //$NON-NLS-2$
initializeForInplace(provider);
} else {
if (base != null && bundles != null && features != null)
provider.initialize(new File(base), null, null, new File[] {new File(bundles)}, new File(features));
}
initializeRepositories(provider);
}
private void initializeArtifactRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.context, IArtifactRepositoryManager.class.getName());
URL location;
try {
location = new URL(artifactLocation);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(NLS.bind(Messages.exception_artifactRepoLocationURL, artifactLocation));
}
String repositoryName = artifactRepoName != null ? artifactRepoName : artifactLocation + " - artifacts"; //$NON-NLS-1$
Map properties = new HashMap(1);
properties.put(IRepository.PROP_COMPRESSED, compress);
if (provider.reuseExistingPack200Files())
properties.put(PUBLISH_PACK_FILES_AS_SIBLINGS, Boolean.TRUE.toString());
IArtifactRepository result = null;
try {
result = manager.createRepository(location, repositoryName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties);
provider.setArtifactRepository(result);
// TODO is this needed?
if (artifactRepoName != null)
result.setName(artifactRepoName);
return;
} catch (ProvisionException e) {
//fall through a load existing repo
}
IArtifactRepository repository = manager.loadRepository(location, null);
if (!repository.isModifiable())
throw new IllegalArgumentException(NLS.bind(Messages.exception_artifactRepoNotWritable, location));
provider.setArtifactRepository(repository);
if (provider.reuseExistingPack200Files())
repository.setProperty(PUBLISH_PACK_FILES_AS_SIBLINGS, "true"); //$NON-NLS-1$
if (!provider.append())
repository.removeAll();
return;
}
public void initializeForInplace(EclipseInstallGeneratorInfoProvider provider) {
File location = provider.getBaseLocation();
if (location == null)
location = provider.getBundleLocations()[0];
try {
metadataLocation = location.toURL().toExternalForm();
artifactLocation = location.toURL().toExternalForm();
} catch (MalformedURLException e) {
// ought not happen...
}
provider.setPublishArtifactRepository(true);
provider.setPublishArtifacts(false);
provider.setMappingRules(INPLACE_MAPPING_RULES);
}
private void initializeMetadataRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
URL location;
try {
location = new URL(metadataLocation);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(NLS.bind(Messages.exception_metadataRepoLocationURL, artifactLocation));
}
// First try to create a simple repo, this will fail if one already exists
// We try creating a repo first instead of just loading what is there because we don't want a repo based
// on a site.xml if there is one there.
String repositoryName = metadataRepoName == null ? metadataLocation + " - metadata" : metadataRepoName; //$NON-NLS-1$
Map properties = new HashMap(1);
properties.put(IRepository.PROP_COMPRESSED, compress);
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.context, IMetadataRepositoryManager.class.getName());
try {
IMetadataRepository result = manager.createRepository(location, repositoryName, IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties);
manager.addRepository(result.getLocation());
// TODO is this needed?
if (metadataRepoName != null)
result.setName(metadataRepoName);
provider.setMetadataRepository(result);
return;
} catch (ProvisionException e) {
//fall through and load the existing repo
}
IMetadataRepository repository = manager.loadRepository(location, null);
if (repository != null) {
// don't set the compress flag here because we don't want to change the format
// of an already existing repository
if (!repository.isModifiable())
throw new IllegalArgumentException(NLS.bind(Messages.exception_metadataRepoNotWritable, location));
provider.setMetadataRepository(repository);
if (!provider.append())
repository.removeAll();
return;
}
}
private void initializeRepositories(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
initializeArtifactRepository(provider);
initializeMetadataRepository(provider);
}
public void setCompress(String value) {
if (Boolean.valueOf(value).booleanValue())
compress = "true"; //$NON-NLS-1$
}
public void processCommandLineArguments(String[] args, EclipseInstallGeneratorInfoProvider provider) throws Exception {
if (args == null)
return;
for (int i = 0; i < args.length; i++) {
// check for args without parameters (i.e., a flag arg)
if (args[i].equalsIgnoreCase("-publishArtifacts") || args[i].equalsIgnoreCase("-pa")) //$NON-NLS-1$ //$NON-NLS-2$
provider.setPublishArtifacts(true);
if (args[i].equalsIgnoreCase("-publishArtifactRepository") || args[i].equalsIgnoreCase("-par")) //$NON-NLS-1$ //$NON-NLS-2$
provider.setPublishArtifactRepository(true);
if (args[i].equalsIgnoreCase("-append")) //$NON-NLS-1$
provider.setAppend(true);
if (args[i].equalsIgnoreCase("-noDefaultIUs")) //$NON-NLS-1$
provider.setAddDefaultIUs(false);
if (args[i].equalsIgnoreCase("-compress")) //$NON-NLS-1$
compress = "true"; //$NON-NLS-1$
if (args[i].equalsIgnoreCase("-reusePack200Files")) //$NON-NLS-1$
provider.reuseExistingPack200Files(true);
// check for args with parameters. If we are at the last argument or if the next one
// has a '-' as the first character, then we can't have an arg with a parm so continue.
if (i == args.length - 1 || args[i + 1].startsWith("-")) //$NON-NLS-1$
continue;
String arg = args[++i];
if (args[i - 1].equalsIgnoreCase("-source")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-inplace")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-config")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-updateSite")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-exe")) //$NON-NLS-1$
provider.setExecutableLocation(arg);
if (args[i - 1].equalsIgnoreCase("-launcherConfig")) //$NON-NLS-1$
provider.setLauncherConfig(arg);
if (args[i - 1].equalsIgnoreCase("-metadataRepository") || args[i - 1].equalsIgnoreCase("-mr")) //$NON-NLS-1$ //$NON-NLS-2$
metadataLocation = arg;
if (args[i - 1].equalsIgnoreCase("-metadataRepositoryName")) //$NON-NLS-1$
metadataRepoName = arg;
if (args[i - 1].equalsIgnoreCase("-artifactRepository") | args[i - 1].equalsIgnoreCase("-ar")) //$NON-NLS-1$ //$NON-NLS-2$
artifactLocation = arg;
if (args[i - 1].equalsIgnoreCase("-artifactRepositoryName")) //$NON-NLS-1$
artifactRepoName = arg;
if (args[i - 1].equalsIgnoreCase("-flavor")) //$NON-NLS-1$
provider.setFlavor(arg);
if (args[i - 1].equalsIgnoreCase("-productFile")) //$NON-NLS-1$
provider.setProductFile(arg);
if (args[i - 1].equalsIgnoreCase("-features")) //$NON-NLS-1$
features = arg;
if (args[i - 1].equalsIgnoreCase("-bundles")) //$NON-NLS-1$
bundles = arg;
if (args[i - 1].equalsIgnoreCase("-base")) //$NON-NLS-1$
base = arg;
if (args[i - 1].equalsIgnoreCase("-root")) //$NON-NLS-1$
provider.setRootId(arg);
if (args[i - 1].equalsIgnoreCase("-rootVersion")) //$NON-NLS-1$
provider.setRootVersion(arg);
if (args[i - 1].equalsIgnoreCase("-p2.os")) //$NON-NLS-1$
provider.setOS(arg);
if (args[i - 1].equalsIgnoreCase("-site")) //$NON-NLS-1$
provider.setSiteLocation(new URL(arg));
}
}
private void registerDefaultArtifactRepoManager() {
if (ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()) == null) {
defaultArtifactManager = new ArtifactRepositoryManager();
registrationDefaultArtifactManager = Activator.getContext().registerService(IArtifactRepositoryManager.class.getName(), defaultArtifactManager, null);
}
}
private void registerDefaultMetadataRepoManager() {
if (ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()) == null) {
defaultMetadataManager = new MetadataRepositoryManager();
registrationDefaultMetadataManager = Activator.getContext().registerService(IMetadataRepositoryManager.class.getName(), defaultMetadataManager, null);
}
}
private void registerEventBus() {
if (ServiceHelper.getService(Activator.getContext(), IProvisioningEventBus.SERVICE_NAME) == null) {
bus = new ProvisioningEventBus();
registrationBus = Activator.getContext().registerService(IProvisioningEventBus.SERVICE_NAME, bus, null);
}
}
public Object run(String args[]) throws Exception {
EclipseInstallGeneratorInfoProvider provider = new EclipseInstallGeneratorInfoProvider();
processCommandLineArguments(args, provider);
Object result = run(provider);
if (result != IApplication.EXIT_OK)
for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
return result;
}
public Object run(EclipseInstallGeneratorInfoProvider provider) throws Exception {
registerEventBus();
registerDefaultMetadataRepoManager();
registerDefaultArtifactRepoManager();
initialize(provider);
if (provider.getBaseLocation() == null && provider.getProductFile() == null && !generateRootIU) {
System.out.println(Messages.exception_baseLocationNotSpecified);
return new Integer(-1);
}
System.out.println(NLS.bind(Messages.message_generatingMetadata, provider.getBaseLocation()));
long before = System.currentTimeMillis();
Generator generator = new Generator(provider);
if (incrementalResult != null)
generator.setIncrementalResult(incrementalResult);
generator.setGenerateRootIU(generateRootIU);
IStatus result = generator.generate();
incrementalResult = null;
long after = System.currentTimeMillis();
if (result.isOK()) {
System.out.println(NLS.bind(Messages.message_generationCompleted, String.valueOf((after - before) / 1000)));
return IApplication.EXIT_OK;
}
System.out.println(result);
return new Integer(1);
}
public Object start(IApplicationContext context) throws Exception {
return run((String[]) context.getArguments().get("application.args")); //$NON-NLS-1$
}
public void stop() {
if (registrationDefaultMetadataManager != null) {
registrationDefaultMetadataManager.unregister();
registrationDefaultMetadataManager = null;
}
if (registrationDefaultArtifactManager != null) {
registrationDefaultArtifactManager.unregister();
registrationDefaultArtifactManager = null;
}
if (registrationBus != null) {
registrationBus.unregister();
registrationBus = null;
}
}
public void setBase(String base) {
this.base = base;
}
public void setArtifactLocation(String location) {
this.artifactLocation = location;
}
public void setBundles(String bundles) {
this.bundles = bundles;
}
public void setOperation(String operation, String argument) {
this.operation = operation;
this.argument = argument;
}
public void setFeatures(String features) {
this.features = features;
}
public void setMetadataLocation(String location) {
this.metadataLocation = location;
}
public void setIncrementalResult(Generator.GeneratorResult ius) {
this.incrementalResult = ius;
}
public void setGeneratorRootIU(boolean b) {
this.generateRootIU = b;
}
}
|
diff --git a/src/org/apache/xml/security/utils/resolver/implementations/ResolverXPointer.java b/src/org/apache/xml/security/utils/resolver/implementations/ResolverXPointer.java
index 292cee56..b0d2ece7 100644
--- a/src/org/apache/xml/security/utils/resolver/implementations/ResolverXPointer.java
+++ b/src/org/apache/xml/security/utils/resolver/implementations/ResolverXPointer.java
@@ -1,191 +1,195 @@
/*
* Copyright 1999-2004 The Apache Software 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.apache.xml.security.utils.resolver.implementations;
import org.apache.xml.security.signature.XMLSignatureInput;
import org.apache.xml.security.utils.IdResolver;
import org.apache.xml.security.utils.resolver.ResourceResolverException;
import org.apache.xml.security.utils.resolver.ResourceResolverSpi;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* Handles barename XPointer Reference URIs.
* <BR />
* To retain comments while selecting an element by an identifier ID,
* use the following full XPointer: URI='#xpointer(id('ID'))'.
* <BR />
* To retain comments while selecting the entire document,
* use the following full XPointer: URI='#xpointer(/)'.
* This XPointer contains a simple XPath expression that includes
* the root node, which the second to last step above replaces with all
* nodes of the parse tree (all descendants, plus all attributes,
* plus all namespaces nodes).
*
* @author $Author$
*/
public class ResolverXPointer extends ResourceResolverSpi {
/** {@link org.apache.commons.logging} logging facility */
static org.apache.commons.logging.Log log =
org.apache.commons.logging.LogFactory.getLog(
ResolverXPointer.class.getName());
/**
* @inheritDoc
*/
public XMLSignatureInput engineResolve(Attr uri, String BaseURI)
throws ResourceResolverException {
Node resultNode = null;
Document doc = uri.getOwnerElement().getOwnerDocument();
// this must be done so that Xalan can catch ALL namespaces
//XMLUtils.circumventBug2650(doc);
//CachedXPathAPI cXPathAPI = new CachedXPathAPI();
String uriStr=uri.getNodeValue();
if (isXPointerSlash(uriStr)) {
resultNode = doc;
} else if (isXPointerId(uriStr)) {
String id = getXPointerId(uriStr);
resultNode =IdResolver.getElementById(doc, id);
// log.debug("Use #xpointer(id('" + id + "')) on element " + selectedElem);
if (resultNode == null) {
Object exArgs[] = { id };
throw new ResourceResolverException(
"signature.Verification.MissingID", exArgs, uri, BaseURI);
}
/*
resultNodes =
cXPathAPI
.selectNodeList(selectedElem, Canonicalizer
.XPATH_C14N_WITH_COMMENTS_SINGLE_NODE);*/
}
//Set resultSet = XMLUtils.convertNodelistToSet(resultNode);
//CachedXPathAPIHolder.setDoc(doc);
XMLSignatureInput result = new XMLSignatureInput(resultNode);
result.setMIMEType("text/xml");
+ if (BaseURI != null && BaseURI.length() > 0) {
result.setSourceURI(BaseURI.concat(uri.getNodeValue()));
+ } else {
+ result.setSourceURI(uri.getNodeValue());
+ }
return result;
}
/**
* @inheritDoc
*/
public boolean engineCanResolve(Attr uri, String BaseURI) {
if (uri == null) {
return false;
}
String uriStr =uri.getNodeValue();
if (isXPointerSlash(uriStr) || isXPointerId(uriStr)) {
return true;
}
return false;
}
/**
* Method isXPointerSlash
*
* @param uri
* @return true if begins with xpointer
*/
private static boolean isXPointerSlash(String uri) {
if (uri.equals("#xpointer(/)")) {
return true;
}
return false;
}
private static final String XP="#xpointer(id(";
private static final int XP_LENGTH=XP.length();
/**
* Method isXPointerId
*
* @param uri
* @return it it has an xpointer id
*
*/
private static boolean isXPointerId(String uri) {
if (uri.startsWith(XP)
&& uri.endsWith("))")) {
String idPlusDelim = uri.substring(XP_LENGTH,
uri.length()
- 2);
// log.debug("idPlusDelim=" + idPlusDelim);
int idLen=idPlusDelim.length() -1;
if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim
.charAt(idLen) == '"')) || ((idPlusDelim
.charAt(0) == '\'') && (idPlusDelim
.charAt(idLen) == '\''))) {
if (log.isDebugEnabled())
log.debug("Id="
+ idPlusDelim.substring(1, idLen));
return true;
}
}
return false;
}
/**
* Method getXPointerId
*
* @param uri
* @return xpointerId to search.
*/
private static String getXPointerId(String uri) {
if (uri.startsWith(XP)
&& uri.endsWith("))")) {
String idPlusDelim = uri.substring(XP_LENGTH,uri.length()
- 2);
int idLen=idPlusDelim.length() -1;
if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim
.charAt(idLen) == '"')) || ((idPlusDelim
.charAt(0) == '\'') && (idPlusDelim
.charAt(idLen) == '\''))) {
return idPlusDelim.substring(1, idLen);
}
}
return null;
}
}
| false | true | public XMLSignatureInput engineResolve(Attr uri, String BaseURI)
throws ResourceResolverException {
Node resultNode = null;
Document doc = uri.getOwnerElement().getOwnerDocument();
// this must be done so that Xalan can catch ALL namespaces
//XMLUtils.circumventBug2650(doc);
//CachedXPathAPI cXPathAPI = new CachedXPathAPI();
String uriStr=uri.getNodeValue();
if (isXPointerSlash(uriStr)) {
resultNode = doc;
} else if (isXPointerId(uriStr)) {
String id = getXPointerId(uriStr);
resultNode =IdResolver.getElementById(doc, id);
// log.debug("Use #xpointer(id('" + id + "')) on element " + selectedElem);
if (resultNode == null) {
Object exArgs[] = { id };
throw new ResourceResolverException(
"signature.Verification.MissingID", exArgs, uri, BaseURI);
}
/*
resultNodes =
cXPathAPI
.selectNodeList(selectedElem, Canonicalizer
.XPATH_C14N_WITH_COMMENTS_SINGLE_NODE);*/
}
//Set resultSet = XMLUtils.convertNodelistToSet(resultNode);
//CachedXPathAPIHolder.setDoc(doc);
XMLSignatureInput result = new XMLSignatureInput(resultNode);
result.setMIMEType("text/xml");
result.setSourceURI(BaseURI.concat(uri.getNodeValue()));
return result;
}
| public XMLSignatureInput engineResolve(Attr uri, String BaseURI)
throws ResourceResolverException {
Node resultNode = null;
Document doc = uri.getOwnerElement().getOwnerDocument();
// this must be done so that Xalan can catch ALL namespaces
//XMLUtils.circumventBug2650(doc);
//CachedXPathAPI cXPathAPI = new CachedXPathAPI();
String uriStr=uri.getNodeValue();
if (isXPointerSlash(uriStr)) {
resultNode = doc;
} else if (isXPointerId(uriStr)) {
String id = getXPointerId(uriStr);
resultNode =IdResolver.getElementById(doc, id);
// log.debug("Use #xpointer(id('" + id + "')) on element " + selectedElem);
if (resultNode == null) {
Object exArgs[] = { id };
throw new ResourceResolverException(
"signature.Verification.MissingID", exArgs, uri, BaseURI);
}
/*
resultNodes =
cXPathAPI
.selectNodeList(selectedElem, Canonicalizer
.XPATH_C14N_WITH_COMMENTS_SINGLE_NODE);*/
}
//Set resultSet = XMLUtils.convertNodelistToSet(resultNode);
//CachedXPathAPIHolder.setDoc(doc);
XMLSignatureInput result = new XMLSignatureInput(resultNode);
result.setMIMEType("text/xml");
if (BaseURI != null && BaseURI.length() > 0) {
result.setSourceURI(BaseURI.concat(uri.getNodeValue()));
} else {
result.setSourceURI(uri.getNodeValue());
}
return result;
}
|
diff --git a/Android/Roger/src/com/bignerdranch/franklin/roger/RogerActivity.java b/Android/Roger/src/com/bignerdranch/franklin/roger/RogerActivity.java
index 5bd1346..4c5b7f0 100644
--- a/Android/Roger/src/com/bignerdranch/franklin/roger/RogerActivity.java
+++ b/Android/Roger/src/com/bignerdranch/franklin/roger/RogerActivity.java
@@ -1,457 +1,458 @@
package com.bignerdranch.franklin.roger;
import java.util.ArrayList;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.bignerdranch.franklin.roger.model.RogerParams;
public class RogerActivity extends FragmentActivity {
public static final String TAG = "RogerActivity";
private static String SERVER_SELECT = "SelectServer";
private static String THE_MANAGEMENT = "Management";
private static final String LAYOUT_PARAM_DIALOG_TAG = "RogerActivity.layoutParamsDialog";
private DownloadManager manager;
private TheManagement management;
private TextView serverNameTextView;
private TextView connectionStatusTextView;
private FrameLayout container;
private ViewGroup rootContainer;
private ViewGroup containerBorder;
private ProgressBar discoveryProgressBar;
private static class TheManagement extends Fragment {
public LayoutDescription layoutDescription;
public RogerParams rogerParams;
public boolean textFillSet;
public boolean textFillEnabled;
public boolean isListView;
@Override
public void onCreate(Bundle sharedInstanceState) {
super.onCreate(sharedInstanceState);
setRetainInstance(true);
}
@Override
public void onDestroy() {
super.onDestroy();
ConnectionHelper.getInstance(getActivity())
.connectToServer(null);
}
}
private DiscoveryHelper.Listener discoveryListener = new DiscoveryHelper.Listener() {
public void onStateChanged(DiscoveryHelper discover) {
if (discoveryProgressBar != null) {
discoveryProgressBar.post(new Runnable() { public void run() {
updateDiscovery();
}});
}
}
};
private ConnectionHelper.Listener connectionStateListener = new ConnectionHelper.Listener() {
public void onStateChanged(ConnectionHelper connector) {
if (connectionStatusTextView != null) {
connectionStatusTextView.post(new Runnable() { public void run() {
updateServerStatus();
}});
}
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
manager = DownloadManager.getInstance();
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
serverNameTextView = (TextView)findViewById(R.id.serverNameTextView);
connectionStatusTextView = (TextView)findViewById(R.id.connectionStatusTextView);
rootContainer = (ViewGroup)findViewById(R.id.main_root);
container = (FrameLayout)findViewById(R.id.container);
containerBorder = (ViewGroup)findViewById(R.id.main_container_border);
containerBorder.setVisibility(View.GONE);
discoveryProgressBar = (ProgressBar)findViewById(R.id.discoveryProgressBar);
DiscoveryHelper.getInstance(this)
.addListener(discoveryListener);
management = (TheManagement)getSupportFragmentManager()
.findFragmentByTag(THE_MANAGEMENT);
if (management == null) {
management = new TheManagement();
getSupportFragmentManager().beginTransaction()
.add(management, THE_MANAGEMENT)
.commit();
}
if (management.layoutDescription != null) {
loadLayout(management.layoutDescription);
}
if (management.rogerParams == null) {
float density = getResources().getDisplayMetrics().density;
management.rogerParams = new RogerParams(density, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}
ConnectionHelper connector = ConnectionHelper.getInstance(this);
if (connector.getState() == ConnectionHelper.STATE_DISCONNECTED || connector.getState() == ConnectionHelper.STATE_FAILED) {
refreshServers();
}
connector.addListener(connectionStateListener);
updateServerStatus();
updateDiscovery();
}
@Override
public void onDestroy() {
super.onDestroy();
ConnectionHelper.getInstance(this)
.removeListener(connectionStateListener);
DiscoveryHelper.getInstance(this)
.removeListener(discoveryListener);
}
private void updateDiscovery() {
DiscoveryHelper discover = DiscoveryHelper.getInstance(this);
if (discover.getState() == DiscoveryHelper.STATE_DISCOVERING) {
discoveryProgressBar.setVisibility(View.VISIBLE);
} else {
discoveryProgressBar.setVisibility(View.GONE);
}
}
public void setRogerParams(RogerParams params) {
management.rogerParams = params;
updateLayoutParams(params);
loadLayout();
}
private void updateLayoutParams(RogerParams params) {
if (container == null) {
return;
}
int width = params.getWidthParam();
int height = params.getHeightParam();
FrameLayout.LayoutParams actualParams = new FrameLayout.LayoutParams(width, height);
container.setLayoutParams(actualParams);
int containerWidth = ViewGroup.LayoutParams.WRAP_CONTENT;
int containerHeight = ViewGroup.LayoutParams.WRAP_CONTENT;
if (width == ViewGroup.LayoutParams.FILL_PARENT) {
containerWidth = width;
}
if (height == ViewGroup.LayoutParams.FILL_PARENT) {
containerHeight = height;
}
FrameLayout.LayoutParams containerParams = (FrameLayout.LayoutParams) containerBorder.getLayoutParams();
containerParams.width = containerWidth;
containerParams.height = containerHeight;
containerBorder.setLayoutParams(containerParams);
}
private void updateServerStatus() {
ConnectionHelper connector = ConnectionHelper.getInstance(this);
ServerDescription desc = connector.getConnectedServer();
if (desc != null) {
serverNameTextView.setText(desc.getName());
serverNameTextView.setVisibility(View.VISIBLE);
connectionStatusTextView.setVisibility(View.VISIBLE);
} else {
serverNameTextView.setText("");
serverNameTextView.setVisibility(View.GONE);
connectionStatusTextView.setVisibility(View.GONE);
}
String state = null;
switch (connector.getState()) {
case ConnectionHelper.STATE_CONNECTING:
state = "Connecting...";
break;
case ConnectionHelper.STATE_CONNECTED:
state = "";
break;
case ConnectionHelper.STATE_FAILED:
state = "Connection failed";
break;
case ConnectionHelper.STATE_DISCONNECTED:
state = "Disconnected";
break;
case ConnectionHelper.STATE_DOWNLOADING:
state = "Downloading...";
break;
default:
break;
}
connectionStatusTextView.setText(state);
}
private BroadcastReceiver foundServersReceiver = new BroadcastReceiver() {
public void onReceive(Context c, Intent i) {
ArrayList<?> addresses = (ArrayList<?>)i.getSerializableExtra(FindServerService.EXTRA_IP_ADDRESSES);
if (addresses == null || addresses.size() == 0) return;
ConnectionHelper connector = ConnectionHelper.getInstance(c);
int state = connector.getState();
if (addresses.size() == 1 &&
(state == ConnectionHelper.STATE_DISCONNECTED || state == ConnectionHelper.STATE_FAILED)) {
// auto connect
connector.connectToServer((ServerDescription)addresses.get(0));
return;
}
Bundle args = new Bundle();
args.putSerializable(FindServerService.EXTRA_IP_ADDRESSES, addresses);
FragmentManager fm = getSupportFragmentManager();
if (fm.findFragmentByTag(SERVER_SELECT) == null) {
DialogFragment f = new SelectServerDialog();
f.setArguments(args);
f.show(fm, SERVER_SELECT);
}
}
};
@Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(FindServerService.ACTION_FOUND_SERVERS);
LocalBroadcastManager.getInstance(this)
.registerReceiver(foundServersReceiver, filter);
}
@Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this)
.unregisterReceiver(foundServersReceiver);
}
private void loadLayout() {
if (management.layoutDescription != null) {
loadLayout(management.layoutDescription);
}
}
private void loadLayout(LayoutDescription description) {
management.layoutDescription = description;
- if (description.getMinVersion() < Build.VERSION.SDK_INT) {
+ if (description.getMinVersion() != 0 && description.getMinVersion() > Build.VERSION.SDK_INT) {
Log.e(TAG, "invalid version of Android");
- ErrorManager.show(getApplicationContext(), rootContainer, "This view requires Android version " + description.getMinVersion());
+ ErrorManager.show(getApplicationContext(),
+ rootContainer, "This view requires Android version " + description.getMinVersion());
containerBorder.setVisibility(View.GONE);
return;
}
container.removeAllViews();
updateLayoutParams(management.rogerParams);
final int id = description.getResId(this);
if (id == 0) {
Log.e(TAG, "ID is 0. Not inflating.");
ErrorManager.show(getApplicationContext(), rootContainer, "Unable to load view");
containerBorder.setVisibility(View.GONE);
return;
}
Log.i(TAG, "getting a layout inflater...");
final LayoutInflater inflater = description.getApk(this).getLayoutInflater(getLayoutInflater());
Log.i(TAG, "inflating???");
try {
if (management.isListView) {
FrameLayout.LayoutParams params =
new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
ListView listView = new ListView(this);
ArrayList<String> items = new ArrayList<String>();
for (int i = 0; i < 100; i++) {
items.add("" + i);
}
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView != null) {
addTextFill(convertView);
return convertView;
} else {
View v = inflater.inflate(id, parent, false);
addTextFill(v);
return v;
}
}
});
container.addView(listView, params);
} else {
View v = inflater.inflate(id, container, false);
container.addView(v);
}
addTextFill();
containerBorder.setVisibility(View.VISIBLE);
} catch (InflateException ex) {
Throwable cause = ex;
while (cause.getCause() != null) {
cause = cause.getCause();
}
ErrorManager.show(getApplicationContext(), rootContainer, cause.getMessage());
}
}
private void addTextFill() {
addTextFill(container);
}
private void addTextFill(View view) {
if (!management.textFillSet) {
return;
}
String dummyText = getString(R.string.dummy_text);
ArrayList<TextView> views = ViewUtils.findViewsByClass(view, TextView.class);
for (TextView textView : views) {
String oldText = (String)ViewUtils.getTag(textView, R.id.original_text);
if (oldText == null) {
oldText = textView.getText() == null ? "" : textView.getText().toString();
ViewUtils.setTag(textView, R.id.original_text);
}
if (management.textFillEnabled) {
textView.setText(dummyText);
} else {
textView.setText(oldText);
}
}
}
protected void showLayoutParamsDialog() {
LayoutDialogFragment dialog = LayoutDialogFragment.newInstance(management.rogerParams);
dialog.show(getSupportFragmentManager(), LAYOUT_PARAM_DIALOG_TAG);
}
protected void refreshServers() {
DiscoveryHelper.getInstance(this)
.startDiscovery();
}
private void updateTextFill() {
management.textFillSet = true;
management.textFillEnabled = !management.textFillEnabled;
loadLayout();
}
private void toggleListView() {
management.isListView = !management.isListView;
loadLayout();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh:
refreshServers();
break;
case R.id.menu_layout_options:
showLayoutParamsDialog();
break;
case R.id.menu_layout_fill_text:
updateTextFill();
break;
case R.id.menu_toggle_list_view:
toggleListView();
break;
}
return true;
}
@Override
protected void onStart() {
super.onStart();
manager.setDownloadListener(downloadListener);
}
@Override
protected void onStop() {
super.onStop();
manager.setDownloadListener(null);
}
private DownloadManager.DownloadListener downloadListener = new DownloadManager.DownloadListener() {
@Override
public void onApkDownloaded(final LayoutDescription description) {
Log.d(TAG, "New apk with path: " + description.getApkPath());
container.post(new Runnable() {
public void run() {
loadLayout(description);
}
});
}
};
}
| false | true | private void loadLayout(LayoutDescription description) {
management.layoutDescription = description;
if (description.getMinVersion() < Build.VERSION.SDK_INT) {
Log.e(TAG, "invalid version of Android");
ErrorManager.show(getApplicationContext(), rootContainer, "This view requires Android version " + description.getMinVersion());
containerBorder.setVisibility(View.GONE);
return;
}
container.removeAllViews();
updateLayoutParams(management.rogerParams);
final int id = description.getResId(this);
if (id == 0) {
Log.e(TAG, "ID is 0. Not inflating.");
ErrorManager.show(getApplicationContext(), rootContainer, "Unable to load view");
containerBorder.setVisibility(View.GONE);
return;
}
Log.i(TAG, "getting a layout inflater...");
final LayoutInflater inflater = description.getApk(this).getLayoutInflater(getLayoutInflater());
Log.i(TAG, "inflating???");
try {
if (management.isListView) {
FrameLayout.LayoutParams params =
new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
ListView listView = new ListView(this);
ArrayList<String> items = new ArrayList<String>();
for (int i = 0; i < 100; i++) {
items.add("" + i);
}
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView != null) {
addTextFill(convertView);
return convertView;
} else {
View v = inflater.inflate(id, parent, false);
addTextFill(v);
return v;
}
}
});
container.addView(listView, params);
} else {
View v = inflater.inflate(id, container, false);
container.addView(v);
}
addTextFill();
containerBorder.setVisibility(View.VISIBLE);
} catch (InflateException ex) {
Throwable cause = ex;
while (cause.getCause() != null) {
cause = cause.getCause();
}
ErrorManager.show(getApplicationContext(), rootContainer, cause.getMessage());
}
}
| private void loadLayout(LayoutDescription description) {
management.layoutDescription = description;
if (description.getMinVersion() != 0 && description.getMinVersion() > Build.VERSION.SDK_INT) {
Log.e(TAG, "invalid version of Android");
ErrorManager.show(getApplicationContext(),
rootContainer, "This view requires Android version " + description.getMinVersion());
containerBorder.setVisibility(View.GONE);
return;
}
container.removeAllViews();
updateLayoutParams(management.rogerParams);
final int id = description.getResId(this);
if (id == 0) {
Log.e(TAG, "ID is 0. Not inflating.");
ErrorManager.show(getApplicationContext(), rootContainer, "Unable to load view");
containerBorder.setVisibility(View.GONE);
return;
}
Log.i(TAG, "getting a layout inflater...");
final LayoutInflater inflater = description.getApk(this).getLayoutInflater(getLayoutInflater());
Log.i(TAG, "inflating???");
try {
if (management.isListView) {
FrameLayout.LayoutParams params =
new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
ListView listView = new ListView(this);
ArrayList<String> items = new ArrayList<String>();
for (int i = 0; i < 100; i++) {
items.add("" + i);
}
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView != null) {
addTextFill(convertView);
return convertView;
} else {
View v = inflater.inflate(id, parent, false);
addTextFill(v);
return v;
}
}
});
container.addView(listView, params);
} else {
View v = inflater.inflate(id, container, false);
container.addView(v);
}
addTextFill();
containerBorder.setVisibility(View.VISIBLE);
} catch (InflateException ex) {
Throwable cause = ex;
while (cause.getCause() != null) {
cause = cause.getCause();
}
ErrorManager.show(getApplicationContext(), rootContainer, cause.getMessage());
}
}
|
diff --git a/src/share/classes/sun/misc/MIDletClassLoader.java b/src/share/classes/sun/misc/MIDletClassLoader.java
index 237bafe8..ec775e6b 100644
--- a/src/share/classes/sun/misc/MIDletClassLoader.java
+++ b/src/share/classes/sun/misc/MIDletClassLoader.java
@@ -1,289 +1,296 @@
/*
* @(#)MIDletClassLoader.java 1.11 06/10/10
*
* Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* 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 version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*
*/
/*
* @(#)MIDletClassLoader.java 1.5 03/07/09
*
* Class loader for midlets running on CDC/PP
*
* It loads from a single JAR file and deligates to other class loaders.
* It has a few of interesting properties:
* 1) it is careful, perhaps overly so, about not loading classes that
* are in system packages from the JAR file persumed to contain the MIDlet
* code.
* 2) it uses a MemberFilter to process classes for illegal field references.
* This is easiest to do after the constant pool is set up.
* 3) it remembers which classes have failed the above test and refuses to
* load them, even though the system thinks they're already loaded.
*
* It lets the underlying URLClassLoader do all the hard work.
*
*/
package sun.misc;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLClassLoader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.AccessController;
import java.security.AccessControlContext;
import java.security.PrivilegedAction;
public class MIDletClassLoader extends URLClassLoader {
URL myBase[];
String[]systemPkgs;
private MemberFilter memberChecker; /* to check for amputated members */
private PermissionCollection perms;
private HashSet badMidletClassnames = new HashSet();
private MIDPImplementationClassLoader implementationClassLoader;
private AccessControlContext ac = AccessController.getContext();
/*
* If the filter is disabled, all classes on the bootclasspath
* can be accessed from midlet.
*/
private boolean enableFilter;
private ClassLoader auxClassLoader;
public MIDletClassLoader(
URL base[],
String systemPkgs[],
PermissionCollection pc,
MemberFilter mf,
MIDPImplementationClassLoader parent,
boolean enableFilter,
ClassLoader auxClassLoader)
{
super(base, parent);
myBase = base;
this.systemPkgs = systemPkgs;
memberChecker = mf;
perms = pc;
implementationClassLoader = parent;
this.enableFilter = enableFilter;
this.auxClassLoader = auxClassLoader;
}
protected PermissionCollection getPermissions(CodeSource cs){
URL srcLocation = cs.getLocation();
for (int i=0; i<myBase.length; i++){
if (srcLocation.equals(myBase[i])){
return perms;
}
}
return super.getPermissions(cs);
}
/* Check if class belongs to restricted system packages. */
private boolean
packageCheck(String pkg) {
String forbidden[] = systemPkgs;
int fLength = forbidden.length;
/* First check the default list specified by MIDPConfig */
for (int i=0; i< fLength; i++){
if (pkg.startsWith(forbidden[i])){
return true;
}
}
/* Then Check with MIDPPkgChecker. The MIDPPkgChecker knows
* the restricted MIDP and JSR packages specified in their
* rom.conf files. */
return MIDPPkgChecker.checkPackage(pkg);
}
private Class
loadFromUrl(String classname) throws ClassNotFoundException
{
Class newClass;
try {
newClass = super.findClass(classname); // call URLClassLoader
}catch(Exception e){
/*DEBUG e.printStackTrace(); */
// didn't find it.
return null;
}
if (newClass == null )
return null;
/*
* Found the requested class. Make sure it's not from
* restricted system packages.
*/
int idx = classname.lastIndexOf('.');
if (idx != -1) {
String pkg = classname.substring(0, idx);
if (packageCheck(pkg)) {
throw new SecurityException("Prohibited package name: " + pkg);
}
}
/*
* Check member access to make sure the class doesn't
* access any hidden CDC APIs.
*/
try {
// memberChecker will throw an Error if it doesn't like
// the class.
if (enableFilter) {
memberChecker.checkMemberAccessValidity(newClass);
}
return newClass;
} catch (Error e){
// If this happens, act as if we cannot find the class.
// remember this class, too. If the MIDlet catches the
// Exception and tries again, we don't want findLoadedClass()
// to return it!!
badMidletClassnames.add(classname);
throw new ClassNotFoundException(e.getMessage());
}
}
public synchronized Class
loadClass(String classname, boolean resolve) throws ClassNotFoundException
{
Class resultClass;
+ Throwable err = null;
int i = classname.lastIndexOf('.');
if (i != -1) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPackageAccess(classname.substring(0, i));
}
}
classname = classname.intern();
if (badMidletClassnames.contains(classname)){
// the system thinks it successfully loaded this class.
// But the member checker does not think we should be able
// to use it. We threw an Exception before. Do it again.
throw new ClassNotFoundException(classname.concat(
" contains illegal member reference"));
}
resultClass = findLoadedClass(classname);
if (resultClass == null){
try {
resultClass = implementationClassLoader.loadClass(
classname, false, enableFilter);
} catch (ClassNotFoundException e) {
- resultClass = null;
} catch (NoClassDefFoundError e) {
- resultClass = null;
}
}
if (resultClass == null) {
try {
resultClass = loadFromUrl(classname);
} catch (ClassNotFoundException e) {
- resultClass = null;
+ err = e;
} catch (NoClassDefFoundError e) {
- resultClass = null;
+ err = e;
}
}
/*
* If MIDletClassLoader and the parents failed to
* load the class, try the auxClassLoader.
*/
if (resultClass == null && auxClassLoader != null) {
resultClass = auxClassLoader.loadClass(classname);
}
if (resultClass == null) {
- throw new ClassNotFoundException(classname);
+ if (err == null) {
+ throw new ClassNotFoundException(classname);
+ } else {
+ if (err instanceof ClassNotFoundException) {
+ throw (ClassNotFoundException)err;
+ } else {
+ throw (NoClassDefFoundError)err;
+ }
+ }
}
if (resolve) {
resolveClass(resultClass);
}
return resultClass;
}
public InputStream
getResourceAsStream(String name){
// prohibit reading .class as a resource
if (name.endsWith(".class")){
return null; // not allowed!
}
int i;
// Replace /./ with /
while ((i = name.indexOf("/./")) >= 0) {
name = name.substring(0, i) + name.substring(i + 2);
}
// Replace /segment/../ with /
i = 0;
int limit;
while ((i = name.indexOf("/../", i)) > 0) {
if ((limit = name.lastIndexOf('/', i - 1)) >= 0) {
name = name.substring(0, limit) + name.substring(i + 3);
i = 0;
} else {
i = i + 3;
}
}
// The JAR reader cannot find the resource if the name starts with
// a slash. So we remove the leading slash if one exists.
if (name.startsWith("/") || name.startsWith(File.separator)) {
name = name.substring(1);
}
final String n = name;
// do not delegate. We only use our own URLClassLoader.findResource to
// look in our own JAR file. That is always allowed.
// Nothing else is.
InputStream retval;
retval = (InputStream) AccessController.doPrivileged(
new PrivilegedAction(){
public Object run(){
URL url = findResource(n);
try {
return url != null ? url.openStream() : null;
} catch (IOException e) {
return null;
}
}
}, ac);
return retval;
}
}
| false | true | public synchronized Class
loadClass(String classname, boolean resolve) throws ClassNotFoundException
{
Class resultClass;
int i = classname.lastIndexOf('.');
if (i != -1) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPackageAccess(classname.substring(0, i));
}
}
classname = classname.intern();
if (badMidletClassnames.contains(classname)){
// the system thinks it successfully loaded this class.
// But the member checker does not think we should be able
// to use it. We threw an Exception before. Do it again.
throw new ClassNotFoundException(classname.concat(
" contains illegal member reference"));
}
resultClass = findLoadedClass(classname);
if (resultClass == null){
try {
resultClass = implementationClassLoader.loadClass(
classname, false, enableFilter);
} catch (ClassNotFoundException e) {
resultClass = null;
} catch (NoClassDefFoundError e) {
resultClass = null;
}
}
if (resultClass == null) {
try {
resultClass = loadFromUrl(classname);
} catch (ClassNotFoundException e) {
resultClass = null;
} catch (NoClassDefFoundError e) {
resultClass = null;
}
}
/*
* If MIDletClassLoader and the parents failed to
* load the class, try the auxClassLoader.
*/
if (resultClass == null && auxClassLoader != null) {
resultClass = auxClassLoader.loadClass(classname);
}
if (resultClass == null) {
throw new ClassNotFoundException(classname);
}
if (resolve) {
resolveClass(resultClass);
}
return resultClass;
}
| public synchronized Class
loadClass(String classname, boolean resolve) throws ClassNotFoundException
{
Class resultClass;
Throwable err = null;
int i = classname.lastIndexOf('.');
if (i != -1) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPackageAccess(classname.substring(0, i));
}
}
classname = classname.intern();
if (badMidletClassnames.contains(classname)){
// the system thinks it successfully loaded this class.
// But the member checker does not think we should be able
// to use it. We threw an Exception before. Do it again.
throw new ClassNotFoundException(classname.concat(
" contains illegal member reference"));
}
resultClass = findLoadedClass(classname);
if (resultClass == null){
try {
resultClass = implementationClassLoader.loadClass(
classname, false, enableFilter);
} catch (ClassNotFoundException e) {
} catch (NoClassDefFoundError e) {
}
}
if (resultClass == null) {
try {
resultClass = loadFromUrl(classname);
} catch (ClassNotFoundException e) {
err = e;
} catch (NoClassDefFoundError e) {
err = e;
}
}
/*
* If MIDletClassLoader and the parents failed to
* load the class, try the auxClassLoader.
*/
if (resultClass == null && auxClassLoader != null) {
resultClass = auxClassLoader.loadClass(classname);
}
if (resultClass == null) {
if (err == null) {
throw new ClassNotFoundException(classname);
} else {
if (err instanceof ClassNotFoundException) {
throw (ClassNotFoundException)err;
} else {
throw (NoClassDefFoundError)err;
}
}
}
if (resolve) {
resolveClass(resultClass);
}
return resultClass;
}
|
diff --git a/src/main/java/com/ghlh/strategy/backma10/BackMA10IntradayStrategy.java b/src/main/java/com/ghlh/strategy/backma10/BackMA10IntradayStrategy.java
index af1ae3b..e9a1118 100644
--- a/src/main/java/com/ghlh/strategy/backma10/BackMA10IntradayStrategy.java
+++ b/src/main/java/com/ghlh/strategy/backma10/BackMA10IntradayStrategy.java
@@ -1,97 +1,97 @@
package com.ghlh.strategy.backma10;
import java.util.Date;
import java.util.List;
import com.common.util.IDGenerator;
import com.ghlh.autotrade.EventRecorder;
import com.ghlh.autotrade.StockTradeIntradyMonitor;
import com.ghlh.autotrade.StockTradeIntradyUtil;
import com.ghlh.data.db.GhlhDAO;
import com.ghlh.data.db.StockdailyinfoDAO;
import com.ghlh.data.db.StockdailyinfoVO;
import com.ghlh.data.db.StocktradeDAO;
import com.ghlh.data.db.StocktradeVO;
import com.ghlh.stockquotes.StockQuotesBean;
import com.ghlh.strategy.AdditionInfoUtil;
import com.ghlh.strategy.MonitoringStrategy;
import com.ghlh.strategy.TradeConstants;
import com.ghlh.strategy.TradeUtil;
import com.ghlh.tradeway.SoftwareTrader;
import com.ghlh.util.MathUtil;
public class BackMA10IntradayStrategy implements MonitoringStrategy {
public void processSell(StockTradeIntradyMonitor monitor,
StockQuotesBean sqb) {
List possibleSellList = monitor.getPossibleSellList();
for (int i = 0; i < possibleSellList.size(); i++) {
StocktradeVO stocktradeVO = (StocktradeVO) possibleSellList.get(i);
if (sqb.getHighestPrice() >= stocktradeVO.getSellprice()) {
String message = TradeUtil.getConfirmedSellMessage(
stocktradeVO.getStockid(), stocktradeVO.getNumber(),
stocktradeVO.getSellprice());
EventRecorder.recordEvent(StockTradeIntradyUtil.class, message);
StocktradeDAO.updateStocktradeFinished(stocktradeVO.getId());
}
}
}
public void processBuy(StockTradeIntradyMonitor monitor, StockQuotesBean sqb) {
if (!Boolean
.parseBoolean(monitor.getMonitorstockVO().getOnmonitoring())) {
return;
}
List possibleSellList = monitor.getPossibleSellList();
if (possibleSellList.size() == 0) {
List previousDailyInfo = StockdailyinfoDAO.getPrevious9DaysInfo(sqb
.getStockId());
int days = previousDailyInfo.size();
double sumClosePrice = 0;
for (int i = 0; i < previousDailyInfo.size(); i++) {
StockdailyinfoVO dailyInfo = (StockdailyinfoVO) previousDailyInfo
.get(i);
- sumClosePrice += dailyInfo.getCloseprice();
+ sumClosePrice += dailyInfo.getYesterdaycloseprice();
}
double ma10Price = MathUtil
.formatDoubleWith2QuanJin((sumClosePrice + sqb
.getCurrentPrice()) / (days + 1));
if (sqb.getCurrentPrice() <= ma10Price) {
AdditionalInfoBean aib = (AdditionalInfoBean) AdditionInfoUtil
.parseAdditionalInfoBean(monitor.getMonitorstockVO()
.getAdditioninfo(),
BackMA10Constants.BACKMA10_STRATEGY_NAME);
int number = TradeUtil.getTradeNumber(aib.getTradeMoney(),
sqb.getCurrentPrice());
String message = TradeUtil.getConfirmedBuyMessage(monitor
.getMonitorstockVO().getStockid(), number, sqb
.getCurrentPrice());
EventRecorder.recordEvent(StockTradeIntradyUtil.class, message);
SoftwareTrader.getInstance().buyStock(sqb.getStockId(), number);
createBuyRecord(monitor, sqb, aib, number);
}
}
}
private void createBuyRecord(StockTradeIntradyMonitor monitor,
StockQuotesBean sqb, AdditionalInfoBean aib, int number) {
StocktradeVO stocktradeVO1 = new StocktradeVO();
stocktradeVO1.setId(IDGenerator.generateId("stocktrade"));
stocktradeVO1.setStockid(sqb.getStockId());
stocktradeVO1.setTradealgorithm(monitor.getMonitorstockVO()
.getTradealgorithm());
stocktradeVO1.setBuydate(new Date());
stocktradeVO1.setBuybaseprice(sqb.getCurrentPrice());
stocktradeVO1.setBuyprice(sqb.getCurrentPrice());
stocktradeVO1.setNumber(number);
double sellPrice = sqb.getCurrentPrice() * (1 + aib.getTargetZf());
sellPrice = MathUtil.formatDoubleWith2QuanShe(sellPrice);
stocktradeVO1.setSellprice(sellPrice);
stocktradeVO1.setCreatedtimestamp(new Date());
stocktradeVO1.setLastmodifiedtimestamp(new Date());
stocktradeVO1.setStatus(TradeConstants.STATUS_T_0_BUY);
GhlhDAO.create(stocktradeVO1);
}
}
| true | true | public void processBuy(StockTradeIntradyMonitor monitor, StockQuotesBean sqb) {
if (!Boolean
.parseBoolean(monitor.getMonitorstockVO().getOnmonitoring())) {
return;
}
List possibleSellList = monitor.getPossibleSellList();
if (possibleSellList.size() == 0) {
List previousDailyInfo = StockdailyinfoDAO.getPrevious9DaysInfo(sqb
.getStockId());
int days = previousDailyInfo.size();
double sumClosePrice = 0;
for (int i = 0; i < previousDailyInfo.size(); i++) {
StockdailyinfoVO dailyInfo = (StockdailyinfoVO) previousDailyInfo
.get(i);
sumClosePrice += dailyInfo.getCloseprice();
}
double ma10Price = MathUtil
.formatDoubleWith2QuanJin((sumClosePrice + sqb
.getCurrentPrice()) / (days + 1));
if (sqb.getCurrentPrice() <= ma10Price) {
AdditionalInfoBean aib = (AdditionalInfoBean) AdditionInfoUtil
.parseAdditionalInfoBean(monitor.getMonitorstockVO()
.getAdditioninfo(),
BackMA10Constants.BACKMA10_STRATEGY_NAME);
int number = TradeUtil.getTradeNumber(aib.getTradeMoney(),
sqb.getCurrentPrice());
String message = TradeUtil.getConfirmedBuyMessage(monitor
.getMonitorstockVO().getStockid(), number, sqb
.getCurrentPrice());
EventRecorder.recordEvent(StockTradeIntradyUtil.class, message);
SoftwareTrader.getInstance().buyStock(sqb.getStockId(), number);
createBuyRecord(monitor, sqb, aib, number);
}
}
}
| public void processBuy(StockTradeIntradyMonitor monitor, StockQuotesBean sqb) {
if (!Boolean
.parseBoolean(monitor.getMonitorstockVO().getOnmonitoring())) {
return;
}
List possibleSellList = monitor.getPossibleSellList();
if (possibleSellList.size() == 0) {
List previousDailyInfo = StockdailyinfoDAO.getPrevious9DaysInfo(sqb
.getStockId());
int days = previousDailyInfo.size();
double sumClosePrice = 0;
for (int i = 0; i < previousDailyInfo.size(); i++) {
StockdailyinfoVO dailyInfo = (StockdailyinfoVO) previousDailyInfo
.get(i);
sumClosePrice += dailyInfo.getYesterdaycloseprice();
}
double ma10Price = MathUtil
.formatDoubleWith2QuanJin((sumClosePrice + sqb
.getCurrentPrice()) / (days + 1));
if (sqb.getCurrentPrice() <= ma10Price) {
AdditionalInfoBean aib = (AdditionalInfoBean) AdditionInfoUtil
.parseAdditionalInfoBean(monitor.getMonitorstockVO()
.getAdditioninfo(),
BackMA10Constants.BACKMA10_STRATEGY_NAME);
int number = TradeUtil.getTradeNumber(aib.getTradeMoney(),
sqb.getCurrentPrice());
String message = TradeUtil.getConfirmedBuyMessage(monitor
.getMonitorstockVO().getStockid(), number, sqb
.getCurrentPrice());
EventRecorder.recordEvent(StockTradeIntradyUtil.class, message);
SoftwareTrader.getInstance().buyStock(sqb.getStockId(), number);
createBuyRecord(monitor, sqb, aib, number);
}
}
}
|
diff --git a/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/JavaHotCodeReplaceManager.java b/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/JavaHotCodeReplaceManager.java
index 10f8535c5..ce742c67e 100644
--- a/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/JavaHotCodeReplaceManager.java
+++ b/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/JavaHotCodeReplaceManager.java
@@ -1,452 +1,452 @@
package org.eclipse.jdt.internal.debug.core;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchListener;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.model.IDebugTarget;
import org.eclipse.debug.core.model.IStackFrame;
import org.eclipse.debug.core.model.IThread;
import org.eclipse.debug.internal.core.ListenerList;
import org.eclipse.jdt.debug.core.IJavaHotCodeReplaceListener;
import org.eclipse.jdt.debug.core.IJavaStackFrame;
import org.eclipse.jdt.debug.core.JDIDebugModel;
/**
* The hot code replace manager listens for changes to
* class files and notifies running debug targets of the changes.
* <p>
* Currently, replacing .jar files has no effect on running targets.
*/
public class JavaHotCodeReplaceManager implements IResourceChangeListener, ILaunchListener {
/**
* Singleton
*/
private static JavaHotCodeReplaceManager fgInstance= null;
/**
* The class file extension
*/
private static final String CLASS_FILE_EXTENSION= "class"; //$NON-NLS-1$
/**
* The list of <code>IJavaHotCodeReplaceListeners</code> which this hot code replace
* manager will notify about hot code replace attempts.
*/
private ListenerList fHotCodeReplaceListeners= new ListenerList(1);
/**
* The lists of hot swap targets which support HCR and those which don't
*/
private List fHotSwapTargets= new ArrayList(1);
private List fNoHotSwapTargets= new ArrayList(1);
/**
* Visitor for resource deltas.
*/
protected ChangedClassFilesVisitor fVisitor = new ChangedClassFilesVisitor();
/**
* Creates a new HCR manager
*/
public JavaHotCodeReplaceManager() {
fgInstance= this;
}
/**
* Returns the singleton HCR manager
*/
public static JavaHotCodeReplaceManager getDefault() {
return fgInstance;
}
/**
* Registers this HCR manager as a resource change listener. This method
* is called by the JDI debug model plugin on startup.
*/
public void startup() {
DebugPlugin.getDefault().getLaunchManager().addLaunchListener(this);
}
/**
* Deregisters this HCR manager as a resource change listener. Removes all hot
* code replace listeners. This method* is called by the JDI debug model plugin
* on shutdown.
*/
public void shutdown() {
DebugPlugin.getDefault().getLaunchManager().removeLaunchListener(this);
getWorkspace().removeResourceChangeListener(this);
fHotCodeReplaceListeners.removeAll();
clearHotSwapTargets();
}
/**
* Returns the workspace.
*/
protected IWorkspace getWorkspace() {
return ResourcesPlugin.getWorkspace();
}
/**
* Returns the launch manager.
*/
protected ILaunchManager getLaunchManager() {
return DebugPlugin.getDefault().getLaunchManager();
}
/**
* @see IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent)
*/
public void resourceChanged(IResourceChangeEvent event) {
final List resources= getChangedClassFiles(event.getDelta());
if (resources.isEmpty()) {
return;
}
final List hotSwapTargets= getHotSwapTargets();
final List noHotSwapTargets= getNoHotSwapTargets();
final List qualifiedNames= JDIDebugUtils.getQualifiedNames(resources);
if (!hotSwapTargets.isEmpty()) {
IWorkspaceRunnable wRunnable= new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) {
notify(hotSwapTargets, resources, qualifiedNames);
}
};
fork(wRunnable);
}
if (!noHotSwapTargets.isEmpty()) {
IWorkspaceRunnable wRunnable= new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) {
notifyFailedHCR(noHotSwapTargets, resources, qualifiedNames);
}
};
fork(wRunnable);
}
}
/**
* Notify the given targets that HCR failed for classes
* with the given fully qualified names.
*/
protected void notifyFailedHCR(List targets, List resources, List qualifiedNames) {
Iterator iter= targets.iterator();
while (iter.hasNext()) {
notifyFailedHCR((JDIDebugTarget) iter.next(), resources, qualifiedNames);
}
}
protected void notifyFailedHCR(JDIDebugTarget target, List resources, List qualifiedNames) {
if (!target.isTerminated() && !target.isDisconnected()) {
target.typesFailedReload(resources, qualifiedNames);
}
}
/**
* Returns the currently registered debug targets that support
* hot code replace.
*/
protected List getHotSwapTargets() {
return fHotSwapTargets;
}
/**
* Returns the currently registered debug targets that do
* not support hot code replace.
*/
protected List getNoHotSwapTargets() {
return fNoHotSwapTargets;
}
protected void clearHotSwapTargets() {
fHotSwapTargets= null;
fNoHotSwapTargets= null;
}
/**
* Notifies the targets of the changed types
*
* @param targets the targets to notify
* @param resources the resources which correspond to the changed classes
*/
private void notify(List targets, List resources, List qualifiedNames) {
MultiStatus ms= new MultiStatus(JDIDebugPlugin.getDefault().getDescriptor().getUniqueIdentifier(), DebugException.TARGET_REQUEST_FAILED, JDIDebugModelMessages.getString("JavaHotCodeReplaceManager.drop_to_frame_failed"), null); //$NON-NLS-1$
Iterator iter= targets.iterator();
while (iter.hasNext()) {
JDIDebugTarget target= (JDIDebugTarget) iter.next();
try {
if (target.isTerminated() || target.isDisconnected()) {
continue;
}
target.typesHaveChanged(resources, qualifiedNames);
try {
attemptDropToFrame(target, qualifiedNames);
} catch (DebugException de) {
ms.merge(de.getStatus());
}
fireHCRSucceeded();
} catch (DebugException de) {
// target update failed
JDIDebugPlugin.logError(de);
notifyFailedHCR(target, resources, qualifiedNames);
fireHCRFailed(de);
}
}
if (!ms.isOK()) {
JDIDebugPlugin.logError(new DebugException(ms));
}
}
/**
* Notifies listeners that a hot code replace attempt succeeded
*/
private void fireHCRSucceeded() {
Object[] listeners= fHotCodeReplaceListeners.getListeners();
for (int i=0; i<listeners.length; i++) {
((IJavaHotCodeReplaceListener)listeners[i]).hotCodeReplaceSucceeded();
}
}
/**
* Notifies listeners that a hot code replace attempt failed with the given exception
*/
private void fireHCRFailed(DebugException exception) {
Object[] listeners= fHotCodeReplaceListeners.getListeners();
for (int i=0; i<listeners.length; i++) {
((IJavaHotCodeReplaceListener)listeners[i]).hotCodeReplaceFailed(exception);
}
}
/**
* Looks for the deepest effected stack frame in the stack
* and forces a drop to frame. Does this for all of the active
* stack frames in the target.
*/
protected void attemptDropToFrame(JDIDebugTarget target, List replacedClassNames) throws DebugException {
- JDIThread[] threads= (JDIThread[])target.getThreads();
+ IThread[] threads= target.getThreads();
List dropFrames= new ArrayList(1);
int numThreads= threads.length;
for (int i = 0; i < numThreads; i++) {
JDIThread thread= (JDIThread) threads[i];
if (thread.isSuspended()) {
List frames= thread.computeStackFrames();
JDIStackFrame dropFrame= null;
for (int j= frames.size() - 1; j >= 0; j--) {
JDIStackFrame f= (JDIStackFrame) frames.get(j);
if (replacedClassNames.contains(f.getDeclaringTypeName())) {
dropFrame = f;
break;
}
}
if (dropFrame == null) {
// No frame to drop to in this thread
continue;
}
if (dropFrame.supportsDropToFrame()) {
dropFrames.add(dropFrame);
} else {
// if any thread that should drop does not support the drop,
// do not drop in any threads.
for (int j= 0; j < numThreads; j++) {
- notifyFailedDrop(threads[i].computeStackFrames(), replacedClassNames);
+ notifyFailedDrop(((JDIThread)threads[i]).computeStackFrames(), replacedClassNames);
}
throw new DebugException(new Status(IStatus.ERROR, JDIDebugModel.getPluginIdentifier(),
DebugException.NOT_SUPPORTED, JDIDebugModelMessages.getString("JDIStackFrame.Drop_to_frame_not_supported"), null)); //$NON-NLS-1$
}
}
}
// All threads that want to drop to frame are able. Proceed with the drop
Iterator iter= dropFrames.iterator();
IJavaStackFrame dropFrame= null;
while (iter.hasNext()) {
try {
dropFrame= ((IJavaStackFrame)iter.next());
dropFrame.dropToFrame();
} catch (DebugException de) {
notifyFailedDrop(((JDIThread)dropFrame.getThread()).computeStackFrames(), replacedClassNames);
}
}
}
private void notifyFailedDrop(List frames, List replacedClassNames) throws DebugException {
JDIStackFrame frame;
Iterator iter= frames.iterator();
while (iter.hasNext()) {
frame= (JDIStackFrame) iter.next();
if (replacedClassNames.contains(frame.getDeclaringTypeName())) {
frame.setOutOfSynch(true);
}
}
}
/**
* Returns the changed class files in the delta or <code>null</code> if none.
*/
protected List getChangedClassFiles(IResourceDelta delta) {
if (delta == null) {
return new ArrayList(0);
}
fVisitor.reset();
try {
delta.accept(fVisitor);
} catch (CoreException e) {
JDIDebugPlugin.logError(e);
return new ArrayList(0); // quiet failure
}
return fVisitor.getChangedClassFiles();
}
/**
* A visitor which collects changed class files.
*/
class ChangedClassFilesVisitor implements IResourceDeltaVisitor {
/**
* The collection of changed class files.
*/
protected List fFiles= null;
/**
* Answers whether children should be visited.
* <p>
* If the associated resource is a class file which
* has been changed, record it.
*/
public boolean visit(IResourceDelta delta) {
if (delta == null || 0 == (delta.getKind() & IResourceDelta.CHANGED)) {
return false;
}
IResource resource= delta.getResource();
if (resource != null) {
switch (resource.getType()) {
case IResource.FILE :
if (0 == (delta.getFlags() & IResourceDelta.CONTENT))
return false;
if (CLASS_FILE_EXTENSION.equals(resource.getFullPath().getFileExtension()))
fFiles.add(resource);
return false;
default :
return true;
}
}
return true;
}
/**
* Resets the file collection to empty
*/
public void reset() {
fFiles = new ArrayList();
}
/**
* Answers a collection of changed class files or <code>null</code>
*/
public List getChangedClassFiles() {
return fFiles;
}
}
/**
* Adds the given listener to the collection of hot code replace listeners.
* Listeners are notified when hot code replace attempts succeed or fail.
*/
public void addHotCodeReplaceListener(IJavaHotCodeReplaceListener listener) {
fHotCodeReplaceListeners.add(listener);
}
/**
* Removes the given listener from the collection of hot code replace listeners.
* Once a listener is removed, it will no longer be notified of hot code replace
* attempt successes or failures.
*/
public void removeHotCodeReplaceListener(IJavaHotCodeReplaceListener listener) {
fHotCodeReplaceListeners.remove(listener);
}
protected void fork(final IWorkspaceRunnable wRunnable) {
Runnable runnable= new Runnable() {
public void run() {
try {
getWorkspace().run(wRunnable, null);
} catch (CoreException ce) {
JDIDebugPlugin.logError(ce);
}
}
};
new Thread(runnable).start();
}
/**
* @see ILaunchListener#launchDeregistered(ILaunch)
*
* When a launch is deregistered, check if there are any
* other launches registered. If not, stop listening
* to resource changes.
*/
public void launchDeregistered(ILaunch launch) {
if (!(launch instanceof JDIDebugTarget)) {
return;
}
JDIDebugTarget target= (JDIDebugTarget) launch.getDebugTarget();
ILaunch[] launches= DebugPlugin.getDefault().getLaunchManager().getLaunches();
// Remove the target from its hot swap target cache.
if (!fHotSwapTargets.remove(target)) {
fNoHotSwapTargets.remove(target);
}
// If there are no more JDIDebugTargets, stop
// listening to resource changes.
for (int i= 0; i < launches.length; i++) {
if (launches[i] instanceof JDIDebugTarget) {
return;
}
}
// To get here, there must be no JDIDebugTargets
getWorkspace().removeResourceChangeListener(this);
}
/**
* @see ILaunchListener#launchRegistered(ILaunch)
*
* Begin listening for resource changes when a launch is
* registered.
*/
public void launchRegistered(ILaunch launch) {
IDebugTarget debugTarget= launch.getDebugTarget();
if (!(debugTarget instanceof JDIDebugTarget)) {
return;
}
JDIDebugTarget target= (JDIDebugTarget) debugTarget;
if (target.supportsHotCodeReplace()) {
fHotSwapTargets.add(target);
} else {
fNoHotSwapTargets.add(target);
}
getWorkspace().addResourceChangeListener(this);
}
}
| false | true | protected void attemptDropToFrame(JDIDebugTarget target, List replacedClassNames) throws DebugException {
JDIThread[] threads= (JDIThread[])target.getThreads();
List dropFrames= new ArrayList(1);
int numThreads= threads.length;
for (int i = 0; i < numThreads; i++) {
JDIThread thread= (JDIThread) threads[i];
if (thread.isSuspended()) {
List frames= thread.computeStackFrames();
JDIStackFrame dropFrame= null;
for (int j= frames.size() - 1; j >= 0; j--) {
JDIStackFrame f= (JDIStackFrame) frames.get(j);
if (replacedClassNames.contains(f.getDeclaringTypeName())) {
dropFrame = f;
break;
}
}
if (dropFrame == null) {
// No frame to drop to in this thread
continue;
}
if (dropFrame.supportsDropToFrame()) {
dropFrames.add(dropFrame);
} else {
// if any thread that should drop does not support the drop,
// do not drop in any threads.
for (int j= 0; j < numThreads; j++) {
notifyFailedDrop(threads[i].computeStackFrames(), replacedClassNames);
}
throw new DebugException(new Status(IStatus.ERROR, JDIDebugModel.getPluginIdentifier(),
DebugException.NOT_SUPPORTED, JDIDebugModelMessages.getString("JDIStackFrame.Drop_to_frame_not_supported"), null)); //$NON-NLS-1$
}
}
}
// All threads that want to drop to frame are able. Proceed with the drop
Iterator iter= dropFrames.iterator();
IJavaStackFrame dropFrame= null;
while (iter.hasNext()) {
try {
dropFrame= ((IJavaStackFrame)iter.next());
dropFrame.dropToFrame();
} catch (DebugException de) {
notifyFailedDrop(((JDIThread)dropFrame.getThread()).computeStackFrames(), replacedClassNames);
}
}
}
| protected void attemptDropToFrame(JDIDebugTarget target, List replacedClassNames) throws DebugException {
IThread[] threads= target.getThreads();
List dropFrames= new ArrayList(1);
int numThreads= threads.length;
for (int i = 0; i < numThreads; i++) {
JDIThread thread= (JDIThread) threads[i];
if (thread.isSuspended()) {
List frames= thread.computeStackFrames();
JDIStackFrame dropFrame= null;
for (int j= frames.size() - 1; j >= 0; j--) {
JDIStackFrame f= (JDIStackFrame) frames.get(j);
if (replacedClassNames.contains(f.getDeclaringTypeName())) {
dropFrame = f;
break;
}
}
if (dropFrame == null) {
// No frame to drop to in this thread
continue;
}
if (dropFrame.supportsDropToFrame()) {
dropFrames.add(dropFrame);
} else {
// if any thread that should drop does not support the drop,
// do not drop in any threads.
for (int j= 0; j < numThreads; j++) {
notifyFailedDrop(((JDIThread)threads[i]).computeStackFrames(), replacedClassNames);
}
throw new DebugException(new Status(IStatus.ERROR, JDIDebugModel.getPluginIdentifier(),
DebugException.NOT_SUPPORTED, JDIDebugModelMessages.getString("JDIStackFrame.Drop_to_frame_not_supported"), null)); //$NON-NLS-1$
}
}
}
// All threads that want to drop to frame are able. Proceed with the drop
Iterator iter= dropFrames.iterator();
IJavaStackFrame dropFrame= null;
while (iter.hasNext()) {
try {
dropFrame= ((IJavaStackFrame)iter.next());
dropFrame.dropToFrame();
} catch (DebugException de) {
notifyFailedDrop(((JDIThread)dropFrame.getThread()).computeStackFrames(), replacedClassNames);
}
}
}
|
diff --git a/BinarySearchTree.java b/BinarySearchTree.java
index 416a169..b7a546a 100644
--- a/BinarySearchTree.java
+++ b/BinarySearchTree.java
@@ -1,263 +1,263 @@
/**
* A generic binary search tree.
*
* This binary search tree class is the outer class to the real BST which is
* implemented internally with nodes. This is NOT a recursive definition of
* the BST (i.e. a BST does not have a BST as a child)
*
* @author Reese Moore
* @author Tyler Kahn
* @version 2011.10.10
*
* @param <K> The type of the key stored in the tree.
* @param <V> The type of the values stored in the tree.
*/
public class BinarySearchTree<K extends Comparable<K>, V> {
private BSTNode root;
/**
* Insert a new KV pair into the BST.
*
* @param key The key to insert.
* @param value The value to insert.
*/
public void insert(K key, V value)
{
// We may have to insert the first node into the tree.
if (root == null) {
root = new BSTNode(key, value);
return;
}
// In the general case this is a lot easier.
new BSTNode(key, value, root);
}
/**
* Find a value from the BST based on the key.
* @param key The key to search on.
* @return an ArrayList (ours, not JavaAPI) of values matching the key.
*/
public ArrayList<V> find(K key)
{
ArrayList<V> found = new ArrayList<V>();
if (root == null) { return found; }
BSTNode found_node = root.find(key);
while (found_node != null) {
found.add(found_node.getValue());
found_node = found_node.getRight().find(key);
}
return found;
}
/**
* Remove a value from the BST. This removes the first occurrence of the
* key to be found
* @param key The key to search on.
* @return The removed value.
*/
public V remove(K key)
{
// Find the node to remove, and it's parent
BSTNode parent = null;
BSTNode remove_node = root;
while (remove_node != null && !remove_node.getKey().equals(key)) {
parent = remove_node;
if (key.compareTo(remove_node.getKey()) < 0) {
remove_node = remove_node.getLeft();
} else {
- remove_node = remove_node.getLeft();
+ remove_node = remove_node.getRight();
}
}
if (remove_node == null) { return null; }
// No children.
if (remove_node.getLeft() == null && remove_node.getRight() == null) {
if (parent == null) {
root = null;
} else if (parent.getLeft() == remove_node) {
parent.setLeft(null);
} else {
parent.setRight(null);
}
return remove_node.getValue();
}
// One child.
if (remove_node.getLeft() == null) {
if (parent == null) {
root = remove_node.getRight();
} else if (parent.getLeft() == remove_node) {
parent.setLeft(remove_node.getRight());
} else {
parent.setRight(remove_node.getRight());
}
return remove_node.getValue();
} else if (remove_node.getRight() == null) {
if (parent == null) {
root = remove_node.getLeft();
} else if (parent.getLeft() == remove_node) {
parent.setLeft(remove_node.getLeft());
} else {
parent.setRight(remove_node.getLeft());
}
return remove_node.getValue();
}
// Both children, find in order predecessor.
BSTNode IOP_parent = remove_node;
BSTNode InOrderPred = remove_node.getLeft();
while (InOrderPred.getRight() != null) {
IOP_parent = InOrderPred;
InOrderPred = InOrderPred.getRight();
}
// Hoist the child (if any) of the IOP.
IOP_parent.setRight(InOrderPred.getLeft());
// Replace remove_node with replacement (IOP)
BSTNode replacement = new BSTNode(InOrderPred.getKey(), InOrderPred.getValue());
replacement.setLeft(remove_node.getLeft());
replacement.setRight(remove_node.getRight());
if (parent == null) {
root = replacement;
} else if (parent.getLeft() == remove_node) {
parent.setLeft(replacement);
} else {
parent.setRight(replacement);
}
return remove_node.getValue();
}
/**
* The internal nodes of the Binary Search Tree.
* This is where all of the work is done.
*
* @author Reese Moore
* @author Tyler Kahn
* @version 2011.10.09
*/
private class BSTNode {
private final K key;
private final V value;
private BSTNode left;
private BSTNode right;
/**
* Create a new Node for the tree.
*
* @param key The key to store in this node.
* @param value The value of this node.
*/
public BSTNode(K key, V value)
{
this.key = key;
this.value = value;
}
/**
* Create a new Node for the tree and insert it in the proper place,
* starting from the root node passed in.
*
* @param key The key to store in this node.
* @param value The value to store in this node.
* @param root The root node to start from for insertion.
*/
public BSTNode(K key, V value, BSTNode root)
{
this(key, value);
root.insert(this);
}
/**
* Insert a node below this.
* Either insert the new node as the proper child, or pass it on down
* the tree until it reaches the proper place.
* @param node The new node to insert.
*/
public void insert(BSTNode node)
{
if (node.getKey().compareTo(getKey()) < 0) {
if (getLeft() == null) {
setLeft(node);
} else {
getLeft().insert(node);
}
} else {
if (getRight() == null) {
setRight(node);
} else {
getRight().insert(node);
}
}
}
/**
* Retrieve a value from the BST.
* @param key The key to search on.
* @return The BSTNode containing a found value.
*/
public BSTNode find(K key)
{
if (key.equals(getKey())) { return this; }
if (key.compareTo(getKey()) < 0) {
return (left == null ? null : left.find(key));
} else {
return (right == null ? null : right.find(key));
}
}
/**
* Get the key of a given node
* @return The key from this node.
*/
public K getKey() {
return key;
}
/**
* Get the value of a given node
* @return The value from this node.
*/
public V getValue() {
return value;
}
/**
* Get the left child node of this node.
* @return the left child.
*/
public BSTNode getLeft() {
return left;
}
/**
* Set the left child node of this node.
* @param left The new left child node of this one.
*/
public void setLeft(BSTNode left) {
this.left = left;
}
/**
* Get the right child node of this node.
* @return the right child.
*/
public BSTNode getRight() {
return right;
}
/**
* Set the right child node of this node.
* @param right The new right child node of this one.
*/
public void setRight(BSTNode right) {
this.right = right;
}
}
}
| true | true | public V remove(K key)
{
// Find the node to remove, and it's parent
BSTNode parent = null;
BSTNode remove_node = root;
while (remove_node != null && !remove_node.getKey().equals(key)) {
parent = remove_node;
if (key.compareTo(remove_node.getKey()) < 0) {
remove_node = remove_node.getLeft();
} else {
remove_node = remove_node.getLeft();
}
}
if (remove_node == null) { return null; }
// No children.
if (remove_node.getLeft() == null && remove_node.getRight() == null) {
if (parent == null) {
root = null;
} else if (parent.getLeft() == remove_node) {
parent.setLeft(null);
} else {
parent.setRight(null);
}
return remove_node.getValue();
}
// One child.
if (remove_node.getLeft() == null) {
if (parent == null) {
root = remove_node.getRight();
} else if (parent.getLeft() == remove_node) {
parent.setLeft(remove_node.getRight());
} else {
parent.setRight(remove_node.getRight());
}
return remove_node.getValue();
} else if (remove_node.getRight() == null) {
if (parent == null) {
root = remove_node.getLeft();
} else if (parent.getLeft() == remove_node) {
parent.setLeft(remove_node.getLeft());
} else {
parent.setRight(remove_node.getLeft());
}
return remove_node.getValue();
}
// Both children, find in order predecessor.
BSTNode IOP_parent = remove_node;
BSTNode InOrderPred = remove_node.getLeft();
while (InOrderPred.getRight() != null) {
IOP_parent = InOrderPred;
InOrderPred = InOrderPred.getRight();
}
// Hoist the child (if any) of the IOP.
IOP_parent.setRight(InOrderPred.getLeft());
// Replace remove_node with replacement (IOP)
BSTNode replacement = new BSTNode(InOrderPred.getKey(), InOrderPred.getValue());
replacement.setLeft(remove_node.getLeft());
replacement.setRight(remove_node.getRight());
if (parent == null) {
root = replacement;
} else if (parent.getLeft() == remove_node) {
parent.setLeft(replacement);
} else {
parent.setRight(replacement);
}
return remove_node.getValue();
}
| public V remove(K key)
{
// Find the node to remove, and it's parent
BSTNode parent = null;
BSTNode remove_node = root;
while (remove_node != null && !remove_node.getKey().equals(key)) {
parent = remove_node;
if (key.compareTo(remove_node.getKey()) < 0) {
remove_node = remove_node.getLeft();
} else {
remove_node = remove_node.getRight();
}
}
if (remove_node == null) { return null; }
// No children.
if (remove_node.getLeft() == null && remove_node.getRight() == null) {
if (parent == null) {
root = null;
} else if (parent.getLeft() == remove_node) {
parent.setLeft(null);
} else {
parent.setRight(null);
}
return remove_node.getValue();
}
// One child.
if (remove_node.getLeft() == null) {
if (parent == null) {
root = remove_node.getRight();
} else if (parent.getLeft() == remove_node) {
parent.setLeft(remove_node.getRight());
} else {
parent.setRight(remove_node.getRight());
}
return remove_node.getValue();
} else if (remove_node.getRight() == null) {
if (parent == null) {
root = remove_node.getLeft();
} else if (parent.getLeft() == remove_node) {
parent.setLeft(remove_node.getLeft());
} else {
parent.setRight(remove_node.getLeft());
}
return remove_node.getValue();
}
// Both children, find in order predecessor.
BSTNode IOP_parent = remove_node;
BSTNode InOrderPred = remove_node.getLeft();
while (InOrderPred.getRight() != null) {
IOP_parent = InOrderPred;
InOrderPred = InOrderPred.getRight();
}
// Hoist the child (if any) of the IOP.
IOP_parent.setRight(InOrderPred.getLeft());
// Replace remove_node with replacement (IOP)
BSTNode replacement = new BSTNode(InOrderPred.getKey(), InOrderPred.getValue());
replacement.setLeft(remove_node.getLeft());
replacement.setRight(remove_node.getRight());
if (parent == null) {
root = replacement;
} else if (parent.getLeft() == remove_node) {
parent.setLeft(replacement);
} else {
parent.setRight(replacement);
}
return remove_node.getValue();
}
|
diff --git a/izpack-src/trunk/src/lib/com/izforge/izpack/util/OsConstraint.java b/izpack-src/trunk/src/lib/com/izforge/izpack/util/OsConstraint.java
index 7518276f..c5ff8f85 100644
--- a/izpack-src/trunk/src/lib/com/izforge/izpack/util/OsConstraint.java
+++ b/izpack-src/trunk/src/lib/com/izforge/izpack/util/OsConstraint.java
@@ -1,273 +1,273 @@
/*
* $Id$
* IzPack
* Copyright (C) 2002 Olexij Tkatchenko
*
* File : OsConstraint.java
* Description : A constraint on the OS to perform some action on.
* Author's email : [email protected]
* Website : http://www.izforge.com
*
* 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 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.izforge.izpack.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.n3.nanoxml.XMLElement;
/**
* Encapsulates OS constraints specified on creation time and allows
* to check them against the current OS.
*
* For example, this is used for <executable>s to check whether
* the executable is suitable for the current OS.
*
* @author Olexij Tkatchenko <[email protected]>
*/
public class OsConstraint implements java.io.Serializable
{
/** The OS family */
private String family;
/** OS name from java system properties */
private String name;
/** OS version from java system properties */
private String version;
/** OS architecture from java system properties */
private String arch;
/**
* Constructs a new instance. Please remember, MacOSX belongs to Unix family.
*
* @param family The OS family (unix, windows or mac).
* @param name The exact OS name.
* @param version The exact OS version (check property <code>os.version</code> for values).
* @param arch The machine architecture (check property <code>os.arch</code> for values).
*/
public OsConstraint(String family, String name, String version, String arch)
{
this.family = (family != null) ? family.toLowerCase() : null;
this.name = (name != null) ? name.toLowerCase() : null;
this.version = (version != null) ? version.toLowerCase() : null;
this.arch = (arch != null) ? arch.toLowerCase() : null;
}
/**
* Matches OS specification in this class against current system properties.
*
* @return Description of the Return Value
*/
public boolean matchCurrentSystem()
{
boolean match = true;
String osName = System.getProperty("os.name").toLowerCase();
if ((arch != null) && (arch.length() != 0))
{
match = System.getProperty("os.arch").toLowerCase().equals(arch);
}
if (match && (version != null) && (version.length() != 0))
{
match = System.getProperty("os.version").toLowerCase().equals(version);
}
if (match && (name != null) && (name.length() != 0))
{
match = osName.equals(name);
}
if (match && (family != null))
{
if (family.equals("windows"))
{
match = (osName.indexOf("windows") > -1);
}
else if (family.equals("mac"))
{
- match = ((osName.indexOf("mac") > -1) && !(osName.endsWith("x")));
+ match = ((osName.indexOf("mac") > -1));
}
else if (family.equals("unix"))
{
String pathSep = System.getProperty("path.separator");
match = ( osName.lastIndexOf("unix") > -1
|| osName.lastIndexOf("linux") > -1
|| osName.lastIndexOf("solaris") > -1
|| osName.lastIndexOf("sunos") > -1
|| osName.lastIndexOf("aix") > -1
|| osName.lastIndexOf("hpux") > -1
|| osName.lastIndexOf("hp-ux") > -1
|| osName.lastIndexOf("irix") > -1
|| osName.lastIndexOf("bsd") > -1
|| ((pathSep.equals(":") && (!osName.startsWith("mac") || osName.endsWith("x"))))
);
}
}
return match && ((family != null) ||
(name != null) ||
(version != null) ||
(arch != null));
}
/**
* Extract a list of OS constraints from given element.
*
* @param element parent XMLElement
* @return List of OsConstraint (or empty List if no constraints found)
*/
static public List getOsList(XMLElement element)
{
// get os info on this executable
ArrayList osList = new ArrayList();
Iterator osIterator = element.getChildrenNamed("os").iterator();
while (osIterator.hasNext())
{
XMLElement os = (XMLElement) osIterator.next();
osList.add (new OsConstraint (
os.getAttribute("family", null),
os.getAttribute("name", null),
os.getAttribute("version", null),
os.getAttribute("arch", null)
)
);
}
// backward compatibility: still support os attribute
String osattr = element.getAttribute ("os");
if ((osattr != null) && (osattr.length() > 0))
{
// add the "os" attribute as a family constraint
osList.add (new OsConstraint (osattr, null, null, null));
}
return osList;
}
/**
* Helper function: Scan a list of OsConstraints for a match.
*
* @param constraint_list List of OsConstraint to check
*
* @return true if one of the OsConstraints matched the current system or
* constraint_list is null (no constraints), false if none of the OsConstraints matched
*/
public static boolean oneMatchesCurrentSystem (List constraint_list)
{
if (constraint_list == null)
return true;
Iterator constraint_it = constraint_list.iterator ();
// no constraints at all - matches!
if (! constraint_it.hasNext ())
return true;
while (constraint_it.hasNext ())
{
OsConstraint osc = (OsConstraint)constraint_it.next();
Debug.trace ("checking if os constraints "+osc+" match current OS");
// check for match
if (osc.matchCurrentSystem ())
{
Debug.trace ("matched current OS.");
return true; // bail out on first match
}
}
Debug.trace ("no match with current OS!");
// no match found
return false;
}
/**
* Helper function: Check whether the given XMLElement is "suitable" for the
* current OS.
*
* @param el The XMLElement to check for OS constraints.
*
* @return true if there were no OS constraints or the constraints matched the current OS.
*
*/
public static boolean oneMatchesCurrentSystem (XMLElement el)
{
return oneMatchesCurrentSystem(getOsList(el));
}
public void setFamily(String f)
{
family = f.toLowerCase();
}
public String getFamily()
{
return family;
}
public void setName(String n)
{
name = n.toLowerCase();
}
public String getName()
{
return name;
}
public void setVersion(String v)
{
version = v.toLowerCase();
}
public String getVersion()
{
return version;
}
public void setArch(String a)
{
arch = a.toLowerCase();
}
public String getArch()
{
return arch;
}
public String toString()
{
StringBuffer retval = new StringBuffer();
retval.append("[Os ");
retval.append(" family "+family);
retval.append(" name "+name);
retval.append(" version "+version);
retval.append(" arch "+arch);
retval.append(" ]");
return retval.toString();
}
}
| true | true | public boolean matchCurrentSystem()
{
boolean match = true;
String osName = System.getProperty("os.name").toLowerCase();
if ((arch != null) && (arch.length() != 0))
{
match = System.getProperty("os.arch").toLowerCase().equals(arch);
}
if (match && (version != null) && (version.length() != 0))
{
match = System.getProperty("os.version").toLowerCase().equals(version);
}
if (match && (name != null) && (name.length() != 0))
{
match = osName.equals(name);
}
if (match && (family != null))
{
if (family.equals("windows"))
{
match = (osName.indexOf("windows") > -1);
}
else if (family.equals("mac"))
{
match = ((osName.indexOf("mac") > -1) && !(osName.endsWith("x")));
}
else if (family.equals("unix"))
{
String pathSep = System.getProperty("path.separator");
match = ( osName.lastIndexOf("unix") > -1
|| osName.lastIndexOf("linux") > -1
|| osName.lastIndexOf("solaris") > -1
|| osName.lastIndexOf("sunos") > -1
|| osName.lastIndexOf("aix") > -1
|| osName.lastIndexOf("hpux") > -1
|| osName.lastIndexOf("hp-ux") > -1
|| osName.lastIndexOf("irix") > -1
|| osName.lastIndexOf("bsd") > -1
|| ((pathSep.equals(":") && (!osName.startsWith("mac") || osName.endsWith("x"))))
);
}
}
return match && ((family != null) ||
(name != null) ||
(version != null) ||
(arch != null));
}
| public boolean matchCurrentSystem()
{
boolean match = true;
String osName = System.getProperty("os.name").toLowerCase();
if ((arch != null) && (arch.length() != 0))
{
match = System.getProperty("os.arch").toLowerCase().equals(arch);
}
if (match && (version != null) && (version.length() != 0))
{
match = System.getProperty("os.version").toLowerCase().equals(version);
}
if (match && (name != null) && (name.length() != 0))
{
match = osName.equals(name);
}
if (match && (family != null))
{
if (family.equals("windows"))
{
match = (osName.indexOf("windows") > -1);
}
else if (family.equals("mac"))
{
match = ((osName.indexOf("mac") > -1));
}
else if (family.equals("unix"))
{
String pathSep = System.getProperty("path.separator");
match = ( osName.lastIndexOf("unix") > -1
|| osName.lastIndexOf("linux") > -1
|| osName.lastIndexOf("solaris") > -1
|| osName.lastIndexOf("sunos") > -1
|| osName.lastIndexOf("aix") > -1
|| osName.lastIndexOf("hpux") > -1
|| osName.lastIndexOf("hp-ux") > -1
|| osName.lastIndexOf("irix") > -1
|| osName.lastIndexOf("bsd") > -1
|| ((pathSep.equals(":") && (!osName.startsWith("mac") || osName.endsWith("x"))))
);
}
}
return match && ((family != null) ||
(name != null) ||
(version != null) ||
(arch != null));
}
|
diff --git a/framework/src/play/Logger.java b/framework/src/play/Logger.java
index 3c17c910..83632101 100644
--- a/framework/src/play/Logger.java
+++ b/framework/src/play/Logger.java
@@ -1,697 +1,697 @@
package play;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.Priority;
import org.apache.log4j.PropertyConfigurator;
import play.exceptions.PlayException;
/**
* Main logger of the application.
* Free to use from the application code.
*/
public class Logger {
/**
* Will force use of java.util.logging (default to try log4j first).
*/
public static boolean forceJuli = false;
/**
* Will redirect all log from java.util.logging to log4j.
*/
public static boolean redirectJuli = false;
/**
* Will record and display the caller method.
*/
public static boolean recordCaller = false;
/**
* The application logger (play).
*/
public static org.apache.log4j.Logger log4j;
/**
* When using java.util.logging.
*/
public static java.util.logging.Logger juli = java.util.logging.Logger.getLogger("play");
/**
* true if logger is configured manually (log4j-config file supplied by application)
*/
public static boolean configuredManually = false;
/**
* Try to init stuff.
*/
public static void init() {
String log4jPath = Play.configuration.getProperty("application.log.path", "/log4j.xml");
URL log4jConf = Logger.class.getResource(log4jPath);
if (log4jConf == null) { // try again with the .properties
log4jPath = Play.configuration.getProperty("application.log.path", "/log4j.properties");
log4jConf = Logger.class.getResource(log4jPath);
}
if (log4jConf == null) {
Properties shutUp = new Properties();
shutUp.setProperty("log4j.rootLogger", "OFF");
PropertyConfigurator.configure(shutUp);
} else if (Logger.log4j == null) {
if(log4jConf.getFile().indexOf(Play.applicationPath.getAbsolutePath()) == 0 ) {
// The log4j configuration file is located somewhere in the application folder,
// so it's probably a custom configuration file
configuredManually = true;
}
PropertyConfigurator.configure(log4jConf);
Logger.log4j = org.apache.log4j.Logger.getLogger("play");
// In test mode, append logs to test-result/application.log
if (Play.runningInTestMode()) {
org.apache.log4j.Logger rootLogger = org.apache.log4j.Logger.getRootLogger();
try {
if (!Play.getFile("test-result").exists()) {
Play.getFile("test-result").mkdir();
}
Appender testLog = new FileAppender(new PatternLayout("%d{DATE} %-5p ~ %m%n"), Play.getFile("test-result/application.log").getAbsolutePath(), false);
rootLogger.addAppender(testLog);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* Force logger to a new level.
* @param level TRACE,DEBUG,INFO,WARN,ERROR,FATAL
*/
public static void setUp(String level) {
if (forceJuli || log4j == null) {
Logger.juli.setLevel(toJuliLevel(level));
} else {
Logger.log4j.setLevel(org.apache.log4j.Level.toLevel(level));
if (redirectJuli) {
java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger("");
for (Handler handler : rootLogger.getHandlers()) {
rootLogger.removeHandler(handler);
}
Handler activeHandler = new JuliToLog4jHandler();
java.util.logging.Level juliLevel = toJuliLevel(level);
activeHandler.setLevel(juliLevel);
rootLogger.addHandler(activeHandler);
rootLogger.setLevel(juliLevel);
}
}
}
/**
* Utility method that translayte log4j levels to java.util.logging levels.
*/
static java.util.logging.Level toJuliLevel(String level) {
java.util.logging.Level juliLevel = java.util.logging.Level.INFO;
if (level.equals("ERROR") || level.equals("FATAL")) {
juliLevel = java.util.logging.Level.SEVERE;
}
if (level.equals("WARN")) {
juliLevel = java.util.logging.Level.WARNING;
}
if (level.equals("DEBUG")) {
juliLevel = java.util.logging.Level.FINE;
}
if (level.equals("TRACE")) {
juliLevel = java.util.logging.Level.FINEST;
}
if (level.equals("ALL")) {
juliLevel = java.util.logging.Level.ALL;
}
if (level.equals("OFF")) {
juliLevel = java.util.logging.Level.OFF;
}
return juliLevel;
}
/**
* @return true if log4j.debug / jul.fine logging is enabled
*/
public static boolean isDebugEnabled() {
if (forceJuli || log4j == null) {
return juli.isLoggable(java.util.logging.Level.FINE);
} else {
return log4j.isDebugEnabled();
}
}
/**
* @return true if log4j.trace / jul.finest logging is enabled
*/
public static boolean isTraceEnabled() {
if (forceJuli || log4j == null) {
return juli.isLoggable(java.util.logging.Level.FINEST);
} else {
return log4j.isTraceEnabled();
}
}
/**
*
* @param level string representation of Logging-levels as used in log4j
* @return true if specified logging-level is enabled
*/
public static boolean isEnabledFor(String level) {
//go from level-string to log4j-level-object
org.apache.log4j.Level log4jLevel = org.apache.log4j.Level.toLevel(level);
if (forceJuli || log4j == null) {
//must translate from log4j-level to jul-level
java.util.logging.Level julLevel = toJuliLevel(log4jLevel.toString());
//check level against jul
return juli.isLoggable(julLevel);
} else {
//check level against log4j
return log4j.isEnabledFor(log4jLevel);
}
}
/**
* Log with TRACE level
* @param message The message pattern
* @param args Pattern arguments
*/
public static void trace(String message, Object... args) {
if (forceJuli || log4j == null) {
try {
juli.finest(format(message, args));
} catch (Throwable ex) {
juli.log(Level.SEVERE, "Oops. Error in Logger !", ex);
}
} else {
try {
if (recordCaller) {
org.apache.log4j.Logger.getLogger(getCallerClassName()).trace(format(message, args));
} else {
log4j.trace(format(message, args));
}
} catch (Throwable ex) {
log4j.error("Oops. Error in Logger !", ex);
}
}
}
/**
* Log with DEBUG level
* @param message The message pattern
* @param args Pattern arguments
*/
public static void debug(String message, Object... args) {
if (forceJuli || log4j == null) {
try {
juli.fine(format(message, args));
} catch (Throwable ex) {
juli.log(Level.SEVERE, "Oops. Error in Logger !", ex);
}
} else {
try {
if (recordCaller) {
org.apache.log4j.Logger.getLogger(getCallerClassName()).debug(format(message, args));
} else {
log4j.debug(format(message, args));
}
} catch (Throwable ex) {
log4j.error("Oops. Error in Logger !", ex);
}
}
}
/**
* Log with DEBUG level
* @param e the exception to log
* @param message The message pattern
* @param args Pattern arguments
*/
public static void debug(Throwable e, String message, Object... args) {
if (forceJuli || log4j == null) {
try {
if (!niceThrowable(org.apache.log4j.Level.DEBUG, e, message, args)) {
juli.log(Level.CONFIG, format(message, args), e);
}
} catch (Throwable ex) {
juli.log(Level.SEVERE, "Oops. Error in Logger !", ex);
}
} else {
try {
if (!niceThrowable(org.apache.log4j.Level.DEBUG, e, message, args)) {
if (recordCaller) {
org.apache.log4j.Logger.getLogger(getCallerClassName()).debug(format(message, args), e);
} else {
log4j.debug(format(message, args), e);
}
}
} catch (Throwable ex) {
log4j.error("Oops. Error in Logger !", ex);
}
}
}
/**
* Log with INFO level
* @param message The message pattern
* @param args Pattern arguments
*/
public static void info(String message, Object... args) {
if (forceJuli || log4j == null) {
try {
juli.info(format(message, args));
} catch (Throwable ex) {
juli.log(Level.SEVERE, "Oops. Error in Logger !", ex);
}
} else {
try {
if (recordCaller) {
// TODO: It is expensive to extract caller-info
// we should only do it if we know the message is being logged (level)
org.apache.log4j.Logger.getLogger(getCallerClassName()).info(format(message, args));
} else {
log4j.info(format(message, args));
}
} catch (Throwable ex) {
log4j.error("Oops. Error in Logger !", ex);
}
}
}
/**
* Log with INFO level
* @param e the exception to log
* @param message The message pattern
* @param args Pattern arguments
*/
public static void info(Throwable e, String message, Object... args) {
if (forceJuli || log4j == null) {
try {
if (!niceThrowable(org.apache.log4j.Level.INFO, e, message, args)) {
juli.log(Level.INFO, format(message, args), e);
}
} catch (Throwable ex) {
juli.log(Level.SEVERE, "Oops. Error in Logger !", ex);
}
} else {
try {
if (!niceThrowable(org.apache.log4j.Level.INFO, e, message, args)) {
if (recordCaller) {
org.apache.log4j.Logger.getLogger(getCallerClassName()).info(format(message, args), e);
} else {
log4j.info(format(message, args), e);
}
}
} catch (Throwable ex) {
log4j.error("Oops. Error in Logger !", ex);
}
}
}
/**
* Log with WARN level
* @param message The message pattern
* @param args Pattern arguments
*/
public static void warn(String message, Object... args) {
if (forceJuli || log4j == null) {
try {
juli.warning(format(message, args));
} catch (Throwable ex) {
juli.log(Level.SEVERE, "Oops. Error in Logger !", ex);
}
} else {
try {
if (recordCaller) {
org.apache.log4j.Logger.getLogger(getCallerClassName()).warn(format(message, args));
} else {
log4j.warn(format(message, args));
}
} catch (Throwable ex) {
log4j.error("Oops. Error in Logger !", ex);
}
}
}
/**
* Log with WARN level
* @param e the exception to log
* @param message The message pattern
* @param args Pattern arguments
*/
public static void warn(Throwable e, String message, Object... args) {
if (forceJuli || log4j == null) {
try {
if (!niceThrowable(org.apache.log4j.Level.WARN, e, message, args)) {
juli.log(Level.WARNING, format(message, args), e);
}
} catch (Throwable ex) {
juli.log(Level.SEVERE, "Oops. Error in Logger !", ex);
}
} else {
try {
if (!niceThrowable(org.apache.log4j.Level.WARN, e, message, args)) {
if (recordCaller) {
org.apache.log4j.Logger.getLogger(getCallerClassName()).warn(format(message, args), e);
} else {
log4j.warn(format(message, args), e);
}
}
} catch (Throwable ex) {
log4j.error("Oops. Error in Logger !", ex);
}
}
}
/**
* Log with ERROR level
* @param message The message pattern
* @param args Pattern arguments
*/
public static void error(String message, Object... args) {
if (forceJuli || log4j == null) {
try {
juli.severe(format(message, args));
} catch (Throwable ex) {
juli.log(Level.SEVERE, "Oops. Error in Logger !", ex);
}
} else {
try {
if (recordCaller) {
org.apache.log4j.Logger.getLogger(getCallerClassName()).error(format(message, args));
} else {
log4j.error(format(message, args));
}
} catch (Throwable ex) {
log4j.error("Oops. Error in Logger !", ex);
}
}
}
/**
* Log with ERROR level
* @param e the exception to log
* @param message The message pattern
* @param args Pattern arguments
*/
public static void error(Throwable e, String message, Object... args) {
if (forceJuli || log4j == null) {
try {
if (!niceThrowable(org.apache.log4j.Level.ERROR, e, message, args)) {
juli.log(Level.SEVERE, format(message, args), e);
}
} catch (Throwable ex) {
juli.log(Level.SEVERE, "Oops. Error in Logger !", ex);
}
} else {
try {
if (!niceThrowable(org.apache.log4j.Level.ERROR, e, message, args)) {
if (recordCaller) {
org.apache.log4j.Logger.getLogger(getCallerClassName()).error(format(message, args), e);
} else {
log4j.error(format(message, args), e);
}
}
} catch (Throwable ex) {
log4j.error("Oops. Error in Logger !", ex);
}
}
}
/**
* Log with FATAL level
* @param message The message pattern
* @param args Pattern arguments
*/
public static void fatal(String message, Object... args) {
if (forceJuli || log4j == null) {
try {
juli.severe(format(message, args));
} catch (Throwable ex) {
juli.log(Level.SEVERE, "Oops. Error in Logger !", ex);
}
} else {
try {
if (recordCaller) {
org.apache.log4j.Logger.getLogger(getCallerClassName()).fatal(format(message, args));
} else {
log4j.fatal(format(message, args));
}
} catch (Throwable ex) {
log4j.error("Oops. Error in Logger !", ex);
}
}
}
/**
* Log with FATAL level
* @param e the exception to log
* @param message The message pattern
* @param args Pattern arguments
*/
public static void fatal(Throwable e, String message, Object... args) {
if (forceJuli || log4j == null) {
try {
if (!niceThrowable(org.apache.log4j.Level.FATAL, e, message, args)) {
juli.log(Level.SEVERE, format(message, args), e);
}
} catch (Throwable ex) {
juli.log(Level.SEVERE, "Oops. Error in Logger !", ex);
}
} else {
try {
if (!niceThrowable(org.apache.log4j.Level.FATAL, e, message, args)) {
if (recordCaller) {
org.apache.log4j.Logger.getLogger(getCallerClassName()).fatal(format(message, args), e);
} else {
log4j.fatal(format(message, args), e);
}
}
} catch (Throwable ex) {
log4j.error("Oops. Error in Logger !", ex);
}
}
}
/**
* If e is a PlayException -> a very clean report
*/
static boolean niceThrowable(org.apache.log4j.Level level, Throwable e, String message, Object... args) {
if (e instanceof Exception) {
Throwable toClean = e;
for (int i = 0; i < 5; i++) {
// Clean stack trace
List<StackTraceElement> cleanTrace = new ArrayList<StackTraceElement>();
for (StackTraceElement se : toClean.getStackTrace()) {
if (se.getClassName().startsWith("play.server.PlayHandler$NettyInvocation")) {
cleanTrace.add(new StackTraceElement("Invocation", "HTTP Request", "Play!", -1));
break;
}
if (se.getClassName().startsWith("play.server.PlayHandler$SslNettyInvocation")) {
cleanTrace.add(new StackTraceElement("Invocation", "HTTP Request", "Play!", -1));
break;
}
if (se.getClassName().startsWith("play.jobs.Job") && se.getMethodName().equals("run")) {
cleanTrace.add(new StackTraceElement("Invocation", "Job", "Play!", -1));
break;
}
if (se.getClassName().startsWith("play.server.PlayHandler") && se.getMethodName().equals("messageReceived")) {
cleanTrace.add(new StackTraceElement("Invocation", "Message Received", "Play!", -1));
break;
}
if (se.getClassName().startsWith("sun.reflect.")) {
continue; // not very interesting
}
if (se.getClassName().startsWith("java.lang.reflect.")) {
continue; // not very interesting
}
if (se.getClassName().startsWith("com.mchange.v2.c3p0.")) {
continue; // not very interesting
}
if (se.getClassName().startsWith("scala.tools.")) {
continue; // not very interesting
}
if (se.getClassName().startsWith("scala.collection.")) {
continue; // not very interesting
}
cleanTrace.add(se);
}
toClean.setStackTrace(cleanTrace.toArray(new StackTraceElement[cleanTrace.size()]));
toClean = toClean.getCause();
if (toClean == null) {
break;
}
}
StringWriter sw = new StringWriter();
// Better format for Play exceptions
if (e instanceof PlayException) {
PlayException playException = (PlayException) e;
PrintWriter errorOut = new PrintWriter(sw);
errorOut.println("");
errorOut.println("");
errorOut.println("@" + playException.getId());
errorOut.println(format(message, args));
errorOut.println("");
if (playException.isSourceAvailable()) {
errorOut.println(playException.getErrorTitle() + " (In " + playException.getSourceFile() + " around line " + playException.getLineNumber() + ")");
} else {
errorOut.println(playException.getErrorTitle());
}
errorOut.println(playException.getErrorDescription().replaceAll("</?\\w+/?>", "").replace("\n", " "));
} else {
sw.append(format(message, args));
}
try {
if (forceJuli || log4j == null) {
juli.log(toJuliLevel(level.toString()), sw.toString(), e);
} else if (recordCaller) {
org.apache.log4j.Logger.getLogger(getCallerClassName(5)).log(level, sw.toString(), null);
} else {
- log4j.log(level, sw.toString(), null);
+ log4j.log(level, sw.toString(), e);
}
}
catch (Exception e1) {
log4j.error("Oops. Error in Logger !", e1);
}
return true;
}
return false;
}
/**
* Try to format messages using java Formatter.
* Fall back to the plain message if error.
*/
static String format(String msg, Object... args) {
try {
if (args != null && args.length > 0) {
return String.format(msg, args);
}
return msg;
} catch (Exception e) {
return msg;
}
}
/**
* Info about the logger caller
*/
static class CallInfo {
public String className;
public String methodName;
public CallInfo() {
}
public CallInfo(String className, String methodName) {
this.className = className;
this.methodName = methodName;
}
}
/**
* @return the className of the class actually logging the message
*/
static String getCallerClassName() {
final int level = 4;
return getCallerClassName(level);
}
/**
* @return the className of the class actually logging the message
*/
static String getCallerClassName(final int level) {
CallInfo ci = getCallerInformations(level);
return ci.className;
}
/**
* Examine stack trace to get caller
* @param level method stack depth
* @return who called the logger
*/
static CallInfo getCallerInformations(int level) {
StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
StackTraceElement caller = callStack[level];
return new CallInfo(caller.getClassName(), caller.getMethodName());
}
/**
* juli handler that Redirect to log4j
*/
public static class JuliToLog4jHandler extends Handler {
public void publish(LogRecord record) {
org.apache.log4j.Logger log4j = getTargetLogger(record.getLoggerName());
Priority priority = toLog4j(record.getLevel());
log4j.log(priority, toLog4jMessage(record), record.getThrown());
}
static org.apache.log4j.Logger getTargetLogger(String loggerName) {
return org.apache.log4j.Logger.getLogger(loggerName);
}
public static org.apache.log4j.Logger getTargetLogger(Class<?> clazz) {
return getTargetLogger(clazz.getName());
}
private String toLog4jMessage(LogRecord record) {
String message = record.getMessage();
// Format message
try {
Object parameters[] = record.getParameters();
if (parameters != null && parameters.length != 0) {
// Check for the first few parameters ?
if (message.indexOf("{0}") >= 0
|| message.indexOf("{1}") >= 0
|| message.indexOf("{2}") >= 0
|| message.indexOf("{3}") >= 0) {
message = MessageFormat.format(message, parameters);
}
}
} catch (Exception ex) {
// ignore Exception
}
return message;
}
private org.apache.log4j.Level toLog4j(java.util.logging.Level level) {
if (java.util.logging.Level.SEVERE == level) {
return org.apache.log4j.Level.ERROR;
} else if (java.util.logging.Level.WARNING == level) {
return org.apache.log4j.Level.WARN;
} else if (java.util.logging.Level.INFO == level) {
return org.apache.log4j.Level.INFO;
} else if (java.util.logging.Level.OFF == level) {
return org.apache.log4j.Level.TRACE;
}
return org.apache.log4j.Level.TRACE;
}
@Override
public void flush() {
// nothing to do
}
@Override
public void close() {
// nothing to do
}
}
}
| true | true | static boolean niceThrowable(org.apache.log4j.Level level, Throwable e, String message, Object... args) {
if (e instanceof Exception) {
Throwable toClean = e;
for (int i = 0; i < 5; i++) {
// Clean stack trace
List<StackTraceElement> cleanTrace = new ArrayList<StackTraceElement>();
for (StackTraceElement se : toClean.getStackTrace()) {
if (se.getClassName().startsWith("play.server.PlayHandler$NettyInvocation")) {
cleanTrace.add(new StackTraceElement("Invocation", "HTTP Request", "Play!", -1));
break;
}
if (se.getClassName().startsWith("play.server.PlayHandler$SslNettyInvocation")) {
cleanTrace.add(new StackTraceElement("Invocation", "HTTP Request", "Play!", -1));
break;
}
if (se.getClassName().startsWith("play.jobs.Job") && se.getMethodName().equals("run")) {
cleanTrace.add(new StackTraceElement("Invocation", "Job", "Play!", -1));
break;
}
if (se.getClassName().startsWith("play.server.PlayHandler") && se.getMethodName().equals("messageReceived")) {
cleanTrace.add(new StackTraceElement("Invocation", "Message Received", "Play!", -1));
break;
}
if (se.getClassName().startsWith("sun.reflect.")) {
continue; // not very interesting
}
if (se.getClassName().startsWith("java.lang.reflect.")) {
continue; // not very interesting
}
if (se.getClassName().startsWith("com.mchange.v2.c3p0.")) {
continue; // not very interesting
}
if (se.getClassName().startsWith("scala.tools.")) {
continue; // not very interesting
}
if (se.getClassName().startsWith("scala.collection.")) {
continue; // not very interesting
}
cleanTrace.add(se);
}
toClean.setStackTrace(cleanTrace.toArray(new StackTraceElement[cleanTrace.size()]));
toClean = toClean.getCause();
if (toClean == null) {
break;
}
}
StringWriter sw = new StringWriter();
// Better format for Play exceptions
if (e instanceof PlayException) {
PlayException playException = (PlayException) e;
PrintWriter errorOut = new PrintWriter(sw);
errorOut.println("");
errorOut.println("");
errorOut.println("@" + playException.getId());
errorOut.println(format(message, args));
errorOut.println("");
if (playException.isSourceAvailable()) {
errorOut.println(playException.getErrorTitle() + " (In " + playException.getSourceFile() + " around line " + playException.getLineNumber() + ")");
} else {
errorOut.println(playException.getErrorTitle());
}
errorOut.println(playException.getErrorDescription().replaceAll("</?\\w+/?>", "").replace("\n", " "));
} else {
sw.append(format(message, args));
}
try {
if (forceJuli || log4j == null) {
juli.log(toJuliLevel(level.toString()), sw.toString(), e);
} else if (recordCaller) {
org.apache.log4j.Logger.getLogger(getCallerClassName(5)).log(level, sw.toString(), null);
} else {
log4j.log(level, sw.toString(), null);
}
}
catch (Exception e1) {
log4j.error("Oops. Error in Logger !", e1);
}
return true;
}
return false;
}
| static boolean niceThrowable(org.apache.log4j.Level level, Throwable e, String message, Object... args) {
if (e instanceof Exception) {
Throwable toClean = e;
for (int i = 0; i < 5; i++) {
// Clean stack trace
List<StackTraceElement> cleanTrace = new ArrayList<StackTraceElement>();
for (StackTraceElement se : toClean.getStackTrace()) {
if (se.getClassName().startsWith("play.server.PlayHandler$NettyInvocation")) {
cleanTrace.add(new StackTraceElement("Invocation", "HTTP Request", "Play!", -1));
break;
}
if (se.getClassName().startsWith("play.server.PlayHandler$SslNettyInvocation")) {
cleanTrace.add(new StackTraceElement("Invocation", "HTTP Request", "Play!", -1));
break;
}
if (se.getClassName().startsWith("play.jobs.Job") && se.getMethodName().equals("run")) {
cleanTrace.add(new StackTraceElement("Invocation", "Job", "Play!", -1));
break;
}
if (se.getClassName().startsWith("play.server.PlayHandler") && se.getMethodName().equals("messageReceived")) {
cleanTrace.add(new StackTraceElement("Invocation", "Message Received", "Play!", -1));
break;
}
if (se.getClassName().startsWith("sun.reflect.")) {
continue; // not very interesting
}
if (se.getClassName().startsWith("java.lang.reflect.")) {
continue; // not very interesting
}
if (se.getClassName().startsWith("com.mchange.v2.c3p0.")) {
continue; // not very interesting
}
if (se.getClassName().startsWith("scala.tools.")) {
continue; // not very interesting
}
if (se.getClassName().startsWith("scala.collection.")) {
continue; // not very interesting
}
cleanTrace.add(se);
}
toClean.setStackTrace(cleanTrace.toArray(new StackTraceElement[cleanTrace.size()]));
toClean = toClean.getCause();
if (toClean == null) {
break;
}
}
StringWriter sw = new StringWriter();
// Better format for Play exceptions
if (e instanceof PlayException) {
PlayException playException = (PlayException) e;
PrintWriter errorOut = new PrintWriter(sw);
errorOut.println("");
errorOut.println("");
errorOut.println("@" + playException.getId());
errorOut.println(format(message, args));
errorOut.println("");
if (playException.isSourceAvailable()) {
errorOut.println(playException.getErrorTitle() + " (In " + playException.getSourceFile() + " around line " + playException.getLineNumber() + ")");
} else {
errorOut.println(playException.getErrorTitle());
}
errorOut.println(playException.getErrorDescription().replaceAll("</?\\w+/?>", "").replace("\n", " "));
} else {
sw.append(format(message, args));
}
try {
if (forceJuli || log4j == null) {
juli.log(toJuliLevel(level.toString()), sw.toString(), e);
} else if (recordCaller) {
org.apache.log4j.Logger.getLogger(getCallerClassName(5)).log(level, sw.toString(), null);
} else {
log4j.log(level, sw.toString(), e);
}
}
catch (Exception e1) {
log4j.error("Oops. Error in Logger !", e1);
}
return true;
}
return false;
}
|
diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Request.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Request.java
index 2cb284269..467937dc4 100644
--- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Request.java
+++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Request.java
@@ -1,228 +1,233 @@
/*******************************************************************************
* Copyright (c) 2002 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM - Initial API and implementation
******************************************************************************/
package org.eclipse.team.internal.ccvs.core.client;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.team.internal.ccvs.core.CVSException;
import org.eclipse.team.internal.ccvs.core.CVSProviderPlugin;
import org.eclipse.team.internal.ccvs.core.CVSStatus;
import org.eclipse.team.internal.ccvs.core.Policy;
import org.eclipse.team.internal.ccvs.core.client.listeners.ICommandOutputListener;
import org.eclipse.team.internal.ccvs.core.client.listeners.IConsoleListener;
/**
* Abstract base class for requests that are to be sent to the server.
*/
public abstract class Request {
public static final ExpandModules EXPAND_MODULES = new ExpandModules();
public static final ValidRequests VALID_REQUESTS = new ValidRequests();
/*** Response handler map ***/
private static final Map responseHandlers = new HashMap();
static {
registerResponseHandler(new CheckedInHandler());
registerResponseHandler(new CopyHandler());
registerResponseHandler(new ModTimeHandler());
registerResponseHandler(new NewEntryHandler());
registerResponseHandler(new RemovedHandler());
registerResponseHandler(new RemoveEntryHandler());
registerResponseHandler(new StaticHandler(true));
registerResponseHandler(new StaticHandler(false));
registerResponseHandler(new StickyHandler(true));
registerResponseHandler(new StickyHandler(false));
registerResponseHandler(new UpdatedHandler(UpdatedHandler.HANDLE_UPDATED));
registerResponseHandler(new UpdatedHandler(UpdatedHandler.HANDLE_UPDATE_EXISTING));
registerResponseHandler(new UpdatedHandler(UpdatedHandler.HANDLE_CREATED));
registerResponseHandler(new UpdatedHandler(UpdatedHandler.HANDLE_MERGED));
registerResponseHandler(new ValidRequestsHandler());
registerResponseHandler(new ModuleExpansionHandler());
registerResponseHandler(new MTHandler());
}
protected static void registerResponseHandler(ResponseHandler handler) {
responseHandlers.put(handler.getResponseID(), handler);
}
protected static void removeResponseHandler(String responseID) {
responseHandlers.remove(responseID);
}
protected static ResponseHandler getResponseHandler(String responseID) {
return (ResponseHandler)responseHandlers.get(responseID);
}
/**
* Prevents client code from instantiating us.
*/
protected Request() { }
/**
* Returns the string used to invoke this request on the server.
* [template method]
*
* @return the request identifier string
*/
protected abstract String getRequestId();
/**
* Executes a request and processes the responses.
*
* @param session the open CVS session
* @param listener the command output listener, or null to discard all messages
* @param monitor the progress monitor
* @return a status code indicating success or failure of the operation
*/
protected IStatus executeRequest(Session session, ICommandOutputListener listener,
IProgressMonitor monitor) throws CVSException {
// send request
session.sendRequest(getRequestId());
// This number can be tweaked if the monitor is judged to move too
// quickly or too slowly. After some experimentation this is a good
// number for both large projects (it doesn't move so quickly as to
// give a false sense of speed) and smaller projects (it actually does
// move some rather than remaining still and then jumping to 100).
final int TOTAL_WORK = 300;
monitor.beginTask(Policy.bind("Command.receivingResponses"), TOTAL_WORK); //$NON-NLS-1$
int halfWay = TOTAL_WORK / 2;
int currentIncrement = 4;
int nextProgress = currentIncrement;
int worked = 0;
// If the session is connected to a CVSNT server (1.11.1.1), we'll need to do some special handling for
// some errors. Unfortunately, CVSNT 1.11.1.1 will drop the connection after so some functionality is
// still effected
boolean isCVSNT = session.isCVSNT();
List accumulatedStatus = new ArrayList();
for (;;) {
// update monitor work amount
if (--nextProgress <= 0) {
monitor.worked(1);
worked++;
if (worked >= halfWay) {
// we have passed the current halfway point, so double the
// increment and reset the halfway point.
currentIncrement *= 2;
halfWay += (TOTAL_WORK - halfWay) / 2;
}
// reset the progress counter to another full increment
nextProgress = currentIncrement;
}
Policy.checkCanceled(monitor);
// retrieve a response line
String response = session.readLine();
int spacePos = response.indexOf(' ');
String argument;
if (spacePos != -1) {
argument = response.substring(spacePos + 1);
response = response.substring(0, spacePos);
} else argument = ""; //$NON-NLS-1$
// handle completion responses
if (response.equals("ok")) { //$NON-NLS-1$
break;
} else if (response.equals("error") || (isCVSNT && response.equals(""))) { //$NON-NLS-1$ //$NON-NLS-2$
if (argument.trim().length() == 0) {
argument = getServerErrorMessage();
}
if (accumulatedStatus.isEmpty()) {
accumulatedStatus.add(new CVSStatus(CVSStatus.ERROR, CVSStatus.SERVER_ERROR, Policy.bind("Command.noMoreInfoAvailable")));//$NON-NLS-1$
}
return new MultiStatus(CVSProviderPlugin.ID, CVSStatus.SERVER_ERROR,
(IStatus[]) accumulatedStatus.toArray(new IStatus[accumulatedStatus.size()]),
argument, null);
// handle message responses
} else if (response.equals("MT")) { //$NON-NLS-1$
// Handle the MT response
MTHandler handler = (MTHandler) responseHandlers.get(response);
if (handler != null) {
handler.handle(session, argument, monitor);
} else {
throw new CVSException(new org.eclipse.core.runtime.Status(IStatus.ERROR,
CVSProviderPlugin.ID, CVSException.IO_FAILED,
Policy.bind("Command.unsupportedResponse", response, argument), null)); //$NON-NLS-1$
}
// If a line is available, pass it on to the message listener
// and console as if it were an M response
if (handler.isLineAvailable()) {
String line = handler.getLine();
IStatus status = listener.messageLine(line, session.getLocalRoot(), monitor);
if (status != ICommandOutputListener.OK) accumulatedStatus.add(status);
if (session.isOutputToConsole()) {
IConsoleListener consoleListener = CVSProviderPlugin.getPlugin().getConsoleListener();
if (consoleListener != null) consoleListener.messageLineReceived(line);
}
}
} else if (response.equals("M")) { //$NON-NLS-1$
IStatus status = listener.messageLine(argument, session.getLocalRoot(), monitor);
if (status != ICommandOutputListener.OK) accumulatedStatus.add(status);
if (session.isOutputToConsole()) {
IConsoleListener consoleListener = CVSProviderPlugin.getPlugin().getConsoleListener();
if (consoleListener != null) consoleListener.messageLineReceived(argument);
}
} else if (response.equals("E")) { //$NON-NLS-1$
+ if (listener == null) {
+ // we need to report the error properly (bug 20729)
+ CVSProviderPlugin.log(new CVSStatus(IStatus.ERROR, "Valid requests operation failed: " + argument)); //$NON-NLS-1$
+ throw new CVSException(new CVSStatus(IStatus.ERROR, Policy.bind("CVSProvider.exception"))); //$NON-NLS-1$
+ }
IStatus status = listener.errorLine(argument, session.getLocalRoot(), monitor);
if (status != ICommandOutputListener.OK) accumulatedStatus.add(status);
if (session.isOutputToConsole()) {
IConsoleListener consoleListener = CVSProviderPlugin.getPlugin().getConsoleListener();
if (consoleListener != null) consoleListener.errorLineReceived(argument);
}
// handle other responses
} else {
ResponseHandler handler = (ResponseHandler) responseHandlers.get(response);
if (handler != null) {
handler.handle(session, argument, monitor);
} else {
throw new CVSException(new org.eclipse.core.runtime.Status(IStatus.ERROR,
CVSProviderPlugin.ID, CVSException.IO_FAILED,
Policy.bind("Command.unsupportedResponse", response, argument), null)); //$NON-NLS-1$
}
}
}
if (accumulatedStatus.isEmpty()) {
return ICommandOutputListener.OK;
} else {
return new MultiStatus(CVSProviderPlugin.ID, CVSStatus.INFO,
(IStatus[]) accumulatedStatus.toArray(new IStatus[accumulatedStatus.size()]),
Policy.bind("Command.warnings", Policy.bind("Command." + getRequestId())), null); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/*
* Provide the message that is used for the status that is generated when the server
* reports as error.
*/
protected String getServerErrorMessage() {
return Policy.bind("Command.serverError", Policy.bind("Command." + getRequestId())); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Makes a list of all valid responses; for initializing a session.
* @return a space-delimited list of all valid response strings
*/
static String makeResponseList() {
StringBuffer result = new StringBuffer("ok error M E"); //$NON-NLS-1$
Iterator elements = responseHandlers.keySet().iterator();
while (elements.hasNext()) {
result.append(' ');
result.append((String) elements.next());
}
return result.toString();
}
}
| true | true | protected IStatus executeRequest(Session session, ICommandOutputListener listener,
IProgressMonitor monitor) throws CVSException {
// send request
session.sendRequest(getRequestId());
// This number can be tweaked if the monitor is judged to move too
// quickly or too slowly. After some experimentation this is a good
// number for both large projects (it doesn't move so quickly as to
// give a false sense of speed) and smaller projects (it actually does
// move some rather than remaining still and then jumping to 100).
final int TOTAL_WORK = 300;
monitor.beginTask(Policy.bind("Command.receivingResponses"), TOTAL_WORK); //$NON-NLS-1$
int halfWay = TOTAL_WORK / 2;
int currentIncrement = 4;
int nextProgress = currentIncrement;
int worked = 0;
// If the session is connected to a CVSNT server (1.11.1.1), we'll need to do some special handling for
// some errors. Unfortunately, CVSNT 1.11.1.1 will drop the connection after so some functionality is
// still effected
boolean isCVSNT = session.isCVSNT();
List accumulatedStatus = new ArrayList();
for (;;) {
// update monitor work amount
if (--nextProgress <= 0) {
monitor.worked(1);
worked++;
if (worked >= halfWay) {
// we have passed the current halfway point, so double the
// increment and reset the halfway point.
currentIncrement *= 2;
halfWay += (TOTAL_WORK - halfWay) / 2;
}
// reset the progress counter to another full increment
nextProgress = currentIncrement;
}
Policy.checkCanceled(monitor);
// retrieve a response line
String response = session.readLine();
int spacePos = response.indexOf(' ');
String argument;
if (spacePos != -1) {
argument = response.substring(spacePos + 1);
response = response.substring(0, spacePos);
} else argument = ""; //$NON-NLS-1$
// handle completion responses
if (response.equals("ok")) { //$NON-NLS-1$
break;
} else if (response.equals("error") || (isCVSNT && response.equals(""))) { //$NON-NLS-1$ //$NON-NLS-2$
if (argument.trim().length() == 0) {
argument = getServerErrorMessage();
}
if (accumulatedStatus.isEmpty()) {
accumulatedStatus.add(new CVSStatus(CVSStatus.ERROR, CVSStatus.SERVER_ERROR, Policy.bind("Command.noMoreInfoAvailable")));//$NON-NLS-1$
}
return new MultiStatus(CVSProviderPlugin.ID, CVSStatus.SERVER_ERROR,
(IStatus[]) accumulatedStatus.toArray(new IStatus[accumulatedStatus.size()]),
argument, null);
// handle message responses
} else if (response.equals("MT")) { //$NON-NLS-1$
// Handle the MT response
MTHandler handler = (MTHandler) responseHandlers.get(response);
if (handler != null) {
handler.handle(session, argument, monitor);
} else {
throw new CVSException(new org.eclipse.core.runtime.Status(IStatus.ERROR,
CVSProviderPlugin.ID, CVSException.IO_FAILED,
Policy.bind("Command.unsupportedResponse", response, argument), null)); //$NON-NLS-1$
}
// If a line is available, pass it on to the message listener
// and console as if it were an M response
if (handler.isLineAvailable()) {
String line = handler.getLine();
IStatus status = listener.messageLine(line, session.getLocalRoot(), monitor);
if (status != ICommandOutputListener.OK) accumulatedStatus.add(status);
if (session.isOutputToConsole()) {
IConsoleListener consoleListener = CVSProviderPlugin.getPlugin().getConsoleListener();
if (consoleListener != null) consoleListener.messageLineReceived(line);
}
}
} else if (response.equals("M")) { //$NON-NLS-1$
IStatus status = listener.messageLine(argument, session.getLocalRoot(), monitor);
if (status != ICommandOutputListener.OK) accumulatedStatus.add(status);
if (session.isOutputToConsole()) {
IConsoleListener consoleListener = CVSProviderPlugin.getPlugin().getConsoleListener();
if (consoleListener != null) consoleListener.messageLineReceived(argument);
}
} else if (response.equals("E")) { //$NON-NLS-1$
IStatus status = listener.errorLine(argument, session.getLocalRoot(), monitor);
if (status != ICommandOutputListener.OK) accumulatedStatus.add(status);
if (session.isOutputToConsole()) {
IConsoleListener consoleListener = CVSProviderPlugin.getPlugin().getConsoleListener();
if (consoleListener != null) consoleListener.errorLineReceived(argument);
}
// handle other responses
} else {
ResponseHandler handler = (ResponseHandler) responseHandlers.get(response);
if (handler != null) {
handler.handle(session, argument, monitor);
} else {
throw new CVSException(new org.eclipse.core.runtime.Status(IStatus.ERROR,
CVSProviderPlugin.ID, CVSException.IO_FAILED,
Policy.bind("Command.unsupportedResponse", response, argument), null)); //$NON-NLS-1$
}
}
}
if (accumulatedStatus.isEmpty()) {
return ICommandOutputListener.OK;
} else {
return new MultiStatus(CVSProviderPlugin.ID, CVSStatus.INFO,
(IStatus[]) accumulatedStatus.toArray(new IStatus[accumulatedStatus.size()]),
Policy.bind("Command.warnings", Policy.bind("Command." + getRequestId())), null); //$NON-NLS-1$ //$NON-NLS-2$
}
}
| protected IStatus executeRequest(Session session, ICommandOutputListener listener,
IProgressMonitor monitor) throws CVSException {
// send request
session.sendRequest(getRequestId());
// This number can be tweaked if the monitor is judged to move too
// quickly or too slowly. After some experimentation this is a good
// number for both large projects (it doesn't move so quickly as to
// give a false sense of speed) and smaller projects (it actually does
// move some rather than remaining still and then jumping to 100).
final int TOTAL_WORK = 300;
monitor.beginTask(Policy.bind("Command.receivingResponses"), TOTAL_WORK); //$NON-NLS-1$
int halfWay = TOTAL_WORK / 2;
int currentIncrement = 4;
int nextProgress = currentIncrement;
int worked = 0;
// If the session is connected to a CVSNT server (1.11.1.1), we'll need to do some special handling for
// some errors. Unfortunately, CVSNT 1.11.1.1 will drop the connection after so some functionality is
// still effected
boolean isCVSNT = session.isCVSNT();
List accumulatedStatus = new ArrayList();
for (;;) {
// update monitor work amount
if (--nextProgress <= 0) {
monitor.worked(1);
worked++;
if (worked >= halfWay) {
// we have passed the current halfway point, so double the
// increment and reset the halfway point.
currentIncrement *= 2;
halfWay += (TOTAL_WORK - halfWay) / 2;
}
// reset the progress counter to another full increment
nextProgress = currentIncrement;
}
Policy.checkCanceled(monitor);
// retrieve a response line
String response = session.readLine();
int spacePos = response.indexOf(' ');
String argument;
if (spacePos != -1) {
argument = response.substring(spacePos + 1);
response = response.substring(0, spacePos);
} else argument = ""; //$NON-NLS-1$
// handle completion responses
if (response.equals("ok")) { //$NON-NLS-1$
break;
} else if (response.equals("error") || (isCVSNT && response.equals(""))) { //$NON-NLS-1$ //$NON-NLS-2$
if (argument.trim().length() == 0) {
argument = getServerErrorMessage();
}
if (accumulatedStatus.isEmpty()) {
accumulatedStatus.add(new CVSStatus(CVSStatus.ERROR, CVSStatus.SERVER_ERROR, Policy.bind("Command.noMoreInfoAvailable")));//$NON-NLS-1$
}
return new MultiStatus(CVSProviderPlugin.ID, CVSStatus.SERVER_ERROR,
(IStatus[]) accumulatedStatus.toArray(new IStatus[accumulatedStatus.size()]),
argument, null);
// handle message responses
} else if (response.equals("MT")) { //$NON-NLS-1$
// Handle the MT response
MTHandler handler = (MTHandler) responseHandlers.get(response);
if (handler != null) {
handler.handle(session, argument, monitor);
} else {
throw new CVSException(new org.eclipse.core.runtime.Status(IStatus.ERROR,
CVSProviderPlugin.ID, CVSException.IO_FAILED,
Policy.bind("Command.unsupportedResponse", response, argument), null)); //$NON-NLS-1$
}
// If a line is available, pass it on to the message listener
// and console as if it were an M response
if (handler.isLineAvailable()) {
String line = handler.getLine();
IStatus status = listener.messageLine(line, session.getLocalRoot(), monitor);
if (status != ICommandOutputListener.OK) accumulatedStatus.add(status);
if (session.isOutputToConsole()) {
IConsoleListener consoleListener = CVSProviderPlugin.getPlugin().getConsoleListener();
if (consoleListener != null) consoleListener.messageLineReceived(line);
}
}
} else if (response.equals("M")) { //$NON-NLS-1$
IStatus status = listener.messageLine(argument, session.getLocalRoot(), monitor);
if (status != ICommandOutputListener.OK) accumulatedStatus.add(status);
if (session.isOutputToConsole()) {
IConsoleListener consoleListener = CVSProviderPlugin.getPlugin().getConsoleListener();
if (consoleListener != null) consoleListener.messageLineReceived(argument);
}
} else if (response.equals("E")) { //$NON-NLS-1$
if (listener == null) {
// we need to report the error properly (bug 20729)
CVSProviderPlugin.log(new CVSStatus(IStatus.ERROR, "Valid requests operation failed: " + argument)); //$NON-NLS-1$
throw new CVSException(new CVSStatus(IStatus.ERROR, Policy.bind("CVSProvider.exception"))); //$NON-NLS-1$
}
IStatus status = listener.errorLine(argument, session.getLocalRoot(), monitor);
if (status != ICommandOutputListener.OK) accumulatedStatus.add(status);
if (session.isOutputToConsole()) {
IConsoleListener consoleListener = CVSProviderPlugin.getPlugin().getConsoleListener();
if (consoleListener != null) consoleListener.errorLineReceived(argument);
}
// handle other responses
} else {
ResponseHandler handler = (ResponseHandler) responseHandlers.get(response);
if (handler != null) {
handler.handle(session, argument, monitor);
} else {
throw new CVSException(new org.eclipse.core.runtime.Status(IStatus.ERROR,
CVSProviderPlugin.ID, CVSException.IO_FAILED,
Policy.bind("Command.unsupportedResponse", response, argument), null)); //$NON-NLS-1$
}
}
}
if (accumulatedStatus.isEmpty()) {
return ICommandOutputListener.OK;
} else {
return new MultiStatus(CVSProviderPlugin.ID, CVSStatus.INFO,
(IStatus[]) accumulatedStatus.toArray(new IStatus[accumulatedStatus.size()]),
Policy.bind("Command.warnings", Policy.bind("Command." + getRequestId())), null); //$NON-NLS-1$ //$NON-NLS-2$
}
}
|
diff --git a/src/main/java/com/laytonsmith/core/functions/ArrayHandling.java b/src/main/java/com/laytonsmith/core/functions/ArrayHandling.java
index 234e3c58..eb7f2e37 100644
--- a/src/main/java/com/laytonsmith/core/functions/ArrayHandling.java
+++ b/src/main/java/com/laytonsmith/core/functions/ArrayHandling.java
@@ -1,1657 +1,1661 @@
package com.laytonsmith.core.functions;
import com.laytonsmith.PureUtilities.LinkedComparatorSet;
import com.laytonsmith.PureUtilities.RunnableQueue;
import com.laytonsmith.PureUtilities.Common.StringUtils;
import com.laytonsmith.abstraction.StaticLayer;
import com.laytonsmith.annotations.api;
import com.laytonsmith.core.*;
import com.laytonsmith.core.constructs.*;
import com.laytonsmith.core.environments.Environment;
import com.laytonsmith.core.environments.GlobalEnv;
import com.laytonsmith.core.exceptions.CancelCommandException;
import com.laytonsmith.core.exceptions.ConfigCompileException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.core.functions.BasicLogic.equals;
import com.laytonsmith.core.functions.BasicLogic.equals_ic;
import com.laytonsmith.core.functions.Exceptions.ExceptionType;
import com.laytonsmith.core.natives.interfaces.ArrayAccess;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
/**
*
* @author Layton
*/
public class ArrayHandling {
public static String docs() {
return "This class contains functions that provide a way to manipulate arrays. To create an array, use the <code>array</code> function."
+ " For more detailed information on array usage, see the page on [[CommandHelper/Arrays|arrays]]";
}
@api
public static class array_size extends AbstractFunction {
public String getName() {
return "array_size";
}
public Integer[] numArgs() {
return new Integer[]{1};
}
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
if (args[0] instanceof CArray) {
return new CInt(((CArray) args[0]).size(), t);
}
throw new ConfigRuntimeException("Argument 1 of array_size must be an array", ExceptionType.CastException, t);
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public String docs() {
return "int {array} Returns the size of this array as an integer.";
}
public boolean isRestricted() {
return false;
}
public CHVersion since() {
return CHVersion.V3_0_1;
}
public Boolean runAsync() {
return null;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Demonstrates usage", "array_size(array(1, 2, 3, 4, 5))"),
};
}
}
@api(environments={GlobalEnv.class})
public static class array_get extends AbstractFunction implements Optimizable {
public String getName() {
return "array_get";
}
public Integer[] numArgs() {
return new Integer[]{1, 2, 3};
}
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
Construct index = new CSlice(0, -1, t);
Construct defaultConstruct = null;
if (args.length >= 2) {
index = args[1];
}
if (args.length >= 3) {
defaultConstruct = args[2];
}
if (args[0] instanceof CArray) {
CArray ca = (CArray) args[0];
if (index instanceof CSlice) {
if (ca.inAssociativeMode()) {
if (((CSlice) index).getStart() == 0 && ((CSlice) index).getFinish() == -1) {
//Special exception, we want to clone the whole array
CArray na = CArray.GetAssociativeArray(t);
for (String key : ca.keySet()) {
try {
na.set(key, ca.get(key, t).clone(), t);
} catch (CloneNotSupportedException ex) {
na.set(key, ca.get(key, t), t);
}
}
return na;
}
throw new ConfigRuntimeException("Array slices are not allowed with an associative array", ExceptionType.CastException, t);
}
//It's a range
long start = ((CSlice) index).getStart();
long finish = ((CSlice) index).getFinish();
try {
//Convert negative indexes
if (start < 0) {
start = ca.size() + start;
}
if (finish < 0) {
finish = ca.size() + finish;
}
CArray na = new CArray(t);
if (finish < start) {
//return an empty array in cases where the indexes don't make sense
return na;
}
for (long i = start; i <= finish; i++) {
try {
na.push(ca.get((int) i, t).clone());
} catch (CloneNotSupportedException e) {
na.push(ca.get((int) i, t));
}
}
return na;
} catch (NumberFormatException e) {
throw new ConfigRuntimeException("Ranges must be integer numbers, i.e., [0..5]", ExceptionType.CastException, t);
}
} else {
try {
if (!ca.inAssociativeMode()) {
long iindex = Static.getInt(args[1], t);
if (iindex < 0) {
//negative index, convert to positive index
iindex = ca.size() + iindex;
}
return ca.get(iindex, t);
} else {
return ca.get(args[1], t);
}
} catch (ConfigRuntimeException e) {
if (e.getExceptionType() == ExceptionType.IndexOverflowException) {
if(defaultConstruct != null){
return defaultConstruct;
}
}
if(env.getEnv(GlobalEnv.class).GetFlag("array-special-get") != null){
//They are asking for an array that doesn't exist yet, so let's create it now.
CArray c;
if(ca.inAssociativeMode()){
c = CArray.GetAssociativeArray(t);
} else {
c = new CArray(t);
}
ca.set(args[1], c, t);
return c;
}
throw e;
}
}
} else if (args[0] instanceof CString) {
if (index instanceof CSlice) {
ArrayAccess aa = (ArrayAccess) args[0];
//It's a range
long start = ((CSlice) index).getStart();
long finish = ((CSlice) index).getFinish();
try {
//Convert negative indexes
if (start < 0) {
start = aa.val().length() + start;
}
if (finish < 0) {
finish = aa.val().length() + finish;
}
CArray na = new CArray(t);
if (finish < start) {
//return an empty array in cases where the indexes don't make sense
return new CString("", t);
}
StringBuilder b = new StringBuilder();
String val = aa.val();
for (long i = start; i <= finish; i++) {
try{
b.append(val.charAt((int) i));
} catch(StringIndexOutOfBoundsException e){
throw new Exceptions.RangeException("String bounds out of range. Tried to get character at index " + i + ", but indicies only go up to " + (val.length() - 1), t);
}
}
return new CString(b.toString(), t);
} catch (NumberFormatException e) {
throw new ConfigRuntimeException("Ranges must be integer numbers, i.e., [0..5]", ExceptionType.CastException, t);
}
} else {
try {
return new CString(args[0].val().charAt(Static.getInt32(index, t)), t);
} catch (ConfigRuntimeException e) {
if (e.getExceptionType() == ExceptionType.CastException) {
- throw new ConfigRuntimeException("Expecting an integer index for the array, but found \"" + index
- + "\". (Array is not associative, and cannot accept string keys here.)", ExceptionType.CastException, t);
+ if(args[0] instanceof CArray){
+ throw new ConfigRuntimeException("Expecting an integer index for the array, but found \"" + index
+ + "\". (Array is not associative, and cannot accept string keys here.)", ExceptionType.CastException, t);
+ } else {
+ throw new ConfigRuntimeException("Expecting an array, but \"" + args[0] + "\" was found.", ExceptionType.CastException, t);
+ }
} else {
throw e;
}
} catch (StringIndexOutOfBoundsException e) {
throw new ConfigRuntimeException("No index at " + index, ExceptionType.RangeException, t);
}
}
} else if (args[0] instanceof ArrayAccess) {
throw ConfigRuntimeException.CreateUncatchableException("Wat. How'd you get here? This isn't supposed to be implemented yet.", t);
} else {
throw new ConfigRuntimeException("Argument 1 of array_get must be an array", ExceptionType.CastException, t);
}
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.IndexOverflowException};
}
public String docs() {
return "mixed {array, index, [default]} Returns the element specified at the index of the array. ---- If the element doesn't exist, an exception is thrown. "
+ "array_get(array, index). Note also that as of 3.1.2, you can use a more traditional method to access elements in an array: "
+ "array[index] is the same as array_get(array, index), where array is a variable, or function that is an array. In fact, the compiler"
+ " does some magic under the covers, and literally converts array[index] into array_get(array, index), so if there is a problem "
+ "with your code, you will get an error message about a problem with the array_get function, even though you may not be using "
+ "that function directly. If using the plain function access, then if a default is provided, the function will always return that value if the"
+ " array otherwise doesn't have a value there. This is opposed to throwing an exception or returning null.";
}
public boolean isRestricted() {
return false;
}
public CHVersion since() {
return CHVersion.V3_0_1;
}
public Boolean runAsync() {
return null;
}
@Override
public Construct optimize(Target t, Construct... args) throws ConfigCompileException {
if (args[0] instanceof ArrayAccess) {
ArrayAccess aa = (ArrayAccess) args[0];
if (!aa.canBeAssociative()) {
if (!(args[1] instanceof CInt) && !(args[1] instanceof CSlice)) {
throw new ConfigCompileException("Accessing an element as an associative array, when it can only accept integers.", t);
}
}
return null;
} else {
throw new ConfigCompileException("Trying to access an element like an array, but it does not support array access.", t);
}
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Demonstrates basic usage", "array_get(array(1, 2, 3), 2)"),
new ExampleScript("Demonstrates exception", "array_get(array(), 1)"),
new ExampleScript("Demonstrates default", "array_get(array(), 1, 'default')"),
new ExampleScript("Demonstrates bracket notation", "array(0, 1, 2)[2]"),
};
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.OPTIMIZE_CONSTANT
);
}
}
@api
public static class array_set extends AbstractFunction {
public String getName() {
return "array_set";
}
public Integer[] numArgs() {
return new Integer[]{3};
}
@Override
public boolean useSpecialExec() {
return true;
}
@Override
public Construct execs(Target t, Environment env, Script parent, ParseTree... nodes) {
env.getEnv(GlobalEnv.class).SetFlag("array-special-get", true);
Construct array = parent.seval(nodes[0], env);
env.getEnv(GlobalEnv.class).ClearFlag("array-special-get");
Construct index = parent.seval(nodes[1], env);
Construct value = parent.seval(nodes[2], env);
if(!(array instanceof CArray)){
throw new ConfigRuntimeException("Argument 1 of array_set must be an array", ExceptionType.CastException, t);
}
try {
((CArray)array).set(index, value, t);
} catch (IndexOutOfBoundsException e) {
throw new ConfigRuntimeException("The index " + index.asString().getQuote() + " is out of bounds", ExceptionType.IndexOverflowException, t);
}
return new CVoid(t);
}
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
if (args[0] instanceof CArray) {
try {
((CArray) args[0]).set(args[1], args[2], t);
} catch (IndexOutOfBoundsException e) {
throw new ConfigRuntimeException("The index " + args[1].val() + " is out of bounds", ExceptionType.IndexOverflowException, t);
}
return new CVoid(t);
}
throw new ConfigRuntimeException("Argument 1 of array_set must be an array", ExceptionType.CastException, t);
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.IndexOverflowException};
}
public String docs() {
return "void {array, index, value} Sets the value of the array at the specified index. array_set(array, index, value). Returns void. If"
+ " the element at the specified index isn't already set, throws an exception. Use array_push to avoid this.";
}
public boolean isRestricted() {
return false;
}
public CHVersion since() {
return CHVersion.V3_0_1;
}
public Boolean runAsync() {
return null;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Demonstrates usage", "assign(@array, array(null))\nmsg(@array)\narray_set(@array, 0, 'value0')\nmsg(@array)"),
new ExampleScript("Demonstrates using assign", "assign(@array, array(null))\nmsg(@array)\nassign(@array[0], 'value0')\nmsg(@array)"),
};
}
}
@api
public static class array_push extends AbstractFunction {
public String getName() {
return "array_push";
}
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
if (args[0] instanceof CArray) {
if (args.length < 2) {
throw new ConfigRuntimeException("At least 2 arguments must be provided to array_push", ExceptionType.InsufficientArgumentsException, t);
}
for (int i = 1; i < args.length; i++) {
((CArray) args[0]).push(args[i]);
}
return new CVoid(t);
}
throw new ConfigRuntimeException("Argument 1 of array_push must be an array", ExceptionType.CastException, t);
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public String docs() {
return "void {array, value, [value2...]} Pushes the specified value(s) onto the end of the array";
}
public boolean isRestricted() {
return false;
}
public CHVersion since() {
return CHVersion.V3_0_1;
}
public Boolean runAsync() {
return null;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Demonstrates usage", "assign(@array, array())\nmsg(@array)\narray_push(@array, 0)\nmsg(@array)"),
new ExampleScript("Demonstrates pushing multiple values", "assign(@array, array())\nmsg(@array)\narray_push(@array, 0, 1, 2)\nmsg(@array)"),
};
}
}
@api
public static class array_insert extends AbstractFunction{
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.IndexOverflowException};
}
public boolean isRestricted() {
return false;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
CArray array = Static.getArray(args[0], t);
Construct value = args[1];
int index = Static.getInt32(args[2], t);
try{
array.push(value, index);
} catch(IllegalArgumentException e){
throw new Exceptions.CastException(e.getMessage(), t);
} catch(IndexOutOfBoundsException ex){
throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.IndexOverflowException, t);
}
return new CVoid(t);
}
public String getName() {
return "array_insert";
}
public Integer[] numArgs() {
return new Integer[]{3};
}
public String docs() {
return "void {array, item, index} Inserts an item at the specified index, and shifts all other items in the array to the right one."
+ " If index is greater than the size of the array, an IndexOverflowException is thrown, though the index may be equal"
+ " to the size, in which case this works just like array_push. The array must be normal though, associative arrays"
+ " are not supported.";
}
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "@array = array(1, 3, 4)\n"
+ "array_insert(@array, 2, 1)\n"
+ "msg(@array)"),
new ExampleScript("Usage as if it were array_push", "@array = array(1, 2, 3)\n"
+ "array_insert(@array, 4, array_size(@array))\n"
+ "msg(@array)")
};
}
}
@api
public static class array_contains extends AbstractFunction {
public String getName() {
return "array_contains";
}
public Integer[] numArgs() {
return new Integer[]{2};
}
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
equals e = new equals();
if (args[0] instanceof CArray) {
CArray ca = (CArray) args[0];
for (int i = 0; i < ca.size(); i++) {
if (((CBoolean) e.exec(t, env, ca.get(i, t), args[1])).getBoolean()) {
return new CBoolean(true, t);
}
}
return new CBoolean(false, t);
} else {
throw new ConfigRuntimeException("Argument 1 of array_contains must be an array", ExceptionType.CastException, t);
}
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public String docs() {
return "boolean {array, testValue} Checks to see if testValue is in array.";
}
public boolean isRestricted() {
return false;
}
public CHVersion since() {
return CHVersion.V3_0_1;
}
public Boolean runAsync() {
return null;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Demonstrates finding a value", "array_contains(array(0, 1, 2), 2)"),
new ExampleScript("Demonstrates not finding a value", "array_contains(array(0, 1, 2), 5)"),
new ExampleScript("Demonstrates finding a value listed multiple times", "array_contains(array(1, 1, 1), 1)"),
new ExampleScript("Demonstrates finding a string", "array_contains(array('a', 'b', 'c'), 'b')"),
};
}
}
@api
public static class array_contains_ic extends AbstractFunction {
public String getName() {
return "array_contains_ic";
}
public Integer[] numArgs() {
return new Integer[]{2};
}
public String docs() {
return "boolean {array, testValue} Works like array_contains, except the comparison ignores case.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public CHVersion since() {
return CHVersion.V3_3_0;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
equals_ic e = new equals_ic();
if (args[0] instanceof CArray) {
CArray ca = (CArray) args[0];
for (int i = 0; i < ca.size(); i++) {
if (((CBoolean) e.exec(t, environment, ca.get(i, t), args[1])).getBoolean()) {
return new CBoolean(true, t);
}
}
return new CBoolean(false, t);
} else {
throw new ConfigRuntimeException("Argument 1 of array_contains_ic must be an array", ExceptionType.CastException, t);
}
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Demonstrates usage", "array_contains_ic(array('A', 'B', 'C'), 'A')"),
new ExampleScript("Demonstrates usage", "array_contains_ic(array('A', 'B', 'C'), 'a')"),
new ExampleScript("Demonstrates usage", "array_contains_ic(array('A', 'B', 'C'), 'd')"),
};
}
}
@api
public static class array_index_exists extends AbstractFunction {
public String getName() {
return "array_index_exists";
}
public Integer[] numArgs() {
return new Integer[]{2};
}
public String docs() {
return "boolean {array, index} Checks to see if the specified array has an element at index";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public CHVersion since() {
return CHVersion.V3_1_2;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
if (args[0] instanceof CArray) {
if (!((CArray) args[0]).inAssociativeMode()) {
try {
int index = Static.getInt32(args[1], t);
CArray ca = (CArray) args[0];
return new CBoolean(index <= ca.size() - 1, t);
} catch (ConfigRuntimeException e) {
//They sent a key that is a string. Obviously it doesn't exist.
return new CBoolean(false, t);
}
} else {
CArray ca = (CArray) args[0];
return new CBoolean(ca.containsKey(args[1].val()), t);
}
} else {
throw new ConfigRuntimeException("Expecting argument 1 to be an array", ExceptionType.CastException, t);
}
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Demonstrates a true condition", "array_index_exists(array(0, 1, 2), 0)"),
new ExampleScript("Demonstrates a false condition", "array_index_exists(array(0, 1, 2), 3)"),
new ExampleScript("Demonstrates an associative array", "array_index_exists(array(a: 'A', b: 'B'), 'a')"),
new ExampleScript("Demonstrates an associative array", "array_index_exists(array(a: 'A', b: 'B'), 'c')"),
};
}
}
@api
public static class array_resize extends AbstractFunction {
public String getName() {
return "array_resize";
}
public Integer[] numArgs() {
return new Integer[]{2, 3};
}
public String docs() {
return "void {array, size, [fill]} Resizes the given array so that it is at least of size size, filling the blank spaces with"
+ " fill, or null by default. If the size of the array is already at least size, nothing happens; in other words this"
+ " function can only be used to increase the size of the array.";
//+ " If the array is an associative array, the non numeric values are simply copied over.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public CHVersion since() {
return CHVersion.V3_2_0;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
if (args[0] instanceof CArray && args[1] instanceof CInt) {
CArray original = (CArray) args[0];
int size = (int) ((CInt) args[1]).getInt();
Construct fill = new CNull(t);
if (args.length == 3) {
fill = args[2];
}
for (long i = original.size(); i < size; i++) {
original.push(fill);
}
} else {
throw new ConfigRuntimeException("Argument 1 must be an array, and argument 2 must be an integer in array_resize", ExceptionType.CastException, t);
}
return new CVoid(t);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Demonstrates basic usage", "assign(@array, array())\nmsg(@array)\narray_resize(@array, 2)\nmsg(@array)"),
new ExampleScript("Demonstrates custom fill", "assign(@array, array())\nmsg(@array)\narray_resize(@array, 2, 'a')\nmsg(@array)"),
};
}
}
@api
public static class range extends AbstractFunction {
public String getName() {
return "range";
}
public Integer[] numArgs() {
return new Integer[]{1, 2, 3};
}
public String docs() {
return "array {start, finish, [increment] | finish} Returns an array of numbers from start to (finish - 1)"
+ " skipping increment integers per count. start defaults to 0, and increment defaults to 1. All inputs"
+ " must be integers. If the input doesn't make sense, it will reasonably degrade, and return an empty array.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public CHVersion since() {
return CHVersion.V3_2_0;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
long start = 0;
long finish = 0;
long increment = 1;
if (args.length == 1) {
finish = Static.getInt(args[0], t);
} else if (args.length == 2) {
start = Static.getInt(args[0], t);
finish = Static.getInt(args[1], t);
} else if (args.length == 3) {
start = Static.getInt(args[0], t);
finish = Static.getInt(args[1], t);
increment = Static.getInt(args[2], t);
}
if (start < finish && increment < 0 || start > finish && increment > 0 || increment == 0) {
return new CArray(t);
}
CArray ret = new CArray(t);
for (long i = start; (increment > 0 ? i < finish : i > finish); i = i + increment) {
ret.push(new CInt(i, t));
}
return ret;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "range(10)"),
new ExampleScript("Complex usage", "range(0, 10)"),
new ExampleScript("With skips", "range(0, 10, 2)"),
new ExampleScript("Invalid input", "range(0, 10, -1)"),
new ExampleScript("In reverse", "range(10, 0, -1)"),
};
}
}
@api
public static class array_keys extends AbstractFunction {
public String getName() {
return "array_keys";
}
public Integer[] numArgs() {
return new Integer[]{1};
}
public String docs() {
return "array {array} Returns the keys in this array as a normal array. If the array passed in is already a normal array,"
+ " the keys will be 0 -> (array_size(array) - 1)";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public CHVersion since() {
return CHVersion.V3_3_0;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
if (args[0] instanceof CArray) {
CArray ca = (CArray) args[0];
CArray ca2 = new CArray(t);
for (String c : ca.keySet()) {
ca2.push(new CString(c, t));
}
return ca2;
} else {
throw new ConfigRuntimeException(this.getName() + " expects arg 1 to be an array", ExceptionType.CastException, t);
}
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "array_keys(array('a', 'b', 'c'))"),
new ExampleScript("With associative array", "array_keys(array(one: 'a', two: 'b', three: 'c'))"),
};
}
}
@api
public static class array_normalize extends AbstractFunction {
public String getName() {
return "array_normalize";
}
public Integer[] numArgs() {
return new Integer[]{1};
}
public String docs() {
return "array {array} Returns a new normal array, given an associative array. (If the array passed in is not associative, a copy of the "
+ " array is returned).";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public CHVersion since() {
return CHVersion.V3_3_0;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
if (args[0] instanceof CArray) {
CArray ca = (CArray) args[0];
CArray ca2 = new CArray(t);
for (String c : ca.keySet()) {
ca2.push(ca.get(c, t));
}
return ca2;
} else {
throw new ConfigRuntimeException(this.getName() + " expects arg 1 to be an array", ExceptionType.CastException, t);
}
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "array_normalize(array(one: 'a', two: 'b', three: 'c'))"),
new ExampleScript("Usage with normal array", "array_normalize(array(1, 2, 3))"),
};
}
}
@api
public static class array_merge extends AbstractFunction {
public String getName() {
return "array_merge";
}
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
public String docs() {
return "array {array1, array2, [arrayN...]} Merges the specified arrays from left to right, and returns a new array. If the array"
+ " merged is associative, it will overwrite the keys from left to right, but if the arrays are normal, the keys are ignored,"
+ " and values are simply pushed.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InsufficientArgumentsException, ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public CHVersion since() {
return CHVersion.V3_3_0;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
CArray newArray = new CArray(t);
if (args.length < 2) {
throw new ConfigRuntimeException("array_merge must be called with at least two parameters", ExceptionType.InsufficientArgumentsException, t);
}
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof CArray) {
CArray cur = (CArray) args[i];
if (!cur.inAssociativeMode()) {
for (int j = 0; j < cur.size(); j++) {
newArray.push(cur.get(j, t));
}
} else {
for (String key : cur.keySet()) {
newArray.set(key, cur.get(key, t), t);
}
}
} else {
throw new ConfigRuntimeException("All arguments to array_merge must be arrays", ExceptionType.CastException, t);
}
}
return newArray;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "array_merge(array(1), array(2), array(3))"),
new ExampleScript("With associative arrays", "array_merge(array(one: 1), array(two: 2), array(three: 3))"),
new ExampleScript("With overwrites", "array_merge(array(one: 1), array(one: 2), array(one: 3))"),
};
}
}
@api
public static class array_remove extends AbstractFunction {
public String getName() {
return "array_remove";
}
public Integer[] numArgs() {
return new Integer[]{2};
}
public String docs() {
return "mixed {array, index} Removes an index from an array. If the array is a normal"
+ " array, all values' indicies are shifted left one. If the array is associative,"
+ " the index is simply removed. If the index doesn't exist, the array remains"
+ " unchanged. The value removed is returned.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.RangeException, ExceptionType.CastException, ExceptionType.PluginInternalException};
}
public boolean isRestricted() {
return false;
}
public CHVersion since() {
return CHVersion.V3_3_0;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
if (args[0] instanceof CArray) {
CArray ca = (CArray) args[0];
return ca.remove(args[1]);
} else {
throw new ConfigRuntimeException("Argument 1 of array_remove should be an array", ExceptionType.CastException, t);
}
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "assign(@array, array(1, 2, 3))\nmsg(array_remove(@array, 2))\nmsg(@array)"),
new ExampleScript("With associative array", "assign(@array, array(one: 'a', two: 'b', three: 'c'))\nmsg(array_remove(@array, 'two'))\nmsg(@array)"),
};
}
}
@api
public static class array_implode extends AbstractFunction {
public String getName() {
return "array_implode";
}
public Integer[] numArgs() {
return new Integer[]{1, 2};
}
public String docs() {
return "string {array, [glue]} Given an array and glue, to-strings all the elements"
+ " in the array (just the values, not the keys), and joins them with the glue, defaulting to a space. For instance"
+ " array_implode(array(1, 2, 3), '-') will return \"1-2-3\".";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
if (!(args[0] instanceof CArray)) {
throw new ConfigRuntimeException("Expecting argument 1 to be an array", ExceptionType.CastException, t);
}
StringBuilder b = new StringBuilder();
CArray ca = (CArray) args[0];
String glue = " ";
if (args.length == 2) {
glue = args[1].val();
}
boolean first = true;
for (String key : ca.keySet()) {
Construct value = ca.get(key, t);
if (!first) {
b.append(glue).append(value.val());
} else {
b.append(value.val());
first = false;
}
}
return new CString(b.toString(), t);
}
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "array_implode(array(1, 2, 3), '-')"),
new ExampleScript("With associative array", "array_implode(array(one: 'a', two: 'b', three: 'c'), '-')"),
};
}
}
@api
public static class cslice extends AbstractFunction {
public String getName() {
return "cslice";
}
public Integer[] numArgs() {
return new Integer[]{2};
}
public String docs() {
return "slice {from, to} Dynamically creates an array slice, which can be used with array_get"
+ " (or the [bracket notation]) to get a range of elements. cslice(0, 5) is equivalent"
+ " to 0..5 directly in code, however with this function you can also do cslice(@var, @var),"
+ " or other more complex expressions, which are not possible in static code.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
return new CSlice(Static.getInt(args[0], t), Static.getInt(args[1], t), t);
}
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "array(1, 2, 3)[cslice(0, 1)]"),
};
}
}
@api
public static class array_sort extends AbstractFunction implements Optimizable {
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException};
}
public boolean isRestricted() {
return false;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
if (!(args[0] instanceof CArray)) {
throw new ConfigRuntimeException("The first parameter to array_sort must be an array", ExceptionType.CastException, t);
}
CArray ca = (CArray) args[0];
CArray.SortType sortType = CArray.SortType.REGULAR;
try {
if (args.length == 2) {
sortType = CArray.SortType.valueOf(args[1].val().toUpperCase());
}
} catch (IllegalArgumentException e) {
throw new ConfigRuntimeException("The sort type must be one of either: " + StringUtils.Join(CArray.SortType.values(), ", ", " or "),
ExceptionType.FormatException, t);
}
ca.sort(sortType);
return ca;
}
public String getName() {
return "array_sort";
}
public Integer[] numArgs() {
return new Integer[]{1, 2};
}
public String docs() {
return "array {array, [sortType]} Sorts an array in place, and also returns a reference to the array. ---- The"
+ " complexity of this sort algorithm is guaranteed to be no worse than n log n, as it uses merge sort."
+ " The array is sorted in place, a new array is not explicitly created, so if you sort an array that"
+ " is passed in as a variable, the contents of that variable will be sorted, even if you don't re-assign"
+ " the returned array back to the variable. If you really need the old array, you should create a copy of"
+ " the array first, like so: assign(@sorted, array_sort(@array[])). The sort type may be one of the following:"
+ " " + StringUtils.Join(CArray.SortType.values(), ", ", " or ") + ". A regular sort sorts the elements without changing types first. A"
+ " numeric sort always converts numeric values to numbers first (so 001 becomes 1). A string sort compares"
+ " values as strings, and a string_ic sort is the same as a string sort, but the comparision is case-insensitive."
+ " If the array contains array values, a CastException is thrown; inner arrays cannot be sorted against each"
+ " other. If the array is associative, a warning will be raised if the General logging channel is set to verbose,"
+ " because the array's keys will all be lost in the process. To avoid this warning, and to be more explicit,"
+ " you can use array_normalize() to normalize the array first. Note that the reason this function is an"
+ " in place sort instead of explicitely cloning the array is because in most cases, you may not need"
+ " to actually clone the array, an expensive operation. Due to this, it has slightly different behavior"
+ " than array_normalize, which could have also been implemented in place.";
}
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.OPTIMIZE_DYNAMIC
);
}
@Override
public ParseTree optimizeDynamic(Target t, List<ParseTree> children) throws ConfigCompileException, ConfigRuntimeException {
if (children.size() == 2) {
if (!children.get(1).getData().isDynamic()) {
try {
CArray.SortType.valueOf(children.get(1).getData().val().toUpperCase());
} catch (IllegalArgumentException e) {
throw new ConfigCompileException("The sort type must be one of either: " + StringUtils.Join(CArray.SortType.values(), ", ", " or "), t);
}
}
}
return null;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Regular sort", "assign(@array, array('a', 2, 4, 'string'))\narray_sort(@array, 'REGULAR')\nmsg(@array)"),
new ExampleScript("Numeric sort", "assign(@array, array('03', '02', '4', '1'))\narray_sort(@array, 'NUMERIC')\nmsg(@array)"),
new ExampleScript("String sort", "assign(@array, array('03', '02', '4', '1'))\narray_sort(@array, 'STRING')\nmsg(@array)"),
new ExampleScript("String sort (with words)", "assign(@array, array('Zeta', 'zebra', 'Minecraft', 'mojang', 'Appliance', 'apple'))\narray_sort(@array, 'STRING')\nmsg(@array)"),
new ExampleScript("Ignore case sort", "assign(@array, array('Zeta', 'zebra', 'Minecraft', 'mojang', 'Appliance', 'apple'))\narray_sort(@array, 'STRING_IC')\nmsg(@array)"),
};
}
}
@api public static class array_sort_async extends AbstractFunction{
RunnableQueue queue = new RunnableQueue("MethodScript-arraySortAsync");
boolean started = false;
private void startup(){
if(!started){
queue.invokeLater(null, new Runnable() {
public void run() {
//This warms up the queue. Apparently.
}
});
StaticLayer.GetConvertor().addShutdownHook(new Runnable() {
public void run() {
queue.shutdown();
started = false;
}
});
started = true;
}
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
startup();
final CArray array = Static.getArray(args[0], t);
final CString sortType = new CString(args.length > 2?args[1].val():CArray.SortType.REGULAR.name(), t);
final CClosure callback = Static.getObject((args.length==2?args[1]:args[2]), t, "closure", CClosure.class);
queue.invokeLater(environment.getEnv(GlobalEnv.class).GetDaemonManager(), new Runnable() {
public void run() {
Construct c = new array_sort().exec(Target.UNKNOWN, null, array, sortType);
callback.execute(new Construct[]{c});
}
});
return new CVoid(t);
}
public String getName() {
return "array_sort_async";
}
public Integer[] numArgs() {
return new Integer[]{2, 3};
}
public String docs() {
return "void {array, [sortType], closure(array)} Works like array_sort, but does the sort on another"
+ " thread, then calls the closure and sends it the sorted array. This is useful if the array"
+ " is large enough to actually \"stall\" the server when doing the sort. Sort type should be"
+ " one of " + StringUtils.Join(CArray.SortType.values(), ", ", " or ");
}
public CHVersion since() {
return CHVersion.V3_3_1;
}
}
@api public static class array_remove_values extends AbstractFunction{
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
if(!(args[0] instanceof CArray)){
throw new ConfigRuntimeException("Expected parameter 1 to be an array, but was " + args[0].val(), ExceptionType.CastException, t);
}
((CArray)args[0]).removeValues(args[1]);
return new CVoid(t);
}
public String getName() {
return "array_remove_values";
}
public Integer[] numArgs() {
return new Integer[]{2};
}
public String docs() {
return "void {array, value} Removes all instances of value from the specified array."
+ " For instance, array_remove_values(array(1, 2, 2, 3), 2) would produce the"
+ " array(1, 3). Note that it returns void however, so it will simply in place"
+ " modify the array passed in, much like array_remove.";
}
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "assign(@array, array(1, 2, 2, 3))\nmsg(@array)\narray_remove_values(@array, 2)\nmsg(@array)"),
};
}
}
@api public static class array_indexes extends AbstractFunction{
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
if(!(args[0] instanceof CArray)){
throw new ConfigRuntimeException("Expected parameter 1 to be an array, but was " + args[0].val(), ExceptionType.CastException, t);
}
return ((CArray)args[0]).indexesOf(args[1]);
}
public String getName() {
return "array_indexes";
}
public Integer[] numArgs() {
return new Integer[]{2};
}
public String docs() {
return "array {array, value} Returns an array with all the keys of the specified array"
+ " at which the specified value is equal. That is, for the array(1, 2, 2, 3), if"
+ " value were 2, would return array(1, 2). If the value cannot be found in the"
+ " array at all, an empty array will be returned.";
}
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "assign(@array, array(1, 2, 2, 3))\nmsg(array_indexes(@array, 2))"),
new ExampleScript("Not found", "assign(@array, array(1, 2, 2, 3))\nmsg(array_indexes(@array, 5))"),
};
}
}
@api public static class array_index extends AbstractFunction{
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
CArray ca = (CArray)new array_indexes().exec(t, environment, args);
if(ca.isEmpty()){
return new CNull(t);
} else {
return ca.get(0);
}
}
public String getName() {
return "array_index";
}
public Integer[] numArgs() {
return new Integer[]{2};
}
public String docs() {
return "mixed {array, value} Works exactly like array_indexes(array, value)[0], except in the case where"
+ " the value is not found, returns null. That is to say, if the value is contained in an"
+ " array (even multiple times) the index of the first element is returned.";
}
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "assign(@array, array(1, 2, 2, 3))\nmsg(array_index(@array, 2))"),
new ExampleScript("Not found", "assign(@array, array(1, 2, 2, 3))\nmsg(array_index(@array, 5))"),
};
}
}
@api
public static class array_reverse extends AbstractFunction{
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
if(args[0] instanceof CArray){
((CArray)args[0]).reverse();
}
return new CVoid(t);
}
public String getName() {
return "array_reverse";
}
public Integer[] numArgs() {
return new Integer[]{1};
}
public String docs() {
return "void {array} Reverses an array in place. However, if the array is associative, throws a CastException, since associative"
+ " arrays are more like a map.";
}
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "assign(@array, array(1, 2, 3))\nmsg(@array)\narray_reverse(@array)\nmsg(@array)"),
new ExampleScript("Failure", "assign(@array, array(one: 1, two: 2))\narray_reverse(@array)")
};
}
}
@api public static class array_rand extends AbstractFunction{
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.RangeException, ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public Boolean runAsync() {
return null;
}
Random r = new Random(System.currentTimeMillis());
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
long number = 1;
boolean getKeys = true;
CArray array = Static.getArray(args[0], t);
CArray newArray = new CArray(t);
if(array.isEmpty()){
return newArray;
}
if(args.length > 1){
number = Static.getInt(args[1], t);
}
if(number < 1){
throw new ConfigRuntimeException("number may not be less than 1.", ExceptionType.RangeException, t);
}
if(number > Integer.MAX_VALUE){
throw new ConfigRuntimeException("Overflow detected. Number cannot be larger than " + Integer.MAX_VALUE, ExceptionType.RangeException, t);
}
if(args.length > 2){
getKeys = Static.getBoolean(args[2]);
}
LinkedHashSet<Integer> randoms = new LinkedHashSet<Integer>();
while(randoms.size() < number){
randoms.add(java.lang.Math.abs(r.nextInt() % (int)array.size()));
}
List<String> keySet = new ArrayList<String>(array.keySet());
for(Integer i : randoms){
if(getKeys){
newArray.push(new CString(keySet.get(i), t));
} else {
newArray.push(array.get(keySet.get(i), t));
}
}
return newArray;
}
public String getName() {
return "array_rand";
}
public Integer[] numArgs() {
return new Integer[]{1, 2, 3};
}
public String docs() {
return "array {array, [number, [getKeys]]} Returns a random selection of keys or values from an array. The array may be"
+ " either normal or associative. Number defaults to 1, and getKey defaults to true. If number is greater than"
+ " the size of the array, a RangeException is thrown. No value will be returned twice from the array however, one it"
+ " is \"drawn\" from the array, it is not placed back in. The order of the elements in the array will also be random,"
+ " if order is important, use array_sort().";
}
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Usage with a normal array", "assign(@array, array('a', 'b', 'c', 'd', 'e'))\nmsg(array_rand(@array))"),
new ExampleScript("Usage with a normal array, using getKeys false, and returning 2 results",
"assign(@array, array('a', 'b', 'c', 'd', 'e'))\nmsg(array_rand(@array, 2, false))"),
new ExampleScript("Usage with an associative array",
"assign(@array, array(one: 'a', two: 'b', three: 'c', four: 'd', five: 'e'))\nmsg(array_rand(@array))"),
};
}
}
@api
public static class array_unique extends AbstractFunction{
private final static equals equals = new equals();
private final static BasicLogic.sequals sequals = new BasicLogic.sequals();
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
public boolean isRestricted() {
return false;
}
public Boolean runAsync() {
return null;
}
public Construct exec(final Target t, final Environment environment, Construct... args) throws ConfigRuntimeException {
CArray array = Static.getArray(args[0], t);
boolean compareTypes = true;
if(args.length == 2){
compareTypes = Static.getBoolean(args[1]);
}
final boolean fCompareTypes = compareTypes;
if(array.inAssociativeMode()){
return array.clone();
} else {
List<Construct> asList = array.asList();
CArray newArray = new CArray(t);
Set<Construct> set = new LinkedComparatorSet<Construct>(asList, new LinkedComparatorSet.EqualsComparator<Construct>() {
public boolean checkIfEquals(Construct item1, Construct item2) {
return (fCompareTypes && Static.getBoolean(sequals.exec(t, environment, item1, item2)))
|| (!fCompareTypes && Static.getBoolean(equals.exec(t, environment, item1, item2)));
}
});
for(Construct c : set){
newArray.push(c);
}
return newArray;
}
}
public String getName() {
return "array_unique";
}
public Integer[] numArgs() {
return new Integer[]{1, 2};
}
public String docs() {
return "array {array, [compareTypes]} Removes all non-unique values from an array. ---- compareTypes is true by default, which means that in the array"
+ " array(1, '1'), nothing would be removed from the array, since both values are different data types. However, if compareTypes is false,"
+ " then the first value would remain, but the second value would be removed. A new array is returned. If the array is associative, by definition,"
+ " there are no unique values, so a clone of the array is returned.";
}
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "array_unique(array(1, 2, 2, 3, 4))"),
new ExampleScript("No removal of different datatypes", "array_unique(array(1, '1'))"),
new ExampleScript("Removal of different datatypes, by setting compareTypes to false", "array_unique(array(1, '1'), false)"),
};
}
}
}
| true | true | public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
Construct index = new CSlice(0, -1, t);
Construct defaultConstruct = null;
if (args.length >= 2) {
index = args[1];
}
if (args.length >= 3) {
defaultConstruct = args[2];
}
if (args[0] instanceof CArray) {
CArray ca = (CArray) args[0];
if (index instanceof CSlice) {
if (ca.inAssociativeMode()) {
if (((CSlice) index).getStart() == 0 && ((CSlice) index).getFinish() == -1) {
//Special exception, we want to clone the whole array
CArray na = CArray.GetAssociativeArray(t);
for (String key : ca.keySet()) {
try {
na.set(key, ca.get(key, t).clone(), t);
} catch (CloneNotSupportedException ex) {
na.set(key, ca.get(key, t), t);
}
}
return na;
}
throw new ConfigRuntimeException("Array slices are not allowed with an associative array", ExceptionType.CastException, t);
}
//It's a range
long start = ((CSlice) index).getStart();
long finish = ((CSlice) index).getFinish();
try {
//Convert negative indexes
if (start < 0) {
start = ca.size() + start;
}
if (finish < 0) {
finish = ca.size() + finish;
}
CArray na = new CArray(t);
if (finish < start) {
//return an empty array in cases where the indexes don't make sense
return na;
}
for (long i = start; i <= finish; i++) {
try {
na.push(ca.get((int) i, t).clone());
} catch (CloneNotSupportedException e) {
na.push(ca.get((int) i, t));
}
}
return na;
} catch (NumberFormatException e) {
throw new ConfigRuntimeException("Ranges must be integer numbers, i.e., [0..5]", ExceptionType.CastException, t);
}
} else {
try {
if (!ca.inAssociativeMode()) {
long iindex = Static.getInt(args[1], t);
if (iindex < 0) {
//negative index, convert to positive index
iindex = ca.size() + iindex;
}
return ca.get(iindex, t);
} else {
return ca.get(args[1], t);
}
} catch (ConfigRuntimeException e) {
if (e.getExceptionType() == ExceptionType.IndexOverflowException) {
if(defaultConstruct != null){
return defaultConstruct;
}
}
if(env.getEnv(GlobalEnv.class).GetFlag("array-special-get") != null){
//They are asking for an array that doesn't exist yet, so let's create it now.
CArray c;
if(ca.inAssociativeMode()){
c = CArray.GetAssociativeArray(t);
} else {
c = new CArray(t);
}
ca.set(args[1], c, t);
return c;
}
throw e;
}
}
} else if (args[0] instanceof CString) {
if (index instanceof CSlice) {
ArrayAccess aa = (ArrayAccess) args[0];
//It's a range
long start = ((CSlice) index).getStart();
long finish = ((CSlice) index).getFinish();
try {
//Convert negative indexes
if (start < 0) {
start = aa.val().length() + start;
}
if (finish < 0) {
finish = aa.val().length() + finish;
}
CArray na = new CArray(t);
if (finish < start) {
//return an empty array in cases where the indexes don't make sense
return new CString("", t);
}
StringBuilder b = new StringBuilder();
String val = aa.val();
for (long i = start; i <= finish; i++) {
try{
b.append(val.charAt((int) i));
} catch(StringIndexOutOfBoundsException e){
throw new Exceptions.RangeException("String bounds out of range. Tried to get character at index " + i + ", but indicies only go up to " + (val.length() - 1), t);
}
}
return new CString(b.toString(), t);
} catch (NumberFormatException e) {
throw new ConfigRuntimeException("Ranges must be integer numbers, i.e., [0..5]", ExceptionType.CastException, t);
}
} else {
try {
return new CString(args[0].val().charAt(Static.getInt32(index, t)), t);
} catch (ConfigRuntimeException e) {
if (e.getExceptionType() == ExceptionType.CastException) {
throw new ConfigRuntimeException("Expecting an integer index for the array, but found \"" + index
+ "\". (Array is not associative, and cannot accept string keys here.)", ExceptionType.CastException, t);
} else {
throw e;
}
} catch (StringIndexOutOfBoundsException e) {
throw new ConfigRuntimeException("No index at " + index, ExceptionType.RangeException, t);
}
}
} else if (args[0] instanceof ArrayAccess) {
throw ConfigRuntimeException.CreateUncatchableException("Wat. How'd you get here? This isn't supposed to be implemented yet.", t);
} else {
throw new ConfigRuntimeException("Argument 1 of array_get must be an array", ExceptionType.CastException, t);
}
}
| public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
Construct index = new CSlice(0, -1, t);
Construct defaultConstruct = null;
if (args.length >= 2) {
index = args[1];
}
if (args.length >= 3) {
defaultConstruct = args[2];
}
if (args[0] instanceof CArray) {
CArray ca = (CArray) args[0];
if (index instanceof CSlice) {
if (ca.inAssociativeMode()) {
if (((CSlice) index).getStart() == 0 && ((CSlice) index).getFinish() == -1) {
//Special exception, we want to clone the whole array
CArray na = CArray.GetAssociativeArray(t);
for (String key : ca.keySet()) {
try {
na.set(key, ca.get(key, t).clone(), t);
} catch (CloneNotSupportedException ex) {
na.set(key, ca.get(key, t), t);
}
}
return na;
}
throw new ConfigRuntimeException("Array slices are not allowed with an associative array", ExceptionType.CastException, t);
}
//It's a range
long start = ((CSlice) index).getStart();
long finish = ((CSlice) index).getFinish();
try {
//Convert negative indexes
if (start < 0) {
start = ca.size() + start;
}
if (finish < 0) {
finish = ca.size() + finish;
}
CArray na = new CArray(t);
if (finish < start) {
//return an empty array in cases where the indexes don't make sense
return na;
}
for (long i = start; i <= finish; i++) {
try {
na.push(ca.get((int) i, t).clone());
} catch (CloneNotSupportedException e) {
na.push(ca.get((int) i, t));
}
}
return na;
} catch (NumberFormatException e) {
throw new ConfigRuntimeException("Ranges must be integer numbers, i.e., [0..5]", ExceptionType.CastException, t);
}
} else {
try {
if (!ca.inAssociativeMode()) {
long iindex = Static.getInt(args[1], t);
if (iindex < 0) {
//negative index, convert to positive index
iindex = ca.size() + iindex;
}
return ca.get(iindex, t);
} else {
return ca.get(args[1], t);
}
} catch (ConfigRuntimeException e) {
if (e.getExceptionType() == ExceptionType.IndexOverflowException) {
if(defaultConstruct != null){
return defaultConstruct;
}
}
if(env.getEnv(GlobalEnv.class).GetFlag("array-special-get") != null){
//They are asking for an array that doesn't exist yet, so let's create it now.
CArray c;
if(ca.inAssociativeMode()){
c = CArray.GetAssociativeArray(t);
} else {
c = new CArray(t);
}
ca.set(args[1], c, t);
return c;
}
throw e;
}
}
} else if (args[0] instanceof CString) {
if (index instanceof CSlice) {
ArrayAccess aa = (ArrayAccess) args[0];
//It's a range
long start = ((CSlice) index).getStart();
long finish = ((CSlice) index).getFinish();
try {
//Convert negative indexes
if (start < 0) {
start = aa.val().length() + start;
}
if (finish < 0) {
finish = aa.val().length() + finish;
}
CArray na = new CArray(t);
if (finish < start) {
//return an empty array in cases where the indexes don't make sense
return new CString("", t);
}
StringBuilder b = new StringBuilder();
String val = aa.val();
for (long i = start; i <= finish; i++) {
try{
b.append(val.charAt((int) i));
} catch(StringIndexOutOfBoundsException e){
throw new Exceptions.RangeException("String bounds out of range. Tried to get character at index " + i + ", but indicies only go up to " + (val.length() - 1), t);
}
}
return new CString(b.toString(), t);
} catch (NumberFormatException e) {
throw new ConfigRuntimeException("Ranges must be integer numbers, i.e., [0..5]", ExceptionType.CastException, t);
}
} else {
try {
return new CString(args[0].val().charAt(Static.getInt32(index, t)), t);
} catch (ConfigRuntimeException e) {
if (e.getExceptionType() == ExceptionType.CastException) {
if(args[0] instanceof CArray){
throw new ConfigRuntimeException("Expecting an integer index for the array, but found \"" + index
+ "\". (Array is not associative, and cannot accept string keys here.)", ExceptionType.CastException, t);
} else {
throw new ConfigRuntimeException("Expecting an array, but \"" + args[0] + "\" was found.", ExceptionType.CastException, t);
}
} else {
throw e;
}
} catch (StringIndexOutOfBoundsException e) {
throw new ConfigRuntimeException("No index at " + index, ExceptionType.RangeException, t);
}
}
} else if (args[0] instanceof ArrayAccess) {
throw ConfigRuntimeException.CreateUncatchableException("Wat. How'd you get here? This isn't supposed to be implemented yet.", t);
} else {
throw new ConfigRuntimeException("Argument 1 of array_get must be an array", ExceptionType.CastException, t);
}
}
|
diff --git a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddResearchDataToPublicationGenerator.java b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddResearchDataToPublicationGenerator.java
index bbd7749..b0db03d 100644
--- a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddResearchDataToPublicationGenerator.java
+++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddResearchDataToPublicationGenerator.java
@@ -1,351 +1,351 @@
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.sdb.SDBFactory;
import com.hp.hpl.jena.sdb.Store;
import com.hp.hpl.jena.sdb.StoreDesc;
import com.hp.hpl.jena.sdb.sql.SDBConnection;
import com.hp.hpl.jena.sdb.store.DatabaseType;
import com.hp.hpl.jena.sdb.store.LayoutType;
import com.hp.hpl.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
import edu.cornell.mannlib.vitro.webapp.servlet.setup.JenaDataSourceSetupBase;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.commons.dbcp.BasicDataSource;
/**
*
* @author dcliff
*/
public class AddResearchDataToPublicationGenerator extends VivoBaseGenerator implements EditConfigurationGenerator
{
private Model queryModel;
private SDBConnection conn;
private static final Log log = LogFactory.getLog(AddResearchDataToPublicationGenerator.class);
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session)
{
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
//Creating an instance of SparqlEvaluateVTwo so that we can run queries
//on our optional inferred statements.
queryModel = editConfiguration.getQueryModelSelector().getModel(vreq, session.getServletContext());
//Basic intialization
initBasics(editConfiguration, vreq);
initPropertyParameters(vreq, session, editConfiguration);
//Overriding URL to return to (as we won't be editing)
- setUrlToReturnTo(editConfiguration, vreq);
+ //setUrlToReturnTo(editConfiguration, vreq);
//set variable names
editConfiguration.setVarNameForSubject("publication");
editConfiguration.setVarNameForPredicate("predicate");
editConfiguration.setVarNameForObject("researchDataUri");
// Required N3
editConfiguration.setN3Required(list(getN3NewResearchData()));
editConfiguration.addNewResource("researchDataUri", DEFAULT_NS_TOKEN);
editConfiguration.setN3Optional(generateN3Optional());
//In scope
setUrisAndLiteralsInScope(editConfiguration, vreq);
//on Form
setUrisAndLiteralsOnForm(editConfiguration, vreq);
//Sparql queries
setSparqlQueries(editConfiguration, vreq);
//set fields
setFields(editConfiguration);
//template file
editConfiguration.setTemplate("addResearchDataToPublication.ftl");
//Adding additional data, specifically edit mode
addFormSpecificData(editConfiguration, vreq);
//TODO: add validators
editConfiguration.addValidator(new AntiXssValidation());
//NOITCE this generator does not run prepare() since it
//is never an update and has no SPARQL for existing
return editConfiguration;
}
private List<String> generateN3Optional() {
return list(
getN3ForResearchDataLabel(),
getN3ForSubjectArea(),
getN3ForCustodianDepartments(),
getN3ForCustodians(),
getN3ForResearchDataDescription());
}
private String getN3ForSubjectArea()
{
return getN3PrefixString() +
"?researchDataUri <http://vivoweb.org/ontology/core#hasSubjectArea> ?subjectArea .";
}
private String getN3ForCustodianDepartments()
{
return getN3PrefixString() +
"?researchDataUri ands:isManagedBy ?custodianDepartments .";
}
private String getN3ForCustodians()
{
return getN3PrefixString() +
"?researchDataUri ands:associatedPrincipleInvestigator ?custodians .";
}
private String getN3ForResearchDataLabel()
{
return getN3PrefixString() +
"?researchDataUri rdfs:label ?researchDataLabel .";
}
private String getN3ForResearchDataDescription()
{
return getN3PrefixString() +
"?researchDataUri ands:researchDataDescription ?dataDescription .";
}
private Map<String, String> getInheritedSubjectAreaLabelAndUri(String subjectUri)
{
Map<String, String> results = new HashMap<String, String>();
String query = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" +
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" +
"PREFIX bibo: <http://purl.org/ontology/bibo/> \n" +
"PREFIX core: <http://vivoweb.org/ontology/core#> \n" +
"SELECT ?subjectArea ?subjectAreaLabel WHERE { \n" +
"<" + subjectUri + "> core:hasSubjectArea ?subjectArea . \n" +
"?subjectArea rdfs:label ?subjectAreaLabel \n" +
"}";
ResultSet rs = sparqlQuery(queryModel, query);
while(rs.hasNext())
{
QuerySolution qs = rs.nextSolution();
String uriString = qs.get("subjectArea").toString();
String labelString = qs.get("subjectAreaLabel").toString();
results.put(uriString, labelString);
}
log.info("Debug: InheritedSubjectArea: " + results.isEmpty());
return results;
}
private Map<String, String> getInheritedCustodianDepartmentsLabelAndUri(String subjectUri)
{
Map<String, String> results = new HashMap<String, String>();
String query = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" +
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" +
"PREFIX bibo: <http://purl.org/ontology/bibo/> \n" +
"PREFIX core: <http://vivoweb.org/ontology/core#> \n" +
"SELECT DISTINCT ?org ?orgLabel WHERE { \n" +
"<" + subjectUri + "> core:informationResourceInAuthorship ?la. \n" +
"?la core:linkedAuthor ?person. \n" +
"?person core:personInPosition ?position. \n" +
"?position core:positionInOrganization ?org. \n" +
"?org rdfs:label ?orgLabel}";
ResultSet rs = sparqlQuery(queryModel, query);
while(rs.hasNext())
{
QuerySolution qs = rs.nextSolution();
String uriString = qs.get("org").toString();
String labelString = qs.get("orgLabel").toString();
results.put(uriString, labelString);
}
log.info("Debug: InheritedCustodianDepartments: " + results.isEmpty());
return results;
}
private Map<String, String> getInheritedCustodiansLabelAndUri(String subjectUri)
{
Map<String, String> results = new HashMap<String, String>();
String query = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" +
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" +
"PREFIX bibo: <http://purl.org/ontology/bibo/> \n" +
"PREFIX core: <http://vivoweb.org/ontology/core#> \n" +
"SELECT DISTINCT ?person ?personLabel WHERE { \n" +
"<" + subjectUri + "> core:informationResourceInAuthorship ?la. \n" +
"?la core:linkedAuthor ?person. \n" +
"?person rdfs:label ?personLabel}";
ResultSet rs = sparqlQuery(queryModel, query);
int i = 0;
while(rs.hasNext())
{
QuerySolution qs = rs.nextSolution();
String uriString = qs.get("person").toString();
String labelString = qs.get("personLabel").toString();
results.put(uriString, labelString);
i++;
}
log.info("Debug: InheritedCustodians: " + i + " " + results.isEmpty());
return results;
}
private ResultSet sparqlQuery(Model queryModel, String queryString)
{
QueryExecution qe = null;
try
{
Query query = QueryFactory.create(queryString);
qe = QueryExecutionFactory.create(query, queryModel);
ResultSet results = null;
results = qe.execSelect();
if(results.hasNext())
{
log.info("Results retrieved.");
return results;
}
else
{
return null;
}
}
catch(Exception ex)
{
throw new Error("could not parse SPARQL in queryToUri: \n" + queryString + '\n' + ex.getMessage());
}
}
private void setUrlToReturnTo(EditConfigurationVTwo editConfiguration, VitroRequest vreq)
{
editConfiguration.setUrlPatternToReturnTo(EditConfigurationUtils.getFormUrlWithoutContext(vreq));
}
public String getN3PrefixString()
{
return "@prefix core: <" + vivoCore + "> .\n" +
"@prefix rdfs: <" + rdfs + "> .\n" +
"@prefix ands: <http://purl.org/ands/ontologies/vivo/> .\n";
}
private String getN3NewResearchData()
{
return getN3PrefixString() +
"?publication ands:hasResearchData ?researchDataUri. \n" +
"?researchDataUri ands:publishedIn ?publication. \n" +
"?researchDataUri a ands:ResearchData ;";
}
/** Set URIS and Literals In Scope and on form and supporting methods */
private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
//Uris in scope always contain subject and predicate
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
urisInScope.put(editConfiguration.getVarNameForSubject(),
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
urisInScope.put(editConfiguration.getVarNameForPredicate(),
Arrays.asList(new String[]{editConfiguration.getPredicateUri()}));
editConfiguration.setUrisInScope(urisInScope);
//no literals in scope
}
private void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
List<String> urisOnForm = new ArrayList<String>();
urisOnForm.add("subjectArea");
editConfiguration.setUrisOnform(urisOnForm);
List<String> literalsOnForm = list("researchDataLabel",
"dataDescription");
editConfiguration.setLiteralsOnForm(literalsOnForm);
}
/** Set SPARQL Queries and supporting methods. */
private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
editConfiguration.setSparqlForExistingUris(new HashMap<String, String>());
editConfiguration.setSparqlForExistingLiterals(new HashMap<String, String>());
editConfiguration.setSparqlForAdditionalUrisInScope(new HashMap<String, String>());
editConfiguration.setSparqlForAdditionalLiteralsInScope(new HashMap<String, String>());
}
/**
*
* Set Fields and supporting methods
*/
private void setFields(EditConfigurationVTwo editConfiguration) {
setResearchDataLabelField(editConfiguration);
setDataDescriptionField(editConfiguration);
setSubjectAreaField(editConfiguration);
}
private void setSubjectAreaField(EditConfigurationVTwo editConfiguration) {
editConfiguration.addField(new FieldVTwo().
setName("subjectArea"));
}
private void setResearchDataLabelField(EditConfigurationVTwo editConfiguration) {
editConfiguration.addField(new FieldVTwo().
setName("researchDataLabel").
setValidators(list("datatype:" + XSD.xstring.toString())).
setRangeDatatypeUri(XSD.xstring.toString())
);
}
private void setDataDescriptionField(EditConfigurationVTwo editConfiguration) {
editConfiguration.addField(new FieldVTwo().
setName("dataDescription").
setValidators(list("datatype:" + XSD.xstring.toString())).
setRangeDatatypeUri(XSD.xstring.toString())
);
}
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq)
{
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
//Call on our custom SPARQL and put the values into the HashMap
String subjectUri = editConfiguration.getSubjectUri();
log.info("Debug: " + subjectUri);
formSpecificData.put("InheritedCustodianDepartments", getInheritedCustodianDepartmentsLabelAndUri(subjectUri));
formSpecificData.put("InheritedCustodians", getInheritedCustodiansLabelAndUri(subjectUri));
//formSpecificData.put("InheritedSubjectArea", getInheritedSubjectAreaLabelAndUri(subjectUri));
log.info("Debug: setting form specific data...");
editConfiguration.setFormSpecificData(formSpecificData);
}
static final String DEFAULT_NS_TOKEN = null; //null forces the default NS
}
| true | true | public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session)
{
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
//Creating an instance of SparqlEvaluateVTwo so that we can run queries
//on our optional inferred statements.
queryModel = editConfiguration.getQueryModelSelector().getModel(vreq, session.getServletContext());
//Basic intialization
initBasics(editConfiguration, vreq);
initPropertyParameters(vreq, session, editConfiguration);
//Overriding URL to return to (as we won't be editing)
setUrlToReturnTo(editConfiguration, vreq);
//set variable names
editConfiguration.setVarNameForSubject("publication");
editConfiguration.setVarNameForPredicate("predicate");
editConfiguration.setVarNameForObject("researchDataUri");
// Required N3
editConfiguration.setN3Required(list(getN3NewResearchData()));
editConfiguration.addNewResource("researchDataUri", DEFAULT_NS_TOKEN);
editConfiguration.setN3Optional(generateN3Optional());
//In scope
setUrisAndLiteralsInScope(editConfiguration, vreq);
//on Form
setUrisAndLiteralsOnForm(editConfiguration, vreq);
//Sparql queries
setSparqlQueries(editConfiguration, vreq);
//set fields
setFields(editConfiguration);
//template file
editConfiguration.setTemplate("addResearchDataToPublication.ftl");
//Adding additional data, specifically edit mode
addFormSpecificData(editConfiguration, vreq);
//TODO: add validators
editConfiguration.addValidator(new AntiXssValidation());
//NOITCE this generator does not run prepare() since it
//is never an update and has no SPARQL for existing
return editConfiguration;
}
| public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session)
{
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
//Creating an instance of SparqlEvaluateVTwo so that we can run queries
//on our optional inferred statements.
queryModel = editConfiguration.getQueryModelSelector().getModel(vreq, session.getServletContext());
//Basic intialization
initBasics(editConfiguration, vreq);
initPropertyParameters(vreq, session, editConfiguration);
//Overriding URL to return to (as we won't be editing)
//setUrlToReturnTo(editConfiguration, vreq);
//set variable names
editConfiguration.setVarNameForSubject("publication");
editConfiguration.setVarNameForPredicate("predicate");
editConfiguration.setVarNameForObject("researchDataUri");
// Required N3
editConfiguration.setN3Required(list(getN3NewResearchData()));
editConfiguration.addNewResource("researchDataUri", DEFAULT_NS_TOKEN);
editConfiguration.setN3Optional(generateN3Optional());
//In scope
setUrisAndLiteralsInScope(editConfiguration, vreq);
//on Form
setUrisAndLiteralsOnForm(editConfiguration, vreq);
//Sparql queries
setSparqlQueries(editConfiguration, vreq);
//set fields
setFields(editConfiguration);
//template file
editConfiguration.setTemplate("addResearchDataToPublication.ftl");
//Adding additional data, specifically edit mode
addFormSpecificData(editConfiguration, vreq);
//TODO: add validators
editConfiguration.addValidator(new AntiXssValidation());
//NOITCE this generator does not run prepare() since it
//is never an update and has no SPARQL for existing
return editConfiguration;
}
|
diff --git a/src/edu/berkeley/gamesman/game/Connections.java b/src/edu/berkeley/gamesman/game/Connections.java
index 64bbc868..ca13a559 100644
--- a/src/edu/berkeley/gamesman/game/Connections.java
+++ b/src/edu/berkeley/gamesman/game/Connections.java
@@ -1,190 +1,190 @@
package edu.berkeley.gamesman.game;
import edu.berkeley.gamesman.core.Configuration;
import edu.berkeley.gamesman.util.Util;
/**
* The game Connections
*
* @author dnspies
*/
public class Connections extends ConnectGame {
private class Edge {
final Point[] xPoints;
// xPoints[0] == down or left
// xPoints[1] == up or right
final Point[] oPoints;
// oPoints[0] == down or left
// oPoints[1] == up or right
private final int charNum;
Edge(int charNum) {
xPoints = new Point[2];
oPoints = new Point[2];
this.charNum = charNum;
}
char getChar() {
return board[charNum];
}
}
private class Point {
private final Edge[] edges;
// 0 == down
// 1 == left
// 2 == up
// 3 == right
private final int row, col;
// List in clockwise order
Point(int row, int col) {
this.row = row;
this.col = col;
edges = new Edge[4];
}
}
private int boardSide;
private int boardSize;
private Point[][] xPoints;
private Point[][] oPoints;
private Edge[][] vertEdges;
private Edge[][] horizEdges;
private char[] board;
/**
* @param conf
* The configuration object
*/
public void initialize(Configuration conf) {
super.initialize(conf);
- boardSide = conf.getInteger("gamesman.game.sideLength", 4);
+ boardSide = conf.getInteger("gamesman.game.side", 4);
boardSize = boardSide * boardSide + (boardSide - 1) * (boardSide - 1);
xPoints = new Point[boardSide + 1][boardSide];
// Bottom to top; Left to right
oPoints = new Point[boardSide + 1][boardSide];
// Left to right; Top to bottom
vertEdges = new Edge[boardSide][boardSide];
// Bottom to top; Left to right
horizEdges = new Edge[boardSide - 1][boardSide - 1];
// Bottom to top; Left to right (only shared edges)
board = new char[boardSize];
int ind = 0;
int horizInd = boardSide * boardSide;
for (int row = 0; row < boardSide; row++) {
for (int col = 0; col < boardSide; col++) {
vertEdges[row][col] = new Edge(ind++);
if (row < boardSide - 1 && col < boardSide - 1)
horizEdges[row][col] = new Edge(horizInd++);
}
}
for (int row = 0; row <= boardSide; row++) {
for (int col = 0; col < boardSide; col++) {
xPoints[row][col] = new Point(row, col);
oPoints[row][col] = new Point(row, col);
Edge nextXEdge = null;
Edge nextOEdge = null;
for (int i = 0; i < 4; i++) {
switch (i) {
case 0:
nextXEdge = Util.getElement(vertEdges, row - 1, col);
nextOEdge = Util.getElement(vertEdges, boardSide - 1
- col, row - 1);
break;
case 1:
nextXEdge = Util.getElement(horizEdges, row - 1,
col - 1);
nextOEdge = Util.getElement(horizEdges, boardSide - 1
- col, row - 1);
break;
case 2:
nextXEdge = Util.getElement(vertEdges, row, col);
nextOEdge = Util.getElement(vertEdges, boardSide - 1
- col, row);
break;
case 3:
nextXEdge = Util.getElement(horizEdges, row - 1, col);
nextOEdge = Util.getElement(horizEdges, boardSide - 2
- col, row - 1);
break;
}
if (nextXEdge != null) {
xPoints[row][col].edges[i] = nextXEdge;
nextXEdge.xPoints[i >> 1] = xPoints[row][col];
}
if (nextOEdge != null) {
oPoints[row][col].edges[i] = nextOEdge;
nextOEdge.oPoints[i >> 1] = oPoints[row][col];
}
}
}
}
}
@Override
protected int getBoardSize() {
return boardSize;
}
@Override
protected char[] getCharArray() {
return board;
}
@Override
protected void setToCharArray(char[] myPieces) {
if (board != myPieces) {
for (int i = 0; i < board.length; i++)
board[i] = myPieces[i];
}
}
@Override
public String displayState() {
// TODO Auto-generated method stub
return null;
}
@Override
public String describe() {
return "Connections " + boardSide + "x" + boardSide;
}
@Override
protected boolean isWin(char c) {
Point nextPoint = (c == 'X' ? xPoints[0][0] : oPoints[0][0]);
do {
nextPoint = testWin(c, nextPoint, c == 'X' ? 1 : 2);
if (nextPoint.row == boardSide)
return true;
nextPoint = Util.getElement(c == 'X' ? xPoints : oPoints, 0,
nextPoint.col + 1);
} while (nextPoint != null);
if (nextPoint == null)
return false;
else
return nextPoint.row == boardSide;
}
private Point testWin(char c, Point p, int dir) {
while (p.row != boardSide) {
Edge e = p.edges[dir];
while (e == null || e.getChar() != c) {
if (e == null)
if (dir != 1)
return p;
dir = ((dir + 1) & 3);
e = p.edges[dir];
}
int ind = 1 - (dir >> 1);
if (c == 'X')
p = e.xPoints[ind];
else
p = e.oPoints[ind];
dir = (dir - 1) & 3;
}
return p;
}
}
| true | true | public void initialize(Configuration conf) {
super.initialize(conf);
boardSide = conf.getInteger("gamesman.game.sideLength", 4);
boardSize = boardSide * boardSide + (boardSide - 1) * (boardSide - 1);
xPoints = new Point[boardSide + 1][boardSide];
// Bottom to top; Left to right
oPoints = new Point[boardSide + 1][boardSide];
// Left to right; Top to bottom
vertEdges = new Edge[boardSide][boardSide];
// Bottom to top; Left to right
horizEdges = new Edge[boardSide - 1][boardSide - 1];
// Bottom to top; Left to right (only shared edges)
board = new char[boardSize];
int ind = 0;
int horizInd = boardSide * boardSide;
for (int row = 0; row < boardSide; row++) {
for (int col = 0; col < boardSide; col++) {
vertEdges[row][col] = new Edge(ind++);
if (row < boardSide - 1 && col < boardSide - 1)
horizEdges[row][col] = new Edge(horizInd++);
}
}
for (int row = 0; row <= boardSide; row++) {
for (int col = 0; col < boardSide; col++) {
xPoints[row][col] = new Point(row, col);
oPoints[row][col] = new Point(row, col);
Edge nextXEdge = null;
Edge nextOEdge = null;
for (int i = 0; i < 4; i++) {
switch (i) {
case 0:
nextXEdge = Util.getElement(vertEdges, row - 1, col);
nextOEdge = Util.getElement(vertEdges, boardSide - 1
- col, row - 1);
break;
case 1:
nextXEdge = Util.getElement(horizEdges, row - 1,
col - 1);
nextOEdge = Util.getElement(horizEdges, boardSide - 1
- col, row - 1);
break;
case 2:
nextXEdge = Util.getElement(vertEdges, row, col);
nextOEdge = Util.getElement(vertEdges, boardSide - 1
- col, row);
break;
case 3:
nextXEdge = Util.getElement(horizEdges, row - 1, col);
nextOEdge = Util.getElement(horizEdges, boardSide - 2
- col, row - 1);
break;
}
if (nextXEdge != null) {
xPoints[row][col].edges[i] = nextXEdge;
nextXEdge.xPoints[i >> 1] = xPoints[row][col];
}
if (nextOEdge != null) {
oPoints[row][col].edges[i] = nextOEdge;
nextOEdge.oPoints[i >> 1] = oPoints[row][col];
}
}
}
}
}
| public void initialize(Configuration conf) {
super.initialize(conf);
boardSide = conf.getInteger("gamesman.game.side", 4);
boardSize = boardSide * boardSide + (boardSide - 1) * (boardSide - 1);
xPoints = new Point[boardSide + 1][boardSide];
// Bottom to top; Left to right
oPoints = new Point[boardSide + 1][boardSide];
// Left to right; Top to bottom
vertEdges = new Edge[boardSide][boardSide];
// Bottom to top; Left to right
horizEdges = new Edge[boardSide - 1][boardSide - 1];
// Bottom to top; Left to right (only shared edges)
board = new char[boardSize];
int ind = 0;
int horizInd = boardSide * boardSide;
for (int row = 0; row < boardSide; row++) {
for (int col = 0; col < boardSide; col++) {
vertEdges[row][col] = new Edge(ind++);
if (row < boardSide - 1 && col < boardSide - 1)
horizEdges[row][col] = new Edge(horizInd++);
}
}
for (int row = 0; row <= boardSide; row++) {
for (int col = 0; col < boardSide; col++) {
xPoints[row][col] = new Point(row, col);
oPoints[row][col] = new Point(row, col);
Edge nextXEdge = null;
Edge nextOEdge = null;
for (int i = 0; i < 4; i++) {
switch (i) {
case 0:
nextXEdge = Util.getElement(vertEdges, row - 1, col);
nextOEdge = Util.getElement(vertEdges, boardSide - 1
- col, row - 1);
break;
case 1:
nextXEdge = Util.getElement(horizEdges, row - 1,
col - 1);
nextOEdge = Util.getElement(horizEdges, boardSide - 1
- col, row - 1);
break;
case 2:
nextXEdge = Util.getElement(vertEdges, row, col);
nextOEdge = Util.getElement(vertEdges, boardSide - 1
- col, row);
break;
case 3:
nextXEdge = Util.getElement(horizEdges, row - 1, col);
nextOEdge = Util.getElement(horizEdges, boardSide - 2
- col, row - 1);
break;
}
if (nextXEdge != null) {
xPoints[row][col].edges[i] = nextXEdge;
nextXEdge.xPoints[i >> 1] = xPoints[row][col];
}
if (nextOEdge != null) {
oPoints[row][col].edges[i] = nextOEdge;
nextOEdge.oPoints[i >> 1] = oPoints[row][col];
}
}
}
}
}
|
diff --git a/audiobox.fm-core/src/main/java/fm/audiobox/AudioBox.java b/audiobox.fm-core/src/main/java/fm/audiobox/AudioBox.java
index 8602b33..45f379a 100644
--- a/audiobox.fm-core/src/main/java/fm/audiobox/AudioBox.java
+++ b/audiobox.fm-core/src/main/java/fm/audiobox/AudioBox.java
@@ -1,675 +1,675 @@
/***************************************************************************
* Copyright (C) 2010 iCoreTech research labs *
* Contributed code from: *
* - Valerio Chiodino - keytwo at keytwo dot net *
* - Fabio Tunno - fat at fatshotty dot net *
* *
* 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 fm.audiobox;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
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.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fm.audiobox.core.exceptions.LoginException;
import fm.audiobox.core.exceptions.ServiceException;
import fm.audiobox.core.models.AbstractCollectionEntity;
import fm.audiobox.core.models.User;
import fm.audiobox.core.observables.Event;
import fm.audiobox.interfaces.IConfiguration;
import fm.audiobox.interfaces.IConfiguration.Connectors;
import fm.audiobox.interfaces.IConfiguration.ContentFormat;
import fm.audiobox.interfaces.IConnector;
import fm.audiobox.interfaces.IEntity;
import fm.audiobox.interfaces.IFactory;
/**
* AudioBox is the main class.<br />
* It uses a {@link IConfiguration} class.
* To get information about {@link User user} use the {@link AudioBox#getUser()} method.
* <p>
*
* Keep in mind that this library provides only the common browsing actions and some other few feature.<br/>
* AudioBox does not streams, nor play or provide a BitmapFactory for albums covers.
*
* <p>
* You can extend default extendable models setting them into {@link IFactory#setEntity(String, Class)} class through {@link IConfiguration#getFactory()} method
*
* <p>
*
* Note that some of the requests, such as the {@link AbstractCollectionEntity} population requests, can be done
* asynchronously.<br/>
* To keep track of the collection building process you can use {@link Observer}.
*
*/
public class AudioBox extends Observable {
private static Logger log = LoggerFactory.getLogger(AudioBox.class);
/** Prefix used to store each property into properties file */
public static final String PREFIX = AudioBox.class.getPackage().getName() + ".";
private final IConfiguration configuration;
private User user;
/**
* Creates a new {@code AudioBox} instance ready to be used
* @param config the {@link IConfiguration} used by this instance
*/
public AudioBox(IConfiguration config) {
this(config, IConfiguration.Environments.live);
}
/**
* Creates a new {@code AudioBox} instance ready to be used
* @param config the {@link IConfiguration} used by this instance
*/
public AudioBox(IConfiguration config, IConfiguration.Environments env) {
log.trace("New AudioBox is going to be instantiated");
this.configuration = config;
this.setEnvironment(env);
log.trace("New AudioBox correctly instantiated");
}
/**
* @return Returns the {@code environment} of the connectors
*/
public IConfiguration.Environments getEnvironment(){
return this.configuration.getEnvironment();
}
/**
* This method is used for setting the {@code environemnt} of the connectors
*/
@SuppressWarnings("deprecation")
public void setEnvironment(IConfiguration.Environments env) {
this.configuration.setEnvironment(env);
// Create connectors
IConnector standardConnector = new Connector(IConfiguration.Connectors.RAILS);
IConnector uploaderConnector = new Connector(IConfiguration.Connectors.NODE);
IConnector daemonerConnector = new Connector(IConfiguration.Connectors.DAEMON);
this.configuration.getFactory().addConnector(IConfiguration.Connectors.RAILS, standardConnector );
this.configuration.getFactory().addConnector(IConfiguration.Connectors.NODE, uploaderConnector );
this.configuration.getFactory().addConnector(IConfiguration.Connectors.DAEMON, daemonerConnector );
log.info("Environment set to: " + env);
}
/**
* Getter method for the {@link User user} Object
* <p>Note: it can be {@code null} if {@code user} is not logged in<p>
*
* @return current {@link User} instance
*/
public User getUser(){
return this.user;
}
/**
* This is the main method returns the {@link User} instance.
* <p>
* It performs a login on AudioBox.fm and returns the logged in User.
* </p>
*
* <p>
* It fires the {@link Event.States#CONNECTED} event passing the {@link User}.
* </p>
*
* @param username is the {@code email} of the user
* @param password of the User
* @param async make this request asynchronously. <b>{@code async} should be always {@code false}</b>
*
* @return the {@link User} instance if everything went ok
*
* @throws LoginException identifies invalid credentials or user cannot be logged in due to subscription error.
* @throws ServiceException if any connection problem occurs.
*/
public User login(final String username, final String password, boolean async) throws LoginException, ServiceException {
log.info("Executing login for user: " + username);
// Destroy old user's pointer
this.logout();
User user = (User) this.configuration.getFactory().getEntity(User.TAGNAME, this.getConfiguration() );
user.setUsername(username);
user.setPassword( password );
user.load(async);
// User can now be set. Note: set user before notifing observers
this.user = user;
// User has been authenticated, notify observers
Event event = new Event(this.user, Event.States.CONNECTED);
this.setChanged();
this.notifyObservers(event);
return this.user;
}
/**
* It calls the {@link AudioBox#login(String, String, boolean)} passing {@code false} as {@code async}
* switch
* @param username is the {@code email} of the user
* @param password of the User
*
* @return the {@link User} instance if everything went ok
*/
public User login(String username, String password) throws LoginException, ServiceException {
return this.login( username, password, false);
}
/**
* Logouts the current logged in {@link User}.
* <p>
* This method clear the {@link User} instance and
* fires the {@link Event.States#DISCONNECTED} passing no arguments
* </p>
* <p>
* <b>Note: this method set User to {@code null}</b>
* </p>
*
* @return boolean: {@code true} if User has been logged out. {@code false} if no logged in user found
*/
public boolean logout() {
if ( this.user != null ) {
// Destroy old user's pointer
this.user = null;
// notify all observer User has been destroyed
Event event = new Event(new Object(), Event.States.DISCONNECTED);
this.setChanged();
this.notifyObservers(event);
return true;
}
return false;
}
/**
* Gets current {@link IConfiguration} related to this instance
* @return current {@link IConfiguration}
*/
public IConfiguration getConfiguration(){
return this.configuration;
}
/**
* Connector is the AudioBox http request wrapper.
*
* <p>
* This class intantiates a {@link IConnector.IConnectionMethod} used for
* invoking AudioBox.fm server through HTTP requests
* </p>
* <p>
* Note: you can use your own {@code IConnection} class
* using {@link IFactory#addConnector(Connectors, IConnector)} method
* </p>
*/
public class Connector implements Serializable, IConnector {
private final Logger log = LoggerFactory.getLogger(Connector.class);
private static final long serialVersionUID = -1947929692214926338L;
// Default value of the server
private IConfiguration.Connectors SERVER = IConfiguration.Connectors.RAILS;
/** Get informations from configuration file */
private String PROTOCOL = "";
private String HOST = "";
private String PORT = "";
private String API_PATH = "";
private ThreadSafeClientConnManager mCm;
private DefaultHttpClient mClient;
/** Default constructor builds http connector */
protected Connector(IConfiguration.Connectors server) {
log.debug("New Connector is going to be instantiated, server: " + server.toString() );
SERVER = server;
PROTOCOL = configuration.getProtocol( SERVER );
HOST = configuration.getHost( SERVER );
PORT = String.valueOf( configuration.getPort( SERVER ) );
API_PATH = PROTOCOL + "://" + HOST + ":" + PORT;
log.info("Remote host for " + server.toString() + " will be: " + API_PATH );
buildClient();
}
public void abort() {
this.destroy();
buildClient();
}
public void destroy() {
log.warn("All older requests will be aborted");
this.mCm.shutdown();
this.mCm = null;
this.mClient = null;
}
/**
* Use this method to configure the timeout limit for reqests made against AudioBox.fm.
*
* @param timeout the milliseconds of the timeout limit
*/
public void setTimeout(int timeout) {
log.info("Setting timeout parameter to: " + timeout);
HttpConnectionParams.setConnectionTimeout( mClient.getParams() , timeout);
}
public int getTimeout() {
return HttpConnectionParams.getConnectionTimeout( mClient.getParams() );
}
/**
* Creates a HttpRequestBase
*
* @param httpVerb the HTTP method to use for the request (ie: GET, PUT, POST and DELETE)
* @param source usually reffers the Model that invokes method
* @param dest Model that intercepts the response
* @param action the remote action to execute on the model that executes the action (ex. "scrobble")
* @param entity HttpEntity used by POST and PUT method
*
* @return the HttpRequestBase
*/
private HttpRequestBase createConnectionMethod(String httpVerb, String path, String action, ContentFormat format, List<NameValuePair> params) {
if ( httpVerb == null ) {
httpVerb = IConnectionMethod.METHOD_GET;
}
String url = this.buildRequestUrl(path, action, httpVerb, format, params);
HttpRequestBase method = null;
if ( IConnectionMethod.METHOD_POST.equals( httpVerb ) ) {
log.debug("Building HttpMethod POST");
method = new HttpPost(url);
} else if ( IConnectionMethod.METHOD_PUT.equals( httpVerb ) ) {
log.debug("Building HttpMethod PUT");
method = new HttpPut(url);
} else if ( IConnectionMethod.METHOD_DELETE.equals( httpVerb ) ) {
log.debug("Building HttpMethod DELETE");
method = new HttpDelete(url);
} else if ( IConnectionMethod.METHOD_HEAD.equals( httpVerb ) ) {
log.debug("Building HttpMethod HEAD");
method = new HttpHead(url);
} else {
log.debug("Building HttpMethod GET");
method = new HttpGet(url);
}
log.info( "[ " + httpVerb + " ] " + url );
if ( log.isDebugEnabled() ) {
log.debug("Setting default headers");
log.debug("-> Accept-Encoding: gzip");
log.debug("-> User-Agent: " + getConfiguration().getUserAgent() );
}
if ( getConfiguration().getEnvironment() == IConfiguration.Environments.live ){
method.addHeader("Accept-Encoding", "gzip");
}
method.addHeader("User-Agent", getConfiguration().getUserAgent());
return method;
}
public IConnectionMethod head(IEntity destEntity, String action, List<NameValuePair> params) {
return head(destEntity, destEntity.getApiPath(), action, params);
}
public IConnectionMethod head(IEntity destEntity, String path, String action, List<NameValuePair> params) {
return head(destEntity, path, action, getConfiguration().getRequestFormat(), params);
}
public IConnectionMethod head(IEntity destEntity, String path, String action, ContentFormat format, List<NameValuePair> params) {
IConnectionMethod method = getConnectionMethod();
if ( method != null ) {
HttpRequestBase originalMethod = this.createConnectionMethod(IConnectionMethod.METHOD_HEAD, path, action, format, params);
method.init(destEntity, originalMethod, this.mClient, getConfiguration(), format );
method.setUser( user );
}
return method;
}
public IConnectionMethod get(IEntity destEntity, String action, List<NameValuePair> params) {
return get(destEntity, destEntity.getApiPath(), action, params);
}
public IConnectionMethod get(IEntity destEntity, String path, String action, List<NameValuePair> params) {
return get(destEntity, path, action, getConfiguration().getRequestFormat(), params);
}
public IConnectionMethod get(IEntity destEntity, String path, String action, ContentFormat format, List<NameValuePair> params) {
IConnectionMethod method = getConnectionMethod();
if ( method != null ) {
HttpRequestBase originalMethod = this.createConnectionMethod(IConnectionMethod.METHOD_GET, path, action, format, params);
method.init(destEntity, originalMethod, this.mClient, getConfiguration(), format );
method.setUser( user );
}
return method;
}
public IConnectionMethod put(IEntity destEntity, String action) {
return put(destEntity, destEntity.getApiPath(), action, getConfiguration().getRequestFormat() );
}
public IConnectionMethod put(IEntity destEntity, String path, String action) {
return put(destEntity, path, action, getConfiguration().getRequestFormat() );
}
public IConnectionMethod put(IEntity destEntity, String path, String action, ContentFormat format) {
IConnectionMethod method = getConnectionMethod();
if ( method != null ) {
HttpRequestBase originalMethod = this.createConnectionMethod(IConnectionMethod.METHOD_PUT, path, action, format, null);
method.init(destEntity, originalMethod, this.mClient, getConfiguration(), format );
method.setUser( user );
}
return method;
}
public IConnectionMethod post(IEntity destEntity, String action) {
return this.post(destEntity, destEntity.getApiPath(), action);
}
public IConnectionMethod post(IEntity destEntity, String path, String action) {
return this.post(destEntity, path, action, getConfiguration().getRequestFormat());
}
public IConnectionMethod post(IEntity destEntity, String path, String action, ContentFormat format) {
IConnectionMethod method = getConnectionMethod();
if ( method != null ) {
HttpRequestBase originalMethod = this.createConnectionMethod(IConnectionMethod.METHOD_POST, path, action, format, null);
method.init(destEntity, originalMethod, this.mClient, getConfiguration(), format );
method.setUser( user );
}
return method;
}
public IConnectionMethod delete(IEntity destEntity, String action, List<NameValuePair> params) {
return delete(destEntity, destEntity.getApiPath(), action, params);
}
public IConnectionMethod delete(IEntity destEntity, String path, String action, List<NameValuePair> params) {
return delete(destEntity, path, action, getConfiguration().getRequestFormat(), params);
}
public IConnectionMethod delete(IEntity destEntity, String path, String action, ContentFormat format, List<NameValuePair> params) {
IConnectionMethod method = getConnectionMethod();
if ( method != null ) {
HttpRequestBase originalMethod = this.createConnectionMethod(IConnectionMethod.METHOD_DELETE, path, action, format, params);
method.init(destEntity, originalMethod, this.mClient, getConfiguration(), format );
method.setUser( user );
}
return method;
}
/* --------------- */
/* Private methods */
/* --------------- */
/**
* This method is used to build the HttpClient used for connections
*/
private void buildClient() {
// this.mAudioBoxRoute = new HttpRoute(new HttpHost( HOST, Integer.parseInt(PORT) ) );
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), Integer.parseInt( PORT ) ));
schemeRegistry.register( new Scheme("https", SSLSocketFactory.getSocketFactory(), 443 ));
HttpParams params = new BasicHttpParams();
- params.setParameter("http.protocol.-charset", "UTF-8");
+ params.setParameter("http.protocol.content-charset", "UTF-8");
HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
HttpConnectionParams.setSoTimeout(params, 30 * 1000);
ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(50));
this.mCm = new ThreadSafeClientConnManager(params, schemeRegistry);
this.mClient = new DefaultHttpClient( this.mCm, params );
this.mClient.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
long keepAlive = super.getKeepAliveDuration(response, context);
if (keepAlive == -1) {
// Keep connections alive 5 seconds if a keep-alive value
// has not be explicitly set by the server
keepAlive = 5000;
}
return keepAlive;
}
});
if ( log.isDebugEnabled() ) {
this.mClient.addRequestInterceptor(new HttpRequestInterceptor() {
public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException {
log.debug("New request detected");
}
});
}
this.mClient.addResponseInterceptor(new HttpResponseInterceptor() {
public void process( final HttpResponse response, final HttpContext context) throws HttpException, IOException {
log.trace("New response intercepted");
HttpEntity entity = response.getEntity();
if (entity != null) {
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
log.info("Response is gzipped");
response.setEntity(new HttpEntityWrapper(entity){
private GZIPInputStream stream = null;
@Override
public InputStream getContent() throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
if ( stream == null ) {
InputStream wrappedin = wrappedEntity.getContent();
stream = new GZIPInputStream(wrappedin);
}
return stream;
}
@Override
public long getContentLength() { return 1; }
});
return;
}
}
}
}
}
});
}
/**
* This method creates a {@link IConnector.IConnectionMethod} class
* that will be used for invoking AudioBox.fm servers
* <p>
* Note: you can use your own {@code IConnectionMethod} class using {@link IConfiguration#setHttpMethodType(Class)} method
* </p>
* @return the {@link IConnector.IConnectionMethod} associated with this {@link AudioBox} class
*/
protected IConnectionMethod getConnectionMethod(){
Class<? extends IConnectionMethod> klass = getConfiguration().getHttpMethodType();
if ( log.isDebugEnabled() )
log.trace("Instantiating IConnectionMethod by class: " + klass.getName() );
try {
IConnectionMethod method = klass.newInstance();
return method;
} catch (InstantiationException e) {
log.error("An error occurred while instantiating IConnectionMethod class", e);
} catch (IllegalAccessException e) {
log.error("An error occurred while accessing to IConnectionMethod class", e);
}
return null;
}
/**
* Creates the correct url starting from parameters
*
* @param entityPath the partial url to call. Typically this is the {@link IEntity#getApiPath()}
* @param action the {@code namespace} of the {@link IEntity} your are invoking. Typically this is the {@link IEntity#getNamespace()}
* @param httpVerb one of {@link IConnector.IConnectionMethod#METHOD_GET GET} {@link IConnector.IConnectionMethod#METHOD_POST POST} {@link IConnector.IConnectionMethod#METHOD_PUT PUT} {@link IConnector.IConnectionMethod#METHOD_DELETE DELETE}
* @param format the {@link ContentFormat} for this request
* @param params the query string parameters used for this request. <b>Used in case of {@link IConnector.IConnectionMethod#METHOD_GET GET} {@link IConnector.IConnectionMethod#METHOD_DELETE DELETE} only</b>
* @return the URL string
*/
protected String buildRequestUrl(String entityPath, String action, String httpVerb, ContentFormat format, List<NameValuePair> params) {
if ( params == null ){
params = new ArrayList<NameValuePair>();
}
if ( httpVerb == null ) {
httpVerb = IConnectionMethod.METHOD_GET;
}
action = ( ( action == null ) ? "" : IConnector.URI_SEPARATOR.concat(action) ).trim();
String url = API_PATH + configuration.getPath( SERVER ) + entityPath + action;
// add extension to request path
if ( format != null ){
url += IConnector.DOT + format.toString().toLowerCase();
}
if ( httpVerb.equals( IConnectionMethod.METHOD_GET ) || httpVerb.equals( IConnectionMethod.METHOD_DELETE ) || httpVerb.equals( IConnectionMethod.METHOD_HEAD ) ){
String query = URLEncodedUtils.format( params , HTTP.UTF_8 );
if ( query.length() > 0 )
url += "?" + query;
}
return url;
}
}
}
| true | true | private void buildClient() {
// this.mAudioBoxRoute = new HttpRoute(new HttpHost( HOST, Integer.parseInt(PORT) ) );
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), Integer.parseInt( PORT ) ));
schemeRegistry.register( new Scheme("https", SSLSocketFactory.getSocketFactory(), 443 ));
HttpParams params = new BasicHttpParams();
params.setParameter("http.protocol.-charset", "UTF-8");
HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
HttpConnectionParams.setSoTimeout(params, 30 * 1000);
ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(50));
this.mCm = new ThreadSafeClientConnManager(params, schemeRegistry);
this.mClient = new DefaultHttpClient( this.mCm, params );
this.mClient.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
long keepAlive = super.getKeepAliveDuration(response, context);
if (keepAlive == -1) {
// Keep connections alive 5 seconds if a keep-alive value
// has not be explicitly set by the server
keepAlive = 5000;
}
return keepAlive;
}
});
if ( log.isDebugEnabled() ) {
this.mClient.addRequestInterceptor(new HttpRequestInterceptor() {
public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException {
log.debug("New request detected");
}
});
}
this.mClient.addResponseInterceptor(new HttpResponseInterceptor() {
public void process( final HttpResponse response, final HttpContext context) throws HttpException, IOException {
log.trace("New response intercepted");
HttpEntity entity = response.getEntity();
if (entity != null) {
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
log.info("Response is gzipped");
response.setEntity(new HttpEntityWrapper(entity){
private GZIPInputStream stream = null;
@Override
public InputStream getContent() throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
if ( stream == null ) {
InputStream wrappedin = wrappedEntity.getContent();
stream = new GZIPInputStream(wrappedin);
}
return stream;
}
@Override
public long getContentLength() { return 1; }
});
return;
}
}
}
}
}
});
}
| private void buildClient() {
// this.mAudioBoxRoute = new HttpRoute(new HttpHost( HOST, Integer.parseInt(PORT) ) );
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), Integer.parseInt( PORT ) ));
schemeRegistry.register( new Scheme("https", SSLSocketFactory.getSocketFactory(), 443 ));
HttpParams params = new BasicHttpParams();
params.setParameter("http.protocol.content-charset", "UTF-8");
HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
HttpConnectionParams.setSoTimeout(params, 30 * 1000);
ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(50));
this.mCm = new ThreadSafeClientConnManager(params, schemeRegistry);
this.mClient = new DefaultHttpClient( this.mCm, params );
this.mClient.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
long keepAlive = super.getKeepAliveDuration(response, context);
if (keepAlive == -1) {
// Keep connections alive 5 seconds if a keep-alive value
// has not be explicitly set by the server
keepAlive = 5000;
}
return keepAlive;
}
});
if ( log.isDebugEnabled() ) {
this.mClient.addRequestInterceptor(new HttpRequestInterceptor() {
public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException {
log.debug("New request detected");
}
});
}
this.mClient.addResponseInterceptor(new HttpResponseInterceptor() {
public void process( final HttpResponse response, final HttpContext context) throws HttpException, IOException {
log.trace("New response intercepted");
HttpEntity entity = response.getEntity();
if (entity != null) {
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
log.info("Response is gzipped");
response.setEntity(new HttpEntityWrapper(entity){
private GZIPInputStream stream = null;
@Override
public InputStream getContent() throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
if ( stream == null ) {
InputStream wrappedin = wrappedEntity.getContent();
stream = new GZIPInputStream(wrappedin);
}
return stream;
}
@Override
public long getContentLength() { return 1; }
});
return;
}
}
}
}
}
});
}
|
diff --git a/src/com/android/browser/AddBookmarkPage.java b/src/com/android/browser/AddBookmarkPage.java
index 7878762a..71bf481b 100644
--- a/src/com/android/browser/AddBookmarkPage.java
+++ b/src/com/android/browser/AddBookmarkPage.java
@@ -1,183 +1,183 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.ParseException;
import android.net.WebAddress;
import android.os.Bundle;
import android.provider.Browser;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
public class AddBookmarkPage extends Activity {
private final String LOGTAG = "Bookmarks";
private EditText mTitle;
private EditText mAddress;
private TextView mButton;
private View mCancelButton;
private boolean mEditingExisting;
private Bundle mMap;
private String mTouchIconUrl;
private Bitmap mThumbnail;
private String mOriginalUrl;
private View.OnClickListener mSaveBookmark = new View.OnClickListener() {
public void onClick(View v) {
if (save()) {
finish();
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_saved,
Toast.LENGTH_LONG).show();
}
}
};
private View.OnClickListener mCancel = new View.OnClickListener() {
public void onClick(View v) {
finish();
}
};
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.browser_add_bookmark);
setTitle(R.string.save_to_bookmarks);
getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.ic_dialog_bookmark);
String title = null;
String url = null;
mMap = getIntent().getExtras();
if (mMap != null) {
Bundle b = mMap.getBundle("bookmark");
if (b != null) {
mMap = b;
mEditingExisting = true;
setTitle(R.string.edit_bookmark);
}
title = mMap.getString("title");
url = mOriginalUrl = mMap.getString("url");
mTouchIconUrl = mMap.getString("touch_icon_url");
mThumbnail = (Bitmap) mMap.getParcelable("thumbnail");
}
mTitle = (EditText) findViewById(R.id.title);
mTitle.setText(title);
mAddress = (EditText) findViewById(R.id.address);
mAddress.setText(url);
View.OnClickListener accept = mSaveBookmark;
mButton = (TextView) findViewById(R.id.OK);
mButton.setOnClickListener(accept);
mCancelButton = findViewById(R.id.cancel);
mCancelButton.setOnClickListener(mCancel);
if (!getWindow().getDecorView().isInTouchMode()) {
mButton.requestFocus();
}
}
/**
* Save the data to the database.
* Also, change the view to dialog stating
* that the webpage has been saved.
*/
boolean save() {
String title = mTitle.getText().toString().trim();
String unfilteredUrl =
BrowserActivity.fixUrl(mAddress.getText().toString());
boolean emptyTitle = title.length() == 0;
boolean emptyUrl = unfilteredUrl.trim().length() == 0;
Resources r = getResources();
if (emptyTitle || emptyUrl) {
if (emptyTitle) {
mTitle.setError(r.getText(R.string.bookmark_needs_title));
}
if (emptyUrl) {
mAddress.setError(r.getText(R.string.bookmark_needs_url));
}
return false;
}
String url = unfilteredUrl;
try {
URI uriObj = new URI(url);
String scheme = uriObj.getScheme();
if (!("about".equals(scheme) || "data".equals(scheme)
|| "javascript".equals(scheme)
|| "file".equals(scheme) || "content".equals(scheme))) {
WebAddress address;
try {
address = new WebAddress(unfilteredUrl);
} catch (ParseException e) {
throw new URISyntaxException("", "");
}
if (address.mHost.length() == 0) {
throw new URISyntaxException("", "");
}
url = address.toString();
}
} catch (URISyntaxException e) {
mAddress.setError(r.getText(R.string.bookmark_url_not_valid));
return false;
}
try {
if (mEditingExisting) {
mMap.putString("title", title);
mMap.putString("url", url);
setResult(RESULT_OK, (new Intent()).setAction(
getIntent().toString()).putExtras(mMap));
} else {
final ContentResolver cr = getContentResolver();
// Only use mThumbnail if url and mOriginalUrl are matches.
// Otherwise the user edited the url and the thumbnail no longer applies.
- if (mOriginalUrl.equals(url)) {
+ if (url.equals(mOriginalUrl)) {
Bookmarks.addBookmark(null, cr, url, title, mThumbnail, true);
} else {
Bookmarks.addBookmark(null, cr, url, title, null, true);
}
if (mTouchIconUrl != null) {
final Cursor c =
BrowserBookmarksAdapter.queryBookmarksForUrl(
cr, null, url, true);
new DownloadTouchIcon(cr, c, url).execute(mTouchIconUrl);
}
setResult(RESULT_OK);
}
} catch (IllegalStateException e) {
setTitle(r.getText(R.string.no_database));
return false;
}
return true;
}
}
| true | true | boolean save() {
String title = mTitle.getText().toString().trim();
String unfilteredUrl =
BrowserActivity.fixUrl(mAddress.getText().toString());
boolean emptyTitle = title.length() == 0;
boolean emptyUrl = unfilteredUrl.trim().length() == 0;
Resources r = getResources();
if (emptyTitle || emptyUrl) {
if (emptyTitle) {
mTitle.setError(r.getText(R.string.bookmark_needs_title));
}
if (emptyUrl) {
mAddress.setError(r.getText(R.string.bookmark_needs_url));
}
return false;
}
String url = unfilteredUrl;
try {
URI uriObj = new URI(url);
String scheme = uriObj.getScheme();
if (!("about".equals(scheme) || "data".equals(scheme)
|| "javascript".equals(scheme)
|| "file".equals(scheme) || "content".equals(scheme))) {
WebAddress address;
try {
address = new WebAddress(unfilteredUrl);
} catch (ParseException e) {
throw new URISyntaxException("", "");
}
if (address.mHost.length() == 0) {
throw new URISyntaxException("", "");
}
url = address.toString();
}
} catch (URISyntaxException e) {
mAddress.setError(r.getText(R.string.bookmark_url_not_valid));
return false;
}
try {
if (mEditingExisting) {
mMap.putString("title", title);
mMap.putString("url", url);
setResult(RESULT_OK, (new Intent()).setAction(
getIntent().toString()).putExtras(mMap));
} else {
final ContentResolver cr = getContentResolver();
// Only use mThumbnail if url and mOriginalUrl are matches.
// Otherwise the user edited the url and the thumbnail no longer applies.
if (mOriginalUrl.equals(url)) {
Bookmarks.addBookmark(null, cr, url, title, mThumbnail, true);
} else {
Bookmarks.addBookmark(null, cr, url, title, null, true);
}
if (mTouchIconUrl != null) {
final Cursor c =
BrowserBookmarksAdapter.queryBookmarksForUrl(
cr, null, url, true);
new DownloadTouchIcon(cr, c, url).execute(mTouchIconUrl);
}
setResult(RESULT_OK);
}
} catch (IllegalStateException e) {
setTitle(r.getText(R.string.no_database));
return false;
}
return true;
}
| boolean save() {
String title = mTitle.getText().toString().trim();
String unfilteredUrl =
BrowserActivity.fixUrl(mAddress.getText().toString());
boolean emptyTitle = title.length() == 0;
boolean emptyUrl = unfilteredUrl.trim().length() == 0;
Resources r = getResources();
if (emptyTitle || emptyUrl) {
if (emptyTitle) {
mTitle.setError(r.getText(R.string.bookmark_needs_title));
}
if (emptyUrl) {
mAddress.setError(r.getText(R.string.bookmark_needs_url));
}
return false;
}
String url = unfilteredUrl;
try {
URI uriObj = new URI(url);
String scheme = uriObj.getScheme();
if (!("about".equals(scheme) || "data".equals(scheme)
|| "javascript".equals(scheme)
|| "file".equals(scheme) || "content".equals(scheme))) {
WebAddress address;
try {
address = new WebAddress(unfilteredUrl);
} catch (ParseException e) {
throw new URISyntaxException("", "");
}
if (address.mHost.length() == 0) {
throw new URISyntaxException("", "");
}
url = address.toString();
}
} catch (URISyntaxException e) {
mAddress.setError(r.getText(R.string.bookmark_url_not_valid));
return false;
}
try {
if (mEditingExisting) {
mMap.putString("title", title);
mMap.putString("url", url);
setResult(RESULT_OK, (new Intent()).setAction(
getIntent().toString()).putExtras(mMap));
} else {
final ContentResolver cr = getContentResolver();
// Only use mThumbnail if url and mOriginalUrl are matches.
// Otherwise the user edited the url and the thumbnail no longer applies.
if (url.equals(mOriginalUrl)) {
Bookmarks.addBookmark(null, cr, url, title, mThumbnail, true);
} else {
Bookmarks.addBookmark(null, cr, url, title, null, true);
}
if (mTouchIconUrl != null) {
final Cursor c =
BrowserBookmarksAdapter.queryBookmarksForUrl(
cr, null, url, true);
new DownloadTouchIcon(cr, c, url).execute(mTouchIconUrl);
}
setResult(RESULT_OK);
}
} catch (IllegalStateException e) {
setTitle(r.getText(R.string.no_database));
return false;
}
return true;
}
|
diff --git a/framework/test/integrationtest-java/test/test/SimpleTest.java b/framework/test/integrationtest-java/test/test/SimpleTest.java
index 9b960a730..ea80c2232 100644
--- a/framework/test/integrationtest-java/test/test/SimpleTest.java
+++ b/framework/test/integrationtest-java/test/test/SimpleTest.java
@@ -1,313 +1,313 @@
/*
* Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
*/
package test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import controllers.routes;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.*;
import play.libs.Json;
import play.mvc.*;
import play.test.*;
import play.data.DynamicForm;
import play.data.validation.ValidationError;
import play.data.validation.Constraints.RequiredValidator;
import play.i18n.Lang;
import play.libs.F;
import play.libs.F.*;
import play.libs.ws.*;
import models.JCustomer;
import play.data.Form;
import static play.test.Helpers.*;
import static org.fest.assertions.Assertions.*;
public class SimpleTest {
@Test
public void simpleCheck() {
int a = 1 + 1;
assertThat(a).isEqualTo(2);
}
@Test
public void sessionCookieShouldOverrideOldValue() {
running(fakeApplication(), new Runnable() {
Boolean shouldNotBeCalled = false;
@Override
public void run() {
FakeRequest req = fakeRequest();
for (int i = 0; i < 5; i++) {
req = req.withSession("key" + i, "value" + i);
}
for (int i = 0; i < 5; i++) {
if (!req.getWrappedRequest().session().get("key" + i).isDefined()) {
shouldNotBeCalled = true;
}
}
assertThat(shouldNotBeCalled).isEqualTo(false);
}
});
}
@Test
public void renderTemplate() {
Content html = views.html.index.render("Coco");
assertThat(contentType(html)).isEqualTo("text/html");
assertThat(contentAsString(html)).contains("Coco");
}
@Test
public void callIndex() {
Result result = callAction(controllers.routes.ref.Application.index("Kiki"));
assertThat(status(result)).isEqualTo(OK);
assertThat(contentType(result)).isEqualTo("text/html");
assertThat(charset(result)).isEqualTo("utf-8");
assertThat(contentAsString(result)).contains("Hello Kiki");
}
@Test
public void badRoute() {
Result result = routeAndCall(fakeRequest(GET, "/xx/Kiki"));
assertThat(result).isNull();
}
@Test
public void routeIndex() {
Result result = routeAndCall(fakeRequest(GET, "/Kiki"));
assertThat(status(result)).isEqualTo(OK);
assertThat(contentType(result)).isEqualTo("text/html");
assertThat(charset(result)).isEqualTo("utf-8");
assertThat(contentAsString(result)).contains("Hello Kiki");
}
@Test
public void inApp() {
running(fakeApplication(), new Runnable() {
public void run() {
Result result = routeAndCall(fakeRequest(GET, "/key"));
assertThat(status(result)).isEqualTo(OK);
assertThat(contentType(result)).isEqualTo("text/plain");
assertThat(charset(result)).isEqualTo("utf-8");
assertThat(contentAsString(result)).contains("secret");
}
});
}
@Test
public void inServer() {
running(testServer(3333), HTMLUNIT, new Callback<TestBrowser>() {
public void invoke(TestBrowser browser) {
browser.goTo("http://localhost:3333");
assertThat(browser.$("#title").getTexts().get(0)).isEqualTo("Hello Guest");
browser.$("a").click();
assertThat(browser.url()).isEqualTo("http://localhost:3333/Coco");
assertThat(browser.$("#title", 0).getText()).isEqualTo("Hello Coco");
}
});
}
@Test
public void errorsAsJson() {
running(fakeApplication(), new Runnable() {
@Override
public void run() {
Lang lang = new Lang(new play.api.i18n.Lang("en", ""));
Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
List<ValidationError> error = new ArrayList<ValidationError>();
error.add(new ValidationError("foo", RequiredValidator.message, new ArrayList<Object>()));
errors.put("foo", error);
DynamicForm form = new DynamicForm(new HashMap<String, String>(), errors, F.None());
JsonNode jsonErrors = form.errorsAsJson(lang);
assertThat(jsonErrors.findPath("foo").iterator().next().asText()).isEqualTo(play.i18n.Messages.get(lang, RequiredValidator.message));
}
});
}
/**
* Checks that we can build fake request with a json body.
* In this test, we use the default method (POST).
*/
@Test
public void withJsonBody() {
running(fakeApplication(), new Runnable() {
@Override
public void run() {
Map map = new HashMap();
map.put("key1", "val1");
map.put("key2", 2);
map.put("key3", true);
JsonNode node = Json.toJson(map);
Result result = routeAndCall(fakeRequest("POST", "/json").withJsonBody(node));
assertThat(status(result)).isEqualTo(OK);
assertThat(contentType(result)).isEqualTo("application/json");
JsonNode node2 = Json.parse(contentAsString(result));
assertThat(node2.get("key1").asText()).isEqualTo("val1");
assertThat(node2.get("key2").asInt()).isEqualTo(2);
assertThat(node2.get("key3").asBoolean()).isTrue();
}
});
}
/**
* Checks that we can build fake request with a json body.
* In this test we specify the method to use (DELETE)
*/
@Test
public void withJsonBodyAndSpecifyMethod() {
running(fakeApplication(), new Runnable() {
@Override
public void run() {
Map map = new HashMap();
map.put("key1", "val1");
map.put("key2", 2);
map.put("key3", true);
JsonNode node = Json.toJson(map);
Result result = callAction(routes.ref.Application.getIdenticalJson(),
fakeRequest().withJsonBody(node, "DELETE"));
assertThat(status(result)).isEqualTo(OK);
assertThat(contentType(result)).isEqualTo("application/json");
JsonNode node2 = Json.parse(contentAsString(result));
assertThat(node2.get("key1").asText()).isEqualTo("val1");
assertThat(node2.get("key2").asInt()).isEqualTo(2);
assertThat(node2.get("key3").asBoolean()).isTrue();
}
});
}
@Test
public void asyncResult() {
running(fakeApplication(), new Runnable() {
@Override
public void run() {
Result result = route(fakeRequest(
GET, "/async"));
assertThat(status(result)).isEqualTo(OK);
assertThat(charset(result)).isEqualTo("utf-8");
assertThat(contentAsString(result)).isEqualTo("success");
assertThat(contentType(result)).isEqualTo("text/plain");
assertThat(header("header_test", result)).isEqualTo(
"header_val");
assertThat(session(result).get("session_test")).isEqualTo(
"session_val");
assertThat(cookie("cookie_test", result).value()).isEqualTo(
"cookie_val");
assertThat(flash(result).get("flash_test")).isEqualTo(
"flash_val");
}
});
}
@Test
- public void nestedContraints() {
+ public void nestedConstraints() {
Form<JCustomer> customerForm = new Form<JCustomer>(JCustomer.class);
// email constraints
assertThat(customerForm.field("email").constraints().size()).as(
"field(\"email\").constraints().size()").isEqualTo(2);
assertThat(customerForm.field("email").constraints().get(0)._1).as(
"field(\"email\").constraints(0)")
.isEqualTo("constraint.email");
assertThat(customerForm.field("email").constraints().get(1)._1).as(
"field(\"email\").constraints(1)").isEqualTo(
"constraint.required");
// orders[0].date constraints
assertThat(customerForm.field("orders[0].date").constraints().size())
.as("field(\"orders[0].date\").constraints().size()")
.isEqualTo(1);
assertThat(customerForm.field("orders[0].date").constraints().get(0)._1)
.as("field(\"orders[0].date\").constraints(0)").isEqualTo(
"constraint.required");
// orders[0].date format
assertThat(customerForm.field("orders[0].date").format()._1).as(
"field(\"orders[0].date\").format()._1").isEqualTo(
"format.date");
assertThat(customerForm.field("orders[0].date").format()._2.toString())
.as("field(\"orders[0].date\").format()._2").isEqualTo(
"[yyyy-MM-dd]");
// orders[0].items[0].qty constraints
assertThat(
customerForm.field("orders[0].items[0].qty").constraints()
.size()).as(
"field(\"orders[0].items[0].qty\").constraints().size()")
.isEqualTo(2);
assertThat(
customerForm.field("orders[0].items[0].qty").constraints()
.get(0)._1).as(
"field(\"orders[0].items[0].qty\").constraints(0)").isEqualTo(
"constraint.min");
assertThat(
customerForm.field("orders[0].items[0].qty").constraints()
.get(0)._2.toString()).as(
"field(\"orders[0].items[0].qty\").constraints(0)._2")
.isEqualTo("[1]");
assertThat(
customerForm.field("orders[0].items[0].qty").constraints()
.get(1)._1).as(
"field(\"orders[0].items[0].qty\").constraints(1)").isEqualTo(
"constraint.required");
// orders[0].items[0].productCode constraints
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().size())
.as("field(\"orders[0].items[0].productCode\").constraints().size()")
.isEqualTo(2);
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().get(0)._1).as(
"field(\"orders[0].items[0].productCode\").constraints(0)")
.isEqualTo("constraint.pattern");
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().get(0)._2.size()).as(
"field(\"orders[0].items[0].productCode\").constraints(0)")
.isEqualTo(1);
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().get(0)._2.get(0)).as(
"field(\"orders[0].items[0].productCode\").constraints(0)")
.isEqualTo("[A-Z]{4}-[0-9]{3,}");
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().get(1)._1).as(
"field(\"orders[0].items[0].productCode\").constraints(1)")
.isEqualTo("constraint.required");
// orders[0].items[0].deliveryDate constraints
assertThat(
customerForm.field("orders[0].items[0].deliveryDate")
.constraints().size())
.as("field(\"orders[0].items[0].deliveryDate\").constraints().size()")
.isEqualTo(0);
// orders[0].items[0].deliveryDate format
assertThat(
customerForm.field("orders[0].items[0].deliveryDate").format()._1)
.as("field(\"orders[0].items[0].deliveryDate\").format()._1")
.isEqualTo("format.date");
assertThat(
customerForm.field("orders[0].items[0].deliveryDate").format()._2
.toString()).as(
"field(\"orders[0].items[0].deliveryDate\").format()._2")
.isEqualTo("[yyyy-MM-dd]");
}
@Test
public void actionShouldBeExecutedInCorrectThread() {
running(testServer(3333), new Runnable() {
public void run() {
WSResponse response = WS.url("http://localhost:3333/thread").get().get(10000);
assertThat(response.getBody()).startsWith("play-akka.actor.default-dispatcher-");
}
});
}
}
| true | true | public void nestedContraints() {
Form<JCustomer> customerForm = new Form<JCustomer>(JCustomer.class);
// email constraints
assertThat(customerForm.field("email").constraints().size()).as(
"field(\"email\").constraints().size()").isEqualTo(2);
assertThat(customerForm.field("email").constraints().get(0)._1).as(
"field(\"email\").constraints(0)")
.isEqualTo("constraint.email");
assertThat(customerForm.field("email").constraints().get(1)._1).as(
"field(\"email\").constraints(1)").isEqualTo(
"constraint.required");
// orders[0].date constraints
assertThat(customerForm.field("orders[0].date").constraints().size())
.as("field(\"orders[0].date\").constraints().size()")
.isEqualTo(1);
assertThat(customerForm.field("orders[0].date").constraints().get(0)._1)
.as("field(\"orders[0].date\").constraints(0)").isEqualTo(
"constraint.required");
// orders[0].date format
assertThat(customerForm.field("orders[0].date").format()._1).as(
"field(\"orders[0].date\").format()._1").isEqualTo(
"format.date");
assertThat(customerForm.field("orders[0].date").format()._2.toString())
.as("field(\"orders[0].date\").format()._2").isEqualTo(
"[yyyy-MM-dd]");
// orders[0].items[0].qty constraints
assertThat(
customerForm.field("orders[0].items[0].qty").constraints()
.size()).as(
"field(\"orders[0].items[0].qty\").constraints().size()")
.isEqualTo(2);
assertThat(
customerForm.field("orders[0].items[0].qty").constraints()
.get(0)._1).as(
"field(\"orders[0].items[0].qty\").constraints(0)").isEqualTo(
"constraint.min");
assertThat(
customerForm.field("orders[0].items[0].qty").constraints()
.get(0)._2.toString()).as(
"field(\"orders[0].items[0].qty\").constraints(0)._2")
.isEqualTo("[1]");
assertThat(
customerForm.field("orders[0].items[0].qty").constraints()
.get(1)._1).as(
"field(\"orders[0].items[0].qty\").constraints(1)").isEqualTo(
"constraint.required");
// orders[0].items[0].productCode constraints
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().size())
.as("field(\"orders[0].items[0].productCode\").constraints().size()")
.isEqualTo(2);
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().get(0)._1).as(
"field(\"orders[0].items[0].productCode\").constraints(0)")
.isEqualTo("constraint.pattern");
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().get(0)._2.size()).as(
"field(\"orders[0].items[0].productCode\").constraints(0)")
.isEqualTo(1);
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().get(0)._2.get(0)).as(
"field(\"orders[0].items[0].productCode\").constraints(0)")
.isEqualTo("[A-Z]{4}-[0-9]{3,}");
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().get(1)._1).as(
"field(\"orders[0].items[0].productCode\").constraints(1)")
.isEqualTo("constraint.required");
// orders[0].items[0].deliveryDate constraints
assertThat(
customerForm.field("orders[0].items[0].deliveryDate")
.constraints().size())
.as("field(\"orders[0].items[0].deliveryDate\").constraints().size()")
.isEqualTo(0);
// orders[0].items[0].deliveryDate format
assertThat(
customerForm.field("orders[0].items[0].deliveryDate").format()._1)
.as("field(\"orders[0].items[0].deliveryDate\").format()._1")
.isEqualTo("format.date");
assertThat(
customerForm.field("orders[0].items[0].deliveryDate").format()._2
.toString()).as(
"field(\"orders[0].items[0].deliveryDate\").format()._2")
.isEqualTo("[yyyy-MM-dd]");
}
| public void nestedConstraints() {
Form<JCustomer> customerForm = new Form<JCustomer>(JCustomer.class);
// email constraints
assertThat(customerForm.field("email").constraints().size()).as(
"field(\"email\").constraints().size()").isEqualTo(2);
assertThat(customerForm.field("email").constraints().get(0)._1).as(
"field(\"email\").constraints(0)")
.isEqualTo("constraint.email");
assertThat(customerForm.field("email").constraints().get(1)._1).as(
"field(\"email\").constraints(1)").isEqualTo(
"constraint.required");
// orders[0].date constraints
assertThat(customerForm.field("orders[0].date").constraints().size())
.as("field(\"orders[0].date\").constraints().size()")
.isEqualTo(1);
assertThat(customerForm.field("orders[0].date").constraints().get(0)._1)
.as("field(\"orders[0].date\").constraints(0)").isEqualTo(
"constraint.required");
// orders[0].date format
assertThat(customerForm.field("orders[0].date").format()._1).as(
"field(\"orders[0].date\").format()._1").isEqualTo(
"format.date");
assertThat(customerForm.field("orders[0].date").format()._2.toString())
.as("field(\"orders[0].date\").format()._2").isEqualTo(
"[yyyy-MM-dd]");
// orders[0].items[0].qty constraints
assertThat(
customerForm.field("orders[0].items[0].qty").constraints()
.size()).as(
"field(\"orders[0].items[0].qty\").constraints().size()")
.isEqualTo(2);
assertThat(
customerForm.field("orders[0].items[0].qty").constraints()
.get(0)._1).as(
"field(\"orders[0].items[0].qty\").constraints(0)").isEqualTo(
"constraint.min");
assertThat(
customerForm.field("orders[0].items[0].qty").constraints()
.get(0)._2.toString()).as(
"field(\"orders[0].items[0].qty\").constraints(0)._2")
.isEqualTo("[1]");
assertThat(
customerForm.field("orders[0].items[0].qty").constraints()
.get(1)._1).as(
"field(\"orders[0].items[0].qty\").constraints(1)").isEqualTo(
"constraint.required");
// orders[0].items[0].productCode constraints
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().size())
.as("field(\"orders[0].items[0].productCode\").constraints().size()")
.isEqualTo(2);
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().get(0)._1).as(
"field(\"orders[0].items[0].productCode\").constraints(0)")
.isEqualTo("constraint.pattern");
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().get(0)._2.size()).as(
"field(\"orders[0].items[0].productCode\").constraints(0)")
.isEqualTo(1);
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().get(0)._2.get(0)).as(
"field(\"orders[0].items[0].productCode\").constraints(0)")
.isEqualTo("[A-Z]{4}-[0-9]{3,}");
assertThat(
customerForm.field("orders[0].items[0].productCode")
.constraints().get(1)._1).as(
"field(\"orders[0].items[0].productCode\").constraints(1)")
.isEqualTo("constraint.required");
// orders[0].items[0].deliveryDate constraints
assertThat(
customerForm.field("orders[0].items[0].deliveryDate")
.constraints().size())
.as("field(\"orders[0].items[0].deliveryDate\").constraints().size()")
.isEqualTo(0);
// orders[0].items[0].deliveryDate format
assertThat(
customerForm.field("orders[0].items[0].deliveryDate").format()._1)
.as("field(\"orders[0].items[0].deliveryDate\").format()._1")
.isEqualTo("format.date");
assertThat(
customerForm.field("orders[0].items[0].deliveryDate").format()._2
.toString()).as(
"field(\"orders[0].items[0].deliveryDate\").format()._2")
.isEqualTo("[yyyy-MM-dd]");
}
|
diff --git a/src/de/unifr/acp/trafo/Main.java b/src/de/unifr/acp/trafo/Main.java
index 8281438..a9515b9 100644
--- a/src/de/unifr/acp/trafo/Main.java
+++ b/src/de/unifr/acp/trafo/Main.java
@@ -1,51 +1,55 @@
package de.unifr.acp.trafo;
import java.io.IOException;
import java.io.InvalidClassException;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;
public class Main {
/**
* @param args
* @throws NotFoundException
* @throws CannotCompileException
* @throws IOException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws NotFoundException, ClassNotFoundException, IOException, CannotCompileException {
try {
String className = args[0];
String outputDir = (args.length >= 2) ? args[1] : "bin";
ClassPool defaultPool = ClassPool.getDefault();
CtClass target = defaultPool.get(className);
// TransClass.doTransform(target,
// !target.getSuperclass().equals(objectClass));
TransClass.transformAndFlushHierarchy(className, outputDir);
// condition needed to avoid bug in writing unmodified class files
// causing invalid class files
// if (target.isModified()) {
// target.writeFile(outputDir);
// }
} catch (ArrayIndexOutOfBoundsException e) {
StringBuilder usage = new StringBuilder();
usage.append("Usage: x2traverse class [output directory]\n");
usage.append(" (to transform the class hierarchy rootet at a class)\n");
usage.append("where options include:\n");
usage.append(" \n");
System.out.println(usage);
} catch (InvalidClassException e) {
e.printStackTrace();
- e.toString();
- System.out.println(e.getMessage());
+ System.out.println(e.toString());
+ throw e;
+ } catch (CannotCompileException e) {
+ e.printStackTrace();
+ System.out.println(e.toString());
+ System.out.println(e.getReason());
}
}
}
| true | true | public static void main(String[] args) throws NotFoundException, ClassNotFoundException, IOException, CannotCompileException {
try {
String className = args[0];
String outputDir = (args.length >= 2) ? args[1] : "bin";
ClassPool defaultPool = ClassPool.getDefault();
CtClass target = defaultPool.get(className);
// TransClass.doTransform(target,
// !target.getSuperclass().equals(objectClass));
TransClass.transformAndFlushHierarchy(className, outputDir);
// condition needed to avoid bug in writing unmodified class files
// causing invalid class files
// if (target.isModified()) {
// target.writeFile(outputDir);
// }
} catch (ArrayIndexOutOfBoundsException e) {
StringBuilder usage = new StringBuilder();
usage.append("Usage: x2traverse class [output directory]\n");
usage.append(" (to transform the class hierarchy rootet at a class)\n");
usage.append("where options include:\n");
usage.append(" \n");
System.out.println(usage);
} catch (InvalidClassException e) {
e.printStackTrace();
e.toString();
System.out.println(e.getMessage());
}
}
| public static void main(String[] args) throws NotFoundException, ClassNotFoundException, IOException, CannotCompileException {
try {
String className = args[0];
String outputDir = (args.length >= 2) ? args[1] : "bin";
ClassPool defaultPool = ClassPool.getDefault();
CtClass target = defaultPool.get(className);
// TransClass.doTransform(target,
// !target.getSuperclass().equals(objectClass));
TransClass.transformAndFlushHierarchy(className, outputDir);
// condition needed to avoid bug in writing unmodified class files
// causing invalid class files
// if (target.isModified()) {
// target.writeFile(outputDir);
// }
} catch (ArrayIndexOutOfBoundsException e) {
StringBuilder usage = new StringBuilder();
usage.append("Usage: x2traverse class [output directory]\n");
usage.append(" (to transform the class hierarchy rootet at a class)\n");
usage.append("where options include:\n");
usage.append(" \n");
System.out.println(usage);
} catch (InvalidClassException e) {
e.printStackTrace();
System.out.println(e.toString());
throw e;
} catch (CannotCompileException e) {
e.printStackTrace();
System.out.println(e.toString());
System.out.println(e.getReason());
}
}
|
diff --git a/tests/org.jboss.tools.jst.css.test/src/org/jboss/tools/jst/css/test/jbide/InputFractionalValueTest_JBIDE4790.java b/tests/org.jboss.tools.jst.css.test/src/org/jboss/tools/jst/css/test/jbide/InputFractionalValueTest_JBIDE4790.java
index 5254a669..58aceddb 100644
--- a/tests/org.jboss.tools.jst.css.test/src/org/jboss/tools/jst/css/test/jbide/InputFractionalValueTest_JBIDE4790.java
+++ b/tests/org.jboss.tools.jst.css.test/src/org/jboss/tools/jst/css/test/jbide/InputFractionalValueTest_JBIDE4790.java
@@ -1,129 +1,129 @@
/*******************************************************************************
* Copyright (c) 2007-2009 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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
*
* Contributor:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.jst.css.test.jbide;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.wst.css.core.internal.document.CSSStructuredDocumentRegionContainer;
import org.eclipse.wst.css.core.internal.provisional.document.ICSSModel;
import org.eclipse.wst.css.core.internal.provisional.document.ICSSStyleSheet;
import org.eclipse.wst.sse.ui.StructuredTextEditor;
import org.jboss.tools.jst.css.properties.CSSPropertyPage;
import org.jboss.tools.jst.css.test.AbstractCSSViewTest;
import org.jboss.tools.jst.css.view.CSSEditorView;
import org.jboss.tools.jst.jsp.outline.cssdialog.common.StyleAttributes;
import org.jboss.tools.jst.jsp.outline.cssdialog.common.Util;
import org.w3c.dom.DOMException;
import org.w3c.dom.css.CSSRule;
import org.w3c.dom.css.CSSStyleDeclaration;
import org.w3c.dom.css.CSSStyleRule;
/**
* @author Sergey Dzmitrovich
*
*/
public class InputFractionalValueTest_JBIDE4790 extends AbstractCSSViewTest {
public static final String TEST_PAGE_NAME = "JBIDE/4790/inputFractional.css"; //$NON-NLS-1$
public static final String TEST_CSS_ATTRIBUTE_NAME = "font-size"; //$NON-NLS-1$
public void testInputFractionalValue() throws CoreException {
IFile pageFile = getComponentPath(TEST_PAGE_NAME, getProjectName());
assertNotNull(pageFile);
StructuredTextEditor editor = (StructuredTextEditor) openEditor(
pageFile, CSS_EDITOR_ID);
assertNotNull(editor);
CSSEditorView view = (CSSEditorView) openView(CSS_EDITOR_VIEW);
assertNotNull(view);
CSSPropertyPage page = (CSSPropertyPage) view.getCurrentPage();
assertNotNull(page);
ICSSModel model = (ICSSModel) getStructuredModel(pageFile);
assertNotNull(model);
ICSSStyleSheet document = (ICSSStyleSheet) model.getDocument();
assertNotNull(document);
CSSRule cssRule = document.getCssRules().item(0);
assertNotNull(cssRule);
int offset = ((CSSStructuredDocumentRegionContainer) cssRule)
.getStartOffset();
setSelection(editor, offset, 0);
CSSStyleDeclaration declaration = ((CSSStyleRule) cssRule).getStyle();
String testedValue = declaration
.getPropertyValue(TEST_CSS_ATTRIBUTE_NAME);
assertNotNull(testedValue);
StyleAttributes styleAttributes = page.getStyleAttributes();
assertEquals(testedValue, styleAttributes
- .getAttribute(TEST_CSS_ATTRIBUTE_NAME));
+ .get(TEST_CSS_ATTRIBUTE_NAME));
String[] parsedTestValue = Util.convertExtString(testedValue);
assertEquals(parsedTestValue.length, 2);
String newTestedValue = parsedTestValue[0] + "." + parsedTestValue[1]; //$NON-NLS-1$
- styleAttributes.getAttributeMap().put(TEST_CSS_ATTRIBUTE_NAME,
+ styleAttributes.put(TEST_CSS_ATTRIBUTE_NAME,
newTestedValue);
testedValue = declaration.getPropertyValue(TEST_CSS_ATTRIBUTE_NAME);
assertNotNull(testedValue);
assertEquals(removeWhitespaces(newTestedValue),
removeWhitespaces(testedValue));
parsedTestValue = Util.convertExtString(testedValue);
assertEquals(parsedTestValue.length, 2);
newTestedValue = parsedTestValue[0] + "3" + parsedTestValue[1]; //$NON-NLS-1$
try {
- styleAttributes.getAttributeMap().put(TEST_CSS_ATTRIBUTE_NAME,
+ styleAttributes.put(TEST_CSS_ATTRIBUTE_NAME,
newTestedValue);
} catch (DOMException e) {
fail("Changing of attribute's value leads to DOMException. Probably it is problem concerned with of JBIDE-4790 "); //$NON-NLS-1$
}
testedValue = declaration.getPropertyValue(TEST_CSS_ATTRIBUTE_NAME);
assertNotNull(testedValue);
assertEquals(removeWhitespaces(testedValue),
removeWhitespaces(newTestedValue));
}
private String removeWhitespaces(String text) {
return text.replaceAll(" ", ""); //$NON-NLS-1$ //$NON-NLS-2$
}
}
| false | true | public void testInputFractionalValue() throws CoreException {
IFile pageFile = getComponentPath(TEST_PAGE_NAME, getProjectName());
assertNotNull(pageFile);
StructuredTextEditor editor = (StructuredTextEditor) openEditor(
pageFile, CSS_EDITOR_ID);
assertNotNull(editor);
CSSEditorView view = (CSSEditorView) openView(CSS_EDITOR_VIEW);
assertNotNull(view);
CSSPropertyPage page = (CSSPropertyPage) view.getCurrentPage();
assertNotNull(page);
ICSSModel model = (ICSSModel) getStructuredModel(pageFile);
assertNotNull(model);
ICSSStyleSheet document = (ICSSStyleSheet) model.getDocument();
assertNotNull(document);
CSSRule cssRule = document.getCssRules().item(0);
assertNotNull(cssRule);
int offset = ((CSSStructuredDocumentRegionContainer) cssRule)
.getStartOffset();
setSelection(editor, offset, 0);
CSSStyleDeclaration declaration = ((CSSStyleRule) cssRule).getStyle();
String testedValue = declaration
.getPropertyValue(TEST_CSS_ATTRIBUTE_NAME);
assertNotNull(testedValue);
StyleAttributes styleAttributes = page.getStyleAttributes();
assertEquals(testedValue, styleAttributes
.getAttribute(TEST_CSS_ATTRIBUTE_NAME));
String[] parsedTestValue = Util.convertExtString(testedValue);
assertEquals(parsedTestValue.length, 2);
String newTestedValue = parsedTestValue[0] + "." + parsedTestValue[1]; //$NON-NLS-1$
styleAttributes.getAttributeMap().put(TEST_CSS_ATTRIBUTE_NAME,
newTestedValue);
testedValue = declaration.getPropertyValue(TEST_CSS_ATTRIBUTE_NAME);
assertNotNull(testedValue);
assertEquals(removeWhitespaces(newTestedValue),
removeWhitespaces(testedValue));
parsedTestValue = Util.convertExtString(testedValue);
assertEquals(parsedTestValue.length, 2);
newTestedValue = parsedTestValue[0] + "3" + parsedTestValue[1]; //$NON-NLS-1$
try {
styleAttributes.getAttributeMap().put(TEST_CSS_ATTRIBUTE_NAME,
newTestedValue);
} catch (DOMException e) {
fail("Changing of attribute's value leads to DOMException. Probably it is problem concerned with of JBIDE-4790 "); //$NON-NLS-1$
}
testedValue = declaration.getPropertyValue(TEST_CSS_ATTRIBUTE_NAME);
assertNotNull(testedValue);
assertEquals(removeWhitespaces(testedValue),
removeWhitespaces(newTestedValue));
}
| public void testInputFractionalValue() throws CoreException {
IFile pageFile = getComponentPath(TEST_PAGE_NAME, getProjectName());
assertNotNull(pageFile);
StructuredTextEditor editor = (StructuredTextEditor) openEditor(
pageFile, CSS_EDITOR_ID);
assertNotNull(editor);
CSSEditorView view = (CSSEditorView) openView(CSS_EDITOR_VIEW);
assertNotNull(view);
CSSPropertyPage page = (CSSPropertyPage) view.getCurrentPage();
assertNotNull(page);
ICSSModel model = (ICSSModel) getStructuredModel(pageFile);
assertNotNull(model);
ICSSStyleSheet document = (ICSSStyleSheet) model.getDocument();
assertNotNull(document);
CSSRule cssRule = document.getCssRules().item(0);
assertNotNull(cssRule);
int offset = ((CSSStructuredDocumentRegionContainer) cssRule)
.getStartOffset();
setSelection(editor, offset, 0);
CSSStyleDeclaration declaration = ((CSSStyleRule) cssRule).getStyle();
String testedValue = declaration
.getPropertyValue(TEST_CSS_ATTRIBUTE_NAME);
assertNotNull(testedValue);
StyleAttributes styleAttributes = page.getStyleAttributes();
assertEquals(testedValue, styleAttributes
.get(TEST_CSS_ATTRIBUTE_NAME));
String[] parsedTestValue = Util.convertExtString(testedValue);
assertEquals(parsedTestValue.length, 2);
String newTestedValue = parsedTestValue[0] + "." + parsedTestValue[1]; //$NON-NLS-1$
styleAttributes.put(TEST_CSS_ATTRIBUTE_NAME,
newTestedValue);
testedValue = declaration.getPropertyValue(TEST_CSS_ATTRIBUTE_NAME);
assertNotNull(testedValue);
assertEquals(removeWhitespaces(newTestedValue),
removeWhitespaces(testedValue));
parsedTestValue = Util.convertExtString(testedValue);
assertEquals(parsedTestValue.length, 2);
newTestedValue = parsedTestValue[0] + "3" + parsedTestValue[1]; //$NON-NLS-1$
try {
styleAttributes.put(TEST_CSS_ATTRIBUTE_NAME,
newTestedValue);
} catch (DOMException e) {
fail("Changing of attribute's value leads to DOMException. Probably it is problem concerned with of JBIDE-4790 "); //$NON-NLS-1$
}
testedValue = declaration.getPropertyValue(TEST_CSS_ATTRIBUTE_NAME);
assertNotNull(testedValue);
assertEquals(removeWhitespaces(testedValue),
removeWhitespaces(newTestedValue));
}
|
diff --git a/InputFileParser.java b/InputFileParser.java
index 9b2838f..85a21eb 100644
--- a/InputFileParser.java
+++ b/InputFileParser.java
@@ -1,66 +1,66 @@
import java.io.*;
import java.util.ArrayList;
public class InputFileParser {
private static final boolean INPUT_DEBUG = true;
public static ArrayList<Process> parseInputFile(String fileName) {
ArrayList<Process> processList = new ArrayList<Process>();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine(); //First line is number of processes... throw it out
while ( (line = br.readLine()) != null) {
processList.add( parseInputLine(line) );
}
} catch (IOException ioe) {
System.err.println("Couldn't read input file '" + fileName + "'");
System.exit(1);
}
return processList;
}
private static Process parseInputLine(String line) {
debugPrint("Got line " + line);
String[] lineParts = line.split("\\s");
debugPrintln(" (" + lineParts.length + ")");
//Need at least 4 items: pid, mem, and an entry/exit pair
//Also, must be an even number of items (pairs of times only)
if (lineParts.length < 4 || lineParts.length % 2 != 0) {
System.err.println("Malformed input file with line '" + line + "'");
System.exit(1);
}
String pid = lineParts[0];
String mem = lineParts[1];
int[] processEntries = new int[ (lineParts.length-2) / 2 ];
int[] processExits = new int[ (lineParts.length-2) / 2 ];
for (int i = 2; i < lineParts.length; i += 2) {
- processEntries[i/2] = Integer.parseInt( lineParts[i] );
- processExits[i/2] = Integer.parseInt( lineParts[i+1] );
+ processEntries[(i/2)-1] = Integer.parseInt( lineParts[i] );
+ processExits[(i/2)-1] = Integer.parseInt( lineParts[i+1] );
//Also, times must be strictly increasing
- if ( processEntries[i] > processExits[i] ) {
+ if ( processEntries[(i/2)-1] > processExits[(i/2)-1] ) {
//Time wasn't strictly increasing
System.err.println("Times not strictly increasing on line '" + line + "'");
System.exit(1);
}
}
Process newProcess = new Process( pid, mem, processEntries, processExits );
return newProcess;
}
private static void debugPrint(String toPrint) {
if (INPUT_DEBUG == true) {
System.out.print(toPrint);
}
}
private static void debugPrintln(String toPrint) {
if (INPUT_DEBUG == true) {
System.out.println(toPrint);
}
}
}
| false | true | private static Process parseInputLine(String line) {
debugPrint("Got line " + line);
String[] lineParts = line.split("\\s");
debugPrintln(" (" + lineParts.length + ")");
//Need at least 4 items: pid, mem, and an entry/exit pair
//Also, must be an even number of items (pairs of times only)
if (lineParts.length < 4 || lineParts.length % 2 != 0) {
System.err.println("Malformed input file with line '" + line + "'");
System.exit(1);
}
String pid = lineParts[0];
String mem = lineParts[1];
int[] processEntries = new int[ (lineParts.length-2) / 2 ];
int[] processExits = new int[ (lineParts.length-2) / 2 ];
for (int i = 2; i < lineParts.length; i += 2) {
processEntries[i/2] = Integer.parseInt( lineParts[i] );
processExits[i/2] = Integer.parseInt( lineParts[i+1] );
//Also, times must be strictly increasing
if ( processEntries[i] > processExits[i] ) {
//Time wasn't strictly increasing
System.err.println("Times not strictly increasing on line '" + line + "'");
System.exit(1);
}
}
Process newProcess = new Process( pid, mem, processEntries, processExits );
return newProcess;
}
| private static Process parseInputLine(String line) {
debugPrint("Got line " + line);
String[] lineParts = line.split("\\s");
debugPrintln(" (" + lineParts.length + ")");
//Need at least 4 items: pid, mem, and an entry/exit pair
//Also, must be an even number of items (pairs of times only)
if (lineParts.length < 4 || lineParts.length % 2 != 0) {
System.err.println("Malformed input file with line '" + line + "'");
System.exit(1);
}
String pid = lineParts[0];
String mem = lineParts[1];
int[] processEntries = new int[ (lineParts.length-2) / 2 ];
int[] processExits = new int[ (lineParts.length-2) / 2 ];
for (int i = 2; i < lineParts.length; i += 2) {
processEntries[(i/2)-1] = Integer.parseInt( lineParts[i] );
processExits[(i/2)-1] = Integer.parseInt( lineParts[i+1] );
//Also, times must be strictly increasing
if ( processEntries[(i/2)-1] > processExits[(i/2)-1] ) {
//Time wasn't strictly increasing
System.err.println("Times not strictly increasing on line '" + line + "'");
System.exit(1);
}
}
Process newProcess = new Process( pid, mem, processEntries, processExits );
return newProcess;
}
|
diff --git a/src/org/oscim/theme/renderinstruction/Line.java b/src/org/oscim/theme/renderinstruction/Line.java
index e814e3b2..a8837abf 100644
--- a/src/org/oscim/theme/renderinstruction/Line.java
+++ b/src/org/oscim/theme/renderinstruction/Line.java
@@ -1,216 +1,216 @@
/*
* Copyright 2010, 2011, 2012 mapsforge.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 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oscim.theme.renderinstruction;
import java.util.Locale;
import java.util.regex.Pattern;
import org.oscim.graphics.Color;
import org.oscim.graphics.Paint.Cap;
import org.oscim.theme.IRenderCallback;
import org.oscim.theme.RenderThemeHandler;
import org.xml.sax.Attributes;
/**
* Represents a polyline on the map.
*/
public final class Line extends RenderInstruction {
private static final Pattern SPLIT_PATTERN = Pattern.compile(",");
/**
* @param line
* ...
* @param elementName
* the name of the XML element.
* @param attributes
* the attributes of the XML element.
* @param level
* the drawing level of this instruction.
* @param isOutline
* ...
* @return a new Line with the given rendering attributes.
*/
public static Line create(Line line, String elementName, Attributes attributes,
int level, boolean isOutline) {
// Style name
String style = null;
// Bitmap
//String src = null;
float width = 0;
Cap cap = Cap.ROUND;
// Extras
int fade = -1;
boolean fixed = false;
float blur = 0;
float min = 0;
// Stipple
int stipple = 0;
float stippleWidth = 0;
int color = Color.RED;
int stippleColor = Color.BLACK;
if (line != null) {
color = line.color;
fixed = line.fixed;
fade = line.fade;
cap = line.cap;
blur = line.blur;
min = line.min;
stipple = line.stipple;
stippleColor = line.stippleColor;
stippleWidth = line.stippleWidth;
}
for (int i = 0; i < attributes.getLength(); ++i) {
String name = attributes.getLocalName(i);
String value = attributes.getValue(i);
if ("name".equals(name))
style = value;
else if ("src".equals(name)) {
//src = value;
} else if ("stroke".equals(name)) {
color = Color.parseColor(value);
} else if ("width".equals(name)) {
width = Float.parseFloat(value);
} else if ("cap".equals(name)) {
cap = Cap.valueOf(value.toUpperCase(Locale.ENGLISH));
- } else if ("fixed".equals(name)) {
+ } else if ("fix".equals(name)) {
fixed = Boolean.parseBoolean(value);
} else if ("stipple".equals(name)) {
stipple = Integer.parseInt(value);
} else if ("stipple-stroke".equals(name)) {
stippleColor = Color.parseColor(value);
} else if ("stipple-width".equals(name)) {
stippleWidth = Float.parseFloat(value);
} else if ("fade".equals(name)) {
fade = Integer.parseInt(value);
} else if ("min".equals(name)) {
min = Float.parseFloat(value);
} else if ("blur".equals(name)) {
blur = Float.parseFloat(value);
} else if ("from".equals(name)) {
} else {
RenderThemeHandler.logUnknownAttribute(elementName, name, value, i);
}
}
// inherit properties from 'line'
if (line != null) {
// use stroke width relative to 'line'
width = line.width + width;
if (width <= 0)
width = 1;
} else if (!isOutline) {
validate(width);
}
return new Line(level, style, color, width, cap, fixed,
stipple, stippleColor, stippleWidth,
fade, blur, isOutline, min);
}
private static void validate(float strokeWidth) {
if (strokeWidth < 0) {
throw new IllegalArgumentException("width must not be negative: "
+ strokeWidth);
}
}
static float[] parseFloatArray(String dashString) {
String[] dashEntries = SPLIT_PATTERN.split(dashString);
float[] dashIntervals = new float[dashEntries.length];
for (int i = 0; i < dashEntries.length; ++i) {
dashIntervals[i] = Float.parseFloat(dashEntries[i]);
}
return dashIntervals;
}
private final int level;
public final String style;
public final float width;
public final int color;
public final Cap cap;
public final boolean outline;
public final boolean fixed;
public final int fade;
public final float blur;
public final float min;
public final int stipple;
public final int stippleColor;
public final float stippleWidth;
private Line(int level, String style, int color, float width,
Cap cap, boolean fixed,
int stipple, int stippleColor, float stippleWidth,
int fade, float blur, boolean isOutline, float min) {
this.level = level;
this.style = style;
this.outline = isOutline;
// paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//
// if (src != null) {
// Shader shader = BitmapUtils.createBitmapShader(src);
// paint.setShader(shader);
// }
//
// paint.setStyle(Style.STROKE);
// paint.setColor(stroke);
// if (strokeDasharray != null) {
// paint.setPathEffect(new DashPathEffect(strokeDasharray, 0));
// }
//GlUtils.changeSaturation(color, 1.02f);
this.cap = cap;
this.color = color;
this.width = width;
this.fixed = fixed;
this.stipple = stipple;
this.stippleColor = stippleColor;
this.stippleWidth = stippleWidth;
this.blur = blur;
this.fade = fade;
this.min = min;
}
public Line(int stroke, float width) {
this(0, "", stroke, width, Cap.BUTT, true, 0, 0, 0, -1, 0, false, 0);
}
public Line(int stroke, float width, Cap cap) {
this(0, "", stroke, width, cap, true, 0, 0, 0, -1, 0, false, 0);
}
@Override
public void renderWay(IRenderCallback renderCallback) {
renderCallback.renderWay(this, level);
}
}
| true | true | public static Line create(Line line, String elementName, Attributes attributes,
int level, boolean isOutline) {
// Style name
String style = null;
// Bitmap
//String src = null;
float width = 0;
Cap cap = Cap.ROUND;
// Extras
int fade = -1;
boolean fixed = false;
float blur = 0;
float min = 0;
// Stipple
int stipple = 0;
float stippleWidth = 0;
int color = Color.RED;
int stippleColor = Color.BLACK;
if (line != null) {
color = line.color;
fixed = line.fixed;
fade = line.fade;
cap = line.cap;
blur = line.blur;
min = line.min;
stipple = line.stipple;
stippleColor = line.stippleColor;
stippleWidth = line.stippleWidth;
}
for (int i = 0; i < attributes.getLength(); ++i) {
String name = attributes.getLocalName(i);
String value = attributes.getValue(i);
if ("name".equals(name))
style = value;
else if ("src".equals(name)) {
//src = value;
} else if ("stroke".equals(name)) {
color = Color.parseColor(value);
} else if ("width".equals(name)) {
width = Float.parseFloat(value);
} else if ("cap".equals(name)) {
cap = Cap.valueOf(value.toUpperCase(Locale.ENGLISH));
} else if ("fixed".equals(name)) {
fixed = Boolean.parseBoolean(value);
} else if ("stipple".equals(name)) {
stipple = Integer.parseInt(value);
} else if ("stipple-stroke".equals(name)) {
stippleColor = Color.parseColor(value);
} else if ("stipple-width".equals(name)) {
stippleWidth = Float.parseFloat(value);
} else if ("fade".equals(name)) {
fade = Integer.parseInt(value);
} else if ("min".equals(name)) {
min = Float.parseFloat(value);
} else if ("blur".equals(name)) {
blur = Float.parseFloat(value);
} else if ("from".equals(name)) {
} else {
RenderThemeHandler.logUnknownAttribute(elementName, name, value, i);
}
}
// inherit properties from 'line'
if (line != null) {
// use stroke width relative to 'line'
width = line.width + width;
if (width <= 0)
width = 1;
} else if (!isOutline) {
validate(width);
}
return new Line(level, style, color, width, cap, fixed,
stipple, stippleColor, stippleWidth,
fade, blur, isOutline, min);
}
| public static Line create(Line line, String elementName, Attributes attributes,
int level, boolean isOutline) {
// Style name
String style = null;
// Bitmap
//String src = null;
float width = 0;
Cap cap = Cap.ROUND;
// Extras
int fade = -1;
boolean fixed = false;
float blur = 0;
float min = 0;
// Stipple
int stipple = 0;
float stippleWidth = 0;
int color = Color.RED;
int stippleColor = Color.BLACK;
if (line != null) {
color = line.color;
fixed = line.fixed;
fade = line.fade;
cap = line.cap;
blur = line.blur;
min = line.min;
stipple = line.stipple;
stippleColor = line.stippleColor;
stippleWidth = line.stippleWidth;
}
for (int i = 0; i < attributes.getLength(); ++i) {
String name = attributes.getLocalName(i);
String value = attributes.getValue(i);
if ("name".equals(name))
style = value;
else if ("src".equals(name)) {
//src = value;
} else if ("stroke".equals(name)) {
color = Color.parseColor(value);
} else if ("width".equals(name)) {
width = Float.parseFloat(value);
} else if ("cap".equals(name)) {
cap = Cap.valueOf(value.toUpperCase(Locale.ENGLISH));
} else if ("fix".equals(name)) {
fixed = Boolean.parseBoolean(value);
} else if ("stipple".equals(name)) {
stipple = Integer.parseInt(value);
} else if ("stipple-stroke".equals(name)) {
stippleColor = Color.parseColor(value);
} else if ("stipple-width".equals(name)) {
stippleWidth = Float.parseFloat(value);
} else if ("fade".equals(name)) {
fade = Integer.parseInt(value);
} else if ("min".equals(name)) {
min = Float.parseFloat(value);
} else if ("blur".equals(name)) {
blur = Float.parseFloat(value);
} else if ("from".equals(name)) {
} else {
RenderThemeHandler.logUnknownAttribute(elementName, name, value, i);
}
}
// inherit properties from 'line'
if (line != null) {
// use stroke width relative to 'line'
width = line.width + width;
if (width <= 0)
width = 1;
} else if (!isOutline) {
validate(width);
}
return new Line(level, style, color, width, cap, fixed,
stipple, stippleColor, stippleWidth,
fade, blur, isOutline, min);
}
|
diff --git a/src/minecraft/biomesoplenty/worldgen/WorldGenQuicksand.java b/src/minecraft/biomesoplenty/worldgen/WorldGenQuicksand.java
index e06579b07..a419eb1b4 100644
--- a/src/minecraft/biomesoplenty/worldgen/WorldGenQuicksand.java
+++ b/src/minecraft/biomesoplenty/worldgen/WorldGenQuicksand.java
@@ -1,79 +1,79 @@
package biomesoplenty.worldgen;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenerator;
public class WorldGenQuicksand extends WorldGenerator
{
/** The block ID of the ore to be placed using this generator. */
private int minableBlockId;
/** The number of blocks to generate. */
private int numberOfBlocks;
public WorldGenQuicksand(int par1, int par2)
{
minableBlockId = par1;
numberOfBlocks = par2;
}
@Override
public boolean generate(World par1World, Random par2Random, int par3, int par4, int par5)
{
float var6 = par2Random.nextFloat() * (float)Math.PI;
double var7 = par3 + 8 + MathHelper.sin(var6) * numberOfBlocks / 8.0F;
double var9 = par3 + 8 - MathHelper.sin(var6) * numberOfBlocks / 8.0F;
double var11 = par5 + 8 + MathHelper.cos(var6) * numberOfBlocks / 8.0F;
double var13 = par5 + 8 - MathHelper.cos(var6) * numberOfBlocks / 8.0F;
double var15 = par4 + par2Random.nextInt(3) - 2;
double var17 = par4 + par2Random.nextInt(3) - 2;
for (int var19 = 0; var19 <= numberOfBlocks; ++var19)
{
double var20 = var7 + (var9 - var7) * var19 / numberOfBlocks;
double var22 = var15 + (var17 - var15) * var19 / numberOfBlocks;
double var24 = var11 + (var13 - var11) * var19 / numberOfBlocks;
double var26 = par2Random.nextDouble() * numberOfBlocks / 16.0D;
double var28 = (MathHelper.sin(var19 * (float)Math.PI / numberOfBlocks) + 1.0F) * var26 + 1.0D;
double var30 = (MathHelper.sin(var19 * (float)Math.PI / numberOfBlocks) + 1.0F) * var26 + 1.0D;
int var32 = MathHelper.floor_double(var20 - var28 / 2.0D);
int var33 = MathHelper.floor_double(var22 - var30 / 2.0D);
int var34 = MathHelper.floor_double(var24 - var28 / 2.0D);
int var35 = MathHelper.floor_double(var20 + var28 / 2.0D);
int var36 = MathHelper.floor_double(var22 + var30 / 2.0D);
int var37 = MathHelper.floor_double(var24 + var28 / 2.0D);
for (int var38 = var32; var38 <= var35; ++var38)
{
double var39 = (var38 + 0.5D - var20) / (var28 / 2.0D);
if (var39 * var39 < 1.0D)
{
for (int var41 = var33; var41 <= var36; ++var41)
{
double var42 = (var41 + 0.5D - var22) / (var30 / 2.0D);
if (var39 * var39 + var42 * var42 < 1.0D)
{
for (int var44 = var34; var44 <= var37; ++var44)
{
double var45 = (var44 + 0.5D - var24) / (var28 / 2.0D);
- if (var39 * var39 + var42 * var42 + var45 * var45 < 1.0D && (par1World.getBlockId(var38, var41, var44) == Block.grass.blockID || par1World.getBlockId(var38, var41, var44) == Block.sand.blockID))
+ if (var39 * var39 + var42 * var42 + var45 * var45 < 1.0D && (par1World.getBlockId(var38, var41, var44) == Block.grass.blockID || par1World.getBlockId(var38, var41, var44) == Block.dirt.blockID || par1World.getBlockId(var38, var41, var44) == Block.sand.blockID))
{
this.setBlockAndMetadata(par1World, var38, var41, var44, minableBlockId, 1);
}
}
}
}
}
}
}
return true;
}
}
| true | true | public boolean generate(World par1World, Random par2Random, int par3, int par4, int par5)
{
float var6 = par2Random.nextFloat() * (float)Math.PI;
double var7 = par3 + 8 + MathHelper.sin(var6) * numberOfBlocks / 8.0F;
double var9 = par3 + 8 - MathHelper.sin(var6) * numberOfBlocks / 8.0F;
double var11 = par5 + 8 + MathHelper.cos(var6) * numberOfBlocks / 8.0F;
double var13 = par5 + 8 - MathHelper.cos(var6) * numberOfBlocks / 8.0F;
double var15 = par4 + par2Random.nextInt(3) - 2;
double var17 = par4 + par2Random.nextInt(3) - 2;
for (int var19 = 0; var19 <= numberOfBlocks; ++var19)
{
double var20 = var7 + (var9 - var7) * var19 / numberOfBlocks;
double var22 = var15 + (var17 - var15) * var19 / numberOfBlocks;
double var24 = var11 + (var13 - var11) * var19 / numberOfBlocks;
double var26 = par2Random.nextDouble() * numberOfBlocks / 16.0D;
double var28 = (MathHelper.sin(var19 * (float)Math.PI / numberOfBlocks) + 1.0F) * var26 + 1.0D;
double var30 = (MathHelper.sin(var19 * (float)Math.PI / numberOfBlocks) + 1.0F) * var26 + 1.0D;
int var32 = MathHelper.floor_double(var20 - var28 / 2.0D);
int var33 = MathHelper.floor_double(var22 - var30 / 2.0D);
int var34 = MathHelper.floor_double(var24 - var28 / 2.0D);
int var35 = MathHelper.floor_double(var20 + var28 / 2.0D);
int var36 = MathHelper.floor_double(var22 + var30 / 2.0D);
int var37 = MathHelper.floor_double(var24 + var28 / 2.0D);
for (int var38 = var32; var38 <= var35; ++var38)
{
double var39 = (var38 + 0.5D - var20) / (var28 / 2.0D);
if (var39 * var39 < 1.0D)
{
for (int var41 = var33; var41 <= var36; ++var41)
{
double var42 = (var41 + 0.5D - var22) / (var30 / 2.0D);
if (var39 * var39 + var42 * var42 < 1.0D)
{
for (int var44 = var34; var44 <= var37; ++var44)
{
double var45 = (var44 + 0.5D - var24) / (var28 / 2.0D);
if (var39 * var39 + var42 * var42 + var45 * var45 < 1.0D && (par1World.getBlockId(var38, var41, var44) == Block.grass.blockID || par1World.getBlockId(var38, var41, var44) == Block.sand.blockID))
{
this.setBlockAndMetadata(par1World, var38, var41, var44, minableBlockId, 1);
}
}
}
}
}
}
}
return true;
}
| public boolean generate(World par1World, Random par2Random, int par3, int par4, int par5)
{
float var6 = par2Random.nextFloat() * (float)Math.PI;
double var7 = par3 + 8 + MathHelper.sin(var6) * numberOfBlocks / 8.0F;
double var9 = par3 + 8 - MathHelper.sin(var6) * numberOfBlocks / 8.0F;
double var11 = par5 + 8 + MathHelper.cos(var6) * numberOfBlocks / 8.0F;
double var13 = par5 + 8 - MathHelper.cos(var6) * numberOfBlocks / 8.0F;
double var15 = par4 + par2Random.nextInt(3) - 2;
double var17 = par4 + par2Random.nextInt(3) - 2;
for (int var19 = 0; var19 <= numberOfBlocks; ++var19)
{
double var20 = var7 + (var9 - var7) * var19 / numberOfBlocks;
double var22 = var15 + (var17 - var15) * var19 / numberOfBlocks;
double var24 = var11 + (var13 - var11) * var19 / numberOfBlocks;
double var26 = par2Random.nextDouble() * numberOfBlocks / 16.0D;
double var28 = (MathHelper.sin(var19 * (float)Math.PI / numberOfBlocks) + 1.0F) * var26 + 1.0D;
double var30 = (MathHelper.sin(var19 * (float)Math.PI / numberOfBlocks) + 1.0F) * var26 + 1.0D;
int var32 = MathHelper.floor_double(var20 - var28 / 2.0D);
int var33 = MathHelper.floor_double(var22 - var30 / 2.0D);
int var34 = MathHelper.floor_double(var24 - var28 / 2.0D);
int var35 = MathHelper.floor_double(var20 + var28 / 2.0D);
int var36 = MathHelper.floor_double(var22 + var30 / 2.0D);
int var37 = MathHelper.floor_double(var24 + var28 / 2.0D);
for (int var38 = var32; var38 <= var35; ++var38)
{
double var39 = (var38 + 0.5D - var20) / (var28 / 2.0D);
if (var39 * var39 < 1.0D)
{
for (int var41 = var33; var41 <= var36; ++var41)
{
double var42 = (var41 + 0.5D - var22) / (var30 / 2.0D);
if (var39 * var39 + var42 * var42 < 1.0D)
{
for (int var44 = var34; var44 <= var37; ++var44)
{
double var45 = (var44 + 0.5D - var24) / (var28 / 2.0D);
if (var39 * var39 + var42 * var42 + var45 * var45 < 1.0D && (par1World.getBlockId(var38, var41, var44) == Block.grass.blockID || par1World.getBlockId(var38, var41, var44) == Block.dirt.blockID || par1World.getBlockId(var38, var41, var44) == Block.sand.blockID))
{
this.setBlockAndMetadata(par1World, var38, var41, var44, minableBlockId, 1);
}
}
}
}
}
}
}
return true;
}
|
diff --git a/src/main/java/com/tysanclan/site/projectewok/TysanApplication.java b/src/main/java/com/tysanclan/site/projectewok/TysanApplication.java
index ed00cb8..47d01a9 100644
--- a/src/main/java/com/tysanclan/site/projectewok/TysanApplication.java
+++ b/src/main/java/com/tysanclan/site/projectewok/TysanApplication.java
@@ -1,498 +1,498 @@
/**
* Tysan Clan Website
* Copyright (C) 2008-2011 Jeroen Steenbeeke and Ties van de Ven
*
* 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.tysanclan.site.projectewok;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.wicket.Application;
import org.apache.wicket.Page;
import org.apache.wicket.Session;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.http.WebRequest;
import org.apache.wicket.request.resource.CssResourceReference;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.odlabs.wiquery.ui.themes.WiQueryCoreThemeResourceReference;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.tysanclan.site.projectewok.auth.TysanSecurity;
import com.tysanclan.site.projectewok.pages.AboutPage;
import com.tysanclan.site.projectewok.pages.AccessDeniedPage;
import com.tysanclan.site.projectewok.pages.CharterPage;
import com.tysanclan.site.projectewok.pages.ForumOverviewPage;
import com.tysanclan.site.projectewok.pages.ForumPage;
import com.tysanclan.site.projectewok.pages.ForumThreadPage;
import com.tysanclan.site.projectewok.pages.GroupPage;
import com.tysanclan.site.projectewok.pages.GroupsPage;
import com.tysanclan.site.projectewok.pages.HistoryPage;
import com.tysanclan.site.projectewok.pages.JoinOverviewPage;
import com.tysanclan.site.projectewok.pages.MemberPage;
import com.tysanclan.site.projectewok.pages.NewsPage;
import com.tysanclan.site.projectewok.pages.PasswordRequestConfirmationPage;
import com.tysanclan.site.projectewok.pages.RealmPage;
import com.tysanclan.site.projectewok.pages.RegistrationPage;
import com.tysanclan.site.projectewok.pages.RegulationPage;
import com.tysanclan.site.projectewok.pages.RosterPage;
import com.tysanclan.site.projectewok.pages.SessionTimeoutPage;
import com.tysanclan.site.projectewok.pages.TysanErrorPage;
import com.tysanclan.site.projectewok.pages.VacationPage;
import com.tysanclan.site.projectewok.pages.forum.ActivationPage;
import com.tysanclan.site.projectewok.pages.member.BugOverviewPage;
import com.tysanclan.site.projectewok.pages.member.SubscriptionPaymentResolvedPage;
import com.tysanclan.site.projectewok.pages.member.ViewBugPage;
import com.tysanclan.site.projectewok.pages.member.admin.MinecraftWhiteListPage;
import com.tysanclan.site.projectewok.pages.member.admin.OldExpensesPage;
import com.tysanclan.site.projectewok.pages.member.admin.ProcessPaymentRequestPage;
import com.tysanclan.site.projectewok.pages.member.admin.RandomContentGenerationPage;
import com.tysanclan.site.projectewok.pages.member.admin.TangoImporterPage;
import com.tysanclan.site.projectewok.tasks.AcceptanceVoteStartTask;
import com.tysanclan.site.projectewok.tasks.AcceptanceVoteStopTask;
import com.tysanclan.site.projectewok.tasks.AchievementProposalTask;
import com.tysanclan.site.projectewok.tasks.ActivationExpirationTask;
import com.tysanclan.site.projectewok.tasks.AutomaticPromotionTask;
import com.tysanclan.site.projectewok.tasks.ChancellorElectionChecker;
import com.tysanclan.site.projectewok.tasks.ChancellorElectionResolutionTask;
import com.tysanclan.site.projectewok.tasks.CheckSubscriptionsDueTask;
import com.tysanclan.site.projectewok.tasks.EmailChangeConfirmationExpirationTask;
import com.tysanclan.site.projectewok.tasks.GroupLeaderElectionResolutionTask;
import com.tysanclan.site.projectewok.tasks.MemberApplicationResolutionTask;
import com.tysanclan.site.projectewok.tasks.MembershipExpirationTask;
import com.tysanclan.site.projectewok.tasks.MumbleServerUpdateTask;
import com.tysanclan.site.projectewok.tasks.NoAccountExpireTask;
import com.tysanclan.site.projectewok.tasks.PasswordRequestExpirationTask;
import com.tysanclan.site.projectewok.tasks.RegulationChangeResolutionTask;
import com.tysanclan.site.projectewok.tasks.ResolveImpeachmentTask;
import com.tysanclan.site.projectewok.tasks.ResolveRoleTransferTask;
import com.tysanclan.site.projectewok.tasks.ResolveTruthsayerComplaintTask;
import com.tysanclan.site.projectewok.tasks.SenateElectionChecker;
import com.tysanclan.site.projectewok.tasks.SenateElectionResolutionTask;
import com.tysanclan.site.projectewok.tasks.TruthsayerAcceptanceVoteResolver;
import com.tysanclan.site.projectewok.tasks.TwitterQueueTask;
import com.tysanclan.site.projectewok.tasks.TwitterSearchTask;
import com.tysanclan.site.projectewok.tasks.TwitterTimelineTask;
import com.tysanclan.site.projectewok.tasks.UntenabilityVoteResolutionTask;
import com.tysanclan.site.projectewok.tasks.WarnInactiveMembersTask;
import com.tysanclan.site.projectewok.util.scheduler.TysanScheduler;
import com.tysanclan.site.projectewok.util.scheduler.TysanTask;
/**
* @author Jeroen Steenbeeke
*/
public class TysanApplication extends WebApplication {
private static Logger log = LoggerFactory.getLogger(TysanApplication.class);
private static String version = null;
public static final String MASTER_KEY = "Sethai Janora Kumirez Dechai";
public final List<SiteWideNotification> notifications = new LinkedList<SiteWideNotification>();
private static ApplicationContext testContext = null;
/**
* Creates a new application object for the Tysan website
*/
public TysanApplication() {
this(false);
}
public static ApplicationContext getApplicationContext() {
if (testContext != null)
return testContext;
TysanApplication ta = (TysanApplication) Application.get();
return WebApplicationContextUtils.getWebApplicationContext(ta
.getServletContext());
}
public static String getApplicationVersion() {
if (version == null) {
try {
Properties props = new Properties();
InputStream stream = get().getServletContext()
.getResourceAsStream("/META-INF/MANIFEST.MF");
if (stream != null) {
props.load(stream);
version = props.getProperty("Implementation-Build");
} else {
version = "SNAPSHOT";
}
} catch (IOException ioe) {
version = "SNAPSHOT";
}
}
return version;
}
private final boolean testMode;
/**
* Creates a new application object for the Tysan website
*
* @param isTestMode
* Whether or not we are running this site in test mode
*/
public TysanApplication(boolean isTestMode) {
this.testMode = isTestMode;
}
/**
* @see org.apache.wicket.Application#getHomePage()
*/
@Override
public Class<? extends Page> getHomePage() {
return NewsPage.class;
}
/**
* @see org.apache.wicket.protocol.http.WebApplication#init()
*/
@Override
protected void init() {
super.init();
ApplicationContext relevantCtx;
getComponentInstantiationListeners().add(new TysanSecurity());
if (testMode) {
relevantCtx = new ClassPathXmlApplicationContext(
new String[] { "services-mock.xml" });
getComponentInstantiationListeners().add(
new SpringComponentInjector(this, relevantCtx, true));
testContext = relevantCtx;
} else {
SpringComponentInjector injector = new SpringComponentInjector(this);
getComponentInstantiationListeners().add(injector);
}
mountBookmarkablePages();
getApplicationSettings().setAccessDeniedPage(AccessDeniedPage.class);
getApplicationSettings().setPageExpiredErrorPage(
SessionTimeoutPage.class);
if (!testMode) {
scheduleDefaultTasks();
}
if (usesDeploymentConfig())
getApplicationSettings().setInternalErrorPage(TysanErrorPage.class);
getResourceSettings().setUseMinifiedResources(false);
addResourceReplacement(WiQueryCoreThemeResourceReference.get(),
new CssResourceReference(TysanApplication.class,
"themes/ui-darkness/jquery-ui-1.10.2.custom.css"));
}
/**
*
*/
private void scheduleDefaultTasks() {
TysanScheduler.getScheduler().setApplication(this);
TysanTask[] tasks = { new AcceptanceVoteStartTask(),
new AcceptanceVoteStopTask(), new ActivationExpirationTask(),
new AutomaticPromotionTask(), new ChancellorElectionChecker(),
new ChancellorElectionResolutionTask(),
new EmailChangeConfirmationExpirationTask(),
new GroupLeaderElectionResolutionTask(),
new MemberApplicationResolutionTask(),
new MembershipExpirationTask(),
new PasswordRequestExpirationTask(),
new RegulationChangeResolutionTask(),
new ResolveImpeachmentTask(), new SenateElectionChecker(),
new SenateElectionResolutionTask(),
new TruthsayerAcceptanceVoteResolver(),
new UntenabilityVoteResolutionTask(), new TwitterQueueTask(),
new TwitterTimelineTask(), new TwitterSearchTask(),
new AchievementProposalTask(), new WarnInactiveMembersTask(),
new ResolveRoleTransferTask(), new CheckSubscriptionsDueTask(),
new ResolveTruthsayerComplaintTask(),
new MumbleServerUpdateTask() };
for (TysanTask task : tasks) {
TysanScheduler.getScheduler().scheduleTask(task);
}
if (System.getProperty("tysan.debug") != null) {
TysanScheduler.getScheduler().scheduleTask(
new NoAccountExpireTask());
}
}
/**
*
*/
private void mountBookmarkablePages() {
mountPage("/news", NewsPage.class);
mountPage("/charter", CharterPage.class);
mountPage("/about", AboutPage.class);
mountPage("/history", HistoryPage.class);
mountPage("/member/${userid}", MemberPage.class);
mountPage("/members", RosterPage.class);
mountPage("/regulations", RegulationPage.class);
mountPage("/realm/${id}", RealmPage.class);
mountPage("groups", GroupsPage.class);
mountPage("join", JoinOverviewPage.class);
mountPage("vacation", VacationPage.class);
- mountPage("/threads/${threadid/${pageid}", ForumThreadPage.class);
+ mountPage("/threads/${threadid}/${pageid}", ForumThreadPage.class);
mountPage("/group/${groupid}", GroupPage.class);
mountPage("/forums/${forumid}/${pageid}", ForumPage.class);
mountPage("/listforums", ForumOverviewPage.class);
mountPage("/register", RegistrationPage.class);
mountPage("/activation/${key}", ActivationPage.class);
mountPage("/resetpassword/${key}",
PasswordRequestConfirmationPage.class);
mountPage("/accessdenied", AccessDeniedPage.class);
mountPage("/mc-whitelist", MinecraftWhiteListPage.class);
mountPage("/tracker/${mode}", BugOverviewPage.class);
mountPage("/processPaymentRequest/${requestId}/${confirmationKey}",
ProcessPaymentRequestPage.class);
mountPage(
"/processSubscriptionPayment/${paymentId}/${confirmationKey}",
SubscriptionPaymentResolvedPage.class);
mountPage("/bug/${id}", ViewBugPage.class);
mountPage("/feature/${id}", ViewBugPage.class);
if (System.getProperty("tysan.install") != null) {
mountPage("/tangoimport", TangoImporterPage.class);
mountPage("/randomcontent", RandomContentGenerationPage.class);
mountPage("/oldexpenses", OldExpensesPage.class);
}
}
/**
* @return The current TysanApplication
*/
public static TysanApplication get() {
return (TysanApplication) Application.get();
}
@Override
public Session newSession(Request request, Response response) {
return new TysanSession(request);
}
@Override
public WebRequest newWebRequest(HttpServletRequest servletRequest,
String filterPath) {
WebRequest request = super.newWebRequest(servletRequest, filterPath);
getSessionStore().setAttribute(
request,
"wickery-theme",
new CssResourceReference(TysanApplication.class,
"themes/ui-darkness/jquery-ui-1.7.2.custom.css"));
return request;
}
/**
* @see org.apache.wicket.Application#onDestroy()
*/
@Override
protected void onDestroy() {
super.onDestroy();
try {
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.shutdown();
} catch (SchedulerException e) {
log.error("Could not stop Quartz Scheduler", e);
}
}
public void notify(SiteWideNotification notification) {
synchronized (notifications) {
notifications.add(notification);
}
}
public List<SiteWideNotification> getActiveNotifications() {
synchronized (notifications) {
Set<SiteWideNotification> exit = new HashSet<SiteWideNotification>();
for (SiteWideNotification next : notifications) {
if (next.isExpired()) {
exit.add(next);
}
}
notifications.removeAll(exit);
return notifications;
}
}
public static class VersionDescriptor implements
Comparable<VersionDescriptor> {
public static VersionDescriptor of(String ver) {
String[] versionData = ver.split("\\.", 4);
int major = Integer.parseInt(versionData[0]);
int minor = Integer.parseInt(versionData[1]);
int date = Integer.parseInt(versionData[2]);
int time = Integer.parseInt(versionData[3]);
return new VersionDescriptor(major, minor, date, time);
}
private final Integer major;
private final Integer minor;
private final Integer date;
private final Integer time;
public VersionDescriptor(int major, int minor, int date, int time) {
super();
this.major = major;
this.minor = minor;
this.date = date;
this.time = time;
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getDate() {
return date;
}
public int getTime() {
return time;
}
@Override
public int compareTo(VersionDescriptor o) {
int compareMajor = major.compareTo(o.major);
int compareMinor = minor.compareTo(o.minor);
int compareDate = date.compareTo(o.date);
int compareTime = time.compareTo(o.time);
if (compareMajor != 0)
return compareMajor;
if (compareMinor != 0)
return compareMinor;
if (compareDate != 0)
return compareDate;
if (compareTime != 0)
return compareTime;
return 0;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((major == null) ? 0 : major.hashCode());
result = prime * result + ((minor == null) ? 0 : minor.hashCode());
result = prime * result + ((time == null) ? 0 : time.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VersionDescriptor other = (VersionDescriptor) obj;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (major == null) {
if (other.major != null)
return false;
} else if (!major.equals(other.major))
return false;
if (minor == null) {
if (other.minor != null)
return false;
} else if (!minor.equals(other.minor))
return false;
if (time == null) {
if (other.time != null)
return false;
} else if (!time.equals(other.time))
return false;
return true;
}
@Override
public String toString() {
return major + "." + minor + "." + date + "." + time;
}
public VersionDescriptor next() {
return new VersionDescriptor(major, minor, date, time + 1);
}
}
}
| true | true | private void mountBookmarkablePages() {
mountPage("/news", NewsPage.class);
mountPage("/charter", CharterPage.class);
mountPage("/about", AboutPage.class);
mountPage("/history", HistoryPage.class);
mountPage("/member/${userid}", MemberPage.class);
mountPage("/members", RosterPage.class);
mountPage("/regulations", RegulationPage.class);
mountPage("/realm/${id}", RealmPage.class);
mountPage("groups", GroupsPage.class);
mountPage("join", JoinOverviewPage.class);
mountPage("vacation", VacationPage.class);
mountPage("/threads/${threadid/${pageid}", ForumThreadPage.class);
mountPage("/group/${groupid}", GroupPage.class);
mountPage("/forums/${forumid}/${pageid}", ForumPage.class);
mountPage("/listforums", ForumOverviewPage.class);
mountPage("/register", RegistrationPage.class);
mountPage("/activation/${key}", ActivationPage.class);
mountPage("/resetpassword/${key}",
PasswordRequestConfirmationPage.class);
mountPage("/accessdenied", AccessDeniedPage.class);
mountPage("/mc-whitelist", MinecraftWhiteListPage.class);
mountPage("/tracker/${mode}", BugOverviewPage.class);
mountPage("/processPaymentRequest/${requestId}/${confirmationKey}",
ProcessPaymentRequestPage.class);
mountPage(
"/processSubscriptionPayment/${paymentId}/${confirmationKey}",
SubscriptionPaymentResolvedPage.class);
mountPage("/bug/${id}", ViewBugPage.class);
mountPage("/feature/${id}", ViewBugPage.class);
if (System.getProperty("tysan.install") != null) {
mountPage("/tangoimport", TangoImporterPage.class);
mountPage("/randomcontent", RandomContentGenerationPage.class);
mountPage("/oldexpenses", OldExpensesPage.class);
}
}
| private void mountBookmarkablePages() {
mountPage("/news", NewsPage.class);
mountPage("/charter", CharterPage.class);
mountPage("/about", AboutPage.class);
mountPage("/history", HistoryPage.class);
mountPage("/member/${userid}", MemberPage.class);
mountPage("/members", RosterPage.class);
mountPage("/regulations", RegulationPage.class);
mountPage("/realm/${id}", RealmPage.class);
mountPage("groups", GroupsPage.class);
mountPage("join", JoinOverviewPage.class);
mountPage("vacation", VacationPage.class);
mountPage("/threads/${threadid}/${pageid}", ForumThreadPage.class);
mountPage("/group/${groupid}", GroupPage.class);
mountPage("/forums/${forumid}/${pageid}", ForumPage.class);
mountPage("/listforums", ForumOverviewPage.class);
mountPage("/register", RegistrationPage.class);
mountPage("/activation/${key}", ActivationPage.class);
mountPage("/resetpassword/${key}",
PasswordRequestConfirmationPage.class);
mountPage("/accessdenied", AccessDeniedPage.class);
mountPage("/mc-whitelist", MinecraftWhiteListPage.class);
mountPage("/tracker/${mode}", BugOverviewPage.class);
mountPage("/processPaymentRequest/${requestId}/${confirmationKey}",
ProcessPaymentRequestPage.class);
mountPage(
"/processSubscriptionPayment/${paymentId}/${confirmationKey}",
SubscriptionPaymentResolvedPage.class);
mountPage("/bug/${id}", ViewBugPage.class);
mountPage("/feature/${id}", ViewBugPage.class);
if (System.getProperty("tysan.install") != null) {
mountPage("/tangoimport", TangoImporterPage.class);
mountPage("/randomcontent", RandomContentGenerationPage.class);
mountPage("/oldexpenses", OldExpensesPage.class);
}
}
|
diff --git a/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ProjectViewAction.java b/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ProjectViewAction.java
index 1e0c66871..a03e042c9 100644
--- a/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ProjectViewAction.java
+++ b/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ProjectViewAction.java
@@ -1,106 +1,102 @@
package org.apache.maven.continuum.web.action;
/*
* Copyright 2004-2006 The Apache Software 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.
*/
import org.apache.maven.continuum.ContinuumException;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectGroup;
/**
* @author <a href="mailto:[email protected]">Emmanuel Venisse</a>
* @version $Id$
*
* @plexus.component
* role="com.opensymphony.xwork.Action"
* role-hint="projectView"
*/
public class ProjectViewAction
extends ContinuumActionSupport
{
private Project project;
private int projectId;
/**
* Target {@link ProjectGroup} to view.
*/
private ProjectGroup projectGroup;
/**
* Identifier for the target {@link ProjectGroup} to obtain for
* viewing.
*/
private int projectGroupId;
public String execute()
throws ContinuumException
{
- // determine if we should obtain ProjectGroup details
- if ( projectGroupId > 0 )
- projectGroup = getContinuum().getProjectGroup( projectGroupId );
- else
- project = getContinuum().getProjectWithAllDetails( projectId );
+ project = getContinuum().getProjectWithAllDetails( projectId );
return SUCCESS;
}
public void setProjectId( int projectId )
{
this.projectId = projectId;
}
public Project getProject()
{
return project;
}
public int getProjectId()
{
return projectId;
}
/**
* Return the identifier for the {@link ProjectGroup} to view.
* @return the projectGroupId
*/
public int getProjectGroupId()
{
return projectGroupId;
}
/**
* Sets the {@link ProjectGroup} identifier to obtain for viewing.
* @param projectGroupId the projectGroupId to set
*/
public void setProjectGroupId( int projectGroupId )
{
this.projectGroupId = projectGroupId;
}
/**
* Returns the {@link ProjectGroup} instance obtained for
* the specified project group Id, or null if it were not set.
*
* @return the projectGroup
*/
public ProjectGroup getProjectGroup()
{
return projectGroup;
}
}
| true | true | public String execute()
throws ContinuumException
{
// determine if we should obtain ProjectGroup details
if ( projectGroupId > 0 )
projectGroup = getContinuum().getProjectGroup( projectGroupId );
else
project = getContinuum().getProjectWithAllDetails( projectId );
return SUCCESS;
}
| public String execute()
throws ContinuumException
{
project = getContinuum().getProjectWithAllDetails( projectId );
return SUCCESS;
}
|
diff --git a/helloworld-jms/src/main/java/org/jboss/as/quickstarts/jms/HelloWorldJMSClient.java b/helloworld-jms/src/main/java/org/jboss/as/quickstarts/jms/HelloWorldJMSClient.java
index d3b8752a..4a6e1218 100644
--- a/helloworld-jms/src/main/java/org/jboss/as/quickstarts/jms/HelloWorldJMSClient.java
+++ b/helloworld-jms/src/main/java/org/jboss/as/quickstarts/jms/HelloWorldJMSClient.java
@@ -1,114 +1,114 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.quickstarts.jms;
import java.util.logging.Logger;
import java.util.Properties;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
public class HelloWorldJMSClient {
private static final Logger log = Logger.getLogger(HelloWorldJMSClient.class.getName());
// Set up all the default values
private static final String DEFAULT_MESSAGE = "Hello, World!";
private static final String DEFAULT_CONNECTION_FACTORY = "jms/RemoteConnectionFactory";
private static final String DEFAULT_DESTINATION = "jms/queue/test";
private static final String DEFAULT_MESSAGE_COUNT = "1";
private static final String DEFAULT_USERNAME = "quickstartUser";
private static final String DEFAULT_PASSWORD = "quickstartPassword";
private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
private static final String PROVIDER_URL = "remote://localhost:4447";
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
MessageProducer producer = null;
MessageConsumer consumer = null;
Destination destination = null;
TextMessage message = null;
Context context = null;
try {
// Set up the context for the JNDI lookup
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));
env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));
context = new InitialContext(env);
// Perform the JNDI lookups
String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);
log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\"");
connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString);
log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI");
String destinationString = System.getProperty("destination", DEFAULT_DESTINATION);
log.info("Attempting to acquire destination \"" + destinationString + "\"");
destination = (Destination) context.lookup(destinationString);
log.info("Found destination \"" + destinationString + "\" in JNDI");
// Create the JMS connection, session, producer, and consumer
connection = connectionFactory.createConnection(System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD));
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(destination);
consumer = session.createConsumer(destination);
connection.start();
int count = Integer.parseInt(System.getProperty("message.count", DEFAULT_MESSAGE_COUNT));
String content = System.getProperty("message.content", DEFAULT_MESSAGE);
log.info("Sending " + count + " messages with content: " + content);
// Send the specified number of messages
for (int i = 0; i < count; i++) {
message = session.createTextMessage(content);
producer.send(message);
}
- // Then receive the same number of messaes that were sent
+ // Then receive the same number of messages that were sent
for (int i = 0; i < count; i++) {
message = (TextMessage) consumer.receive(5000);
log.info("Received message with content " + message.getText());
}
} catch (Exception e) {
log.severe(e.getMessage());
throw e;
} finally {
if (context != null) {
context.close();
}
// closing the connection takes care of the session, producer, and consumer
if (connection != null) {
connection.close();
}
}
}
}
| true | true | public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
MessageProducer producer = null;
MessageConsumer consumer = null;
Destination destination = null;
TextMessage message = null;
Context context = null;
try {
// Set up the context for the JNDI lookup
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));
env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));
context = new InitialContext(env);
// Perform the JNDI lookups
String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);
log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\"");
connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString);
log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI");
String destinationString = System.getProperty("destination", DEFAULT_DESTINATION);
log.info("Attempting to acquire destination \"" + destinationString + "\"");
destination = (Destination) context.lookup(destinationString);
log.info("Found destination \"" + destinationString + "\" in JNDI");
// Create the JMS connection, session, producer, and consumer
connection = connectionFactory.createConnection(System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD));
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(destination);
consumer = session.createConsumer(destination);
connection.start();
int count = Integer.parseInt(System.getProperty("message.count", DEFAULT_MESSAGE_COUNT));
String content = System.getProperty("message.content", DEFAULT_MESSAGE);
log.info("Sending " + count + " messages with content: " + content);
// Send the specified number of messages
for (int i = 0; i < count; i++) {
message = session.createTextMessage(content);
producer.send(message);
}
// Then receive the same number of messaes that were sent
for (int i = 0; i < count; i++) {
message = (TextMessage) consumer.receive(5000);
log.info("Received message with content " + message.getText());
}
} catch (Exception e) {
log.severe(e.getMessage());
throw e;
} finally {
if (context != null) {
context.close();
}
// closing the connection takes care of the session, producer, and consumer
if (connection != null) {
connection.close();
}
}
}
| public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
MessageProducer producer = null;
MessageConsumer consumer = null;
Destination destination = null;
TextMessage message = null;
Context context = null;
try {
// Set up the context for the JNDI lookup
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));
env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));
context = new InitialContext(env);
// Perform the JNDI lookups
String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);
log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\"");
connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString);
log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI");
String destinationString = System.getProperty("destination", DEFAULT_DESTINATION);
log.info("Attempting to acquire destination \"" + destinationString + "\"");
destination = (Destination) context.lookup(destinationString);
log.info("Found destination \"" + destinationString + "\" in JNDI");
// Create the JMS connection, session, producer, and consumer
connection = connectionFactory.createConnection(System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD));
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(destination);
consumer = session.createConsumer(destination);
connection.start();
int count = Integer.parseInt(System.getProperty("message.count", DEFAULT_MESSAGE_COUNT));
String content = System.getProperty("message.content", DEFAULT_MESSAGE);
log.info("Sending " + count + " messages with content: " + content);
// Send the specified number of messages
for (int i = 0; i < count; i++) {
message = session.createTextMessage(content);
producer.send(message);
}
// Then receive the same number of messages that were sent
for (int i = 0; i < count; i++) {
message = (TextMessage) consumer.receive(5000);
log.info("Received message with content " + message.getText());
}
} catch (Exception e) {
log.severe(e.getMessage());
throw e;
} finally {
if (context != null) {
context.close();
}
// closing the connection takes care of the session, producer, and consumer
if (connection != null) {
connection.close();
}
}
}
|
diff --git a/core/src/main/java/woko/actions/WokoFormatterFactory.java b/core/src/main/java/woko/actions/WokoFormatterFactory.java
index 5e590e4c..b86dbd52 100644
--- a/core/src/main/java/woko/actions/WokoFormatterFactory.java
+++ b/core/src/main/java/woko/actions/WokoFormatterFactory.java
@@ -1,38 +1,38 @@
package woko.actions;
import net.sourceforge.stripes.config.Configuration;
import net.sourceforge.stripes.format.DefaultFormatterFactory;
import net.sourceforge.stripes.format.Formatter;
import woko.Woko;
import woko.persistence.ObjectStore;
import java.util.List;
import java.util.Locale;
public class WokoFormatterFactory extends DefaultFormatterFactory {
private Woko<?,?,?,?> woko = null;
@Override
public void init(Configuration configuration) throws Exception {
super.init(configuration);
woko = Woko.getWoko(getConfiguration().getServletContext());
}
@Override
public Formatter<?> getFormatter(Class<?> clazz, Locale locale, String formatType, String formatPattern) {
if (woko!=null) {
ObjectStore store = woko.getObjectStore();
List<Class<?>> mappedClasses = store.getMappedClasses();
for (Class<?> mappedClass : mappedClasses) {
if (mappedClass.isAssignableFrom(clazz)) {
// class is mapped, return a TC that uses the store to load the object
- return new WokoFormatter<Object>(woko);
+ return new WokoFormatter(woko);
}
}
}
// class ain't mapped in store, use default formatter
return super.getFormatter(clazz, locale, formatType, formatPattern);
}
}
| true | true | public Formatter<?> getFormatter(Class<?> clazz, Locale locale, String formatType, String formatPattern) {
if (woko!=null) {
ObjectStore store = woko.getObjectStore();
List<Class<?>> mappedClasses = store.getMappedClasses();
for (Class<?> mappedClass : mappedClasses) {
if (mappedClass.isAssignableFrom(clazz)) {
// class is mapped, return a TC that uses the store to load the object
return new WokoFormatter<Object>(woko);
}
}
}
// class ain't mapped in store, use default formatter
return super.getFormatter(clazz, locale, formatType, formatPattern);
}
| public Formatter<?> getFormatter(Class<?> clazz, Locale locale, String formatType, String formatPattern) {
if (woko!=null) {
ObjectStore store = woko.getObjectStore();
List<Class<?>> mappedClasses = store.getMappedClasses();
for (Class<?> mappedClass : mappedClasses) {
if (mappedClass.isAssignableFrom(clazz)) {
// class is mapped, return a TC that uses the store to load the object
return new WokoFormatter(woko);
}
}
}
// class ain't mapped in store, use default formatter
return super.getFormatter(clazz, locale, formatType, formatPattern);
}
|
diff --git a/src/image/processing/experimental/HistogramNormalization.java b/src/image/processing/experimental/HistogramNormalization.java
index 4ccf8af..af22d62 100644
--- a/src/image/processing/experimental/HistogramNormalization.java
+++ b/src/image/processing/experimental/HistogramNormalization.java
@@ -1,156 +1,156 @@
/*
* HistogramNormalization.java
*
* Copyright (C) 2012 Pavel Prokhorov ([email protected])
*
* 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 image.processing.experimental;
import image.AbstractImageProcessor;
import image.ImageProcessor;
import image.color.RGB;
import java.awt.image.BufferedImage;
/**
* Нормализация гистограммы.
*
* @author pavelvpster
*
*/
public class HistogramNormalization extends AbstractImageProcessor implements ImageProcessor {
/**
* Конструктор по умолчанию.
*
*/
public HistogramNormalization() {
}
// Параметризованные конструкторы
public HistogramNormalization(BufferedImage sourceImage) {
super(sourceImage);
}
/**
* @see IImageProcessor
*
*/
@Override
public void process() {
if (sourceImage == null) {
throw new RuntimeException("Source image undefined!");
}
// Для нормализации нам понадобятся интенсивности точек
Grayscale grayscale = new Grayscale(sourceImage);
grayscale.process();
BufferedImage intensityImage = grayscale.getProcessedImage();
// Строим гистограмму интенсивностей
int[] histogram = new int [256];
for (int y = 0; y < intensityImage.getHeight(); y ++) {
for (int x = 0; x < intensityImage.getWidth(); x ++) {
RGB a = RGB.get(intensityImage, x, y);
histogram[ a.I ] ++ ;
}
}
// Строим CDF
int[] CDF = new int [256];
int sum = 0;
for (int i = 0; i < 256; i ++) {
sum += histogram[i];
CDF[i] = sum;
}
// Расчитываем минимум и максимум
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < 256; i ++) {
if (CDF[i] != 0) {
if (CDF[i] < min) min = CDF[i];
if (CDF[i] > max) max = CDF[i];
}
}
// Нормализуем гистограмму
int[] map = new int [256];
double s = intensityImage.getWidth() * intensityImage.getHeight();
for (int i = 0; i < 256; i ++) {
- map[i] = (int)(((double)(CDF[i] - min) / s) * 255.0);
+ map[i] = (int)(((double)(CDF[i] - min) / (s - min)) * 255.0);
}
// Создаем обработанное изображение
processedImage = new BufferedImage
(sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getType());
// Color Remapping
for (int y = 0; y < processedImage.getHeight(); y ++) {
for (int x = 0; x < processedImage.getWidth(); x ++) {
RGB a = RGB.get(sourceImage, x, y);
int i = RGB.get(intensityImage, x, y).I;
int c = map[i];
double f = (double)c / (double)i;
a.R *= f;
a.G *= f;
a.B *= f;
a.clamp();
a.set(processedImage, x, y);
}
}
}
}
| true | true | public void process() {
if (sourceImage == null) {
throw new RuntimeException("Source image undefined!");
}
// Для нормализации нам понадобятся интенсивности точек
Grayscale grayscale = new Grayscale(sourceImage);
grayscale.process();
BufferedImage intensityImage = grayscale.getProcessedImage();
// Строим гистограмму интенсивностей
int[] histogram = new int [256];
for (int y = 0; y < intensityImage.getHeight(); y ++) {
for (int x = 0; x < intensityImage.getWidth(); x ++) {
RGB a = RGB.get(intensityImage, x, y);
histogram[ a.I ] ++ ;
}
}
// Строим CDF
int[] CDF = new int [256];
int sum = 0;
for (int i = 0; i < 256; i ++) {
sum += histogram[i];
CDF[i] = sum;
}
// Расчитываем минимум и максимум
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < 256; i ++) {
if (CDF[i] != 0) {
if (CDF[i] < min) min = CDF[i];
if (CDF[i] > max) max = CDF[i];
}
}
// Нормализуем гистограмму
int[] map = new int [256];
double s = intensityImage.getWidth() * intensityImage.getHeight();
for (int i = 0; i < 256; i ++) {
map[i] = (int)(((double)(CDF[i] - min) / s) * 255.0);
}
// Создаем обработанное изображение
processedImage = new BufferedImage
(sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getType());
// Color Remapping
for (int y = 0; y < processedImage.getHeight(); y ++) {
for (int x = 0; x < processedImage.getWidth(); x ++) {
RGB a = RGB.get(sourceImage, x, y);
int i = RGB.get(intensityImage, x, y).I;
int c = map[i];
double f = (double)c / (double)i;
a.R *= f;
a.G *= f;
a.B *= f;
a.clamp();
a.set(processedImage, x, y);
}
}
}
| public void process() {
if (sourceImage == null) {
throw new RuntimeException("Source image undefined!");
}
// Для нормализации нам понадобятся интенсивности точек
Grayscale grayscale = new Grayscale(sourceImage);
grayscale.process();
BufferedImage intensityImage = grayscale.getProcessedImage();
// Строим гистограмму интенсивностей
int[] histogram = new int [256];
for (int y = 0; y < intensityImage.getHeight(); y ++) {
for (int x = 0; x < intensityImage.getWidth(); x ++) {
RGB a = RGB.get(intensityImage, x, y);
histogram[ a.I ] ++ ;
}
}
// Строим CDF
int[] CDF = new int [256];
int sum = 0;
for (int i = 0; i < 256; i ++) {
sum += histogram[i];
CDF[i] = sum;
}
// Расчитываем минимум и максимум
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < 256; i ++) {
if (CDF[i] != 0) {
if (CDF[i] < min) min = CDF[i];
if (CDF[i] > max) max = CDF[i];
}
}
// Нормализуем гистограмму
int[] map = new int [256];
double s = intensityImage.getWidth() * intensityImage.getHeight();
for (int i = 0; i < 256; i ++) {
map[i] = (int)(((double)(CDF[i] - min) / (s - min)) * 255.0);
}
// Создаем обработанное изображение
processedImage = new BufferedImage
(sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getType());
// Color Remapping
for (int y = 0; y < processedImage.getHeight(); y ++) {
for (int x = 0; x < processedImage.getWidth(); x ++) {
RGB a = RGB.get(sourceImage, x, y);
int i = RGB.get(intensityImage, x, y).I;
int c = map[i];
double f = (double)c / (double)i;
a.R *= f;
a.G *= f;
a.B *= f;
a.clamp();
a.set(processedImage, x, y);
}
}
}
|
diff --git a/plugins/org.eclipse.jst.j2ee.ui/j2ee_ui/org/eclipse/jst/j2ee/internal/ui/J2EEModuleDependenciesPropertyPage.java b/plugins/org.eclipse.jst.j2ee.ui/j2ee_ui/org/eclipse/jst/j2ee/internal/ui/J2EEModuleDependenciesPropertyPage.java
index ea6009650..4b57ea2b0 100644
--- a/plugins/org.eclipse.jst.j2ee.ui/j2ee_ui/org/eclipse/jst/j2ee/internal/ui/J2EEModuleDependenciesPropertyPage.java
+++ b/plugins/org.eclipse.jst.j2ee.ui/j2ee_ui/org/eclipse/jst/j2ee/internal/ui/J2EEModuleDependenciesPropertyPage.java
@@ -1,398 +1,398 @@
/******************************************************************************
* Copyright (c) 2009 Red Hat 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:
* Rob Stryker - initial implementation and ongoing maintenance
* Chuck Bridgham - additional support
* Konstantin Komissarchik - misc. UI cleanup
******************************************************************************/
package org.eclipse.jst.j2ee.internal.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathAttribute;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jst.common.jdt.internal.javalite.IJavaProjectLite;
import org.eclipse.jst.common.jdt.internal.javalite.JavaCoreLite;
import org.eclipse.jst.j2ee.classpathdep.ClasspathDependencyUtil;
import org.eclipse.jst.j2ee.classpathdep.IClasspathDependencyConstants.DependencyAttributeType;
import org.eclipse.jst.j2ee.internal.common.classpath.J2EEComponentClasspathUpdater;
import org.eclipse.jst.j2ee.internal.componentcore.JavaEEModuleHandler;
import org.eclipse.jst.j2ee.internal.plugin.J2EEUIPlugin;
import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities;
import org.eclipse.jst.j2ee.project.JavaEEProjectUtilities;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.wst.common.componentcore.internal.IModuleHandler;
import org.eclipse.wst.common.componentcore.internal.impl.TaskModel;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.common.componentcore.resources.IVirtualReference;
import org.eclipse.wst.common.componentcore.ui.internal.propertypage.ComponentDependencyContentProvider;
import org.eclipse.wst.common.componentcore.ui.internal.taskwizard.TaskWizard;
import org.eclipse.wst.common.componentcore.ui.propertypage.AddModuleDependenciesPropertiesPage;
import org.eclipse.wst.common.componentcore.ui.propertypage.IReferenceWizardConstants;
import org.eclipse.wst.common.componentcore.ui.propertypage.IReferenceWizardConstants.ProjectConverterOperationProvider;
import org.eclipse.wst.common.componentcore.ui.propertypage.ModuleAssemblyRootPage;
import org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation;
public class J2EEModuleDependenciesPropertyPage extends
AddModuleDependenciesPropertiesPage {
public J2EEModuleDependenciesPropertyPage(IProject project,
ModuleAssemblyRootPage page) {
super(project, page);
}
public class ClasspathEntryProxy {
public IClasspathEntry entry;
public ClasspathEntryProxy(IClasspathEntry entry){
this.entry = entry;
}
}
protected List <IClasspathEntry> originalClasspathEntries = new ArrayList<IClasspathEntry>();
protected List <ClasspathEntryProxy> currentClasspathEntries = new ArrayList<ClasspathEntryProxy>();
@Override
protected void initialize() {
super.initialize();
resetClasspathEntries();
}
private void resetClasspathEntries() {
originalClasspathEntries.clear();
currentClasspathEntries.clear();
originalClasspathEntries.addAll(readRawEntries());
for(IClasspathEntry entry:originalClasspathEntries){
currentClasspathEntries.add(new ClasspathEntryProxy(entry));
}
}
@Override
public void performDefaults() {
resetClasspathEntries();
super.performDefaults();
}
protected List <IClasspathEntry> readRawEntries(){
return readRawEntries(rootComponent);
}
public static List <IClasspathEntry> readRawEntries(IVirtualComponent component){
List <IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
IJavaProjectLite javaProjectLite = JavaCoreLite.create(component.getProject());
try {
Map<IClasspathEntry, IClasspathAttribute> rawComponentClasspathDependencies = ClasspathDependencyUtil.getRawComponentClasspathDependencies(javaProjectLite, DependencyAttributeType.CLASSPATH_COMPONENT_DEPENDENCY);
entries.addAll(rawComponentClasspathDependencies.keySet());
} catch (CoreException e) {
J2EEUIPlugin.logError(e);
}
return entries;
}
@Override
public boolean postHandleChanges(IProgressMonitor monitor) {
return true;
}
@Override
protected void handleRemoved(ArrayList<IVirtualReference> removed) {
super.handleRemoved(removed);
J2EEComponentClasspathUpdater.getInstance().queueUpdateEAR(rootComponent.getProject());
}
@Override
protected void remove(Object selectedItem) {
if(selectedItem instanceof ClasspathEntryProxy){
ClasspathEntryProxy entry = (ClasspathEntryProxy)selectedItem;
currentClasspathEntries.remove(entry);
} else {
super.remove(selectedItem);
}
}
@Override
protected String getModuleAssemblyRootPageDescription() {
if (JavaEEProjectUtilities.isEJBProject(project))
return Messages.J2EEModuleDependenciesPropertyPage_3;
if (JavaEEProjectUtilities.isApplicationClientProject(project))
return Messages.J2EEModuleDependenciesPropertyPage_4;
if (JavaEEProjectUtilities.isJCAProject(project))
return Messages.J2EEModuleDependenciesPropertyPage_5;
return super.getModuleAssemblyRootPageDescription();
}
@Override
protected IModuleHandler getModuleHandler() {
if(moduleHandler == null)
moduleHandler = new JavaEEModuleHandler();
return moduleHandler;
}
@Override
protected void setCustomReferenceWizardProperties(TaskModel model) {
model.putObject(IReferenceWizardConstants.PROJECT_CONVERTER_OPERATION_PROVIDER, getConverterProvider());
}
public ProjectConverterOperationProvider getConverterProvider() {
return new ProjectConverterOperationProvider() {
public IDataModelOperation getConversionOperation(IProject project) {
return J2EEProjectUtilities.createFlexJavaProjectForProjectOperation(project);
}
};
}
@Override
protected ComponentDependencyContentProvider createProvider() {
JavaEEComponentDependencyContentProvider provider = new JavaEEComponentDependencyContentProvider(this);
provider.setClasspathEntries(currentClasspathEntries);
return provider;
}
@Override
protected boolean canRemove(Object selectedObject) {
return super.canRemove(selectedObject) && !(selectedObject instanceof JavaEEComponentDependencyContentProvider.ConsumedClasspathEntryProxy);
}
@Override
protected RuntimePathCellModifier getRuntimePathCellModifier() {
return new AddModuleDependenciesPropertiesPage.RuntimePathCellModifier(){
@Override
public boolean canModify(Object element, String property) {
if( property.equals(DEPLOY_PATH_PROPERTY) && element instanceof ClasspathEntryProxy) {
return true;
}
return super.canModify(element, property);
}
@Override
public Object getValue(Object element, String property) {
if(element instanceof ClasspathEntryProxy){
IClasspathEntry entry = ((ClasspathEntryProxy)element).entry;
return ClasspathDependencyUtil.getRuntimePath(entry).toString();
}
return super.getValue(element, property);
}
@Override
public void modify(Object element, String property, Object value) {
if (property.equals(DEPLOY_PATH_PROPERTY)) {
TreeItem item = (TreeItem) element;
if(item.getData() instanceof ClasspathEntryProxy){
TreeItem[] components = availableComponentsViewer.getTree().getItems();
int tableIndex = -1;
for(int i=0; i < components.length; i++) {
if(components[i] == item) {
tableIndex = i;
break;
}
}
ClasspathEntryProxy proxy = (ClasspathEntryProxy)item.getData();
IPath runtimePath = new Path((String)value);
IClasspathEntry newEntry = ClasspathDependencyUtil.modifyDependencyPath(proxy.entry, runtimePath);
proxy.entry = newEntry;
resourceMappingsChanged = true;
if(tableIndex >= 0)
components[tableIndex].setText(AddModuleDependenciesPropertiesPage.DEPLOY_COLUMN, (String)value);
}
}
super.modify(element, property, value);
}
};
}
@Override
protected boolean saveReferenceChanges() {
boolean subResult = super.saveReferenceChanges();
if(!subResult){
return subResult;
}
Map <IPath, IClasspathEntry> modified = new HashMap <IPath, IClasspathEntry>();
Map <IPath, IClasspathEntry> originalMap = new HashMap <IPath, IClasspathEntry>();
for(IClasspathEntry originalEntry : originalClasspathEntries){
originalMap.put(originalEntry.getPath(), originalEntry);
}
for(ClasspathEntryProxy proxy: currentClasspathEntries){
IClasspathEntry currentEntry = proxy.entry;
IPath path = currentEntry.getPath();
IClasspathEntry originalEntry = originalMap.remove(path);
if(currentEntry.equals(originalEntry)){
//no change
continue;
}
modified.put(path, currentEntry);
}
Map <IPath, IClasspathEntry> removed = originalMap;
IJavaProject javaProject = JavaCore.create(rootComponent.getProject());
try {
final IClasspathEntry [] rawClasspath = javaProject.getRawClasspath();
List <IClasspathEntry> newClasspath = new ArrayList <IClasspathEntry>();
for(IClasspathEntry entry:rawClasspath){
IPath path = entry.getPath();
if(removed.containsKey(path)){
//user removed entry
IClasspathEntry newEntry = ClasspathDependencyUtil.modifyDependencyPath(entry, null);
newClasspath.add(newEntry);
} else if(modified.containsKey(path)){
//user changed path value
IClasspathEntry newEntry = modified.get(path);
IPath runtimePath = ClasspathDependencyUtil.getRuntimePath(newEntry);
- if(runtimePath.toString().isEmpty()){
+ if(runtimePath.toString().length() == 0){
//prevent the user from specifying no path
newEntry = ClasspathDependencyUtil.modifyDependencyPath(newEntry, new Path("/")); //$NON-NLS-1$
}
newClasspath.add(newEntry);
} else {
//no change
newClasspath.add(entry);
}
}
javaProject.setRawClasspath( newClasspath.toArray( new IClasspathEntry[ newClasspath.size() ] ), null );
originalClasspathEntries.clear();
currentClasspathEntries.clear();
resetClasspathEntries();
} catch (JavaModelException e) {
J2EEUIPlugin.logError(e);
return false;
}
return true;
}
@Override
protected void handleAddDirective( final TaskWizard wizard )
{
final List<IClasspathEntry> classpathEntries
= (List<IClasspathEntry>) wizard.getTaskModel().getObject( AddJavaBuildPathEntriesWizardFragment.PROP_SELECTION );
if( classpathEntries != null && ! classpathEntries.isEmpty() )
{
for( IClasspathEntry cpe : classpathEntries )
{
this.currentClasspathEntries.add( new ClasspathEntryProxy( cpe ) );
}
}
else
{
super.handleAddDirective(wizard);
}
}
//
// @Override
// protected IDataModelProvider getAddReferenceDataModelProvider(IVirtualComponent component) {
// return new AddComponentToEnterpriseApplicationDataModelProvider();
// }
//
// protected void addToManifest(ArrayList<IVirtualComponent> components) {
// StringBuffer newComps = getCompsForManifest(components);
// if(newComps.toString().length() > 0) {
// UpdateManifestOperation op = createManifestOperation(newComps.toString());
// try {
// op.run(new NullProgressMonitor());
// } catch (InvocationTargetException e) {
// J2EEUIPlugin.logError(e);
// } catch (InterruptedException e) {
// J2EEUIPlugin.logError(e);
// }
// }
// }
//
// protected void addOneComponent(IVirtualComponent component, IPath path, String archiveName) throws CoreException {
// //Find the Ear's that contain this component
// IProject[] earProjects = EarUtilities.getReferencingEARProjects(rootComponent.getProject());
// for (int i = 0; i < earProjects.length; i++) {
// IProject project = earProjects[i];
//
// IDataModelProvider provider = getAddReferenceDataModelProvider(component);
// IDataModel dm = DataModelFactory.createDataModel(provider);
//
// dm.setProperty(ICreateReferenceComponentsDataModelProperties.SOURCE_COMPONENT, ComponentCore.createComponent(project));
// dm.setProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENT_LIST, Arrays.asList(component));
//
// //[Bug 238264] the uri map needs to be manually set correctly
// Map<IVirtualComponent, String> uriMap = new HashMap<IVirtualComponent, String>();
// uriMap.put(component, archiveName);
// dm.setProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENTS_TO_URI_MAP, uriMap);
// dm.setProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENTS_DEPLOY_PATH, path);
//
// IStatus stat = dm.validateProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENT_LIST);
// if (stat != OK_STATUS)
// throw new CoreException(stat);
// try {
// dm.getDefaultOperation().execute(new NullProgressMonitor(), null);
// } catch (ExecutionException e) {
// ModuleCoreUIPlugin.logError(e);
// }
// }
// }
//
//
// protected StringBuffer getCompsForManifest(ArrayList<IVirtualComponent> components) {
// StringBuffer newComps = new StringBuffer();
// for (Iterator iterator = components.iterator(); iterator.hasNext();) {
// IVirtualComponent comp = (IVirtualComponent) iterator.next();
// String archiveName = new Path(derivedRefsObjectToRuntimePath.get(comp)).lastSegment();
// newComps.append(archiveName);
// newComps.append(' ');
// }
// return newComps;
// }
//
// protected UpdateManifestOperation createManifestOperation(String newComps) {
// return new UpdateManifestOperation(project.getName(), newComps, false);
// }
//
// private void removeFromManifest(ArrayList<IVirtualComponent> removed) {
// String sourceProjName = project.getName();
// IProgressMonitor monitor = new NullProgressMonitor();
// IFile manifestmf = J2EEProjectUtilities.getManifestFile(project);
// ArchiveManifest mf = J2EEProjectUtilities.readManifest(project);
// if (mf == null)
// return;
// IDataModel updateManifestDataModel = DataModelFactory.createDataModel(new UpdateManifestDataModelProvider());
// updateManifestDataModel.setProperty(UpdateManifestDataModelProperties.PROJECT_NAME, sourceProjName);
// updateManifestDataModel.setBooleanProperty(UpdateManifestDataModelProperties.MERGE, false);
// updateManifestDataModel.setProperty(UpdateManifestDataModelProperties.MANIFEST_FILE, manifestmf);
// String[] cp = mf.getClassPathTokenized();
// List cpList = new ArrayList();
//
// for (int i = 0; i < cp.length; i++) {
// boolean foundMatch = false;
// for (Iterator iterator = removed.iterator(); iterator.hasNext();) {
// IVirtualComponent comp = (IVirtualComponent) iterator.next();
// String cpToRemove = new Path(derivedRefsOldComponentToRuntimePath.get(comp)).lastSegment();
// if (cp[i].equals(cpToRemove))
// foundMatch = true;
// }
// if (!foundMatch)
// cpList.add(cp[i]);
// }
// updateManifestDataModel.setProperty(UpdateManifestDataModelProperties.JAR_LIST, cpList);
// try {
// updateManifestDataModel.getDefaultOperation().execute(monitor, null );
// } catch (ExecutionException e) {
// J2EEUIPlugin.logError(e);
// }
// }
}
| true | true | protected boolean saveReferenceChanges() {
boolean subResult = super.saveReferenceChanges();
if(!subResult){
return subResult;
}
Map <IPath, IClasspathEntry> modified = new HashMap <IPath, IClasspathEntry>();
Map <IPath, IClasspathEntry> originalMap = new HashMap <IPath, IClasspathEntry>();
for(IClasspathEntry originalEntry : originalClasspathEntries){
originalMap.put(originalEntry.getPath(), originalEntry);
}
for(ClasspathEntryProxy proxy: currentClasspathEntries){
IClasspathEntry currentEntry = proxy.entry;
IPath path = currentEntry.getPath();
IClasspathEntry originalEntry = originalMap.remove(path);
if(currentEntry.equals(originalEntry)){
//no change
continue;
}
modified.put(path, currentEntry);
}
Map <IPath, IClasspathEntry> removed = originalMap;
IJavaProject javaProject = JavaCore.create(rootComponent.getProject());
try {
final IClasspathEntry [] rawClasspath = javaProject.getRawClasspath();
List <IClasspathEntry> newClasspath = new ArrayList <IClasspathEntry>();
for(IClasspathEntry entry:rawClasspath){
IPath path = entry.getPath();
if(removed.containsKey(path)){
//user removed entry
IClasspathEntry newEntry = ClasspathDependencyUtil.modifyDependencyPath(entry, null);
newClasspath.add(newEntry);
} else if(modified.containsKey(path)){
//user changed path value
IClasspathEntry newEntry = modified.get(path);
IPath runtimePath = ClasspathDependencyUtil.getRuntimePath(newEntry);
if(runtimePath.toString().isEmpty()){
//prevent the user from specifying no path
newEntry = ClasspathDependencyUtil.modifyDependencyPath(newEntry, new Path("/")); //$NON-NLS-1$
}
newClasspath.add(newEntry);
} else {
//no change
newClasspath.add(entry);
}
}
javaProject.setRawClasspath( newClasspath.toArray( new IClasspathEntry[ newClasspath.size() ] ), null );
originalClasspathEntries.clear();
currentClasspathEntries.clear();
resetClasspathEntries();
} catch (JavaModelException e) {
J2EEUIPlugin.logError(e);
return false;
}
return true;
}
| protected boolean saveReferenceChanges() {
boolean subResult = super.saveReferenceChanges();
if(!subResult){
return subResult;
}
Map <IPath, IClasspathEntry> modified = new HashMap <IPath, IClasspathEntry>();
Map <IPath, IClasspathEntry> originalMap = new HashMap <IPath, IClasspathEntry>();
for(IClasspathEntry originalEntry : originalClasspathEntries){
originalMap.put(originalEntry.getPath(), originalEntry);
}
for(ClasspathEntryProxy proxy: currentClasspathEntries){
IClasspathEntry currentEntry = proxy.entry;
IPath path = currentEntry.getPath();
IClasspathEntry originalEntry = originalMap.remove(path);
if(currentEntry.equals(originalEntry)){
//no change
continue;
}
modified.put(path, currentEntry);
}
Map <IPath, IClasspathEntry> removed = originalMap;
IJavaProject javaProject = JavaCore.create(rootComponent.getProject());
try {
final IClasspathEntry [] rawClasspath = javaProject.getRawClasspath();
List <IClasspathEntry> newClasspath = new ArrayList <IClasspathEntry>();
for(IClasspathEntry entry:rawClasspath){
IPath path = entry.getPath();
if(removed.containsKey(path)){
//user removed entry
IClasspathEntry newEntry = ClasspathDependencyUtil.modifyDependencyPath(entry, null);
newClasspath.add(newEntry);
} else if(modified.containsKey(path)){
//user changed path value
IClasspathEntry newEntry = modified.get(path);
IPath runtimePath = ClasspathDependencyUtil.getRuntimePath(newEntry);
if(runtimePath.toString().length() == 0){
//prevent the user from specifying no path
newEntry = ClasspathDependencyUtil.modifyDependencyPath(newEntry, new Path("/")); //$NON-NLS-1$
}
newClasspath.add(newEntry);
} else {
//no change
newClasspath.add(entry);
}
}
javaProject.setRawClasspath( newClasspath.toArray( new IClasspathEntry[ newClasspath.size() ] ), null );
originalClasspathEntries.clear();
currentClasspathEntries.clear();
resetClasspathEntries();
} catch (JavaModelException e) {
J2EEUIPlugin.logError(e);
return false;
}
return true;
}
|
diff --git a/src/main/java/org/monstercraft/support/plugin/managers/SettingsManager.java b/src/main/java/org/monstercraft/support/plugin/managers/SettingsManager.java
index 020b71b..3c2a472 100644
--- a/src/main/java/org/monstercraft/support/plugin/managers/SettingsManager.java
+++ b/src/main/java/org/monstercraft/support/plugin/managers/SettingsManager.java
@@ -1,181 +1,184 @@
package org.monstercraft.support.plugin.managers;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.monstercraft.support.MonsterTickets;
import org.monstercraft.support.plugin.Configuration;
import org.monstercraft.support.plugin.Configuration.Variables;
import org.monstercraft.support.plugin.command.commands.Close;
import org.monstercraft.support.plugin.util.Status;
import org.monstercraft.support.plugin.wrappers.HelpTicket;
/**
* This class contains all of the plugins settings.
*
* @author fletch_to_99 <[email protected]>
*
*/
public class SettingsManager {
private MonsterTickets plugin = null;
private String SETTINGS_PATH = null;
private String SETTINGS_FILE = "Config.yml";
/**
* Creates an instance of the Settings class.
*
* @param plugin
* The parent plugin.
* @throws InvalidConfigurationException
* @throws IOException
* @throws FileNotFoundException
*/
public SettingsManager(MonsterTickets plugin) {
this.plugin = plugin;
this.SETTINGS_PATH = plugin.getDataFolder().getAbsolutePath();
load();
loadTicketsConfig();
}
private void save(final FileConfiguration config, final File file) {
try {
config.save(file);
} catch (IOException e) {
Configuration.debug(e);
}
}
/**
* This method loads the plugins configuration file.
*/
public void save() {
final FileConfiguration config = this.plugin.getConfig();
final File CONFIGURATION_FILE = new File(SETTINGS_PATH + File.separator
+ SETTINGS_FILE);
try {
config.set("MONSTERTICKETS.OPTIONS.OVERRIDE_HELP_COMMAND",
Variables.overridehelp);
save(config, CONFIGURATION_FILE);
} catch (Exception e) {
Configuration.debug(e);
}
}
/**
* This method loads the plugins configuration file.
*/
public void load() {
final FileConfiguration config = this.plugin.getConfig();
final File CONFIGURATION_FILE = new File(SETTINGS_PATH, SETTINGS_FILE);
boolean exists = CONFIGURATION_FILE.exists();
if (exists) {
try {
Configuration.log("Loading settings!");
config.options()
.header("MonsterTickets configuration file, refer to our DBO page for help.");
config.load(CONFIGURATION_FILE);
} catch (Exception e) {
Configuration.debug(e);
}
} else {
Configuration.log("Loading default settings!");
config.options()
.header("MonsterTickets configuration file, refer to our DBO page for help.");
config.options().copyDefaults(true);
}
try {
Variables.overridehelp = config.getBoolean(
"MONSTERTICKETS.OPTIONS.OVERRIDE_HELP_COMMAND",
Variables.overridehelp);
save(config, CONFIGURATION_FILE);
} catch (Exception e) {
Configuration.debug(e);
}
}
private void loadTicketsConfig() {
File TICKETS_FILE = new File(SETTINGS_PATH, "Tickets.dat");
if (!TICKETS_FILE.exists()) {
return;
}
List<String> tickets = new ArrayList<String>();
FileConfiguration config = new YamlConfiguration();
try {
config.load(TICKETS_FILE);
} catch (Exception e) {
Configuration.log("Error loading cached tickets!");
File back = new File(SETTINGS_PATH, "OLD_Tickets.dat");
if (back.exists()) {
back.delete();// prevent errors when saving later
}
TICKETS_FILE.renameTo(back); // prevent errors when saving
return;
}
config.options().header("DO NOT MODIFY");
tickets = config.getStringList("TICKETS");
if (!tickets.isEmpty()) {
for (String str : tickets) {
if (str.contains("|")) {
int count = 0;
for (char c : str.toCharArray()) {
if (c == '|') {
count++;
}
}
- int idx1 = str.indexOf("|");
- int idx2 = str.indexOf("|", idx1);
- if (count == 3) {
- int id = Integer.parseInt(str.substring(0, idx1));
- String player = str.substring(idx1 + 1, idx2);
- String description = str.substring(idx2 + 1);
- Variables.tickets.add(new HelpTicket(id, description,
- player));
- } else if (count == 4) {
- int idx3 = str.indexOf("|", idx2);
- int id = Integer.parseInt(str.substring(0, idx1));
- String player = str.substring(idx1 + 1, idx2);
- String description = str.substring(idx2 + 1, idx3);
- String modname = str.substring(idx3 + 1);
- HelpTicket t = new HelpTicket(id, description, player);
- Variables.tickets.add(t);
- Variables.tickets.getLast().Claim(modname);
- Variables.tickets.getLast().close();
+ if (count > 0) {
+ int idx1 = str.indexOf("|");
+ int idx2 = str.indexOf("|", idx1);
+ if (count == 3) {
+ int id = Integer.parseInt(str.substring(0, idx1));
+ String player = str.substring(idx1 + 1, idx2);
+ String description = str.substring(idx2 + 1);
+ Variables.tickets.add(new HelpTicket(id,
+ description, player));
+ } else if (count == 4) {
+ int idx3 = str.indexOf("|", idx2);
+ int id = Integer.parseInt(str.substring(0, idx1));
+ String player = str.substring(idx1 + 1, idx2);
+ String description = str.substring(idx2 + 1, idx3);
+ String modname = str.substring(idx3 + 1);
+ HelpTicket t = new HelpTicket(id, description,
+ player);
+ Variables.tickets.add(t);
+ Variables.tickets.getLast().Claim(modname);
+ Variables.tickets.getLast().close();
+ }
}
}
}
}
}
public void saveTicketsConfig() {
File TICKETS_FILE = new File(SETTINGS_PATH + File.separator
+ "Tickets.dat");
ArrayList<String> tickets = new ArrayList<String>();
FileConfiguration config = new YamlConfiguration();
config.options().header("DO NOT MODIFY");
for (HelpTicket t : Variables.tickets) {
if (t.getStatus().equals(Status.OPEN)) {
tickets.add(t.getID() + "|" + t.getNoobName() + "|"
+ t.getDescription());
} else if (t.getStatus().equals(Status.CLAIMED)) {
Close.close(t.getMod());
}
if (t.getStatus().equals(Status.CLOSED)) {
tickets.add(t.getID() + "|" + t.getNoobName() + "|"
+ t.getDescription() + "|" + t.getModName());
}
}
if (!tickets.isEmpty()) {
config.set("TICKETS", tickets);
}
save(config, TICKETS_FILE);
}
}
| true | true | private void loadTicketsConfig() {
File TICKETS_FILE = new File(SETTINGS_PATH, "Tickets.dat");
if (!TICKETS_FILE.exists()) {
return;
}
List<String> tickets = new ArrayList<String>();
FileConfiguration config = new YamlConfiguration();
try {
config.load(TICKETS_FILE);
} catch (Exception e) {
Configuration.log("Error loading cached tickets!");
File back = new File(SETTINGS_PATH, "OLD_Tickets.dat");
if (back.exists()) {
back.delete();// prevent errors when saving later
}
TICKETS_FILE.renameTo(back); // prevent errors when saving
return;
}
config.options().header("DO NOT MODIFY");
tickets = config.getStringList("TICKETS");
if (!tickets.isEmpty()) {
for (String str : tickets) {
if (str.contains("|")) {
int count = 0;
for (char c : str.toCharArray()) {
if (c == '|') {
count++;
}
}
int idx1 = str.indexOf("|");
int idx2 = str.indexOf("|", idx1);
if (count == 3) {
int id = Integer.parseInt(str.substring(0, idx1));
String player = str.substring(idx1 + 1, idx2);
String description = str.substring(idx2 + 1);
Variables.tickets.add(new HelpTicket(id, description,
player));
} else if (count == 4) {
int idx3 = str.indexOf("|", idx2);
int id = Integer.parseInt(str.substring(0, idx1));
String player = str.substring(idx1 + 1, idx2);
String description = str.substring(idx2 + 1, idx3);
String modname = str.substring(idx3 + 1);
HelpTicket t = new HelpTicket(id, description, player);
Variables.tickets.add(t);
Variables.tickets.getLast().Claim(modname);
Variables.tickets.getLast().close();
}
}
}
}
}
| private void loadTicketsConfig() {
File TICKETS_FILE = new File(SETTINGS_PATH, "Tickets.dat");
if (!TICKETS_FILE.exists()) {
return;
}
List<String> tickets = new ArrayList<String>();
FileConfiguration config = new YamlConfiguration();
try {
config.load(TICKETS_FILE);
} catch (Exception e) {
Configuration.log("Error loading cached tickets!");
File back = new File(SETTINGS_PATH, "OLD_Tickets.dat");
if (back.exists()) {
back.delete();// prevent errors when saving later
}
TICKETS_FILE.renameTo(back); // prevent errors when saving
return;
}
config.options().header("DO NOT MODIFY");
tickets = config.getStringList("TICKETS");
if (!tickets.isEmpty()) {
for (String str : tickets) {
if (str.contains("|")) {
int count = 0;
for (char c : str.toCharArray()) {
if (c == '|') {
count++;
}
}
if (count > 0) {
int idx1 = str.indexOf("|");
int idx2 = str.indexOf("|", idx1);
if (count == 3) {
int id = Integer.parseInt(str.substring(0, idx1));
String player = str.substring(idx1 + 1, idx2);
String description = str.substring(idx2 + 1);
Variables.tickets.add(new HelpTicket(id,
description, player));
} else if (count == 4) {
int idx3 = str.indexOf("|", idx2);
int id = Integer.parseInt(str.substring(0, idx1));
String player = str.substring(idx1 + 1, idx2);
String description = str.substring(idx2 + 1, idx3);
String modname = str.substring(idx3 + 1);
HelpTicket t = new HelpTicket(id, description,
player);
Variables.tickets.add(t);
Variables.tickets.getLast().Claim(modname);
Variables.tickets.getLast().close();
}
}
}
}
}
}
|
diff --git a/src/main/java/hudson/plugins/analysis/core/BuildHistory.java b/src/main/java/hudson/plugins/analysis/core/BuildHistory.java
index f091f70..b0f3286 100644
--- a/src/main/java/hudson/plugins/analysis/core/BuildHistory.java
+++ b/src/main/java/hudson/plugins/analysis/core/BuildHistory.java
@@ -1,142 +1,142 @@
package hudson.plugins.analysis.core;
import java.util.Collection;
import java.util.Collections;
import hudson.model.AbstractBuild;
import hudson.plugins.analysis.util.model.AnnotationContainer;
import hudson.plugins.analysis.util.model.DefaultAnnotationContainer;
import hudson.plugins.analysis.util.model.FileAnnotation;
/**
* History of build results of a specific plug-in. The plug-in is identified by
* the corresponding {@link ResultAction} type.
*
* @author Ulli Hafner
*/
public class BuildHistory {
/** The build to start the history from. */
private final AbstractBuild<?, ?> baseline;
/** Type of the action that contains the build results. */
private final Class<? extends ResultAction<? extends BuildResult>> type;
/**
* Creates a new instance of {@link BuildHistory}.
*
* @param baseline
* the build to start the history from
* @param type
* type of the action that contains the build results
*/
public BuildHistory(final AbstractBuild<?, ?> baseline, final Class<? extends ResultAction<? extends BuildResult>> type) {
this.baseline = baseline;
this.type = type;
}
/**
* Returns whether a reference build result exists.
*
* @return <code>true</code> if a reference build result exists.
*/
public boolean hasReferenceResult() {
return getReferenceAction() != null;
}
/**
* Returns the results of the reference build.
*
* @return the result of the reference build
*/
public AnnotationContainer getReferenceResult() {
ResultAction<? extends BuildResult> action = getReferenceAction();
if (action != null) {
return action.getResult().getContainer();
}
return new DefaultAnnotationContainer();
}
/**
* Returns the action of the reference build.
*
* @return the action of the reference build, or <code>null</code> if no
* such build exists
*/
private ResultAction<? extends BuildResult> getReferenceAction() {
- ResultAction<? extends BuildResult> currentAction = baseline.getAction(type);
- if (currentAction.hasReferenceAction()) {
- return currentAction.getReferenceAction();
+ ResultAction<? extends BuildResult> action = baseline.getAction(type);
+ if (action != null && action.hasReferenceAction()) {
+ return action.getReferenceAction();
}
else {
return getPreviousAction(); // fallback, use previous build
}
}
/**
* Returns whether a previous build result exists.
*
* @return <code>true</code> if a previous build result exists.
*/
public boolean hasPreviousResult() {
ResultAction<?> action = baseline.getAction(type);
return action != null && action.hasPreviousAction();
}
/**
* Returns the action of the previous build.
*
* @return the action of the previous build, or <code>null</code> if no
* such build exists
*/
private ResultAction<? extends BuildResult> getPreviousAction() {
ResultAction<? extends BuildResult> action = baseline.getAction(type);
return action.getPreviousAction();
}
/**
* Returns the action of the previous build.
*
* @return the action of the previous build, or <code>null</code> if no
* such build exists
*/
public BuildResult getPreviousResult() {
return getPreviousAction().getResult();
}
/**
* Returns the new warnings as a difference between the specified collection
* of warnings and the warnings of the reference build.
*
* @param annotations
* the warnings in the current build
* @return the difference "current build" - "reference build"
*/
public Collection<FileAnnotation> getNewWarnings(final Collection<FileAnnotation> annotations) {
if (hasReferenceResult()) {
return AnnotationDifferencer.getNewAnnotations(annotations, getReferenceResult().getAnnotations());
}
else {
return annotations;
}
}
/**
* Returns the fixed warnings as a difference between the warnings of the
* reference build and the specified collection of warnings.
*
* @param annotations
* the warnings in the current build
* @return the difference "reference build" - "current build"
*/
public Collection<FileAnnotation> getFixedWarnings(final Collection<FileAnnotation> annotations) {
if (hasReferenceResult()) {
return AnnotationDifferencer.getFixedAnnotations(annotations, getReferenceResult().getAnnotations());
}
else {
return Collections.emptyList();
}
}
}
| true | true | private ResultAction<? extends BuildResult> getReferenceAction() {
ResultAction<? extends BuildResult> currentAction = baseline.getAction(type);
if (currentAction.hasReferenceAction()) {
return currentAction.getReferenceAction();
}
else {
return getPreviousAction(); // fallback, use previous build
}
}
| private ResultAction<? extends BuildResult> getReferenceAction() {
ResultAction<? extends BuildResult> action = baseline.getAction(type);
if (action != null && action.hasReferenceAction()) {
return action.getReferenceAction();
}
else {
return getPreviousAction(); // fallback, use previous build
}
}
|
diff --git a/waterken/remote/src/org/waterken/remote/http/Pipeline.java b/waterken/remote/src/org/waterken/remote/http/Pipeline.java
index f73d2914..25464531 100755
--- a/waterken/remote/src/org/waterken/remote/http/Pipeline.java
+++ b/waterken/remote/src/org/waterken/remote/http/Pipeline.java
@@ -1,240 +1,240 @@
// Copyright 2007 Waterken Inc. under the terms of the MIT X license
// found at http://www.opensource.org/licenses/mit-license.html
package org.waterken.remote.http;
import static org.ref_send.promise.Fulfilled.ref;
import static org.web_send.Entity.maxContentSize;
import java.io.Serializable;
import org.joe_e.Struct;
import org.ref_send.list.List;
import org.ref_send.promise.Fulfilled;
import org.ref_send.promise.Promise;
import org.ref_send.promise.Rejected;
import org.ref_send.promise.eventual.Do;
import org.ref_send.promise.eventual.Loop;
import org.waterken.http.Request;
import org.waterken.http.Response;
import org.waterken.http.Server;
import org.waterken.io.limited.Limited;
import org.waterken.io.snapshot.Snapshot;
import org.waterken.remote.Remoting;
import org.waterken.vat.Effect;
import org.waterken.vat.Root;
import org.waterken.vat.Service;
import org.waterken.vat.Transaction;
import org.waterken.vat.Vat;
import org.web_send.Failure;
/**
* Manages a pending request queue for a specific host.
*/
final class
Pipeline implements Serializable {
static private final long serialVersionUID = 1L;
static private final class
Entry extends Struct implements Serializable {
static private final long serialVersionUID = 1L;
final int id; // serial number
final Message msg; // pending message
Entry(final int id, final Message message) {
this.id = id;
this.msg = message;
}
}
private final String peer;
private final Loop<Effect> effect;
private final Vat model;
private final Fulfilled<Outbound> outbound;
private final List<Entry> pending = List.list();
private int serialMID = 0;
private int halts = 0; // number of pending pipeline flushes
private int queries = 0; // number of queries after the last flush
Pipeline(final String peer, final Root local) {
this.peer = peer;
effect = (Loop<Effect>)local.fetch(null, Root.effect);
model = (Vat)local.fetch(null, Root.vat);
outbound = Fulfilled.detach((Outbound)local.fetch(null, AMP.outbound));
}
void
resend() { effect.run(restart(model, peer, pending.getSize(), false, 0)); }
/*
* Message sending is halted when an Update follows a Query. Sending resumes
* once the response to the preceeding Query has been received.
*/
void
enqueue(final Message message) {
if (pending.isEmpty()) {
outbound.cast().add(peer, this);
}
final int mid = serialMID++;
pending.append(new Entry(mid, message));
if (message instanceof Update) {
if (0 != queries) {
++halts;
queries = 0;
}
}
if (message instanceof Query) { ++queries; }
if (0 == halts) { effect.run(restart(model, peer, 1, true, mid)); }
}
private Message
dequeue(final int mid) {
if (pending.getFront().id != mid) { throw new RuntimeException(); }
final Entry front = pending.pop();
if (pending.isEmpty()) {
outbound.cast().remove(peer);
}
if (front.msg instanceof Query) {
if (0 == halts) {
--queries;
} else {
int max = pending.getSize();
for (final Entry x : pending) {
if (x.msg instanceof Update) {
--halts;
effect.run(restart(model, peer, max, true, x.id));
break;
}
if (x.msg instanceof Query) { break; }
--max;
}
}
}
return front.msg;
}
static private Effect
restart(final Vat vat, final String peer,
final int max, final boolean skipTo, final int mid) {
// Create a transaction effect that will schedule a new extend
// transaction that actually puts the messages on the wire.
return new Effect() {
public void
run() throws Exception {
vat.service.run(new Service() {
public void
run() throws Exception {
vat.enter(Vat.extend, new Transaction<Void>() {
public Void
run(final Root local) throws Exception {
final Server client =
(Server)local.fetch(null, Remoting.client);
final Loop<Effect> effect =
- (Loop)local.fetch(null, Root.effect);
+ (Loop<Effect>)local.fetch(null, Root.effect);
final Outbound outbound =
(Outbound)local.fetch(null, AMP.outbound);
boolean found = !skipTo;
boolean q = false;
int n = max;
for (final Entry x: outbound.find(peer).pending){
if (!found) {
if (mid == x.id) {
found = true;
} else {
continue;
}
}
if (0 == n--) { break; }
if (q && x.msg instanceof Update) { break; }
if (x.msg instanceof Query) { q = true; }
effect.run(send(vat, client, peer, x));
}
return null;
}
});
}
});
}
};
}
static private Effect
send(final Vat vat, final Server client, final String peer, final Entry x) {
Promise<Request> rendered;
try {
rendered = ref(x.msg.send());
} catch (final Exception reason) {
rendered = new Rejected<Request>(reason);
}
final Promise<Request> request = rendered;
final int mid = x.id;
return new Effect() {
public void
run() throws Exception {
client.serve(peer, request, new Receive(vat, peer, mid));
}
};
}
static private final class
Receive extends Do<Response,Void> {
private final Vat vat;
private final String peer;
private final int mid;
Receive(final Vat vat, final String peer, final int mid) {
this.vat = vat;
this.peer = peer;
this.mid = mid;
}
public Void
fulfill(Response r) throws Exception {
if (null != r.body) {
try {
final int length = r.getContentLength();
if (length > maxContentSize) { throw Failure.tooBig(); }
r = new Response(r.version, r.status, r.phrase, r.header,
Snapshot.snapshot(length < 0 ? 1024 : length,
Limited.limit(maxContentSize, r.body)));
} catch (final Failure e) { return reject(e); }
}
return resolve(ref(r));
}
public Void
reject(final Exception reason) {
return resolve(new Rejected<Response>(reason));
}
private Void
resolve(final Promise<Response> response) {
vat.service.run(new Service() {
public void
run() throws Exception {
vat.enter(Vat.change, new Transaction<Void>() {
public Void
run(final Root local) throws Exception {
final Outbound outbound =
(Outbound)local.fetch(null, AMP.outbound);
final Pipeline msgs = outbound.find(peer);
final Message respond = msgs.dequeue(mid);
Response value;
try {
value = response.cast();
} catch (final Exception reason) {
return respond.reject(reason);
}
return respond.fulfill(value);
}
});
}
});
return null;
}
}
}
| true | true | static private Effect
restart(final Vat vat, final String peer,
final int max, final boolean skipTo, final int mid) {
// Create a transaction effect that will schedule a new extend
// transaction that actually puts the messages on the wire.
return new Effect() {
public void
run() throws Exception {
vat.service.run(new Service() {
public void
run() throws Exception {
vat.enter(Vat.extend, new Transaction<Void>() {
public Void
run(final Root local) throws Exception {
final Server client =
(Server)local.fetch(null, Remoting.client);
final Loop<Effect> effect =
(Loop)local.fetch(null, Root.effect);
final Outbound outbound =
(Outbound)local.fetch(null, AMP.outbound);
boolean found = !skipTo;
boolean q = false;
int n = max;
for (final Entry x: outbound.find(peer).pending){
if (!found) {
if (mid == x.id) {
found = true;
} else {
continue;
}
}
if (0 == n--) { break; }
if (q && x.msg instanceof Update) { break; }
if (x.msg instanceof Query) { q = true; }
effect.run(send(vat, client, peer, x));
}
return null;
}
});
}
});
}
};
}
| static private Effect
restart(final Vat vat, final String peer,
final int max, final boolean skipTo, final int mid) {
// Create a transaction effect that will schedule a new extend
// transaction that actually puts the messages on the wire.
return new Effect() {
public void
run() throws Exception {
vat.service.run(new Service() {
public void
run() throws Exception {
vat.enter(Vat.extend, new Transaction<Void>() {
public Void
run(final Root local) throws Exception {
final Server client =
(Server)local.fetch(null, Remoting.client);
final Loop<Effect> effect =
(Loop<Effect>)local.fetch(null, Root.effect);
final Outbound outbound =
(Outbound)local.fetch(null, AMP.outbound);
boolean found = !skipTo;
boolean q = false;
int n = max;
for (final Entry x: outbound.find(peer).pending){
if (!found) {
if (mid == x.id) {
found = true;
} else {
continue;
}
}
if (0 == n--) { break; }
if (q && x.msg instanceof Update) { break; }
if (x.msg instanceof Query) { q = true; }
effect.run(send(vat, client, peer, x));
}
return null;
}
});
}
});
}
};
}
|
diff --git a/coastal-hazards-ui/src/main/java/gov/usgs/cida/utilities/communication/UploadHandlerServlet.java b/coastal-hazards-ui/src/main/java/gov/usgs/cida/utilities/communication/UploadHandlerServlet.java
index a52e6d410..627d03595 100644
--- a/coastal-hazards-ui/src/main/java/gov/usgs/cida/utilities/communication/UploadHandlerServlet.java
+++ b/coastal-hazards-ui/src/main/java/gov/usgs/cida/utilities/communication/UploadHandlerServlet.java
@@ -1,404 +1,408 @@
package gov.usgs.cida.utilities.communication;
import com.google.gson.Gson;
import gov.usgs.cida.config.DynamicReadOnlyProperties;
import gov.usgs.cida.utilities.properties.JNDISingleton;
import java.io.File;
//import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
//import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
//import org.apache.commons.codec.binary.Base64OutputStream;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
//import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
//import org.apache.http.HttpResponse;
//import org.apache.http.client.HttpClient;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.entity.AbstractHttpEntity;
//import org.apache.http.entity.InputStreamEntity;
//import org.apache.http.impl.client.DefaultHttpClient;
//import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;
public class UploadHandlerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(UploadHandlerServlet.class);
private static DynamicReadOnlyProperties props = null;
private static String uploadDirectory = null;
// Config param string constants
private static String FILE_UPLOAD_MAX_SIZE_CONFIG_KEY = "coastal-hazards.files.upload.max-size";
private static String FILE_UPLOAD_FILENAME_PARAM_CONFIG_KEY = "coastal-hazards.files.upload.filename-param";
private static String DIRECTORY_BASE_PARAM_CONFIG_KEY = "coastal-hazards.files.directory.base";
private static String DIRECTORY_UPLOAD_PARAM_CONFIG_KEY = "coastal-hazards.files.directory.upload";
// Config defaults
private static int FILE_UPLOAD_MAX_SIZE_DEFAULT = 15728640;
private static String FILE_UPLOAD_FILENAME_PARAM_DEFAULT = "qqfile";
@Override
public void init() throws ServletException {
super.init();
props = JNDISingleton.getInstance();
uploadDirectory = props.getProperty(DIRECTORY_BASE_PARAM_CONFIG_KEY) + props.getProperty(DIRECTORY_UPLOAD_PARAM_CONFIG_KEY);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int maxFileSize = FILE_UPLOAD_MAX_SIZE_DEFAULT;
int fileSize = Integer.parseInt(request.getHeader("Content-Length"));
String fileParamKey = props.getProperty(FILE_UPLOAD_FILENAME_PARAM_CONFIG_KEY, FILE_UPLOAD_FILENAME_PARAM_DEFAULT);
String fileName = request.getParameter(fileParamKey);
String destinationDirectoryChild = UUID.randomUUID().toString();
File uploadDestinationDirectory = new File(new File(uploadDirectory), destinationDirectoryChild);
File uploadDestinationFile = new File(uploadDestinationDirectory, fileName);
Map<String, String> responseMap = new HashMap<String, String>();
try {
maxFileSize = Integer.parseInt(props.get(FILE_UPLOAD_MAX_SIZE_CONFIG_KEY));
} catch (NumberFormatException nfe) {
LOG.info("JNDI property '" + FILE_UPLOAD_MAX_SIZE_CONFIG_KEY + "' not set or is an invalid value. Using: " + maxFileSize);
}
// Check that the incoming file is not larger than our limit
if (maxFileSize > 0 && fileSize > maxFileSize) {
+ LOG.info("Upload exceeds max file size of " + maxFileSize + " bytes");
responseMap.put("error", "Upload exceeds max file size of " + maxFileSize + " bytes");
sendErrorResponse(response, responseMap);
return;
}
// Create destination directory
try {
FileUtils.forceMkdir(uploadDestinationDirectory);
} catch (IOException ioe) {
responseMap.put("error", "Could not save file.");
responseMap.put("exception", ioe.getMessage());
sendErrorResponse(response, responseMap);
+ return;
}
// Save the file to the upload directory
try {
saveFileFromRequest(request, fileParamKey, uploadDestinationFile);
} catch (FileUploadException ex) {
responseMap.put("error", "Could not save file.");
responseMap.put("exception", ex.getMessage());
sendErrorResponse(response, responseMap);
+ return;
} catch (IOException ex) {
responseMap.put("error", "Could not save file.");
responseMap.put("exception", ex.getMessage());
sendErrorResponse(response, responseMap);
+ return;
}
responseMap.put("file-token", destinationDirectoryChild);
responseMap.put("file-checksum", Long.toString(FileUtils.checksumCRC32(uploadDestinationFile)));
responseMap.put("file-size", Long.toString(FileUtils.sizeOf(uploadDestinationFile)));
sendResponse(response, responseMap);
}
File saveFileFromRequest(HttpServletRequest request, String filenameParameter, File destinationFile) throws FileUploadException, IOException {
if (StringUtils.isBlank(filenameParameter)) {
throw new IllegalArgumentException();
}
if (ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
FileItemIterator iter;
iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
if (filenameParameter.toLowerCase().equals(name.toLowerCase())) {
saveFileFromInputStream(item.openStream(), destinationFile);
break;
}
}
} else {
saveFileFromInputStream(request.getInputStream(), destinationFile);
}
return destinationFile;
}
// @Override
// protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
//
// int maxFileSize = Integer.parseInt(request.getParameter("maxfilesize"));
// int fileSize = Integer.parseInt(request.getHeader("Content-Length"));
// if (fileSize > maxFileSize) {
// sendErrorResponse(response, "Upload exceeds max file size of " + maxFileSize + " bytes");
// return;
// }
//
// // qqfile is parameter passed by our javascript uploader
// String filename = request.getParameter("qqfile");
// String utilityWpsUrl = request.getParameter("utilitywps");
// String wfsEndpoint = request.getParameter("wfs-url");
// String tempDir = System.getProperty("java.io.tmpdir");
//
// File destinationFile = new File(tempDir + File.separator + filename);
//
// // Handle form-based upload (from IE)
// if (ServletFileUpload.isMultipartContent(request)) {
// FileItemFactory factory = new DiskFileItemFactory();
// ServletFileUpload upload = new ServletFileUpload(factory);
//
// // Parse the request
// FileItemIterator iter;
// try {
// iter = upload.getItemIterator(request);
// while (iter.hasNext()) {
// FileItemStream item = iter.next();
// String name = item.getFieldName();
// if ("qqfile".equals(name)) {
// saveFileFromRequest(item.openStream(), destinationFile);
// break;
// }
// }
// } catch (Exception ex) {
// sendErrorResponse(response, "Unable to upload file");
// return;
// }
// } else {
// // Handle octet streams (from standards browsers)
// try {
// saveFileFromRequest(request.getInputStream(), destinationFile);
// } catch (IOException ex) {
// Logger.getLogger(UploadHandlerServlet.class.getName()).log(Level.SEVERE, null, ex);
// }
// }
//
// String responseText = null;
// try {
// String wpsResponse = postToWPS(utilityWpsUrl, wfsEndpoint, destinationFile);
//
// responseText = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
// + "<wpsResponse><![CDATA[" + wpsResponse + "]]></wpsResponse>";
//
// } catch (Exception ex) {
// Logger.getLogger(UploadHandlerServlet.class.getName()).log(Level.SEVERE, null, ex);
// sendErrorResponse(response, "Unable to upload file");
// return;
// } finally {
// FileUtils.deleteQuietly(destinationFile);
// }
//
// sendResponse(response, responseText);
// }// @Override
// protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
//
// int maxFileSize = Integer.parseInt(request.getParameter("maxfilesize"));
// int fileSize = Integer.parseInt(request.getHeader("Content-Length"));
// if (fileSize > maxFileSize) {
// sendErrorResponse(response, "Upload exceeds max file size of " + maxFileSize + " bytes");
// return;
// }
//
// // qqfile is parameter passed by our javascript uploader
// String filename = request.getParameter("qqfile");
// String utilityWpsUrl = request.getParameter("utilitywps");
// String wfsEndpoint = request.getParameter("wfs-url");
// String tempDir = System.getProperty("java.io.tmpdir");
//
// File destinationFile = new File(tempDir + File.separator + filename);
//
// // Handle form-based upload (from IE)
// if (ServletFileUpload.isMultipartContent(request)) {
// FileItemFactory factory = new DiskFileItemFactory();
// ServletFileUpload upload = new ServletFileUpload(factory);
//
// // Parse the request
// FileItemIterator iter;
// try {
// iter = upload.getItemIterator(request);
// while (iter.hasNext()) {
// FileItemStream item = iter.next();
// String name = item.getFieldName();
// if ("qqfile".equals(name)) {
// saveFileFromRequest(item.openStream(), destinationFile);
// break;
// }
// }
// } catch (Exception ex) {
// sendErrorResponse(response, "Unable to upload file");
// return;
// }
// } else {
// // Handle octet streams (from standards browsers)
// try {
// saveFileFromRequest(request.getInputStream(), destinationFile);
// } catch (IOException ex) {
// Logger.getLogger(UploadHandlerServlet.class.getName()).log(Level.SEVERE, null, ex);
// }
// }
//
// String responseText = null;
// try {
// String wpsResponse = postToWPS(utilityWpsUrl, wfsEndpoint, destinationFile);
//
// responseText = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
// + "<wpsResponse><![CDATA[" + wpsResponse + "]]></wpsResponse>";
//
// } catch (Exception ex) {
// Logger.getLogger(UploadHandlerServlet.class.getName()).log(Level.SEVERE, null, ex);
// sendErrorResponse(response, "Unable to upload file");
// return;
// } finally {
// FileUtils.deleteQuietly(destinationFile);
// }
//
// sendResponse(response, responseText);
// }
static void sendResponse(HttpServletResponse response, Map<String, String> responseMap) {
responseMap.put("success", "true");
sendJSONResponse(response, responseMap);
}
static void sendErrorResponse(HttpServletResponse response, Map<String, String> responseMap) {
responseMap.put("success", "false");
sendJSONResponse(response, responseMap);
}
static void sendJSONResponse(HttpServletResponse response, Map<String, String> responseMap) {
String responseContent = new Gson().toJson(responseMap);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Length", Integer.toString(responseContent.length()));
try {
Writer writer = response.getWriter();
writer.write(responseContent);
writer.close();
} catch (IOException ex) {
Logger.getLogger(UploadHandlerServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void saveFileFromInputStream(InputStream is, File destinationFile) throws IOException {
FileOutputStream os = null;
try {
os = new FileOutputStream(destinationFile);
IOUtils.copy(is, os);
} finally {
IOUtils.closeQuietly(os);
}
}
//
// private String postToWPS(String url, String wfsEndpoint, File uploadedFile) throws IOException, MessagingException {
// HttpPost post = null;
// HttpClient httpClient = new DefaultHttpClient();
//
// post = new HttpPost(url);
//
// File wpsRequestFile = createWPSReceiveFilesXML(uploadedFile, wfsEndpoint);
// FileInputStream wpsRequestInputStream = null;
//
// try {
// wpsRequestInputStream = new FileInputStream(wpsRequestFile);
//
// AbstractHttpEntity entity = new InputStreamEntity(wpsRequestInputStream, wpsRequestFile.length());
//
// post.setEntity(entity);
//
// HttpResponse response = httpClient.execute(post);
//
// return EntityUtils.toString(response.getEntity());
//
// } finally {
// IOUtils.closeQuietly(wpsRequestInputStream);
// FileUtils.deleteQuietly(wpsRequestFile);
// }
// }
//
// private static File createWPSReceiveFilesXML(final File uploadedFile, final String wfsEndpoint) throws IOException, MessagingException {
//
// File wpsRequestFile = null;
// FileOutputStream wpsRequestOutputStream = null;
// FileInputStream uploadedInputStream = null;
//
// try {
// wpsRequestFile = File.createTempFile("wps.upload.", ".xml");
// wpsRequestOutputStream = new FileOutputStream(wpsRequestFile);
// uploadedInputStream = new FileInputStream(uploadedFile);
//
// wpsRequestOutputStream.write(new String(
// "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
// + "<wps:Execute service=\"WPS\" version=\"1.0.0\" "
// + "xmlns:wps=\"http://www.opengis.net/wps/1.0.0\" "
// + "xmlns:ows=\"http://www.opengis.net/ows/1.1\" "
// + "xmlns:xlink=\"http://www.w3.org/1999/xlink\" "
// + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
// + "xsi:schemaLocation=\"http://www.opengis.net/wps/1.0.0 "
// + "http://schemas.opengis.net/wps/1.0.0/wpsExecute_request.xsd\">"
// + "<ows:Identifier>gov.usgs.cida.gdp.wps.algorithm.filemanagement.ReceiveFiles</ows:Identifier>"
// + "<wps:DataInputs>"
// + "<wps:Input>"
// + "<ows:Identifier>filename</ows:Identifier>"
// + "<wps:Data>"
// + "<wps:LiteralData>"
// + StringEscapeUtils.escapeXml(uploadedFile.getName().replace(".zip", ""))
// + "</wps:LiteralData>"
// + "</wps:Data>"
// + "</wps:Input>"
// + "<wps:Input>"
// + "<ows:Identifier>wfs-url</ows:Identifier>"
// + "<wps:Data>"
// + "<wps:LiteralData>"
// + StringEscapeUtils.escapeXml(wfsEndpoint)
// + "</wps:LiteralData>"
// + "</wps:Data>"
// + "</wps:Input>"
// + "<wps:Input>"
// + "<ows:Identifier>file</ows:Identifier>"
// + "<wps:Data>"
// + "<wps:ComplexData mimeType=\"application/x-zipped-shp\" encoding=\"Base64\">").getBytes());
// IOUtils.copy(uploadedInputStream, new Base64OutputStream(wpsRequestOutputStream, true, 0, null));
// wpsRequestOutputStream.write(new String(
// "</wps:ComplexData>"
// + "</wps:Data>"
// + "</wps:Input>"
// + "</wps:DataInputs>"
// + "<wps:ResponseForm>"
// + "<wps:ResponseDocument>"
// + "<wps:Output>"
// + "<ows:Identifier>result</ows:Identifier>"
// + "</wps:Output>"
// + "<wps:Output>"
// + "<ows:Identifier>wfs-url</ows:Identifier>"
// + "</wps:Output>"
// + "<wps:Output>"
// + "<ows:Identifier>featuretype</ows:Identifier>"
// + "</wps:Output>"
// + "</wps:ResponseDocument>"
// + "</wps:ResponseForm>"
// + "</wps:Execute>").getBytes());
// } finally {
// IOUtils.closeQuietly(wpsRequestOutputStream);
// IOUtils.closeQuietly(uploadedInputStream);
// }
// return wpsRequestFile;
// }
}
| false | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int maxFileSize = FILE_UPLOAD_MAX_SIZE_DEFAULT;
int fileSize = Integer.parseInt(request.getHeader("Content-Length"));
String fileParamKey = props.getProperty(FILE_UPLOAD_FILENAME_PARAM_CONFIG_KEY, FILE_UPLOAD_FILENAME_PARAM_DEFAULT);
String fileName = request.getParameter(fileParamKey);
String destinationDirectoryChild = UUID.randomUUID().toString();
File uploadDestinationDirectory = new File(new File(uploadDirectory), destinationDirectoryChild);
File uploadDestinationFile = new File(uploadDestinationDirectory, fileName);
Map<String, String> responseMap = new HashMap<String, String>();
try {
maxFileSize = Integer.parseInt(props.get(FILE_UPLOAD_MAX_SIZE_CONFIG_KEY));
} catch (NumberFormatException nfe) {
LOG.info("JNDI property '" + FILE_UPLOAD_MAX_SIZE_CONFIG_KEY + "' not set or is an invalid value. Using: " + maxFileSize);
}
// Check that the incoming file is not larger than our limit
if (maxFileSize > 0 && fileSize > maxFileSize) {
responseMap.put("error", "Upload exceeds max file size of " + maxFileSize + " bytes");
sendErrorResponse(response, responseMap);
return;
}
// Create destination directory
try {
FileUtils.forceMkdir(uploadDestinationDirectory);
} catch (IOException ioe) {
responseMap.put("error", "Could not save file.");
responseMap.put("exception", ioe.getMessage());
sendErrorResponse(response, responseMap);
}
// Save the file to the upload directory
try {
saveFileFromRequest(request, fileParamKey, uploadDestinationFile);
} catch (FileUploadException ex) {
responseMap.put("error", "Could not save file.");
responseMap.put("exception", ex.getMessage());
sendErrorResponse(response, responseMap);
} catch (IOException ex) {
responseMap.put("error", "Could not save file.");
responseMap.put("exception", ex.getMessage());
sendErrorResponse(response, responseMap);
}
responseMap.put("file-token", destinationDirectoryChild);
responseMap.put("file-checksum", Long.toString(FileUtils.checksumCRC32(uploadDestinationFile)));
responseMap.put("file-size", Long.toString(FileUtils.sizeOf(uploadDestinationFile)));
sendResponse(response, responseMap);
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int maxFileSize = FILE_UPLOAD_MAX_SIZE_DEFAULT;
int fileSize = Integer.parseInt(request.getHeader("Content-Length"));
String fileParamKey = props.getProperty(FILE_UPLOAD_FILENAME_PARAM_CONFIG_KEY, FILE_UPLOAD_FILENAME_PARAM_DEFAULT);
String fileName = request.getParameter(fileParamKey);
String destinationDirectoryChild = UUID.randomUUID().toString();
File uploadDestinationDirectory = new File(new File(uploadDirectory), destinationDirectoryChild);
File uploadDestinationFile = new File(uploadDestinationDirectory, fileName);
Map<String, String> responseMap = new HashMap<String, String>();
try {
maxFileSize = Integer.parseInt(props.get(FILE_UPLOAD_MAX_SIZE_CONFIG_KEY));
} catch (NumberFormatException nfe) {
LOG.info("JNDI property '" + FILE_UPLOAD_MAX_SIZE_CONFIG_KEY + "' not set or is an invalid value. Using: " + maxFileSize);
}
// Check that the incoming file is not larger than our limit
if (maxFileSize > 0 && fileSize > maxFileSize) {
LOG.info("Upload exceeds max file size of " + maxFileSize + " bytes");
responseMap.put("error", "Upload exceeds max file size of " + maxFileSize + " bytes");
sendErrorResponse(response, responseMap);
return;
}
// Create destination directory
try {
FileUtils.forceMkdir(uploadDestinationDirectory);
} catch (IOException ioe) {
responseMap.put("error", "Could not save file.");
responseMap.put("exception", ioe.getMessage());
sendErrorResponse(response, responseMap);
return;
}
// Save the file to the upload directory
try {
saveFileFromRequest(request, fileParamKey, uploadDestinationFile);
} catch (FileUploadException ex) {
responseMap.put("error", "Could not save file.");
responseMap.put("exception", ex.getMessage());
sendErrorResponse(response, responseMap);
return;
} catch (IOException ex) {
responseMap.put("error", "Could not save file.");
responseMap.put("exception", ex.getMessage());
sendErrorResponse(response, responseMap);
return;
}
responseMap.put("file-token", destinationDirectoryChild);
responseMap.put("file-checksum", Long.toString(FileUtils.checksumCRC32(uploadDestinationFile)));
responseMap.put("file-size", Long.toString(FileUtils.sizeOf(uploadDestinationFile)));
sendResponse(response, responseMap);
}
|
diff --git a/src/main/java/org/apache/hadoop/hbase/master/LoadBalancer.java b/src/main/java/org/apache/hadoop/hbase/master/LoadBalancer.java
index 901be8bb4..cd83b054f 100644
--- a/src/main/java/org/apache/hadoop/hbase/master/LoadBalancer.java
+++ b/src/main/java/org/apache/hadoop/hbase/master/LoadBalancer.java
@@ -1,674 +1,674 @@
/**
* Copyright 2010 The Apache Software Foundation
*
* 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.hbase.master;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Random;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HServerAddress;
import org.apache.hadoop.hbase.HServerInfo;
/**
* Makes decisions about the placement and movement of Regions across
* RegionServers.
*
* <p>Cluster-wide load balancing will occur only when there are no regions in
* transition and according to a fixed period of a time using {@link #balanceCluster(Map)}.
*
* <p>Inline region placement with {@link #immediateAssignment} can be used when
* the Master needs to handle closed regions that it currently does not have
* a destination set for. This can happen during master failover.
*
* <p>On cluster startup, bulk assignment can be used to determine
* locations for all Regions in a cluster.
*
* <p>This classes produces plans for the {@link AssignmentManager} to execute.
*/
public class LoadBalancer {
private static final Log LOG = LogFactory.getLog(LoadBalancer.class);
private static final Random rand = new Random();
static class RegionPlanComparator implements Comparator<RegionPlan> {
@Override
public int compare(RegionPlan l, RegionPlan r) {
long diff = r.getRegionInfo().getRegionId() - l.getRegionInfo().getRegionId();
if (diff < 0) return -1;
if (diff > 0) return 1;
return 0;
}
}
static RegionPlanComparator rpComparator = new RegionPlanComparator();
/**
* Generate a global load balancing plan according to the specified map of
* server information to the most loaded regions of each server.
*
* The load balancing invariant is that all servers are within 1 region of the
* average number of regions per server. If the average is an integer number,
* all servers will be balanced to the average. Otherwise, all servers will
* have either floor(average) or ceiling(average) regions.
*
* The algorithm is currently implemented as such:
*
* <ol>
* <li>Determine the two valid numbers of regions each server should have,
* <b>MIN</b>=floor(average) and <b>MAX</b>=ceiling(average).
*
* <li>Iterate down the most loaded servers, shedding regions from each so
* each server hosts exactly <b>MAX</b> regions. Stop once you reach a
* server that already has <= <b>MAX</b> regions.
* <p>
* Order the regions to move from most recent to least.
*
* <li>Iterate down the least loaded servers, assigning regions so each server
* has exactly </b>MIN</b> regions. Stop once you reach a server that
* already has >= <b>MIN</b> regions.
*
* Regions being assigned to underloaded servers are those that were shed
* in the previous step. It is possible that there were not enough
* regions shed to fill each underloaded server to <b>MIN</b>. If so we
* end up with a number of regions required to do so, <b>neededRegions</b>.
*
* It is also possible that we were able fill each underloaded but ended
* up with regions that were unassigned from overloaded servers but that
* still do not have assignment.
*
* If neither of these conditions hold (no regions needed to fill the
* underloaded servers, no regions leftover from overloaded servers),
* we are done and return. Otherwise we handle these cases below.
*
* <li>If <b>neededRegions</b> is non-zero (still have underloaded servers),
* we iterate the most loaded servers again, shedding a single server from
* each (this brings them from having <b>MAX</b> regions to having
* <b>MIN</b> regions).
*
* <li>We now definitely have more regions that need assignment, either from
* the previous step or from the original shedding from overloaded servers.
*
* Iterate the least loaded servers filling each to <b>MIN</b>.
*
* <li>If we still have more regions that need assignment, again iterate the
* least loaded servers, this time giving each one (filling them to
* </b>MAX</b>) until we run out.
*
* <li>All servers will now either host <b>MIN</b> or <b>MAX</b> regions.
*
* In addition, any server hosting >= <b>MAX</b> regions is guaranteed
* to end up with <b>MAX</b> regions at the end of the balancing. This
* ensures the minimal number of regions possible are moved.
* </ol>
*
* TODO: We can at-most reassign the number of regions away from a particular
* server to be how many they report as most loaded.
* Should we just keep all assignment in memory? Any objections?
* Does this mean we need HeapSize on HMaster? Or just careful monitor?
* (current thinking is we will hold all assignments in memory)
*
* @param clusterState Map of regionservers and their load/region information to
* a list of their most loaded regions
* @return a list of regions to be moved, including source and destination,
* or null if cluster is already balanced
*/
public List<RegionPlan> balanceCluster(
Map<HServerInfo,List<HRegionInfo>> clusterState) {
long startTime = System.currentTimeMillis();
// Make a map sorted by load and count regions
TreeMap<HServerInfo,List<HRegionInfo>> serversByLoad =
new TreeMap<HServerInfo,List<HRegionInfo>>(
new HServerInfo.LoadComparator());
int numServers = clusterState.size();
if (numServers == 0) {
LOG.debug("numServers=0 so skipping load balancing");
return null;
}
int numRegions = 0;
// Iterate so we can count regions as we build the map
for(Map.Entry<HServerInfo, List<HRegionInfo>> server:
clusterState.entrySet()) {
server.getKey().getLoad().setNumberOfRegions(server.getValue().size());
numRegions += server.getKey().getLoad().getNumberOfRegions();
serversByLoad.put(server.getKey(), server.getValue());
}
// Check if we even need to do any load balancing
float average = (float)numRegions / numServers; // for logging
int min = numRegions / numServers;
int max = numRegions % numServers == 0 ? min : min + 1;
if(serversByLoad.lastKey().getLoad().getNumberOfRegions() <= max &&
serversByLoad.firstKey().getLoad().getNumberOfRegions() >= min) {
// Skipped because no server outside (min,max) range
LOG.info("Skipping load balancing. servers=" + numServers + " " +
"regions=" + numRegions + " average=" + average + " " +
"mostloaded=" + serversByLoad.lastKey().getLoad().getNumberOfRegions() +
- " leastloaded=" + serversByLoad.lastKey().getLoad().getNumberOfRegions());
+ " leastloaded=" + serversByLoad.firstKey().getLoad().getNumberOfRegions());
return null;
}
// Balance the cluster
// TODO: Look at data block locality or a more complex load to do this
List<RegionPlan> regionsToMove = new ArrayList<RegionPlan>();
int regionidx = 0; // track the index in above list for setting destination
// Walk down most loaded, pruning each to the max
int serversOverloaded = 0;
Map<HServerInfo,BalanceInfo> serverBalanceInfo =
new TreeMap<HServerInfo,BalanceInfo>();
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.descendingMap().entrySet()) {
HServerInfo serverInfo = server.getKey();
int regionCount = serverInfo.getLoad().getNumberOfRegions();
if(regionCount <= max) {
serverBalanceInfo.put(serverInfo, new BalanceInfo(0, 0));
break;
}
serversOverloaded++;
List<HRegionInfo> regions = server.getValue();
int numToOffload = Math.min(regionCount - max, regions.size());
int numTaken = 0;
for (int i = regions.size() - 1; i >= 0; i--) {
HRegionInfo hri = regions.get(i);
// Don't rebalance meta regions.
if (hri.isMetaRegion()) continue;
regionsToMove.add(new RegionPlan(hri, serverInfo, null));
numTaken++;
if (numTaken >= numToOffload) break;
}
serverBalanceInfo.put(serverInfo,
new BalanceInfo(numToOffload, (-1)*numTaken));
}
// put young regions at the beginning of regionsToMove
Collections.sort(regionsToMove, rpComparator);
// Walk down least loaded, filling each to the min
int serversUnderloaded = 0; // number of servers that get new regions
int neededRegions = 0; // number of regions needed to bring all up to min
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.entrySet()) {
int regionCount = server.getKey().getLoad().getNumberOfRegions();
if(regionCount >= min) {
break;
}
serversUnderloaded++;
int numToTake = min - regionCount;
int numTaken = 0;
while(numTaken < numToTake && regionidx < regionsToMove.size()) {
regionsToMove.get(regionidx).setDestination(server.getKey());
numTaken++;
regionidx++;
}
serverBalanceInfo.put(server.getKey(), new BalanceInfo(0, numTaken));
// If we still want to take some, increment needed
if(numTaken < numToTake) {
neededRegions += (numToTake - numTaken);
}
}
// If none needed to fill all to min and none left to drain all to max,
// we are done
if(neededRegions == 0 && regionidx == regionsToMove.size()) {
long endTime = System.currentTimeMillis();
LOG.info("Calculated a load balance in " + (endTime-startTime) + "ms. " +
"Moving " + regionsToMove.size() + " regions off of " +
serversOverloaded + " overloaded servers onto " +
serversUnderloaded + " less loaded servers");
return regionsToMove;
}
// Need to do a second pass.
// Either more regions to assign out or servers that are still underloaded
// If we need more to fill min, grab one from each most loaded until enough
if (neededRegions != 0) {
// Walk down most loaded, grabbing one from each until we get enough
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.descendingMap().entrySet()) {
BalanceInfo balanceInfo = serverBalanceInfo.get(server.getKey());
int idx =
balanceInfo == null ? 0 : balanceInfo.getNextRegionForUnload();
if (idx >= server.getValue().size()) break;
HRegionInfo region = server.getValue().get(idx);
if (region.isMetaRegion()) continue; // Don't move meta regions.
regionsToMove.add(new RegionPlan(region, server.getKey(), null));
if(--neededRegions == 0) {
// No more regions needed, done shedding
break;
}
}
}
// Now we have a set of regions that must be all assigned out
// Assign each underloaded up to the min, then if leftovers, assign to max
// Walk down least loaded, assigning to each to fill up to min
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.entrySet()) {
int regionCount = server.getKey().getLoad().getNumberOfRegions();
if (regionCount >= min) break;
BalanceInfo balanceInfo = serverBalanceInfo.get(server.getKey());
if(balanceInfo != null) {
regionCount += balanceInfo.getNumRegionsAdded();
}
if(regionCount >= min) {
continue;
}
int numToTake = min - regionCount;
int numTaken = 0;
while(numTaken < numToTake && regionidx < regionsToMove.size()) {
regionsToMove.get(regionidx).setDestination(server.getKey());
numTaken++;
regionidx++;
}
}
// If we still have regions to dish out, assign underloaded to max
if(regionidx != regionsToMove.size()) {
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.entrySet()) {
int regionCount = server.getKey().getLoad().getNumberOfRegions();
if(regionCount >= max) {
break;
}
regionsToMove.get(regionidx).setDestination(server.getKey());
regionidx++;
if(regionidx == regionsToMove.size()) {
break;
}
}
}
long endTime = System.currentTimeMillis();
if (regionidx != regionsToMove.size() || neededRegions != 0) {
// Emit data so can diagnose how balancer went astray.
LOG.warn("regionidx=" + regionidx + ", regionsToMove=" + regionsToMove.size() +
", numServers=" + numServers + ", serversOverloaded=" + serversOverloaded +
", serversUnderloaded=" + serversUnderloaded);
StringBuilder sb = new StringBuilder();
for (Map.Entry<HServerInfo, List<HRegionInfo>> e: clusterState.entrySet()) {
if (sb.length() > 0) sb.append(", ");
sb.append(e.getKey().getServerName());
sb.append(" ");
sb.append(e.getValue().size());
}
LOG.warn("Input " + sb.toString());
}
// All done!
LOG.info("Calculated a load balance in " + (endTime-startTime) + "ms. " +
"Moving " + regionsToMove.size() + " regions off of " +
serversOverloaded + " overloaded servers onto " +
serversUnderloaded + " less loaded servers");
return regionsToMove;
}
/**
* Stores additional per-server information about the regions added/removed
* during the run of the balancing algorithm.
*
* For servers that receive additional regions, we are not updating the number
* of regions in HServerInfo once we decide to reassign regions to a server,
* but we need this information later in the algorithm. This is stored in
* <b>numRegionsAdded</b>.
*
* For servers that shed regions, we need to track which regions we have
* already shed. <b>nextRegionForUnload</b> contains the index in the list
* of regions on the server that is the next to be shed.
*/
private static class BalanceInfo {
private final int nextRegionForUnload;
private final int numRegionsAdded;
public BalanceInfo(int nextRegionForUnload, int numRegionsAdded) {
this.nextRegionForUnload = nextRegionForUnload;
this.numRegionsAdded = numRegionsAdded;
}
public int getNextRegionForUnload() {
return nextRegionForUnload;
}
public int getNumRegionsAdded() {
return numRegionsAdded;
}
}
/**
* Generates a bulk assignment plan to be used on cluster startup using a
* simple round-robin assignment.
* <p>
* Takes a list of all the regions and all the servers in the cluster and
* returns a map of each server to the regions that it should be assigned.
* <p>
* Currently implemented as a round-robin assignment. Same invariant as
* load balancing, all servers holding floor(avg) or ceiling(avg).
*
* TODO: Use block locations from HDFS to place regions with their blocks
*
* @param regions all regions
* @param servers all servers
* @return map of server to the regions it should take, or null if no
* assignment is possible (ie. no regions or no servers)
*/
public static Map<HServerInfo,List<HRegionInfo>> roundRobinAssignment(
List<HRegionInfo> regions, List<HServerInfo> servers) {
if(regions.size() == 0 || servers.size() == 0) {
return null;
}
Map<HServerInfo,List<HRegionInfo>> assignments =
new TreeMap<HServerInfo,List<HRegionInfo>>();
int numRegions = regions.size();
int numServers = servers.size();
int max = (int)Math.ceil((float)numRegions/numServers);
int serverIdx = 0;
if (numServers > 1) {
serverIdx = rand.nextInt(numServers);
}
int regionIdx = 0;
for (int j = 0; j < numServers; j++) {
HServerInfo server = servers.get((j+serverIdx) % numServers);
List<HRegionInfo> serverRegions = new ArrayList<HRegionInfo>(max);
for (int i=regionIdx; i<numRegions; i += numServers) {
serverRegions.add(regions.get(i % numRegions));
}
assignments.put(server, serverRegions);
regionIdx++;
}
return assignments;
}
/**
* Generates a bulk assignment startup plan, attempting to reuse the existing
* assignment information from META, but adjusting for the specified list of
* available/online servers available for assignment.
* <p>
* Takes a map of all regions to their existing assignment from META. Also
* takes a list of online servers for regions to be assigned to. Attempts to
* retain all assignment, so in some instances initial assignment will not be
* completely balanced.
* <p>
* Any leftover regions without an existing server to be assigned to will be
* assigned randomly to available servers.
* @param regions regions and existing assignment from meta
* @param servers available servers
* @return map of servers and regions to be assigned to them
*/
public static Map<HServerInfo, List<HRegionInfo>> retainAssignment(
Map<HRegionInfo, HServerAddress> regions, List<HServerInfo> servers) {
Map<HServerInfo, List<HRegionInfo>> assignments =
new TreeMap<HServerInfo, List<HRegionInfo>>();
// Build a map of server addresses to server info so we can match things up
Map<HServerAddress, HServerInfo> serverMap =
new TreeMap<HServerAddress, HServerInfo>();
for (HServerInfo server : servers) {
serverMap.put(server.getServerAddress(), server);
assignments.put(server, new ArrayList<HRegionInfo>());
}
for (Map.Entry<HRegionInfo, HServerAddress> region : regions.entrySet()) {
HServerAddress hsa = region.getValue();
HServerInfo server = hsa == null? null: serverMap.get(hsa);
if (server != null) {
assignments.get(server).add(region.getKey());
} else {
assignments.get(servers.get(rand.nextInt(assignments.size()))).add(
region.getKey());
}
}
return assignments;
}
/**
* Find the block locations for all of the files for the specified region.
*
* Returns an ordered list of hosts that are hosting the blocks for this
* region. The weight of each host is the sum of the block lengths of all
* files on that host, so the first host in the list is the server which
* holds the most bytes of the given region's HFiles.
*
* TODO: Make this work. Need to figure out how to match hadoop's hostnames
* given for block locations with our HServerAddress.
* TODO: Use the right directory for the region
* TODO: Use getFileBlockLocations on the files not the directory
*
* @param fs the filesystem
* @param region region
* @return ordered list of hosts holding blocks of the specified region
* @throws IOException if any filesystem errors
*/
@SuppressWarnings("unused")
private List<String> getTopBlockLocations(FileSystem fs, HRegionInfo region)
throws IOException {
String encodedName = region.getEncodedName();
Path path = new Path("/hbase/table/" + encodedName);
FileStatus status = fs.getFileStatus(path);
BlockLocation [] blockLocations =
fs.getFileBlockLocations(status, 0, status.getLen());
Map<HostAndWeight,HostAndWeight> hostWeights =
new TreeMap<HostAndWeight,HostAndWeight>(new HostAndWeight.HostComparator());
for(BlockLocation bl : blockLocations) {
String [] hosts = bl.getHosts();
long len = bl.getLength();
for(String host : hosts) {
HostAndWeight haw = hostWeights.get(host);
if(haw == null) {
haw = new HostAndWeight(host, len);
hostWeights.put(haw, haw);
} else {
haw.addWeight(len);
}
}
}
NavigableSet<HostAndWeight> orderedHosts = new TreeSet<HostAndWeight>(
new HostAndWeight.WeightComparator());
orderedHosts.addAll(hostWeights.values());
List<String> topHosts = new ArrayList<String>(orderedHosts.size());
for(HostAndWeight haw : orderedHosts.descendingSet()) {
topHosts.add(haw.getHost());
}
return topHosts;
}
/**
* Stores the hostname and weight for that hostname.
*
* This is used when determining the physical locations of the blocks making
* up a region.
*
* To make a prioritized list of the hosts holding the most data of a region,
* this class is used to count the total weight for each host. The weight is
* currently just the size of the file.
*/
private static class HostAndWeight {
private final String host;
private long weight;
public HostAndWeight(String host, long weight) {
this.host = host;
this.weight = weight;
}
public void addWeight(long weight) {
this.weight += weight;
}
public String getHost() {
return host;
}
public long getWeight() {
return weight;
}
private static class HostComparator implements Comparator<HostAndWeight> {
@Override
public int compare(HostAndWeight l, HostAndWeight r) {
return l.getHost().compareTo(r.getHost());
}
}
private static class WeightComparator implements Comparator<HostAndWeight> {
@Override
public int compare(HostAndWeight l, HostAndWeight r) {
if(l.getWeight() == r.getWeight()) {
return l.getHost().compareTo(r.getHost());
}
return l.getWeight() < r.getWeight() ? -1 : 1;
}
}
}
/**
* Generates an immediate assignment plan to be used by a new master for
* regions in transition that do not have an already known destination.
*
* Takes a list of regions that need immediate assignment and a list of
* all available servers. Returns a map of regions to the server they
* should be assigned to.
*
* This method will return quickly and does not do any intelligent
* balancing. The goal is to make a fast decision not the best decision
* possible.
*
* Currently this is random.
*
* @param regions
* @param servers
* @return map of regions to the server it should be assigned to
*/
public static Map<HRegionInfo,HServerInfo> immediateAssignment(
List<HRegionInfo> regions, List<HServerInfo> servers) {
Map<HRegionInfo,HServerInfo> assignments =
new TreeMap<HRegionInfo,HServerInfo>();
for(HRegionInfo region : regions) {
assignments.put(region, servers.get(rand.nextInt(servers.size())));
}
return assignments;
}
public static HServerInfo randomAssignment(List<HServerInfo> servers) {
if (servers == null || servers.isEmpty()) {
LOG.warn("Wanted to do random assignment but no servers to assign to");
return null;
}
return servers.get(rand.nextInt(servers.size()));
}
/**
* Stores the plan for the move of an individual region.
*
* Contains info for the region being moved, info for the server the region
* should be moved from, and info for the server the region should be moved
* to.
*
* The comparable implementation of this class compares only the region
* information and not the source/dest server info.
*/
public static class RegionPlan implements Comparable<RegionPlan> {
private final HRegionInfo hri;
private final HServerInfo source;
private HServerInfo dest;
/**
* Instantiate a plan for a region move, moving the specified region from
* the specified source server to the specified destination server.
*
* Destination server can be instantiated as null and later set
* with {@link #setDestination(HServerInfo)}.
*
* @param hri region to be moved
* @param source regionserver region should be moved from
* @param dest regionserver region should be moved to
*/
public RegionPlan(final HRegionInfo hri, HServerInfo source, HServerInfo dest) {
this.hri = hri;
this.source = source;
this.dest = dest;
}
/**
* Set the destination server for the plan for this region.
*/
public void setDestination(HServerInfo dest) {
this.dest = dest;
}
/**
* Get the source server for the plan for this region.
* @return server info for source
*/
public HServerInfo getSource() {
return source;
}
/**
* Get the destination server for the plan for this region.
* @return server info for destination
*/
public HServerInfo getDestination() {
return dest;
}
/**
* Get the encoded region name for the region this plan is for.
* @return Encoded region name
*/
public String getRegionName() {
return this.hri.getEncodedName();
}
public HRegionInfo getRegionInfo() {
return this.hri;
}
/**
* Compare the region info.
* @param o region plan you are comparing against
*/
@Override
public int compareTo(RegionPlan o) {
return getRegionName().compareTo(o.getRegionName());
}
@Override
public String toString() {
return "hri=" + this.hri.getRegionNameAsString() + ", src=" +
(this.source == null? "": this.source.getServerName()) +
", dest=" + (this.dest == null? "": this.dest.getServerName());
}
}
}
| true | true | public List<RegionPlan> balanceCluster(
Map<HServerInfo,List<HRegionInfo>> clusterState) {
long startTime = System.currentTimeMillis();
// Make a map sorted by load and count regions
TreeMap<HServerInfo,List<HRegionInfo>> serversByLoad =
new TreeMap<HServerInfo,List<HRegionInfo>>(
new HServerInfo.LoadComparator());
int numServers = clusterState.size();
if (numServers == 0) {
LOG.debug("numServers=0 so skipping load balancing");
return null;
}
int numRegions = 0;
// Iterate so we can count regions as we build the map
for(Map.Entry<HServerInfo, List<HRegionInfo>> server:
clusterState.entrySet()) {
server.getKey().getLoad().setNumberOfRegions(server.getValue().size());
numRegions += server.getKey().getLoad().getNumberOfRegions();
serversByLoad.put(server.getKey(), server.getValue());
}
// Check if we even need to do any load balancing
float average = (float)numRegions / numServers; // for logging
int min = numRegions / numServers;
int max = numRegions % numServers == 0 ? min : min + 1;
if(serversByLoad.lastKey().getLoad().getNumberOfRegions() <= max &&
serversByLoad.firstKey().getLoad().getNumberOfRegions() >= min) {
// Skipped because no server outside (min,max) range
LOG.info("Skipping load balancing. servers=" + numServers + " " +
"regions=" + numRegions + " average=" + average + " " +
"mostloaded=" + serversByLoad.lastKey().getLoad().getNumberOfRegions() +
" leastloaded=" + serversByLoad.lastKey().getLoad().getNumberOfRegions());
return null;
}
// Balance the cluster
// TODO: Look at data block locality or a more complex load to do this
List<RegionPlan> regionsToMove = new ArrayList<RegionPlan>();
int regionidx = 0; // track the index in above list for setting destination
// Walk down most loaded, pruning each to the max
int serversOverloaded = 0;
Map<HServerInfo,BalanceInfo> serverBalanceInfo =
new TreeMap<HServerInfo,BalanceInfo>();
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.descendingMap().entrySet()) {
HServerInfo serverInfo = server.getKey();
int regionCount = serverInfo.getLoad().getNumberOfRegions();
if(regionCount <= max) {
serverBalanceInfo.put(serverInfo, new BalanceInfo(0, 0));
break;
}
serversOverloaded++;
List<HRegionInfo> regions = server.getValue();
int numToOffload = Math.min(regionCount - max, regions.size());
int numTaken = 0;
for (int i = regions.size() - 1; i >= 0; i--) {
HRegionInfo hri = regions.get(i);
// Don't rebalance meta regions.
if (hri.isMetaRegion()) continue;
regionsToMove.add(new RegionPlan(hri, serverInfo, null));
numTaken++;
if (numTaken >= numToOffload) break;
}
serverBalanceInfo.put(serverInfo,
new BalanceInfo(numToOffload, (-1)*numTaken));
}
// put young regions at the beginning of regionsToMove
Collections.sort(regionsToMove, rpComparator);
// Walk down least loaded, filling each to the min
int serversUnderloaded = 0; // number of servers that get new regions
int neededRegions = 0; // number of regions needed to bring all up to min
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.entrySet()) {
int regionCount = server.getKey().getLoad().getNumberOfRegions();
if(regionCount >= min) {
break;
}
serversUnderloaded++;
int numToTake = min - regionCount;
int numTaken = 0;
while(numTaken < numToTake && regionidx < regionsToMove.size()) {
regionsToMove.get(regionidx).setDestination(server.getKey());
numTaken++;
regionidx++;
}
serverBalanceInfo.put(server.getKey(), new BalanceInfo(0, numTaken));
// If we still want to take some, increment needed
if(numTaken < numToTake) {
neededRegions += (numToTake - numTaken);
}
}
// If none needed to fill all to min and none left to drain all to max,
// we are done
if(neededRegions == 0 && regionidx == regionsToMove.size()) {
long endTime = System.currentTimeMillis();
LOG.info("Calculated a load balance in " + (endTime-startTime) + "ms. " +
"Moving " + regionsToMove.size() + " regions off of " +
serversOverloaded + " overloaded servers onto " +
serversUnderloaded + " less loaded servers");
return regionsToMove;
}
// Need to do a second pass.
// Either more regions to assign out or servers that are still underloaded
// If we need more to fill min, grab one from each most loaded until enough
if (neededRegions != 0) {
// Walk down most loaded, grabbing one from each until we get enough
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.descendingMap().entrySet()) {
BalanceInfo balanceInfo = serverBalanceInfo.get(server.getKey());
int idx =
balanceInfo == null ? 0 : balanceInfo.getNextRegionForUnload();
if (idx >= server.getValue().size()) break;
HRegionInfo region = server.getValue().get(idx);
if (region.isMetaRegion()) continue; // Don't move meta regions.
regionsToMove.add(new RegionPlan(region, server.getKey(), null));
if(--neededRegions == 0) {
// No more regions needed, done shedding
break;
}
}
}
// Now we have a set of regions that must be all assigned out
// Assign each underloaded up to the min, then if leftovers, assign to max
// Walk down least loaded, assigning to each to fill up to min
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.entrySet()) {
int regionCount = server.getKey().getLoad().getNumberOfRegions();
if (regionCount >= min) break;
BalanceInfo balanceInfo = serverBalanceInfo.get(server.getKey());
if(balanceInfo != null) {
regionCount += balanceInfo.getNumRegionsAdded();
}
if(regionCount >= min) {
continue;
}
int numToTake = min - regionCount;
int numTaken = 0;
while(numTaken < numToTake && regionidx < regionsToMove.size()) {
regionsToMove.get(regionidx).setDestination(server.getKey());
numTaken++;
regionidx++;
}
}
// If we still have regions to dish out, assign underloaded to max
if(regionidx != regionsToMove.size()) {
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.entrySet()) {
int regionCount = server.getKey().getLoad().getNumberOfRegions();
if(regionCount >= max) {
break;
}
regionsToMove.get(regionidx).setDestination(server.getKey());
regionidx++;
if(regionidx == regionsToMove.size()) {
break;
}
}
}
long endTime = System.currentTimeMillis();
if (regionidx != regionsToMove.size() || neededRegions != 0) {
// Emit data so can diagnose how balancer went astray.
LOG.warn("regionidx=" + regionidx + ", regionsToMove=" + regionsToMove.size() +
", numServers=" + numServers + ", serversOverloaded=" + serversOverloaded +
", serversUnderloaded=" + serversUnderloaded);
StringBuilder sb = new StringBuilder();
for (Map.Entry<HServerInfo, List<HRegionInfo>> e: clusterState.entrySet()) {
if (sb.length() > 0) sb.append(", ");
sb.append(e.getKey().getServerName());
sb.append(" ");
sb.append(e.getValue().size());
}
LOG.warn("Input " + sb.toString());
}
// All done!
LOG.info("Calculated a load balance in " + (endTime-startTime) + "ms. " +
"Moving " + regionsToMove.size() + " regions off of " +
serversOverloaded + " overloaded servers onto " +
serversUnderloaded + " less loaded servers");
return regionsToMove;
}
| public List<RegionPlan> balanceCluster(
Map<HServerInfo,List<HRegionInfo>> clusterState) {
long startTime = System.currentTimeMillis();
// Make a map sorted by load and count regions
TreeMap<HServerInfo,List<HRegionInfo>> serversByLoad =
new TreeMap<HServerInfo,List<HRegionInfo>>(
new HServerInfo.LoadComparator());
int numServers = clusterState.size();
if (numServers == 0) {
LOG.debug("numServers=0 so skipping load balancing");
return null;
}
int numRegions = 0;
// Iterate so we can count regions as we build the map
for(Map.Entry<HServerInfo, List<HRegionInfo>> server:
clusterState.entrySet()) {
server.getKey().getLoad().setNumberOfRegions(server.getValue().size());
numRegions += server.getKey().getLoad().getNumberOfRegions();
serversByLoad.put(server.getKey(), server.getValue());
}
// Check if we even need to do any load balancing
float average = (float)numRegions / numServers; // for logging
int min = numRegions / numServers;
int max = numRegions % numServers == 0 ? min : min + 1;
if(serversByLoad.lastKey().getLoad().getNumberOfRegions() <= max &&
serversByLoad.firstKey().getLoad().getNumberOfRegions() >= min) {
// Skipped because no server outside (min,max) range
LOG.info("Skipping load balancing. servers=" + numServers + " " +
"regions=" + numRegions + " average=" + average + " " +
"mostloaded=" + serversByLoad.lastKey().getLoad().getNumberOfRegions() +
" leastloaded=" + serversByLoad.firstKey().getLoad().getNumberOfRegions());
return null;
}
// Balance the cluster
// TODO: Look at data block locality or a more complex load to do this
List<RegionPlan> regionsToMove = new ArrayList<RegionPlan>();
int regionidx = 0; // track the index in above list for setting destination
// Walk down most loaded, pruning each to the max
int serversOverloaded = 0;
Map<HServerInfo,BalanceInfo> serverBalanceInfo =
new TreeMap<HServerInfo,BalanceInfo>();
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.descendingMap().entrySet()) {
HServerInfo serverInfo = server.getKey();
int regionCount = serverInfo.getLoad().getNumberOfRegions();
if(regionCount <= max) {
serverBalanceInfo.put(serverInfo, new BalanceInfo(0, 0));
break;
}
serversOverloaded++;
List<HRegionInfo> regions = server.getValue();
int numToOffload = Math.min(regionCount - max, regions.size());
int numTaken = 0;
for (int i = regions.size() - 1; i >= 0; i--) {
HRegionInfo hri = regions.get(i);
// Don't rebalance meta regions.
if (hri.isMetaRegion()) continue;
regionsToMove.add(new RegionPlan(hri, serverInfo, null));
numTaken++;
if (numTaken >= numToOffload) break;
}
serverBalanceInfo.put(serverInfo,
new BalanceInfo(numToOffload, (-1)*numTaken));
}
// put young regions at the beginning of regionsToMove
Collections.sort(regionsToMove, rpComparator);
// Walk down least loaded, filling each to the min
int serversUnderloaded = 0; // number of servers that get new regions
int neededRegions = 0; // number of regions needed to bring all up to min
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.entrySet()) {
int regionCount = server.getKey().getLoad().getNumberOfRegions();
if(regionCount >= min) {
break;
}
serversUnderloaded++;
int numToTake = min - regionCount;
int numTaken = 0;
while(numTaken < numToTake && regionidx < regionsToMove.size()) {
regionsToMove.get(regionidx).setDestination(server.getKey());
numTaken++;
regionidx++;
}
serverBalanceInfo.put(server.getKey(), new BalanceInfo(0, numTaken));
// If we still want to take some, increment needed
if(numTaken < numToTake) {
neededRegions += (numToTake - numTaken);
}
}
// If none needed to fill all to min and none left to drain all to max,
// we are done
if(neededRegions == 0 && regionidx == regionsToMove.size()) {
long endTime = System.currentTimeMillis();
LOG.info("Calculated a load balance in " + (endTime-startTime) + "ms. " +
"Moving " + regionsToMove.size() + " regions off of " +
serversOverloaded + " overloaded servers onto " +
serversUnderloaded + " less loaded servers");
return regionsToMove;
}
// Need to do a second pass.
// Either more regions to assign out or servers that are still underloaded
// If we need more to fill min, grab one from each most loaded until enough
if (neededRegions != 0) {
// Walk down most loaded, grabbing one from each until we get enough
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.descendingMap().entrySet()) {
BalanceInfo balanceInfo = serverBalanceInfo.get(server.getKey());
int idx =
balanceInfo == null ? 0 : balanceInfo.getNextRegionForUnload();
if (idx >= server.getValue().size()) break;
HRegionInfo region = server.getValue().get(idx);
if (region.isMetaRegion()) continue; // Don't move meta regions.
regionsToMove.add(new RegionPlan(region, server.getKey(), null));
if(--neededRegions == 0) {
// No more regions needed, done shedding
break;
}
}
}
// Now we have a set of regions that must be all assigned out
// Assign each underloaded up to the min, then if leftovers, assign to max
// Walk down least loaded, assigning to each to fill up to min
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.entrySet()) {
int regionCount = server.getKey().getLoad().getNumberOfRegions();
if (regionCount >= min) break;
BalanceInfo balanceInfo = serverBalanceInfo.get(server.getKey());
if(balanceInfo != null) {
regionCount += balanceInfo.getNumRegionsAdded();
}
if(regionCount >= min) {
continue;
}
int numToTake = min - regionCount;
int numTaken = 0;
while(numTaken < numToTake && regionidx < regionsToMove.size()) {
regionsToMove.get(regionidx).setDestination(server.getKey());
numTaken++;
regionidx++;
}
}
// If we still have regions to dish out, assign underloaded to max
if(regionidx != regionsToMove.size()) {
for(Map.Entry<HServerInfo, List<HRegionInfo>> server :
serversByLoad.entrySet()) {
int regionCount = server.getKey().getLoad().getNumberOfRegions();
if(regionCount >= max) {
break;
}
regionsToMove.get(regionidx).setDestination(server.getKey());
regionidx++;
if(regionidx == regionsToMove.size()) {
break;
}
}
}
long endTime = System.currentTimeMillis();
if (regionidx != regionsToMove.size() || neededRegions != 0) {
// Emit data so can diagnose how balancer went astray.
LOG.warn("regionidx=" + regionidx + ", regionsToMove=" + regionsToMove.size() +
", numServers=" + numServers + ", serversOverloaded=" + serversOverloaded +
", serversUnderloaded=" + serversUnderloaded);
StringBuilder sb = new StringBuilder();
for (Map.Entry<HServerInfo, List<HRegionInfo>> e: clusterState.entrySet()) {
if (sb.length() > 0) sb.append(", ");
sb.append(e.getKey().getServerName());
sb.append(" ");
sb.append(e.getValue().size());
}
LOG.warn("Input " + sb.toString());
}
// All done!
LOG.info("Calculated a load balance in " + (endTime-startTime) + "ms. " +
"Moving " + regionsToMove.size() + " regions off of " +
serversOverloaded + " overloaded servers onto " +
serversUnderloaded + " less loaded servers");
return regionsToMove;
}
|
diff --git a/src/java/org/infoglue/cms/util/SetCharacterEncodingFilter.java b/src/java/org/infoglue/cms/util/SetCharacterEncodingFilter.java
index fd7fb2ed5..5db323459 100755
--- a/src/java/org/infoglue/cms/util/SetCharacterEncodingFilter.java
+++ b/src/java/org/infoglue/cms/util/SetCharacterEncodingFilter.java
@@ -1,169 +1,171 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2, as published by the
* Free Software Foundation. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including 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. / 59 Temple
* Place, Suite 330 / Boston, MA 02111-1307 / USA.
*
* ===============================================================================
*/
package org.infoglue.cms.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.infoglue.cms.controllers.kernel.impl.simple.LanguageController;
import org.infoglue.cms.entities.management.LanguageVO;
public class SetCharacterEncodingFilter implements Filter
{
/**
* The default character encoding to set for requests that pass through
* this filter.
*/
protected String encoding = null;
/**
* The filter configuration object we are associated with. If this value
* is null, this filter instance is not currently configured.
*/
protected FilterConfig filterConfig = null;
/**
* Should a character encoding specified by the client be ignored?
*/
protected boolean ignore = true;
/**
* Take this filter out of service.
*/
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
/**
* Select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*
* @param request The servlet request we are processing
* @param result The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
// Conditionally select and set the character encoding to be used
String referer = ((HttpServletRequest)request).getHeader("referer");
if(referer != null && referer.length() > 0 && referer.indexOf("ViewPage!renderDecoratedPage.action") > -1)
{
try
{
int startIndex = referer.indexOf("&languageId=");
if(startIndex > -1)
{
int endIndex = referer.indexOf("&", startIndex + 12);
- String languageId = referer.substring(startIndex + 12, endIndex);
+ String languageId = referer.substring(startIndex + 12);
+ if(endIndex != -1)
+ languageId = referer.substring(startIndex + 12, endIndex);
//System.out.println("languageId:" + languageId);
LanguageVO languageVO = LanguageController.getController().getLanguageVOWithId(new Integer(languageId));
request.setCharacterEncoding(languageVO.getCharset());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
else if (ignore || (request.getCharacterEncoding() == null))
{
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
}
// Pass control on to the next filter
chain.doFilter(request, response);
}
/**
* Place this filter into service.
*
* @param filterConfig The filter configuration object
*/
public void init(FilterConfig filterConfig) throws ServletException
{
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
}
/**
* Select an appropriate character encoding to be used, based on the
* characteristics of the current request and/or filter initialization
* parameters. If no character encoding should be set, return
* <code>null</code>.
* <p>
* The default implementation unconditionally returns the value configured
* by the <strong>encoding</strong> initialization parameter for this
* filter.
*
* @param request The servlet request we are processing
*/
protected String selectEncoding(ServletRequest request)
{
String inputCharacterEncoding = CmsPropertyHandler.getInputCharacterEncoding(this.encoding);
if(inputCharacterEncoding != null && !inputCharacterEncoding.equals("") && !inputCharacterEncoding.equalsIgnoreCase("@inputCharacterEncoding@"))
return inputCharacterEncoding;
else
return (this.encoding);
}
}
| true | true | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
// Conditionally select and set the character encoding to be used
String referer = ((HttpServletRequest)request).getHeader("referer");
if(referer != null && referer.length() > 0 && referer.indexOf("ViewPage!renderDecoratedPage.action") > -1)
{
try
{
int startIndex = referer.indexOf("&languageId=");
if(startIndex > -1)
{
int endIndex = referer.indexOf("&", startIndex + 12);
String languageId = referer.substring(startIndex + 12, endIndex);
//System.out.println("languageId:" + languageId);
LanguageVO languageVO = LanguageController.getController().getLanguageVOWithId(new Integer(languageId));
request.setCharacterEncoding(languageVO.getCharset());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
else if (ignore || (request.getCharacterEncoding() == null))
{
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
}
// Pass control on to the next filter
chain.doFilter(request, response);
}
| public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
// Conditionally select and set the character encoding to be used
String referer = ((HttpServletRequest)request).getHeader("referer");
if(referer != null && referer.length() > 0 && referer.indexOf("ViewPage!renderDecoratedPage.action") > -1)
{
try
{
int startIndex = referer.indexOf("&languageId=");
if(startIndex > -1)
{
int endIndex = referer.indexOf("&", startIndex + 12);
String languageId = referer.substring(startIndex + 12);
if(endIndex != -1)
languageId = referer.substring(startIndex + 12, endIndex);
//System.out.println("languageId:" + languageId);
LanguageVO languageVO = LanguageController.getController().getLanguageVOWithId(new Integer(languageId));
request.setCharacterEncoding(languageVO.getCharset());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
else if (ignore || (request.getCharacterEncoding() == null))
{
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
}
// Pass control on to the next filter
chain.doFilter(request, response);
}
|
diff --git a/src/com/guntherdw/bukkit/tweakcraft/Commands/General/CommandLc.java b/src/com/guntherdw/bukkit/tweakcraft/Commands/General/CommandLc.java
index e5cf286..c5783f2 100644
--- a/src/com/guntherdw/bukkit/tweakcraft/Commands/General/CommandLc.java
+++ b/src/com/guntherdw/bukkit/tweakcraft/Commands/General/CommandLc.java
@@ -1,48 +1,48 @@
package com.guntherdw.bukkit.tweakcraft.Commands.General;
import com.guntherdw.bukkit.tweakcraft.ChatMode;
import com.guntherdw.bukkit.tweakcraft.Command;
import com.guntherdw.bukkit.tweakcraft.Exceptions.*;
import com.guntherdw.bukkit.tweakcraft.TweakcraftUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
/**
* @author GuntherDW
*/
public class CommandLc implements Command {
public boolean executeCommand(CommandSender sender, String command, String[] args, TweakcraftUtils plugin)
throws PermissionsException, CommandSenderException, CommandUsageException, CommandException {
if(sender instanceof Player)
{
if(!plugin.check((Player)sender, "localchat"))
throw new PermissionsException(command);
try {
ChatMode cm = plugin.getChathandler().getChatMode("local");
List<String> sublist = cm.getSubscribers();
if(!sublist.contains(((Player) sender).getName()))
{
cm.addRecipient(((Player) sender).getName());
plugin.getChathandler().setPlayerchatmode(((Player) sender).getName(),"local");
sender.sendMessage(ChatColor.YELLOW + "You will now chat locally!");
} else {
cm.removeRecipient(((Player) sender).getName());
- plugin.getChathandler().setPlayerchatmode(((Player) sender).getName(),"null");
+ plugin.getChathandler().setPlayerchatmode(((Player) sender).getName(), null);
sender.sendMessage(ChatColor.YELLOW + "You will now chat globally!");
}
} catch (ChatModeException e) {
throw new CommandException("Exception thrown when setting chatmode!");
}
} else {
// It's the console!
throw new CommandSenderException("You need to be a player to use LocalChat!");
}
return true;
}
}
| true | true | public boolean executeCommand(CommandSender sender, String command, String[] args, TweakcraftUtils plugin)
throws PermissionsException, CommandSenderException, CommandUsageException, CommandException {
if(sender instanceof Player)
{
if(!plugin.check((Player)sender, "localchat"))
throw new PermissionsException(command);
try {
ChatMode cm = plugin.getChathandler().getChatMode("local");
List<String> sublist = cm.getSubscribers();
if(!sublist.contains(((Player) sender).getName()))
{
cm.addRecipient(((Player) sender).getName());
plugin.getChathandler().setPlayerchatmode(((Player) sender).getName(),"local");
sender.sendMessage(ChatColor.YELLOW + "You will now chat locally!");
} else {
cm.removeRecipient(((Player) sender).getName());
plugin.getChathandler().setPlayerchatmode(((Player) sender).getName(),"null");
sender.sendMessage(ChatColor.YELLOW + "You will now chat globally!");
}
} catch (ChatModeException e) {
throw new CommandException("Exception thrown when setting chatmode!");
}
} else {
// It's the console!
throw new CommandSenderException("You need to be a player to use LocalChat!");
}
return true;
}
| public boolean executeCommand(CommandSender sender, String command, String[] args, TweakcraftUtils plugin)
throws PermissionsException, CommandSenderException, CommandUsageException, CommandException {
if(sender instanceof Player)
{
if(!plugin.check((Player)sender, "localchat"))
throw new PermissionsException(command);
try {
ChatMode cm = plugin.getChathandler().getChatMode("local");
List<String> sublist = cm.getSubscribers();
if(!sublist.contains(((Player) sender).getName()))
{
cm.addRecipient(((Player) sender).getName());
plugin.getChathandler().setPlayerchatmode(((Player) sender).getName(),"local");
sender.sendMessage(ChatColor.YELLOW + "You will now chat locally!");
} else {
cm.removeRecipient(((Player) sender).getName());
plugin.getChathandler().setPlayerchatmode(((Player) sender).getName(), null);
sender.sendMessage(ChatColor.YELLOW + "You will now chat globally!");
}
} catch (ChatModeException e) {
throw new CommandException("Exception thrown when setting chatmode!");
}
} else {
// It's the console!
throw new CommandSenderException("You need to be a player to use LocalChat!");
}
return true;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.