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/edu/ucsc/cs/mturk/lib/topone/BubbleAlgorithm.java b/src/edu/ucsc/cs/mturk/lib/topone/BubbleAlgorithm.java
index a6a7dce..cd105a1 100644
--- a/src/edu/ucsc/cs/mturk/lib/topone/BubbleAlgorithm.java
+++ b/src/edu/ucsc/cs/mturk/lib/topone/BubbleAlgorithm.java
@@ -1,394 +1,395 @@
package edu.ucsc.cs.mturk.lib.topone;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import com.amazonaws.mturk.service.axis.RequesterService;
import com.amazonaws.mturk.util.PropertiesClientConfig;
import com.amazonaws.mturk.requester.HIT;
import com.amazonaws.mturk.requester.HITStatus;
/**
* <p>This class is the implementation of bubble algorithm. It simulates the
* process of the bubble algorithm. Users build an object of the bubble
* algorithm through this class, put questions into this object, and
* the object takes care the rest job. Finally, it returns the final answer
* of this running instance.</p>
*
* <p>Since some operations, such as creating a HIT and getting answers from
* workers etc., should be customized by library users, we use callback
* routine to make it. Therefore, library users need to implement <i><b>
* MyHit</b></i> interface, build an instance of the class and use this instance
* as a parameter in the constructor.</p>
*
* Also, generally there are two ways to enable the library to have the access to
* your Amazon Mechanical Turk account. The first one is to pass <tt>service</tt>
* of type <tt>import com.amazonaws.mturk.service.axis.RequesterService</tt>
* into the constructor. The second one is to locate your Amazon Mechanical
* Turk property file, which stores your <tt>access_key</tt>, <tt>secret_key</tt> and
* <tt>service_url</tt>, in the same directory of the source file and to pass the
* file name as a parameter in the constructor.
*
* <p>Finally, an instance of this class should be created in a Builder
* pattern. To create an instance of the algorithm, a static inner class
* Builder may be used like this:<br/>
* <pre>BubbleAlgorithm bubble = new BubbleAlgorithm.Builder(questions, myHit).
* propertyFile("mturk.properties").inputSize(6).outputSize(2).
* numberOfAssignments(5).isLogged(true).logName("Log.txt").
* jobId("E9FG6X9LO");</pre> <br />
* Note that you do not need to configure all the parameters. You can choose
* to configure only what you need. However, questions and myHit are still
* required.
* </p>
*
* @author Kerui Huang
* @version 1.1
*
*/
public class BubbleAlgorithm {
/* The inputs and output of the algorithm*/
private final RequesterService service; //MTurk service
private final MyHit myHit; // the object for callback
private final ArrayList<Object> questions;
private final int nInput; // number of outputs of a HIT
private int nOutput; // number of outputs of a HIT
private final int nAssignment; // number of assignments of a normal HIT
private final int nTieAssignment; // number of assignments of a tie-solving HIT
private final boolean isShuffled; // shuffle the inputs
private final boolean isLogged; // whether generate log automatically
private final String logName; // the name of the log file
private final String jobId; // programmers can assign an ID to this job.
private boolean isDone;
private Object finalAnswer;
public static class Builder {
// Required parameters.
private final MyHit myHit;
private final ArrayList<Object> questions;
// Optional parameters.
private RequesterService service = new RequesterService(
new PropertiesClientConfig(
System.getProperty("user.dir") +
java.io.File.separator +
"mturk.properties"));
private int nInput = 6;
private int nOutput = 2;
private int nAssignment = 5;
private int nTieAssignment = 1;
private boolean isShuffled = true;
private boolean isLogged = true;
private String logName = "Bubble_Algorithm_" + new Date().hashCode() + ".txt";;
private String jobId = null;
/**
* Constructs a Builder with questions and myHit.
* @param questions the questions to be solved by workers.
* @param myHit the object which implements <i>MyHit</i> interface and
* provides callback functions.
*/
public Builder(ArrayList<Object> questions, MyHit myHit) {
this.questions = questions;
this.myHit = myHit;
}
/**
* Set the service object of the library user.
* @param service the service object of the library user.
* @return the Builder object itself.
*/
public Builder service(RequesterService service) {
this.service = service;
return this;
}
/**
* Set the name of the the name of the MTurk property file.
* @param propertyFileName the name of the property file.
* @return the Builder object itself.
*/
public Builder propertyFile(String propertyFileName) {
this.service = new RequesterService(
new PropertiesClientConfig(
System.getProperty("user.dir") +
java.io.File.separator +
propertyFileName));
return this;
}
/**
* Set the number of inputs of a HIT.
* @param inputSize the number of inputs of a HIT.
* @return the Builder object itself.
*/
public Builder inputSize(int inputSize) {
this.nInput = inputSize;
return this;
}
/**
* Set the number of outputs of a HIT.
* @param outputSize the number of outputs of a HIT.
* @return the Builder object itself.
*/
public Builder outputSize(int outputSize) {
this.nOutput = outputSize;
return this;
}
/**
* Set the number of assignments for a normal HIT.
* @param numberOfAssignments the number of assignments for a normal
* HIT.
* @return the Builder object itself.
*/
public Builder numberOfAssignments(int numberOfAssignments) {
this.nAssignment = numberOfAssignments;
return this;
}
/**
* Set the number of assignments for a tie-solving HIT.
* @param numberOfTieAssignments the number of assignments for a
* tie-solving HIT.
* @return the Builder object itself.
*/
public Builder numberOfTieAssignments(int numberOfTieAssignments) {
this.nTieAssignment = numberOfTieAssignments;
return this;
}
/**
* Set whether the inputs are shuffled by the algorithm.
* @param isShuffled <tt>true</tt> if the inputs are shuffled by the algorithm.
* @return the Builder object itself.
*/
public Builder isShuffled(boolean isShuffled) {
this.isShuffled = isShuffled;
return this;
}
/**
* Set whether the algorithm records the computation process.
* @param isLogged <tt>true</tt> if the algorithm records the computation
* process.
* @return the Builder object itself.
*/
public Builder isLogged(boolean isLogged) {
this.isLogged = isLogged;
return this;
}
/**
* Set the name of the log file.
* @param logName the name of the log file.
* @return the Builder object itself.
*/
public Builder logName(String logName) {
this.logName = logName;
return this;
}
/**
* Set the job ID for this algorithm instance.
* @param jobId the job ID for this algorithm instance.
* @return the Builder object itself.
*/
public Builder jobId(String jobId) {
this.jobId = jobId;
return this;
}
/**
* Create a new instance of TreeAlgorithm.
* @return the newly created instance of TreeAlgorithm.
*/
public BubbleAlgorithm build() {
validateInitialization(questions, nInput, nOutput,
nAssignment, nTieAssignment);
return new BubbleAlgorithm(this);
}
/*
* This function validates the values of parameters input by library users.
*/
private void validateInitialization(ArrayList<Object> questions,
int numberOfInputs,int numberOfOutputs,
int numberOfAssignments, int numberOfTieAssignments) {
if (questions.size() == 0) {
throw new BubbleAlgorithmException("The size of questions is 0." +
" [questions.size() == 0]");
}
if (questions.size() < numberOfInputs) {
throw new BubbleAlgorithmException("The size of questions is" +
" less than the number of inputs of a HIT." +
" [questions.size() < numberOfInputs]");
}
if (questions.size() < numberOfOutputs) {
throw new BubbleAlgorithmException("The size of questions is" +
" less than the number of outputs of a HIT." +
" [questions.size() < numberOfOutputs]");
}
if (numberOfInputs < numberOfOutputs) {
throw new BubbleAlgorithmException("The number of inputs of a HIT" +
" is less than the number of outputs of a HIT." +
" [numberOfInputs < numberOfOutputs]");
}
if (numberOfInputs < 0) {
throw new BubbleAlgorithmException("The number of inputs of a HIT" +
" is negative." +
" [numberOfInputs < 0]");
}
if (numberOfOutputs < 0) {
throw new BubbleAlgorithmException("The number of outputs of a HIT" +
" is negative." +
" [numberOfOutputs < 0]");
}
if (numberOfAssignments < 1) {
throw new BubbleAlgorithmException("The number of assignments of " +
"a normal HIT is less than 1." +
" [numberOfAssignments < 1]");
}
if (numberOfTieAssignments < 1) {
throw new BubbleAlgorithmException("The number of assignments of " +
"a tie-solving HIT is less than 1." +
" [numberOfTieAssignments < 1]");
}
}
}
private BubbleAlgorithm(Builder builder) {
this.questions = builder.questions;
this.myHit = builder.myHit;
this.service = builder.service;
this.nInput = builder.nInput;
this.nOutput = builder.nOutput;
this.nAssignment = builder.nAssignment;
this.nTieAssignment = builder.nTieAssignment;
this.isShuffled = builder.isShuffled;
this.isLogged = builder.isLogged;
this.logName = builder.logName;
this.jobId = builder.jobId;
this.isDone = false;
this.finalAnswer = null;
}
public void start() {
if (isShuffled) {
Collections.shuffle(questions);
}
if (isLogged) {
String log = "";
LogWriter.createOrResetLog(logName);
log += "The bubble algorithm started at " + new Date().toString() + "\n\n";
log += "The Table of Parameters \n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Number of Inputs of a Normal HIT | " + nInput + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Number of Outputs of a Normal HIT | " + nOutput + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Number of Assignments of a Normal HIT | " + nAssignment + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Number of Assignments of a Tie-Solving HIT | " + nTieAssignment + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Inputs Are Shuffled | " + isShuffled + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Generate Automatic Log | " + isLogged + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| The Name of the Automatic Log | " + logName + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Job ID | " + jobId + "\n" +
"+-----------------------------------------------+-------------------------------+ \n\n";
LogWriter.writeLog(log, logName);
System.out.println(log);
}
while (questions.size() > 1) {
ArrayList<Object> answers = new ArrayList<Object>();
ArrayList<Object> inputs = new ArrayList<Object>();
if (questions.size() >= nInput) {
for (int i = 0; i < nInput; i++) {
inputs.add(questions.get(0));
questions.remove(0);
}
} else {
nOutput = 1;
int questionSize = questions.size();
for (int i = 0; i < questionSize; i++) {
inputs.add(questions.get(0));
questions.remove(0);
}
}
// Create a new HIT.
String hitId = myHit.createMyHit(service, inputs, nOutput, nAssignment);
if (isLogged) {
LogWriter.writeBubbleCreateHitLog(service, hitId, nAssignment, nOutput, inputs, logName);
}
// Keep waiting and checking the status of this new HIT, until it is done.
HIT hit = service.getHIT(hitId);
while (hit.getHITStatus() != HITStatus.Reviewable) {
try {
Thread.sleep(1000*5);
} catch (InterruptedException e) {
e.printStackTrace();
}
hit = service.getHIT(hitId);
}
// Retrieve the answers of the HIT.
answers = AnswerProcessor.refineRawAnswers(
myHit.getMyHitAnswers(service, hitId),
nOutput, service, myHit, nTieAssignment,
isLogged, logName, AnswerProcessor.BUBBLE_ALGORITHM);
if (isLogged) {
LogWriter.writeGetAnswerLog(hitId, answers, logName);
}
// Put the new answers into the questions queue.
for (int i = answers.size() -1; i >= 0; i--) {
questions.add(0, answers.get(i));
}
// Deal with the this already used HIT.
myHit.dumpPastHit(service, hitId);
}
finalAnswer = questions.get(0);
+ isDone = true;
String info = "The bubble algorithm ended at " +
new Date().toString() + "\n\n";;
info = "The final answer is: " + finalAnswer + "\n";
LogWriter.writeLog(info, logName);
System.out.println(info);
}
/**
* Indicate whether this instance is done.
*
* @return <tt>true</tt> if the program is done.
*/
public boolean isDone() {
return isDone;
}
/**
* Return the final answer.
*
* @return The final answer.
*/
public Object getFinalAnswer() {
return finalAnswer;
}
}
| true | true |
public void start() {
if (isShuffled) {
Collections.shuffle(questions);
}
if (isLogged) {
String log = "";
LogWriter.createOrResetLog(logName);
log += "The bubble algorithm started at " + new Date().toString() + "\n\n";
log += "The Table of Parameters \n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Number of Inputs of a Normal HIT | " + nInput + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Number of Outputs of a Normal HIT | " + nOutput + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Number of Assignments of a Normal HIT | " + nAssignment + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Number of Assignments of a Tie-Solving HIT | " + nTieAssignment + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Inputs Are Shuffled | " + isShuffled + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Generate Automatic Log | " + isLogged + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| The Name of the Automatic Log | " + logName + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Job ID | " + jobId + "\n" +
"+-----------------------------------------------+-------------------------------+ \n\n";
LogWriter.writeLog(log, logName);
System.out.println(log);
}
while (questions.size() > 1) {
ArrayList<Object> answers = new ArrayList<Object>();
ArrayList<Object> inputs = new ArrayList<Object>();
if (questions.size() >= nInput) {
for (int i = 0; i < nInput; i++) {
inputs.add(questions.get(0));
questions.remove(0);
}
} else {
nOutput = 1;
int questionSize = questions.size();
for (int i = 0; i < questionSize; i++) {
inputs.add(questions.get(0));
questions.remove(0);
}
}
// Create a new HIT.
String hitId = myHit.createMyHit(service, inputs, nOutput, nAssignment);
if (isLogged) {
LogWriter.writeBubbleCreateHitLog(service, hitId, nAssignment, nOutput, inputs, logName);
}
// Keep waiting and checking the status of this new HIT, until it is done.
HIT hit = service.getHIT(hitId);
while (hit.getHITStatus() != HITStatus.Reviewable) {
try {
Thread.sleep(1000*5);
} catch (InterruptedException e) {
e.printStackTrace();
}
hit = service.getHIT(hitId);
}
// Retrieve the answers of the HIT.
answers = AnswerProcessor.refineRawAnswers(
myHit.getMyHitAnswers(service, hitId),
nOutput, service, myHit, nTieAssignment,
isLogged, logName, AnswerProcessor.BUBBLE_ALGORITHM);
if (isLogged) {
LogWriter.writeGetAnswerLog(hitId, answers, logName);
}
// Put the new answers into the questions queue.
for (int i = answers.size() -1; i >= 0; i--) {
questions.add(0, answers.get(i));
}
// Deal with the this already used HIT.
myHit.dumpPastHit(service, hitId);
}
finalAnswer = questions.get(0);
String info = "The bubble algorithm ended at " +
new Date().toString() + "\n\n";;
info = "The final answer is: " + finalAnswer + "\n";
LogWriter.writeLog(info, logName);
System.out.println(info);
}
|
public void start() {
if (isShuffled) {
Collections.shuffle(questions);
}
if (isLogged) {
String log = "";
LogWriter.createOrResetLog(logName);
log += "The bubble algorithm started at " + new Date().toString() + "\n\n";
log += "The Table of Parameters \n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Number of Inputs of a Normal HIT | " + nInput + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Number of Outputs of a Normal HIT | " + nOutput + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Number of Assignments of a Normal HIT | " + nAssignment + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Number of Assignments of a Tie-Solving HIT | " + nTieAssignment + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Inputs Are Shuffled | " + isShuffled + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Generate Automatic Log | " + isLogged + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| The Name of the Automatic Log | " + logName + "\n" +
"+-----------------------------------------------+-------------------------------+ \n" +
"| Job ID | " + jobId + "\n" +
"+-----------------------------------------------+-------------------------------+ \n\n";
LogWriter.writeLog(log, logName);
System.out.println(log);
}
while (questions.size() > 1) {
ArrayList<Object> answers = new ArrayList<Object>();
ArrayList<Object> inputs = new ArrayList<Object>();
if (questions.size() >= nInput) {
for (int i = 0; i < nInput; i++) {
inputs.add(questions.get(0));
questions.remove(0);
}
} else {
nOutput = 1;
int questionSize = questions.size();
for (int i = 0; i < questionSize; i++) {
inputs.add(questions.get(0));
questions.remove(0);
}
}
// Create a new HIT.
String hitId = myHit.createMyHit(service, inputs, nOutput, nAssignment);
if (isLogged) {
LogWriter.writeBubbleCreateHitLog(service, hitId, nAssignment, nOutput, inputs, logName);
}
// Keep waiting and checking the status of this new HIT, until it is done.
HIT hit = service.getHIT(hitId);
while (hit.getHITStatus() != HITStatus.Reviewable) {
try {
Thread.sleep(1000*5);
} catch (InterruptedException e) {
e.printStackTrace();
}
hit = service.getHIT(hitId);
}
// Retrieve the answers of the HIT.
answers = AnswerProcessor.refineRawAnswers(
myHit.getMyHitAnswers(service, hitId),
nOutput, service, myHit, nTieAssignment,
isLogged, logName, AnswerProcessor.BUBBLE_ALGORITHM);
if (isLogged) {
LogWriter.writeGetAnswerLog(hitId, answers, logName);
}
// Put the new answers into the questions queue.
for (int i = answers.size() -1; i >= 0; i--) {
questions.add(0, answers.get(i));
}
// Deal with the this already used HIT.
myHit.dumpPastHit(service, hitId);
}
finalAnswer = questions.get(0);
isDone = true;
String info = "The bubble algorithm ended at " +
new Date().toString() + "\n\n";;
info = "The final answer is: " + finalAnswer + "\n";
LogWriter.writeLog(info, logName);
System.out.println(info);
}
|
diff --git a/openejb/tomee/tomee-webapp/src/main/java/org/apache/tomee/webapp/command/impl/RunInstaller.java b/openejb/tomee/tomee-webapp/src/main/java/org/apache/tomee/webapp/command/impl/RunInstaller.java
index bbcf80cf3..9377705f2 100644
--- a/openejb/tomee/tomee-webapp/src/main/java/org/apache/tomee/webapp/command/impl/RunInstaller.java
+++ b/openejb/tomee/tomee-webapp/src/main/java/org/apache/tomee/webapp/command/impl/RunInstaller.java
@@ -1,141 +1,141 @@
/*
* 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.tomee.webapp.command.impl;
import org.apache.tomee.installer.Installer;
import org.apache.tomee.installer.Paths;
import org.apache.tomee.webapp.Application;
import org.apache.tomee.webapp.command.Command;
import org.apache.tomee.webapp.command.IsProtected;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
@IsProtected
public class RunInstaller implements Command {
@Override
public Object execute(final Map<String, Object> params) throws Exception {
final String path = Application.getInstance().getRootPath();
File openejbWarDir = null;
if (path != null) {
openejbWarDir = new File(path);
}
final Paths paths = new Paths(openejbWarDir);
final Installer installer = new Installer(paths);
final Map<String, Object> json = new HashMap<String, Object>();
if (Installer.Status.NONE.equals(installer.getStatus())) {
paths.reset();
installer.reset();
if (Boolean.valueOf(String.valueOf(params.get("auto")))) {
paths.setCatalinaHomeDir(System.getProperty("catalina.home"));
paths.setCatalinaBaseDir(System.getProperty("catalina.base"));
paths.setServerXmlFile(System.getProperty("catalina.base") + "/conf/server.xml");
} else {
paths.setCatalinaHomeDir((String) params.get("catalina-home"));
paths.setCatalinaBaseDir((String) params.get("catalina-base"));
paths.setServerXmlFile((String) params.get("catalina-server-xml"));
}
if (paths.verify()) {
installer.installAll();
}
}
json.put("status", installer.getStatus());
json.put("errors", installer.getAlerts().getErrors());
json.put("warnings", installer.getAlerts().getWarnings());
json.put("infos", installer.getAlerts().getInfos());
final Map<String, Object> test = new HashMap<String, Object>();
- json.put("test", test);
+ json.put("tests", test);
{
test.put("hasHome", false);
test.put("doesHomeExist", false);
test.put("isHomeDirectory", false);
test.put("hasLibDirectory", false);
final String homePath = System.getProperty("openejb.home");
if (homePath != null) {
test.put("hasHome", true);
final File homeDir = new File(homePath);
test.put("doesHomeExist", homeDir.exists());
if (homeDir.exists()) {
test.put("isHomeDirectory", homeDir.isDirectory());
final File libDir = new File(homeDir, "lib");
test.put("hasLibDirectory", libDir.exists());
}
}
}
{
test.put("wereTheOpenEJBClassesInstalled", false);
test.put("wereTheEjbClassesInstalled", false);
test.put("wasOpenEJBStarted", false);
test.put("canILookupAnything", false);
try {
final ClassLoader myLoader = this.getClass().getClassLoader();
Class.forName("org.apache.openejb.OpenEJB", true, myLoader);
test.put("wereTheOpenEJBClassesInstalled", true);
} catch (Exception e) {
// noop
}
try {
Class.forName("javax.ejb.EJBHome", true, this.getClass().getClassLoader());
test.put("wereTheEjbClassesInstalled", true);
} catch (Exception e) {
// noop
}
try {
final Class openejb = Class.forName("org.apache.openejb.OpenEJB", true, this.getClass().getClassLoader());
final Method isInitialized = openejb.getDeclaredMethod("isInitialized");
final Boolean running = (Boolean) isInitialized.invoke(openejb);
test.put("wasOpenEJBStarted", running);
} catch (Exception e) {
// noop
}
try {
final Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory");
p.put("openejb.loader", "embed");
final InitialContext ctx = new InitialContext(p);
final Object obj = ctx.lookup("");
if (obj.getClass().getName().equals("org.apache.openejb.core.ivm.naming.IvmContext")) {
test.put("canILookupAnything", true);
}
} catch (Exception e) {
// noop
}
}
return json;
}
}
| true | true |
public Object execute(final Map<String, Object> params) throws Exception {
final String path = Application.getInstance().getRootPath();
File openejbWarDir = null;
if (path != null) {
openejbWarDir = new File(path);
}
final Paths paths = new Paths(openejbWarDir);
final Installer installer = new Installer(paths);
final Map<String, Object> json = new HashMap<String, Object>();
if (Installer.Status.NONE.equals(installer.getStatus())) {
paths.reset();
installer.reset();
if (Boolean.valueOf(String.valueOf(params.get("auto")))) {
paths.setCatalinaHomeDir(System.getProperty("catalina.home"));
paths.setCatalinaBaseDir(System.getProperty("catalina.base"));
paths.setServerXmlFile(System.getProperty("catalina.base") + "/conf/server.xml");
} else {
paths.setCatalinaHomeDir((String) params.get("catalina-home"));
paths.setCatalinaBaseDir((String) params.get("catalina-base"));
paths.setServerXmlFile((String) params.get("catalina-server-xml"));
}
if (paths.verify()) {
installer.installAll();
}
}
json.put("status", installer.getStatus());
json.put("errors", installer.getAlerts().getErrors());
json.put("warnings", installer.getAlerts().getWarnings());
json.put("infos", installer.getAlerts().getInfos());
final Map<String, Object> test = new HashMap<String, Object>();
json.put("test", test);
{
test.put("hasHome", false);
test.put("doesHomeExist", false);
test.put("isHomeDirectory", false);
test.put("hasLibDirectory", false);
final String homePath = System.getProperty("openejb.home");
if (homePath != null) {
test.put("hasHome", true);
final File homeDir = new File(homePath);
test.put("doesHomeExist", homeDir.exists());
if (homeDir.exists()) {
test.put("isHomeDirectory", homeDir.isDirectory());
final File libDir = new File(homeDir, "lib");
test.put("hasLibDirectory", libDir.exists());
}
}
}
{
test.put("wereTheOpenEJBClassesInstalled", false);
test.put("wereTheEjbClassesInstalled", false);
test.put("wasOpenEJBStarted", false);
test.put("canILookupAnything", false);
try {
final ClassLoader myLoader = this.getClass().getClassLoader();
Class.forName("org.apache.openejb.OpenEJB", true, myLoader);
test.put("wereTheOpenEJBClassesInstalled", true);
} catch (Exception e) {
// noop
}
try {
Class.forName("javax.ejb.EJBHome", true, this.getClass().getClassLoader());
test.put("wereTheEjbClassesInstalled", true);
} catch (Exception e) {
// noop
}
try {
final Class openejb = Class.forName("org.apache.openejb.OpenEJB", true, this.getClass().getClassLoader());
final Method isInitialized = openejb.getDeclaredMethod("isInitialized");
final Boolean running = (Boolean) isInitialized.invoke(openejb);
test.put("wasOpenEJBStarted", running);
} catch (Exception e) {
// noop
}
try {
final Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory");
p.put("openejb.loader", "embed");
final InitialContext ctx = new InitialContext(p);
final Object obj = ctx.lookup("");
if (obj.getClass().getName().equals("org.apache.openejb.core.ivm.naming.IvmContext")) {
test.put("canILookupAnything", true);
}
} catch (Exception e) {
// noop
}
}
return json;
}
|
public Object execute(final Map<String, Object> params) throws Exception {
final String path = Application.getInstance().getRootPath();
File openejbWarDir = null;
if (path != null) {
openejbWarDir = new File(path);
}
final Paths paths = new Paths(openejbWarDir);
final Installer installer = new Installer(paths);
final Map<String, Object> json = new HashMap<String, Object>();
if (Installer.Status.NONE.equals(installer.getStatus())) {
paths.reset();
installer.reset();
if (Boolean.valueOf(String.valueOf(params.get("auto")))) {
paths.setCatalinaHomeDir(System.getProperty("catalina.home"));
paths.setCatalinaBaseDir(System.getProperty("catalina.base"));
paths.setServerXmlFile(System.getProperty("catalina.base") + "/conf/server.xml");
} else {
paths.setCatalinaHomeDir((String) params.get("catalina-home"));
paths.setCatalinaBaseDir((String) params.get("catalina-base"));
paths.setServerXmlFile((String) params.get("catalina-server-xml"));
}
if (paths.verify()) {
installer.installAll();
}
}
json.put("status", installer.getStatus());
json.put("errors", installer.getAlerts().getErrors());
json.put("warnings", installer.getAlerts().getWarnings());
json.put("infos", installer.getAlerts().getInfos());
final Map<String, Object> test = new HashMap<String, Object>();
json.put("tests", test);
{
test.put("hasHome", false);
test.put("doesHomeExist", false);
test.put("isHomeDirectory", false);
test.put("hasLibDirectory", false);
final String homePath = System.getProperty("openejb.home");
if (homePath != null) {
test.put("hasHome", true);
final File homeDir = new File(homePath);
test.put("doesHomeExist", homeDir.exists());
if (homeDir.exists()) {
test.put("isHomeDirectory", homeDir.isDirectory());
final File libDir = new File(homeDir, "lib");
test.put("hasLibDirectory", libDir.exists());
}
}
}
{
test.put("wereTheOpenEJBClassesInstalled", false);
test.put("wereTheEjbClassesInstalled", false);
test.put("wasOpenEJBStarted", false);
test.put("canILookupAnything", false);
try {
final ClassLoader myLoader = this.getClass().getClassLoader();
Class.forName("org.apache.openejb.OpenEJB", true, myLoader);
test.put("wereTheOpenEJBClassesInstalled", true);
} catch (Exception e) {
// noop
}
try {
Class.forName("javax.ejb.EJBHome", true, this.getClass().getClassLoader());
test.put("wereTheEjbClassesInstalled", true);
} catch (Exception e) {
// noop
}
try {
final Class openejb = Class.forName("org.apache.openejb.OpenEJB", true, this.getClass().getClassLoader());
final Method isInitialized = openejb.getDeclaredMethod("isInitialized");
final Boolean running = (Boolean) isInitialized.invoke(openejb);
test.put("wasOpenEJBStarted", running);
} catch (Exception e) {
// noop
}
try {
final Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory");
p.put("openejb.loader", "embed");
final InitialContext ctx = new InitialContext(p);
final Object obj = ctx.lookup("");
if (obj.getClass().getName().equals("org.apache.openejb.core.ivm.naming.IvmContext")) {
test.put("canILookupAnything", true);
}
} catch (Exception e) {
// noop
}
}
return json;
}
|
diff --git a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/SslProtocolSocketFactoryTest.java b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/SslProtocolSocketFactoryTest.java
index 7eb1df4..ba12818 100644
--- a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/SslProtocolSocketFactoryTest.java
+++ b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/SslProtocolSocketFactoryTest.java
@@ -1,53 +1,53 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.tests;
import java.net.InetAddress;
import java.net.Socket;
import junit.framework.TestCase;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.eclipse.mylyn.web.core.SslProtocolSocketFactory;
public class SslProtocolSocketFactoryTest extends TestCase {
public void testTrustAllSslProtocolSocketFactory() throws Exception {
SslProtocolSocketFactory factory = SslProtocolSocketFactory.getInstance();
Socket s;
- s = factory.createSocket("mylar.eclipse.org", 80);
+ s = factory.createSocket("mylyn.eclipse.org", 80);
assertNotNull(s);
assertTrue(s.isConnected());
s.close();
InetAddress anyHost = new Socket().getLocalAddress();
- s = factory.createSocket("mylar.eclipse.org", 80, anyHost, 0);
+ s = factory.createSocket("mylyn.eclipse.org", 80, anyHost, 0);
assertNotNull(s);
assertTrue(s.isConnected());
s.close();
HttpConnectionParams params = new HttpConnectionParams();
- s = factory.createSocket("mylar.eclipse.org", 80, anyHost, 0, params);
+ s = factory.createSocket("mylyn.eclipse.org", 80, anyHost, 0, params);
assertNotNull(s);
assertTrue(s.isConnected());
s.close();
params.setConnectionTimeout(1000);
- s = factory.createSocket("mylar.eclipse.org", 80, anyHost, 0, params);
+ s = factory.createSocket("mylyn.eclipse.org", 80, anyHost, 0, params);
assertNotNull(s);
assertTrue(s.isConnected());
s.close();
}
}
| false | true |
public void testTrustAllSslProtocolSocketFactory() throws Exception {
SslProtocolSocketFactory factory = SslProtocolSocketFactory.getInstance();
Socket s;
s = factory.createSocket("mylar.eclipse.org", 80);
assertNotNull(s);
assertTrue(s.isConnected());
s.close();
InetAddress anyHost = new Socket().getLocalAddress();
s = factory.createSocket("mylar.eclipse.org", 80, anyHost, 0);
assertNotNull(s);
assertTrue(s.isConnected());
s.close();
HttpConnectionParams params = new HttpConnectionParams();
s = factory.createSocket("mylar.eclipse.org", 80, anyHost, 0, params);
assertNotNull(s);
assertTrue(s.isConnected());
s.close();
params.setConnectionTimeout(1000);
s = factory.createSocket("mylar.eclipse.org", 80, anyHost, 0, params);
assertNotNull(s);
assertTrue(s.isConnected());
s.close();
}
|
public void testTrustAllSslProtocolSocketFactory() throws Exception {
SslProtocolSocketFactory factory = SslProtocolSocketFactory.getInstance();
Socket s;
s = factory.createSocket("mylyn.eclipse.org", 80);
assertNotNull(s);
assertTrue(s.isConnected());
s.close();
InetAddress anyHost = new Socket().getLocalAddress();
s = factory.createSocket("mylyn.eclipse.org", 80, anyHost, 0);
assertNotNull(s);
assertTrue(s.isConnected());
s.close();
HttpConnectionParams params = new HttpConnectionParams();
s = factory.createSocket("mylyn.eclipse.org", 80, anyHost, 0, params);
assertNotNull(s);
assertTrue(s.isConnected());
s.close();
params.setConnectionTimeout(1000);
s = factory.createSocket("mylyn.eclipse.org", 80, anyHost, 0, params);
assertNotNull(s);
assertTrue(s.isConnected());
s.close();
}
|
diff --git a/patientview/src/main/java/com/worthsoln/repository/impl/TestResultDaoImpl.java b/patientview/src/main/java/com/worthsoln/repository/impl/TestResultDaoImpl.java
index 9740b3b8..10910c17 100644
--- a/patientview/src/main/java/com/worthsoln/repository/impl/TestResultDaoImpl.java
+++ b/patientview/src/main/java/com/worthsoln/repository/impl/TestResultDaoImpl.java
@@ -1,182 +1,184 @@
package com.worthsoln.repository.impl;
import com.worthsoln.patientview.model.TestResult;
import com.worthsoln.patientview.model.TestResultWithUnitShortname;
import com.worthsoln.patientview.model.Panel;
import com.worthsoln.patientview.model.Unit;
import com.worthsoln.repository.AbstractHibernateDAO;
import com.worthsoln.repository.TestResultDao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.persistence.Query;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
*
*/
@Repository(value = "testResultDao")
public class TestResultDaoImpl extends AbstractHibernateDAO<TestResult> implements TestResultDao {
private JdbcTemplate jdbcTemplate;
@Inject
private DataSource dataSource;
@PostConstruct
public void init() {
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public List<TestResultWithUnitShortname> getTestResultForPatient(String username, Panel panel, List<Unit> units) {
String sql = "SELECT testresult.*, unit.shortname FROM testresult, user, usermapping, result_heading, unit " +
"WHERE user.username = ? " +
"AND user.username = usermapping.username " +
"AND usermapping.nhsno = testresult.nhsno " +
"AND testresult.testcode = result_heading.headingcode " +
+ "AND testresult.unitcode = usermapping.unitcode " +
+ "AND testresult.unitcode = unit.unitcode " +
"AND result_heading.panel = ? ";
List<Object> params = new ArrayList<Object>();
params.add(username);
params.add(panel.getPanel());
if (units != null && !units.isEmpty()) {
sql += " AND unit.unitcode IN (";
int i = 0;
for (Unit unit : units) {
i++;
sql += " ? ";
params.add(unit.getUnitcode());
if (i != units.size()) {
sql += ",";
}
}
sql += ") ";
}
sql += "ORDER BY testresult.datestamp desc";
return jdbcTemplate.query(sql, params.toArray(), new TestResultWithUnitShortnameMapper());
}
@Override
public List<TestResult> get(String nhsno, String unitcode) {
String sql = "SELECT testresult.* FROM testresult WHERE testresult.nhsno = ? AND testresult.unitcode = ? " +
" ORDER BY testcode, datestamp";
List<Object> params = new ArrayList<Object>();
params.add(nhsno);
params.add(unitcode);
return jdbcTemplate.query(sql, params.toArray(), new TestResultMapper());
}
@Override
public String getLatestWeightFromResults(String nhsno, List<String> unitcodes) {
List<Object> params = new ArrayList<Object>();
params.add(nhsno);
params.add("weight");
String sql = "SELECT testresult.* FROM testresult WHERE testresult.nhsno = ? " +
" AND testresult.testcode = ? AND testresult.unitcode IN (";
for (int x = 0; x < unitcodes.size(); x++) {
sql += " ? ";
params.add(unitcodes.get(x));
if (x != unitcodes.size() - 1) {
sql += ",";
}
}
sql += ") ORDER BY datestamp DESC";
List<TestResult> testResult = jdbcTemplate.query(sql, params.toArray(), new TestResultMapper());
if (testResult != null && !testResult.isEmpty()) {
return testResult.get(0).getValue();
}
return null;
}
private class TestResultMapper implements RowMapper<TestResult> {
@Override
public TestResult mapRow(ResultSet resultSet, int i) throws SQLException {
TestResult testResult = new TestResult();
testResult.setId(resultSet.getLong("id"));
testResult.setDatestamp(resultSet.getTimestamp("datestamp"));
testResult.setNhsno(resultSet.getString("nhsno"));
testResult.setPrepost(resultSet.getString("prepost"));
testResult.setTestcode(resultSet.getString("testcode"));
testResult.setUnitcode(resultSet.getString("unitcode"));
testResult.setValue(resultSet.getString("value"));
return testResult;
}
}
private class TestResultWithUnitShortnameMapper implements RowMapper<TestResultWithUnitShortname> {
@Override
public TestResultWithUnitShortname mapRow(ResultSet resultSet, int i) throws SQLException {
TestResultWithUnitShortname testResultWithUnitShortname = new TestResultWithUnitShortname();
testResultWithUnitShortname.setId(resultSet.getLong("id"));
testResultWithUnitShortname.setShortname(resultSet.getString("shortname"));
testResultWithUnitShortname.setDatestamp(resultSet.getTimestamp("datestamp"));
testResultWithUnitShortname.setNhsno(resultSet.getString("nhsno"));
testResultWithUnitShortname.setPrepost(resultSet.getString("prepost"));
testResultWithUnitShortname.setTestcode(resultSet.getString("testcode"));
testResultWithUnitShortname.setUnitcode(resultSet.getString("unitcode"));
testResultWithUnitShortname.setValue(resultSet.getString("value"));
return testResultWithUnitShortname;
}
}
@Override
public void deleteTestResultsWithinTimeRange(String nhsno, String unitcode, String testcode, Date startDate,
Date endDate) {
Query query = getEntityManager().createQuery("DELETE FROM testresult WHERE nhsno = :nhsno AND unitcode = " +
":unitcode AND testcode = :testcode AND datestamp > :startDate AND datestamp < :endDate");
query.setParameter("nhsno", nhsno);
query.setParameter("unitcode", unitcode);
query.setParameter("testcode", testcode);
query.setParameter("startDate", new Timestamp(startDate.getTime()));
query.setParameter("endDate", new Timestamp(endDate.getTime()));
query.executeUpdate();
}
@Override
public void deleteTestResults(String nhsno, String unitcode) {
Query query = getEntityManager().createQuery("DELETE FROM testresult WHERE nhsno = :nhsno AND unitcode = " +
":unitcode");
query.setParameter("nhsno", nhsno);
query.setParameter("unitcode", unitcode);
query.executeUpdate();
}
}
| true | true |
public List<TestResultWithUnitShortname> getTestResultForPatient(String username, Panel panel, List<Unit> units) {
String sql = "SELECT testresult.*, unit.shortname FROM testresult, user, usermapping, result_heading, unit " +
"WHERE user.username = ? " +
"AND user.username = usermapping.username " +
"AND usermapping.nhsno = testresult.nhsno " +
"AND testresult.testcode = result_heading.headingcode " +
"AND result_heading.panel = ? ";
List<Object> params = new ArrayList<Object>();
params.add(username);
params.add(panel.getPanel());
if (units != null && !units.isEmpty()) {
sql += " AND unit.unitcode IN (";
int i = 0;
for (Unit unit : units) {
i++;
sql += " ? ";
params.add(unit.getUnitcode());
if (i != units.size()) {
sql += ",";
}
}
sql += ") ";
}
sql += "ORDER BY testresult.datestamp desc";
return jdbcTemplate.query(sql, params.toArray(), new TestResultWithUnitShortnameMapper());
}
|
public List<TestResultWithUnitShortname> getTestResultForPatient(String username, Panel panel, List<Unit> units) {
String sql = "SELECT testresult.*, unit.shortname FROM testresult, user, usermapping, result_heading, unit " +
"WHERE user.username = ? " +
"AND user.username = usermapping.username " +
"AND usermapping.nhsno = testresult.nhsno " +
"AND testresult.testcode = result_heading.headingcode " +
"AND testresult.unitcode = usermapping.unitcode " +
"AND testresult.unitcode = unit.unitcode " +
"AND result_heading.panel = ? ";
List<Object> params = new ArrayList<Object>();
params.add(username);
params.add(panel.getPanel());
if (units != null && !units.isEmpty()) {
sql += " AND unit.unitcode IN (";
int i = 0;
for (Unit unit : units) {
i++;
sql += " ? ";
params.add(unit.getUnitcode());
if (i != units.size()) {
sql += ",";
}
}
sql += ") ";
}
sql += "ORDER BY testresult.datestamp desc";
return jdbcTemplate.query(sql, params.toArray(), new TestResultWithUnitShortnameMapper());
}
|
diff --git a/org.whole.test/test/org/whole/lang/templates/ResourceTemplateTest.java b/org.whole.test/test/org/whole/lang/templates/ResourceTemplateTest.java
index 737289e00..654f20832 100755
--- a/org.whole.test/test/org/whole/lang/templates/ResourceTemplateTest.java
+++ b/org.whole.test/test/org/whole/lang/templates/ResourceTemplateTest.java
@@ -1,182 +1,182 @@
/**
* Copyright 2004-2012 Riccardo Solmi. All rights reserved.
* This file is part of the Whole Platform.
*
* The Whole Platform is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The Whole Platform is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the Whole Platform. If not, see <http://www.gnu.org/licenses/>.
*/
package org.whole.lang.templates;
import java.io.File;
import java.io.IOException;
import java.util.Comparator;
import java.util.HashMap;
import junit.framework.TestCase;
import org.whole.lang.artifacts.builders.IArtifactsBuilder;
import org.whole.lang.artifacts.model.AttributeEnum;
import org.whole.lang.artifacts.model.FolderArtifact;
import org.whole.lang.artifacts.reflect.ArtifactsEntityDescriptorEnum;
import org.whole.lang.artifacts.reflect.ArtifactsFeatureDescriptorEnum;
import org.whole.lang.artifacts.reflect.ArtifactsLanguageKit;
import org.whole.lang.artifacts.templates.ResourceTemplate;
import org.whole.lang.builders.ModelBuilderOperation;
import org.whole.lang.commons.builders.ICommonsBuilder;
import org.whole.lang.commons.reflect.CommonsLanguageKit;
import org.whole.lang.iterators.IEntityIterator;
import org.whole.lang.iterators.IteratorFactory;
import org.whole.lang.matchers.Matcher;
import org.whole.lang.model.IEntity;
import org.whole.lang.rdb.codebase.OrderedMatcher;
import org.whole.lang.reflect.EntityDescriptor;
import org.whole.lang.reflect.ReflectionFactory;
/**
* @author Enrico Persiani
*/
public class ResourceTemplateTest extends TestCase {
private HashMap<EntityDescriptor<?>, Comparator<IEntity>> comparatorsMap = new HashMap<EntityDescriptor<?>, Comparator<IEntity>>();
public ResourceTemplateTest() {
comparatorsMap.put(ArtifactsEntityDescriptorEnum.Artifacts, new OrderedMatcher.SimpleFeatureComparator(ArtifactsFeatureDescriptorEnum.name));
}
protected void setUp() throws Exception {
super.setUp();
ReflectionFactory.deployWholePlatform();
new File("data/testfolder/empty.folder").mkdir();
}
public void testReadArtifacts() {
File testfolder = new File("data/testfolder");
ResourceTemplate template = new ResourceTemplate(testfolder);
ModelBuilderOperation op = new ModelBuilderOperation();
template.apply(op);
IEntity artifacts = getFilesystemPattern();
IEntity artifactsFromFilesystem = op.wGetResult();
assertTrue(OrderedMatcher.match(artifacts, artifactsFromFilesystem, comparatorsMap));
}
public void testSubtreeArtifacts() {
File testfolder = new File("data/testfolder");
File testsubfolder = new File("data/testfolder/subfolder");
ResourceTemplate template = new ResourceTemplate(testfolder);
ModelBuilderOperation op = new ModelBuilderOperation();
template.apply(op);
IEntity testFolder = op.wGetResult();
template = new ResourceTemplate(testsubfolder);
op = new ModelBuilderOperation();
template.apply(op);
IEntity testSubFolder = op.wGetResult();
FolderArtifact compareTo = null;
IEntityIterator<FolderArtifact> iterator = IteratorFactory.<FolderArtifact>childMatcherIterator()
.withPattern(ArtifactsEntityDescriptorEnum.FolderArtifact);
iterator.reset(testFolder.wGet(ArtifactsFeatureDescriptorEnum.artifacts));
while (iterator.hasNext()) {
FolderArtifact folder = iterator.next();
if (folder.getName().wEquals(testSubFolder.wGet(ArtifactsFeatureDescriptorEnum.name))) {
compareTo = folder;
break;
}
}
assertNotNull(compareTo);
assertTrue(OrderedMatcher.match(testSubFolder, compareTo, comparatorsMap));
}
public void testReadOnlyArtifact() throws IOException {
IEntity readOnlyMetadata = getMetadataPattern();
File tempFile = File.createTempFile("whole", null);
tempFile.deleteOnExit();
ResourceTemplate template = new ResourceTemplate(tempFile);
ModelBuilderOperation op = new ModelBuilderOperation();
template.apply(op);
IEntity readWriteArtifact = op.wGetResult();
assertFalse(Matcher.match(readOnlyMetadata, readWriteArtifact));
tempFile.setReadOnly();
template = new ResourceTemplate(tempFile);
op = new ModelBuilderOperation();
template.apply(op);
IEntity readOnlyArtifact = op.wGetResult();
assertFalse(Matcher.match(readOnlyMetadata, readOnlyArtifact));
}
private IEntity getMetadataPattern() {
ModelBuilderOperation op = new ModelBuilderOperation();
IArtifactsBuilder ab = (IArtifactsBuilder) op.wGetBuilder(ArtifactsLanguageKit.URI);
ICommonsBuilder cb = (ICommonsBuilder) op.wGetBuilder(CommonsLanguageKit.URI);
ab.Metadata_();
cb.Resolver();
cb.Resolver();
cb.Resolver();
ab.Attributes_(1);
ab.Attribute(AttributeEnum.readonly);
ab._Attributes();
cb.Resolver();
ab._Metadata();
return op.wGetResult();
}
private IEntity getFilesystemPattern() {
ModelBuilderOperation op = new ModelBuilderOperation();
IArtifactsBuilder ab = (IArtifactsBuilder) op.wGetBuilder(ArtifactsLanguageKit.URI);
ICommonsBuilder cb = (ICommonsBuilder) op.wGetBuilder(CommonsLanguageKit.URI);
ab.FolderArtifact_();
ab.Name("testfolder");
cb.Resolver();
ab.Artifacts_(3);
-// ab.FolderArtifact_();
-// ab.Name("empty.folder");
-// cb.Resolver();
-// ab.Artifacts();
-// ab._FolderArtifact();
+ ab.FolderArtifact_();
+ ab.Name("empty.folder");
+ cb.Resolver();
+ ab.Artifacts();
+ ab._FolderArtifact();
ab.FolderArtifact_();
ab.Name("subfolder");
cb.Resolver();
ab.Artifacts_(1);
ab.FileArtifact_();
ab.NameWithExtension_();
ab.Name("test");
ab.Extension("txt");
ab._NameWithExtension();
cb.Resolver();
cb.Resolver();
ab._FileArtifact();
ab._Artifacts();
ab._FolderArtifact();
ab.FileArtifact_();
ab.NameWithExtension_();
ab.Name("test.extensions");
ab.Extension("txt");
ab._NameWithExtension();
cb.Resolver();
cb.Resolver();
ab._FileArtifact();
ab.FileArtifact_();
ab.Name("withoutext");
cb.Resolver();
cb.Resolver();
ab._FileArtifact();
return op.wGetResult();
}
}
| true | true |
private IEntity getFilesystemPattern() {
ModelBuilderOperation op = new ModelBuilderOperation();
IArtifactsBuilder ab = (IArtifactsBuilder) op.wGetBuilder(ArtifactsLanguageKit.URI);
ICommonsBuilder cb = (ICommonsBuilder) op.wGetBuilder(CommonsLanguageKit.URI);
ab.FolderArtifact_();
ab.Name("testfolder");
cb.Resolver();
ab.Artifacts_(3);
// ab.FolderArtifact_();
// ab.Name("empty.folder");
// cb.Resolver();
// ab.Artifacts();
// ab._FolderArtifact();
ab.FolderArtifact_();
ab.Name("subfolder");
cb.Resolver();
ab.Artifacts_(1);
ab.FileArtifact_();
ab.NameWithExtension_();
ab.Name("test");
ab.Extension("txt");
ab._NameWithExtension();
cb.Resolver();
cb.Resolver();
ab._FileArtifact();
ab._Artifacts();
ab._FolderArtifact();
ab.FileArtifact_();
ab.NameWithExtension_();
ab.Name("test.extensions");
ab.Extension("txt");
ab._NameWithExtension();
cb.Resolver();
cb.Resolver();
ab._FileArtifact();
ab.FileArtifact_();
ab.Name("withoutext");
cb.Resolver();
cb.Resolver();
ab._FileArtifact();
return op.wGetResult();
}
|
private IEntity getFilesystemPattern() {
ModelBuilderOperation op = new ModelBuilderOperation();
IArtifactsBuilder ab = (IArtifactsBuilder) op.wGetBuilder(ArtifactsLanguageKit.URI);
ICommonsBuilder cb = (ICommonsBuilder) op.wGetBuilder(CommonsLanguageKit.URI);
ab.FolderArtifact_();
ab.Name("testfolder");
cb.Resolver();
ab.Artifacts_(3);
ab.FolderArtifact_();
ab.Name("empty.folder");
cb.Resolver();
ab.Artifacts();
ab._FolderArtifact();
ab.FolderArtifact_();
ab.Name("subfolder");
cb.Resolver();
ab.Artifacts_(1);
ab.FileArtifact_();
ab.NameWithExtension_();
ab.Name("test");
ab.Extension("txt");
ab._NameWithExtension();
cb.Resolver();
cb.Resolver();
ab._FileArtifact();
ab._Artifacts();
ab._FolderArtifact();
ab.FileArtifact_();
ab.NameWithExtension_();
ab.Name("test.extensions");
ab.Extension("txt");
ab._NameWithExtension();
cb.Resolver();
cb.Resolver();
ab._FileArtifact();
ab.FileArtifact_();
ab.Name("withoutext");
cb.Resolver();
cb.Resolver();
ab._FileArtifact();
return op.wGetResult();
}
|
diff --git a/bobik.jar/src/bobik/BobikHelper.java b/bobik.jar/src/bobik/BobikHelper.java
index 3df20d9..c68417d 100644
--- a/bobik.jar/src/bobik/BobikHelper.java
+++ b/bobik.jar/src/bobik/BobikHelper.java
@@ -1,50 +1,65 @@
package bobik;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* A collection of recurring and useful utility functions
* @author Eugene Mirkin
*/
public class BobikHelper {
/**
* Takes a hash of parallel arrays
* and turns it into a list of hashes, each having all keys from the original hash.
* <br><br>
* <b>Example:</b>
* <pre>
* {@code
* {'title':['A', 'B', 'C'], 'price':[4,2,5]}
* becomes
[{'price':4, 'title':'A'} , {'price':2, 'title':'B'}, {'price':5, 'title':'C'}]
* }
* @param x a hash of parallel arrays
* @throws ArrayIndexOutOfBoundsException if arrays are not of equal length
* @throws JSONException if the incoming object is not of the expected format
* @return a transposed array
*/
public static List<JSONObject> transpose(JSONObject x) throws ArrayIndexOutOfBoundsException, JSONException {
List<JSONObject> results = null;
+ // First pass is for initializing variables
+ int max_len = 0;
for (Iterator i=x.keys(); i.hasNext(); ) {
String key = (String)i.next();
JSONArray values = x.getJSONArray(key);
- // Fill array with empty container objects if this is the first pass
- if (results == null) {
- results = new ArrayList<JSONObject>(values.length());
- for (int z=0; z<values.length(); z++)
- results.add(new JSONObject());
+ if (values.length() > max_len)
+ max_len = values.length();
+ }
+ // Fill array with empty container objects
+ if (results == null) {
+ results = new ArrayList<JSONObject>(max_len);
+ for (int z=0; z<max_len; z++)
+ results.add(new JSONObject());
+ }
+ // Now, populate the array with real results, inserting null when no data is available upon transposition
+ for (Iterator i=x.keys(); i.hasNext(); ) {
+ String key = (String)i.next();
+ JSONArray values = x.getJSONArray(key);
+ for (int z=0; z<values.length(); z++) {
+ Object val = null;
+ try {
+ val = values.get(z);
+ } catch (JSONException e) {
+ }
+ results.get(z).put(key, val);
}
- for (int z=0; z<values.length(); z++)
- results.get(z).put(key, values.get(z));
}
return results;
}
}
| false | true |
public static List<JSONObject> transpose(JSONObject x) throws ArrayIndexOutOfBoundsException, JSONException {
List<JSONObject> results = null;
for (Iterator i=x.keys(); i.hasNext(); ) {
String key = (String)i.next();
JSONArray values = x.getJSONArray(key);
// Fill array with empty container objects if this is the first pass
if (results == null) {
results = new ArrayList<JSONObject>(values.length());
for (int z=0; z<values.length(); z++)
results.add(new JSONObject());
}
for (int z=0; z<values.length(); z++)
results.get(z).put(key, values.get(z));
}
return results;
}
|
public static List<JSONObject> transpose(JSONObject x) throws ArrayIndexOutOfBoundsException, JSONException {
List<JSONObject> results = null;
// First pass is for initializing variables
int max_len = 0;
for (Iterator i=x.keys(); i.hasNext(); ) {
String key = (String)i.next();
JSONArray values = x.getJSONArray(key);
if (values.length() > max_len)
max_len = values.length();
}
// Fill array with empty container objects
if (results == null) {
results = new ArrayList<JSONObject>(max_len);
for (int z=0; z<max_len; z++)
results.add(new JSONObject());
}
// Now, populate the array with real results, inserting null when no data is available upon transposition
for (Iterator i=x.keys(); i.hasNext(); ) {
String key = (String)i.next();
JSONArray values = x.getJSONArray(key);
for (int z=0; z<values.length(); z++) {
Object val = null;
try {
val = values.get(z);
} catch (JSONException e) {
}
results.get(z).put(key, val);
}
}
return results;
}
|
diff --git a/src/main/java/org/spoutcraft/launcher/skin/MetroLoginFrame.java b/src/main/java/org/spoutcraft/launcher/skin/MetroLoginFrame.java
index 08f48da..33e1451 100644
--- a/src/main/java/org/spoutcraft/launcher/skin/MetroLoginFrame.java
+++ b/src/main/java/org/spoutcraft/launcher/skin/MetroLoginFrame.java
@@ -1,430 +1,430 @@
/*
* This file is part of Spoutcraft.
*
* Copyright (c) 2011-2012, Spout LLC <http://www.spout.org/>
* Spoutcraft is licensed under the Spout License Version 1.
*
* Spoutcraft 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.
*
* Spoutcraft 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://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spoutcraft.launcher.skin;
import static org.spoutcraft.launcher.util.ResourceUtils.getResourceAsStream;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;
import org.spoutcraft.launcher.skin.components.BackgroundImage;
import org.spoutcraft.launcher.skin.components.DynamicButton;
import org.spoutcraft.launcher.skin.components.HyperlinkJLabel;
import org.spoutcraft.launcher.skin.components.ImageHyperlinkButton;
import org.spoutcraft.launcher.skin.components.LiteButton;
import org.spoutcraft.launcher.skin.components.LitePasswordBox;
import org.spoutcraft.launcher.skin.components.LiteProgressBar;
import org.spoutcraft.launcher.skin.components.LiteTextBox;
import org.spoutcraft.launcher.skin.components.LoginFrame;
import org.spoutcraft.launcher.skin.components.TransparentButton;
import org.spoutcraft.launcher.util.ImageUtils;
import org.spoutcraft.launcher.util.OperatingSystem;
import org.spoutcraft.launcher.util.ResourceUtils;
public class MetroLoginFrame extends LoginFrame implements ActionListener, KeyListener{
private static final long serialVersionUID = 1L;
private static final URL gearIcon = LoginFrame.class.getResource("/org/spoutcraft/launcher/resources/gear.png");
private static final int FRAME_WIDTH = 880;
private static final int FRAME_HEIGHT = 520;
private static final String OPTIONS_ACTION = "options";
private static final String LOGIN_ACTION = "login";
private static final String IMAGE_LOGIN_ACTION = "image_login";
private static final String REMOVE_USER = "remove";
private final Map<JButton, DynamicButton> removeButtons = new HashMap<JButton, DynamicButton>();
private LiteTextBox name;
private LitePasswordBox pass;
private LiteButton login;
private JCheckBox remember;
private TransparentButton options;
private LiteProgressBar progressBar;
private OptionsMenu optionsMenu = null;
public MetroLoginFrame() {
initComponents();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((dim.width - FRAME_WIDTH) / 2, (dim.height - FRAME_HEIGHT) / 2, FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
getContentPane().add(new BackgroundImage(FRAME_WIDTH, FRAME_HEIGHT));
}
private void initComponents() {
Font minecraft = getMinecraftFont(12);
int xShift = 0;
int yShift = 0;
if (this.isUndecorated()) {
yShift += 30;
}
// Setup username box
name = new LiteTextBox(this, "Username...");
name.setBounds(622 + xShift, 426 + yShift, 140, 24);
name.setFont(minecraft);
name.addKeyListener(this);
// Setup password box
pass = new LitePasswordBox(this, "Password...");
pass.setBounds(622 + xShift, 455 + yShift, 140, 24);
pass.setFont(minecraft);
pass.addKeyListener(this);
// Setup remember checkbox
remember = new JCheckBox("Remember");
remember.setBounds(775 + xShift, 455 + yShift, 110, 24);
remember.setFont(minecraft);
remember.setOpaque(false);
remember.setBorderPainted(false);
remember.setContentAreaFilled(false);
remember.setBorder(null);
remember.setForeground(Color.WHITE);
remember.addKeyListener(this);
// Setup login button
login = new LiteButton("Login");
login.setBounds(775 + xShift, 426 + yShift, 92, 24);
login.setFont(minecraft);
login.setActionCommand(LOGIN_ACTION);
login.addActionListener(this);
login.addKeyListener(this);
// Spoutcraft logo
JLabel logo = new JLabel();
logo.setBounds(8, 15, 400, 109);
- setIcon(logo, "spoutcraft.png", logo.getWidth(), logo.getHeight());
+ setIcon(logo, "techniclauncher.png", logo.getWidth(), logo.getHeight());
// Progress Bar
progressBar = new LiteProgressBar();
progressBar.setBounds(8, 130, 395, 23);
progressBar.setVisible(false);
progressBar.setStringPainted(true);
progressBar.setOpaque(true);
progressBar.setTransparency(0.70F);
progressBar.setHoverTransparency(0.70F);
progressBar.setFont(minecraft);
// Home Link
Font largerMinecraft;
if (OperatingSystem.getOS().isUnix()) {
largerMinecraft = minecraft.deriveFont((float)18);
} else {
largerMinecraft = minecraft.deriveFont((float)20);
}
- HyperlinkJLabel home = new HyperlinkJLabel("Home", "http://www.spout.org/");
+ HyperlinkJLabel home = new HyperlinkJLabel("Home", "http://www.technicpack.net");
home.setFont(largerMinecraft);
home.setBounds(545, 35, 65, 20);
home.setForeground(Color.WHITE);
home.setOpaque(false);
home.setTransparency(0.70F);
home.setHoverTransparency(1F);
// Forums link
- HyperlinkJLabel forums = new HyperlinkJLabel("Forums", "http://forums.spout.org/");
+ HyperlinkJLabel forums = new HyperlinkJLabel("Forums", "http://forums.technicpack.net/");
forums.setFont(largerMinecraft);
forums.setBounds(625, 35, 90, 20);
forums.setForeground(Color.WHITE);
forums.setOpaque(false);
forums.setTransparency(0.70F);
forums.setHoverTransparency(1F);
// Issues link
- HyperlinkJLabel issues = new HyperlinkJLabel("Issues", "http://spout.in/issues");
+ HyperlinkJLabel issues = new HyperlinkJLabel("Issues", "http://forums.technicpack.net/forums/bug-reports.81/");
issues.setFont(largerMinecraft);
issues.setBounds(733, 35, 85, 20);
issues.setForeground(Color.WHITE);
issues.setOpaque(false);
issues.setTransparency(0.70F);
issues.setHoverTransparency(1F);
// Options Button
options = new TransparentButton();
options.setIcon(new ImageIcon(Toolkit.getDefaultToolkit().getImage(gearIcon)));
options.setBounds(828, 28, 30, 30);
options.setTransparency(0.70F);
options.setHoverTransparency(1F);
options.setActionCommand(OPTIONS_ACTION);
options.addActionListener(this);
// Steam button
JButton steam = new ImageHyperlinkButton("http://spout.in/steam");
steam.setToolTipText("Game with us on Steam");
steam.setBounds(6, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(steam, "steam.png", 28);
// Twitter button
JButton twitter = new ImageHyperlinkButton("http://spout.in/twitter");
twitter.setToolTipText("Follow us on Twitter");
twitter.setBounds(6 + 34 * 4 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(twitter, "twitter.png", 28);
// Facebook button
JButton facebook = new ImageHyperlinkButton("http://spout.in/facebook");
facebook.setToolTipText("Like us on Facebook");
facebook.setBounds(6 + 34 * 3 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(facebook, "facebook.png", 28);
// Google+ button
JButton gplus = new ImageHyperlinkButton("http://spout.in/gplus");
gplus.setToolTipText("Follow us on Google+");
gplus.setBounds(6 + 34 * 2 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(gplus, "gplus.png", 28);
// YouTube button
JButton youtube = new ImageHyperlinkButton("http://spout.in/youtube");
youtube.setToolTipText("Subscribe to our videos");
youtube.setBounds(6 + 34 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(youtube, "youtube.png", 28);
Container contentPane = getContentPane();
contentPane.setLayout(null);
java.util.List<String> savedUsers = getSavedUsernames();
int users = Math.min(5, this.getSavedUsernames().size());
for (int i = 0; i < users; i++) {
String accountName = savedUsers.get(i);
String userName = this.getUsername(accountName);
DynamicButton userButton = new DynamicButton(this, getImage(userName), 44, accountName, userName);
userButton.setFont(minecraft.deriveFont(14F));
userButton.setBounds((FRAME_WIDTH - 75) * (i + 1) / (users + 1), (FRAME_HEIGHT - 75) / 2 , 75, 75);
contentPane.add(userButton);
userButton.setActionCommand(IMAGE_LOGIN_ACTION);
userButton.addActionListener(this);
setIcon(userButton.getRemoveIcon(), "remove.png", 16);
userButton.getRemoveIcon().addActionListener(this);
userButton.getRemoveIcon().setActionCommand(REMOVE_USER);
removeButtons.put(userButton.getRemoveIcon(), userButton);
}
contentPane.add(name);
contentPane.add(pass);
contentPane.add(remember);
contentPane.add(login);
contentPane.add(steam);
contentPane.add(twitter);
contentPane.add(facebook);
contentPane.add(gplus);
contentPane.add(youtube);
contentPane.add(home);
contentPane.add(forums);
contentPane.add(issues);
contentPane.add(logo);
contentPane.add(options);
contentPane.add(progressBar);
setFocusTraversalPolicy(new LoginFocusTraversalPolicy());
}
private void setIcon(JButton button, String iconName, int size) {
try {
button.setIcon(new ImageIcon(ImageUtils.scaleImage(ImageIO.read(ResourceUtils.getResourceAsStream("/org/spoutcraft/launcher/resources/" + iconName)), size, size)));
} catch (IOException e) {
e.printStackTrace();
}
}
private void setIcon(JLabel label, String iconName, int w, int h) {
try {
label.setIcon(new ImageIcon(ImageUtils.scaleImage(ImageIO.read(ResourceUtils.getResourceAsStream("/org/spoutcraft/launcher/resources/" + iconName)), w, h)));
} catch (IOException e) {
e.printStackTrace();
}
}
private BufferedImage getImage(String user){
try {
URLConnection conn = (new URL("https://minotar.net/helm/" + user + "/100")).openConnection();
InputStream stream = conn.getInputStream();
BufferedImage image = ImageIO.read(stream);
if (image != null) {
return image;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
return ImageIO.read(getResourceAsStream("/org/spoutcraft/launcher/resources/face.png"));
} catch (IOException e1) {
throw new RuntimeException("Error reading backup image", e1);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JComponent) {
action(e.getActionCommand(), (JComponent)e.getSource());
}
}
private void action(String action, JComponent c) {
if (action.equals(OPTIONS_ACTION)) {
if (optionsMenu == null || !optionsMenu.isVisible()) {
optionsMenu = new OptionsMenu();
optionsMenu.setModal(true);
optionsMenu.setVisible(true);
}
} else if (action.equals(LOGIN_ACTION)) {
String pass = new String(this.pass.getPassword());
if (getSelectedUser().length() > 0 && pass.length() > 0) {
this.doLogin(getSelectedUser(), pass);
if (remember.isSelected()) {
saveUsername(getSelectedUser(), pass);
}
}
} else if (action.equals(IMAGE_LOGIN_ACTION)) {
DynamicButton userButton = (DynamicButton)c;
this.name.setText(userButton.getAccount());
this.pass.setText(this.getSavedPassword(userButton.getAccount()));
this.remember.setSelected(true);
action(LOGIN_ACTION, userButton);
} else if (action.equals(REMOVE_USER)) {
DynamicButton userButton = removeButtons.get((JButton)c);
this.removeAccount(userButton.getAccount());
userButton.setVisible(false);
userButton.setEnabled(false);
getContentPane().remove(userButton);
c.setVisible(false);
c.setEnabled(false);
getContentPane().remove(c);
removeButtons.remove(c);
writeUsernameList();
}
}
@Override
public void stateChanged(final String status, final float progress) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
int intProgress = Math.round(progress);
progressBar.setValue(intProgress);
String text = status;
if (text.length() > 60) {
text = text.substring(0, 60) + "...";
}
progressBar.setString(intProgress + "% " + text);
}
});
}
@Override
public JProgressBar getProgressBar() {
return progressBar;
}
@Override
public void disableForm() {
}
@Override
public void enableForm() {
}
@Override
public String getSelectedUser() {
return this.name.getText();
}
// Emulates tab focus policy of name -> pass -> remember -> login
private class LoginFocusTraversalPolicy extends FocusTraversalPolicy{
@Override
public Component getComponentAfter(Container con, Component c) {
if (c == name) {
return pass;
} else if (c == pass) {
return remember;
} else if (c == remember) {
return login;
} else if (c == login) {
return name;
}
return getFirstComponent(con);
}
@Override
public Component getComponentBefore(Container con, Component c) {
if (c == name) {
return login;
} else if (c == pass) {
return name;
} else if (c == remember) {
return pass;
} else if (c == login) {
return remember;
}
return getFirstComponent(con);
}
@Override
public Component getFirstComponent(Container c) {
return name;
}
@Override
public Component getLastComponent(Container c) {
return login;
}
@Override
public Component getDefaultComponent(Container c) {
return name;
}
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER){
// Allows the user to press enter and log in from the login box focus, username box focus, or password box focus
if (e.getComponent() == login || e.getComponent() == name || e.getComponent() == pass) {
action(LOGIN_ACTION, (JComponent) e.getComponent());
} else if (e.getComponent() == remember) {
remember.setSelected(!remember.isSelected());
}
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
| false | true |
private void initComponents() {
Font minecraft = getMinecraftFont(12);
int xShift = 0;
int yShift = 0;
if (this.isUndecorated()) {
yShift += 30;
}
// Setup username box
name = new LiteTextBox(this, "Username...");
name.setBounds(622 + xShift, 426 + yShift, 140, 24);
name.setFont(minecraft);
name.addKeyListener(this);
// Setup password box
pass = new LitePasswordBox(this, "Password...");
pass.setBounds(622 + xShift, 455 + yShift, 140, 24);
pass.setFont(minecraft);
pass.addKeyListener(this);
// Setup remember checkbox
remember = new JCheckBox("Remember");
remember.setBounds(775 + xShift, 455 + yShift, 110, 24);
remember.setFont(minecraft);
remember.setOpaque(false);
remember.setBorderPainted(false);
remember.setContentAreaFilled(false);
remember.setBorder(null);
remember.setForeground(Color.WHITE);
remember.addKeyListener(this);
// Setup login button
login = new LiteButton("Login");
login.setBounds(775 + xShift, 426 + yShift, 92, 24);
login.setFont(minecraft);
login.setActionCommand(LOGIN_ACTION);
login.addActionListener(this);
login.addKeyListener(this);
// Spoutcraft logo
JLabel logo = new JLabel();
logo.setBounds(8, 15, 400, 109);
setIcon(logo, "spoutcraft.png", logo.getWidth(), logo.getHeight());
// Progress Bar
progressBar = new LiteProgressBar();
progressBar.setBounds(8, 130, 395, 23);
progressBar.setVisible(false);
progressBar.setStringPainted(true);
progressBar.setOpaque(true);
progressBar.setTransparency(0.70F);
progressBar.setHoverTransparency(0.70F);
progressBar.setFont(minecraft);
// Home Link
Font largerMinecraft;
if (OperatingSystem.getOS().isUnix()) {
largerMinecraft = minecraft.deriveFont((float)18);
} else {
largerMinecraft = minecraft.deriveFont((float)20);
}
HyperlinkJLabel home = new HyperlinkJLabel("Home", "http://www.spout.org/");
home.setFont(largerMinecraft);
home.setBounds(545, 35, 65, 20);
home.setForeground(Color.WHITE);
home.setOpaque(false);
home.setTransparency(0.70F);
home.setHoverTransparency(1F);
// Forums link
HyperlinkJLabel forums = new HyperlinkJLabel("Forums", "http://forums.spout.org/");
forums.setFont(largerMinecraft);
forums.setBounds(625, 35, 90, 20);
forums.setForeground(Color.WHITE);
forums.setOpaque(false);
forums.setTransparency(0.70F);
forums.setHoverTransparency(1F);
// Issues link
HyperlinkJLabel issues = new HyperlinkJLabel("Issues", "http://spout.in/issues");
issues.setFont(largerMinecraft);
issues.setBounds(733, 35, 85, 20);
issues.setForeground(Color.WHITE);
issues.setOpaque(false);
issues.setTransparency(0.70F);
issues.setHoverTransparency(1F);
// Options Button
options = new TransparentButton();
options.setIcon(new ImageIcon(Toolkit.getDefaultToolkit().getImage(gearIcon)));
options.setBounds(828, 28, 30, 30);
options.setTransparency(0.70F);
options.setHoverTransparency(1F);
options.setActionCommand(OPTIONS_ACTION);
options.addActionListener(this);
// Steam button
JButton steam = new ImageHyperlinkButton("http://spout.in/steam");
steam.setToolTipText("Game with us on Steam");
steam.setBounds(6, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(steam, "steam.png", 28);
// Twitter button
JButton twitter = new ImageHyperlinkButton("http://spout.in/twitter");
twitter.setToolTipText("Follow us on Twitter");
twitter.setBounds(6 + 34 * 4 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(twitter, "twitter.png", 28);
// Facebook button
JButton facebook = new ImageHyperlinkButton("http://spout.in/facebook");
facebook.setToolTipText("Like us on Facebook");
facebook.setBounds(6 + 34 * 3 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(facebook, "facebook.png", 28);
// Google+ button
JButton gplus = new ImageHyperlinkButton("http://spout.in/gplus");
gplus.setToolTipText("Follow us on Google+");
gplus.setBounds(6 + 34 * 2 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(gplus, "gplus.png", 28);
// YouTube button
JButton youtube = new ImageHyperlinkButton("http://spout.in/youtube");
youtube.setToolTipText("Subscribe to our videos");
youtube.setBounds(6 + 34 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(youtube, "youtube.png", 28);
Container contentPane = getContentPane();
contentPane.setLayout(null);
java.util.List<String> savedUsers = getSavedUsernames();
int users = Math.min(5, this.getSavedUsernames().size());
for (int i = 0; i < users; i++) {
String accountName = savedUsers.get(i);
String userName = this.getUsername(accountName);
DynamicButton userButton = new DynamicButton(this, getImage(userName), 44, accountName, userName);
userButton.setFont(minecraft.deriveFont(14F));
userButton.setBounds((FRAME_WIDTH - 75) * (i + 1) / (users + 1), (FRAME_HEIGHT - 75) / 2 , 75, 75);
contentPane.add(userButton);
userButton.setActionCommand(IMAGE_LOGIN_ACTION);
userButton.addActionListener(this);
setIcon(userButton.getRemoveIcon(), "remove.png", 16);
userButton.getRemoveIcon().addActionListener(this);
userButton.getRemoveIcon().setActionCommand(REMOVE_USER);
removeButtons.put(userButton.getRemoveIcon(), userButton);
}
contentPane.add(name);
contentPane.add(pass);
contentPane.add(remember);
contentPane.add(login);
contentPane.add(steam);
contentPane.add(twitter);
contentPane.add(facebook);
contentPane.add(gplus);
contentPane.add(youtube);
contentPane.add(home);
contentPane.add(forums);
contentPane.add(issues);
contentPane.add(logo);
contentPane.add(options);
contentPane.add(progressBar);
setFocusTraversalPolicy(new LoginFocusTraversalPolicy());
}
|
private void initComponents() {
Font minecraft = getMinecraftFont(12);
int xShift = 0;
int yShift = 0;
if (this.isUndecorated()) {
yShift += 30;
}
// Setup username box
name = new LiteTextBox(this, "Username...");
name.setBounds(622 + xShift, 426 + yShift, 140, 24);
name.setFont(minecraft);
name.addKeyListener(this);
// Setup password box
pass = new LitePasswordBox(this, "Password...");
pass.setBounds(622 + xShift, 455 + yShift, 140, 24);
pass.setFont(minecraft);
pass.addKeyListener(this);
// Setup remember checkbox
remember = new JCheckBox("Remember");
remember.setBounds(775 + xShift, 455 + yShift, 110, 24);
remember.setFont(minecraft);
remember.setOpaque(false);
remember.setBorderPainted(false);
remember.setContentAreaFilled(false);
remember.setBorder(null);
remember.setForeground(Color.WHITE);
remember.addKeyListener(this);
// Setup login button
login = new LiteButton("Login");
login.setBounds(775 + xShift, 426 + yShift, 92, 24);
login.setFont(minecraft);
login.setActionCommand(LOGIN_ACTION);
login.addActionListener(this);
login.addKeyListener(this);
// Spoutcraft logo
JLabel logo = new JLabel();
logo.setBounds(8, 15, 400, 109);
setIcon(logo, "techniclauncher.png", logo.getWidth(), logo.getHeight());
// Progress Bar
progressBar = new LiteProgressBar();
progressBar.setBounds(8, 130, 395, 23);
progressBar.setVisible(false);
progressBar.setStringPainted(true);
progressBar.setOpaque(true);
progressBar.setTransparency(0.70F);
progressBar.setHoverTransparency(0.70F);
progressBar.setFont(minecraft);
// Home Link
Font largerMinecraft;
if (OperatingSystem.getOS().isUnix()) {
largerMinecraft = minecraft.deriveFont((float)18);
} else {
largerMinecraft = minecraft.deriveFont((float)20);
}
HyperlinkJLabel home = new HyperlinkJLabel("Home", "http://www.technicpack.net");
home.setFont(largerMinecraft);
home.setBounds(545, 35, 65, 20);
home.setForeground(Color.WHITE);
home.setOpaque(false);
home.setTransparency(0.70F);
home.setHoverTransparency(1F);
// Forums link
HyperlinkJLabel forums = new HyperlinkJLabel("Forums", "http://forums.technicpack.net/");
forums.setFont(largerMinecraft);
forums.setBounds(625, 35, 90, 20);
forums.setForeground(Color.WHITE);
forums.setOpaque(false);
forums.setTransparency(0.70F);
forums.setHoverTransparency(1F);
// Issues link
HyperlinkJLabel issues = new HyperlinkJLabel("Issues", "http://forums.technicpack.net/forums/bug-reports.81/");
issues.setFont(largerMinecraft);
issues.setBounds(733, 35, 85, 20);
issues.setForeground(Color.WHITE);
issues.setOpaque(false);
issues.setTransparency(0.70F);
issues.setHoverTransparency(1F);
// Options Button
options = new TransparentButton();
options.setIcon(new ImageIcon(Toolkit.getDefaultToolkit().getImage(gearIcon)));
options.setBounds(828, 28, 30, 30);
options.setTransparency(0.70F);
options.setHoverTransparency(1F);
options.setActionCommand(OPTIONS_ACTION);
options.addActionListener(this);
// Steam button
JButton steam = new ImageHyperlinkButton("http://spout.in/steam");
steam.setToolTipText("Game with us on Steam");
steam.setBounds(6, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(steam, "steam.png", 28);
// Twitter button
JButton twitter = new ImageHyperlinkButton("http://spout.in/twitter");
twitter.setToolTipText("Follow us on Twitter");
twitter.setBounds(6 + 34 * 4 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(twitter, "twitter.png", 28);
// Facebook button
JButton facebook = new ImageHyperlinkButton("http://spout.in/facebook");
facebook.setToolTipText("Like us on Facebook");
facebook.setBounds(6 + 34 * 3 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(facebook, "facebook.png", 28);
// Google+ button
JButton gplus = new ImageHyperlinkButton("http://spout.in/gplus");
gplus.setToolTipText("Follow us on Google+");
gplus.setBounds(6 + 34 * 2 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(gplus, "gplus.png", 28);
// YouTube button
JButton youtube = new ImageHyperlinkButton("http://spout.in/youtube");
youtube.setToolTipText("Subscribe to our videos");
youtube.setBounds(6 + 34 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28);
setIcon(youtube, "youtube.png", 28);
Container contentPane = getContentPane();
contentPane.setLayout(null);
java.util.List<String> savedUsers = getSavedUsernames();
int users = Math.min(5, this.getSavedUsernames().size());
for (int i = 0; i < users; i++) {
String accountName = savedUsers.get(i);
String userName = this.getUsername(accountName);
DynamicButton userButton = new DynamicButton(this, getImage(userName), 44, accountName, userName);
userButton.setFont(minecraft.deriveFont(14F));
userButton.setBounds((FRAME_WIDTH - 75) * (i + 1) / (users + 1), (FRAME_HEIGHT - 75) / 2 , 75, 75);
contentPane.add(userButton);
userButton.setActionCommand(IMAGE_LOGIN_ACTION);
userButton.addActionListener(this);
setIcon(userButton.getRemoveIcon(), "remove.png", 16);
userButton.getRemoveIcon().addActionListener(this);
userButton.getRemoveIcon().setActionCommand(REMOVE_USER);
removeButtons.put(userButton.getRemoveIcon(), userButton);
}
contentPane.add(name);
contentPane.add(pass);
contentPane.add(remember);
contentPane.add(login);
contentPane.add(steam);
contentPane.add(twitter);
contentPane.add(facebook);
contentPane.add(gplus);
contentPane.add(youtube);
contentPane.add(home);
contentPane.add(forums);
contentPane.add(issues);
contentPane.add(logo);
contentPane.add(options);
contentPane.add(progressBar);
setFocusTraversalPolicy(new LoginFocusTraversalPolicy());
}
|
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmute.java b/Essentials/src/com/earth2me/essentials/commands/Commandmute.java
index 8c8c2e6b..c6022cc5 100644
--- a/Essentials/src/com/earth2me/essentials/commands/Commandmute.java
+++ b/Essentials/src/com/earth2me/essentials/commands/Commandmute.java
@@ -1,52 +1,52 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
public class Commandmute extends EssentialsCommand
{
public Commandmute()
{
super("mute");
}
@Override
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
User p = getPlayer(server, args, 0, true);
- if (p.isAuthorized("essentials.mute.exempt"))
+ if (!p.isMuted() && p.isAuthorized("essentials.mute.exempt"))
{
sender.sendMessage(Util.i18n("muteExempt"));
return;
}
long muteTimestamp = 0;
if (args.length > 1)
{
String time = getFinalArg(args, 1);
muteTimestamp = Util.parseDateDiff(time, true);
}
p.setMuteTimeout(muteTimestamp);
charge(sender);
boolean muted = p.toggleMuted();
sender.sendMessage(
muted
? (muteTimestamp > 0
? Util.format("mutedPlayerFor", p.getDisplayName(), Util.formatDateDiff(muteTimestamp))
: Util.format("mutedPlayer", p.getDisplayName()))
: Util.format("unmutedPlayer", p.getDisplayName()));
p.sendMessage(
muted
? (muteTimestamp > 0
? Util.format("playerMutedFor", Util.formatDateDiff(muteTimestamp))
: Util.i18n("playerMuted"))
: Util.i18n("playerUnmuted"));
}
}
| true | true |
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
User p = getPlayer(server, args, 0, true);
if (p.isAuthorized("essentials.mute.exempt"))
{
sender.sendMessage(Util.i18n("muteExempt"));
return;
}
long muteTimestamp = 0;
if (args.length > 1)
{
String time = getFinalArg(args, 1);
muteTimestamp = Util.parseDateDiff(time, true);
}
p.setMuteTimeout(muteTimestamp);
charge(sender);
boolean muted = p.toggleMuted();
sender.sendMessage(
muted
? (muteTimestamp > 0
? Util.format("mutedPlayerFor", p.getDisplayName(), Util.formatDateDiff(muteTimestamp))
: Util.format("mutedPlayer", p.getDisplayName()))
: Util.format("unmutedPlayer", p.getDisplayName()));
p.sendMessage(
muted
? (muteTimestamp > 0
? Util.format("playerMutedFor", Util.formatDateDiff(muteTimestamp))
: Util.i18n("playerMuted"))
: Util.i18n("playerUnmuted"));
}
|
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
User p = getPlayer(server, args, 0, true);
if (!p.isMuted() && p.isAuthorized("essentials.mute.exempt"))
{
sender.sendMessage(Util.i18n("muteExempt"));
return;
}
long muteTimestamp = 0;
if (args.length > 1)
{
String time = getFinalArg(args, 1);
muteTimestamp = Util.parseDateDiff(time, true);
}
p.setMuteTimeout(muteTimestamp);
charge(sender);
boolean muted = p.toggleMuted();
sender.sendMessage(
muted
? (muteTimestamp > 0
? Util.format("mutedPlayerFor", p.getDisplayName(), Util.formatDateDiff(muteTimestamp))
: Util.format("mutedPlayer", p.getDisplayName()))
: Util.format("unmutedPlayer", p.getDisplayName()));
p.sendMessage(
muted
? (muteTimestamp > 0
? Util.format("playerMutedFor", Util.formatDateDiff(muteTimestamp))
: Util.i18n("playerMuted"))
: Util.i18n("playerUnmuted"));
}
|
diff --git a/src/story/book/StoryFragmentReadActivity.java b/src/story/book/StoryFragmentReadActivity.java
index 87b5c54..4156f72 100644
--- a/src/story/book/StoryFragmentReadActivity.java
+++ b/src/story/book/StoryFragmentReadActivity.java
@@ -1,113 +1,114 @@
/**
*
*/
package story.book;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.TabHost;
/**
* StoryFragmentReadActivity is an interface for users to read a story
* fragment (left tab), as well as an interface for users to add
* annotations (right tab) on the story fragment which is currently being read.
*
* @author jsurya
*
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
public class StoryFragmentReadActivity extends FragmentActivity implements StoryView<Story> {
// Declare Tab Variable
ActionBar.Tab Tab1, Tab2;
Fragment readingTab1;
Fragment annotationsTab2;
ActionBar actionBar;
StoryReadController SRC;
ArrayList<Illustration> illustrations;
static StoryFragment SF = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.story_fragment_read_activity);
SRC = new StoryReadController();
SF = SRC.getStartingFragment();
-// illustrations = SF.getIllustrations();
+ String title = SF.getFragmentTitle();
+ illustrations = SF.getIllustrations();
readingTab1 = new ReadingFragment();
annotationsTab2 = new AnnotationFragment();
actionBar = getActionBar();
- actionBar.setTitle(R.string.FragmentTitle);
+ actionBar.setTitle(title);
// Create Actionbar Tabs
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set Tab Icon and Titles
Tab1 = actionBar.newTab().setText("Story");
Tab2 = actionBar.newTab().setText("Annotations");
// Set Tab Listeners
Tab1.setTabListener(new TabListener(readingTab1));
Tab2.setTabListener(new TabListener(annotationsTab2));
// Add tabs to action bar
actionBar.addTab(Tab1);
actionBar.addTab(Tab2);
}
@Override
public void onStart() {
super.onStart();
// if (SF == null) {
// SF = SRC.getStartingFragment();
// }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.standard_menu, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.title_activity_dashboard:
Intent intent = new Intent(this, Dashboard.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void update(Story model) {
// TODO Auto-generated method stub
}
public StoryReadController getController() {
return SRC;
}
}
| false | true |
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.story_fragment_read_activity);
SRC = new StoryReadController();
SF = SRC.getStartingFragment();
// illustrations = SF.getIllustrations();
readingTab1 = new ReadingFragment();
annotationsTab2 = new AnnotationFragment();
actionBar = getActionBar();
actionBar.setTitle(R.string.FragmentTitle);
// Create Actionbar Tabs
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set Tab Icon and Titles
Tab1 = actionBar.newTab().setText("Story");
Tab2 = actionBar.newTab().setText("Annotations");
// Set Tab Listeners
Tab1.setTabListener(new TabListener(readingTab1));
Tab2.setTabListener(new TabListener(annotationsTab2));
// Add tabs to action bar
actionBar.addTab(Tab1);
actionBar.addTab(Tab2);
}
|
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.story_fragment_read_activity);
SRC = new StoryReadController();
SF = SRC.getStartingFragment();
String title = SF.getFragmentTitle();
illustrations = SF.getIllustrations();
readingTab1 = new ReadingFragment();
annotationsTab2 = new AnnotationFragment();
actionBar = getActionBar();
actionBar.setTitle(title);
// Create Actionbar Tabs
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set Tab Icon and Titles
Tab1 = actionBar.newTab().setText("Story");
Tab2 = actionBar.newTab().setText("Annotations");
// Set Tab Listeners
Tab1.setTabListener(new TabListener(readingTab1));
Tab2.setTabListener(new TabListener(annotationsTab2));
// Add tabs to action bar
actionBar.addTab(Tab1);
actionBar.addTab(Tab2);
}
|
diff --git a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/backwards/GitServicesTest.java b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/backwards/GitServicesTest.java
index ee29ef8a..24d19b50 100644
--- a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/backwards/GitServicesTest.java
+++ b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/backwards/GitServicesTest.java
@@ -1,35 +1,35 @@
package org.cloudifysource.quality.iTests.test.cli.cloudify.backwards;
import iTests.framework.tools.SGTestHelper;
import iTests.framework.utils.JGitUtils;
import iTests.framework.utils.ScriptUtils;
import org.cloudifysource.quality.iTests.test.cli.cloudify.AbstractLocalCloudTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
/**
*
* @author Eli Polonsky
*/
public class GitServicesTest extends AbstractLocalCloudTest {
private static String localGitRepoPath;
private static String BRANCH_NAME = SGTestHelper.getBranchName();
@BeforeClass(alwaysRun = true)
protected void bootstrap() throws Exception {
localGitRepoPath = ScriptUtils.getBuildPath() + "/git-recipes-" + this.getClass().getSimpleName() ;
String remotePath = "https://github.com/CloudifySource/cloudify-recipes.git";
- JGitUtils.clone(localGitRepoPath, remotePath, "2_6_2");
+ JGitUtils.clone(localGitRepoPath, remotePath, SGTestHelper.getBackwardsRecipesBranch());
}
@Test(timeOut = DEFAULT_TEST_TIMEOUT, enabled = true)
public void testTomcat() throws IOException, InterruptedException {
installServiceAndWait(localGitRepoPath + "/services/tomcat", "tomcat", false);
}
}
| true | true |
protected void bootstrap() throws Exception {
localGitRepoPath = ScriptUtils.getBuildPath() + "/git-recipes-" + this.getClass().getSimpleName() ;
String remotePath = "https://github.com/CloudifySource/cloudify-recipes.git";
JGitUtils.clone(localGitRepoPath, remotePath, "2_6_2");
}
|
protected void bootstrap() throws Exception {
localGitRepoPath = ScriptUtils.getBuildPath() + "/git-recipes-" + this.getClass().getSimpleName() ;
String remotePath = "https://github.com/CloudifySource/cloudify-recipes.git";
JGitUtils.clone(localGitRepoPath, remotePath, SGTestHelper.getBackwardsRecipesBranch());
}
|
diff --git a/src/myMaps.java b/src/myMaps.java
index 02cc85d..a871b4c 100644
--- a/src/myMaps.java
+++ b/src/myMaps.java
@@ -1,226 +1,226 @@
import java.util.*;
public class myMaps
{
public static Map<String, String> getHTMLMap()
{
Map<String, String> htmlMap = new HashMap<String, String>();
/* lowcase */
// br
htmlMap.put("<br />", "\n");
htmlMap.put("<br>", "\n");
// hr
htmlMap.put("<hr />", "[hr]");
htmlMap.put("<hr>", "[hr]");
// strong
htmlMap.put("<strong>(.+?)</strong>", "\\[b\\]$1\\[/b\\]");
htmlMap.put("<b>(.+?)</b>", "\\[b\\]$1\\[/b\\]");
// italic
htmlMap.put("<i>(.+?)</i>", "\\[i\\]$1\\[/i\\]");
htmlMap.put("<span style='font-style:italic;'>(.+?)</span>", "\\[i\\]$1\\[/i\\]");
htmlMap.put("<span style=\"font-style:italic;\">(.+?)</span>", "\\[i\\]$1\\[/i\\]");
// underline
htmlMap.put("<u>(.+?)</u>", "\\[u\\]$1\\[/u\\]");
htmlMap.put("<span style='text-decoration:underline;'>(.+?)</span>", "\\[u\\]$1\\[/u\\]");
htmlMap.put("<span style=\"text-decoration:underline;\">(.+?)</span>", "\\[u\\]$1\\[/u\\]");
// h title
htmlMap.put("<h1>(.+?)</h1>", "\\[h1\\]$1\\[/h1\\]");
htmlMap.put("<h2>(.+?)</h2>", "\\[h2\\]$1\\[/h2\\]");
htmlMap.put("<h3>(.+?)</h3>", "\\[h3\\]$1\\[/h3\\]");
htmlMap.put("<h4>(.+?)</h4>", "\\[h4\\]$1\\[/h4\\]");
htmlMap.put("<h5>(.+?)</h5>", "\\[h5\\]$1\\[/h5\\]");
htmlMap.put("<h6>(.+?)</h6>", "\\[h6\\]$1\\[/h6\\]");
// blockquote
htmlMap.put("<blockquote>(.+?)</blockquote>", "\\[quote\\]$1\\[/quote\\]");
// p & aligns
htmlMap.put("<p>(.+?)</p>", "\\[p\\](.+?)\\[/p\\]");
htmlMap.put("<p style='text-indent:(.+?)px;line-height:(.+?)%;'>(.+?)</p>", "\\[p=$1,$2\\]$3\\[/p\\]");
htmlMap.put("<div align='center'>(.+?)</div>", "\\[center\\]$1\\[/center\\]");
htmlMap.put("<div align=\"center\">(.+?)</div>", "\\[center\\]$1\\[/center\\]");
htmlMap.put("<p align='center'>(.+?)</p>", "\\[center\\]$1\\[/center\\]");
htmlMap.put("<p align=\"center\">(.+?)</p>", "\\[center\\]$1\\[/center\\]");
htmlMap.put("<div align='(.+?)'>(.+?)", "\\[align=$1\\]$2\\[/align\\]");
htmlMap.put("<div align=\"(.+?)\">(.+?)", "\\[align=$1\\]$2\\[/align\\]");
// fonts
htmlMap.put("<span style='color:(.+?);'>(.+?)</span>", "\\[color=$1\\]$2\\[/color\\]");
htmlMap.put("<span style=\"color:(.+?);\">(.+?)</span>", "\\[color=$1\\]$2\\[/color\\]");
htmlMap.put("<span style='font-size:(.+?);'>(.+?)</span>", "\\[size=$1\\]$2\\[/size\\]");
htmlMap.put("<span style=\"font-size:(.+?);\">(.+?)</span>", "\\[size=$1\\]$2\\[/size\\]");
htmlMap.put("<font color=\"(.+?);\">(.+?)</span>", "\\[color=$1\\]$2\\[/color\\]");
htmlMap.put("<font color='(.+?);'>(.+?)</span>", "\\[color=$1\\]$2\\[/color\\]");
htmlMap.put("<font face=\"(.+?);\">(.+?)</span>", "$2");
htmlMap.put("<font face='(.+?);'>(.+?)</span>", "$2]");
htmlMap.put("<font face='(.+?);' color=\"(.+?);\">(.+?)</span>", "\\[color=$2\\]$3\\[/color\\]");
htmlMap.put("<font face='(.+?);' color='(.+?);'>(.+?)</span>", "\\[color=$2\\]$3\\[/color\\]");
htmlMap.put("<font color=\"(.+?);\" face=\"(.+?)\">(.+?)</span>", "\\[color=$1\\]$3\\[/color\\]");
htmlMap.put("<font color='(.+?);' face='(.+?);'>(.+?)</span>", "\\[color=$1\\]$3\\[/color\\]");
// images
htmlMap.put("<img src='(.+?)' />", "\\[img\\]$1\\[/img\\]");
htmlMap.put("<img width='(.+?)' height='(.+?)' src='(.+?)' />", "\\[img=$1,$2\\]$3\\[/img\\]");
// links & mails
htmlMap.put("<a href='mailto:(.+?)'>(.+?)</a>", "\\[email=$1\\]$2\\[/email\\]");;
htmlMap.put("<a href=\"mailto:(.+?)\">(.+?)</a>", "\\[email=$1\\]$2\\[/email\\]");;
- htmlMap.put("<a href='(.+?)'>(.+?)</a>", "\\[url=$1\"\\]$2\\[/url\\]");
+ htmlMap.put("<a href='(.+?)'>(.+?)</a>", "\\[url=$1\\]$2\\[/url\\]");
htmlMap.put("<a href=\"(.+?)\">(.+?)</a>", "\\[url=$1\"\\]$2\\[/url\\]");
// videos
htmlMap.put("<object width='(.+?)' height='(.+?)'><param name='(.+?)' value='http://www.youtube.com/v/(.+?)'></param><embed src='http://www.youtube.com/v/(.+?)' type='(.+?)' width='(.+?)' height='(.+?)'></embed></object>", "\\[youtube\\]$4\\[/youtube\\]");
htmlMap.put("<object width=\"(.+?)\" height=\"(.+?)\"><param name=\"(.+?)\" value=\"http://www.youtube.com/v/(.+?)\"></param><embed src=\"http://www.youtube.com/v/(.+?)\" type=\"(.+?)\" width=\"(.+?)\" height=\"(.+?)\"></embed></object>", "\\[youtube\\]$4\\[/youtube\\]");
htmlMap.put("<video src='(.+?)' />", "\\[video\\]$1\\[/video\\]");
htmlMap.put("<video src=\"(.+?)\" />", "\\[video\\]$1\\[/video\\]");
/* UPPERCASE */
// BR
htmlMap.put("<BR />", "\n");
htmlMap.put("<BR>", "\n");
// HR
htmlMap.put("<HR>", "[HR]");
htmlMap.put("<HR />", "[HR]");
// STRONG
htmlMap.put("<STRONG>(.+?)</STRONG>", "\\[B\\]$1\\[/B\\]");
htmlMap.put("<B>(.+?)</B>", "\\[B\\]$1\\[/B\\]");
// ITALIC
htmlMap.put("<I>(.+?)</I>", "\\[I\\]$1\\[/I\\]");
htmlMap.put("<SPAN STYLE='font-style:italic;'>(.+?)</SPAN>", "\\[I\\]$1\\[/I\\]");
htmlMap.put("<SPAN STYLE=\"font-style:italic;\">(.+?)</SPAN>", "\\[I\\]$1\\[/I\\]");
// UNDERLINE
htmlMap.put("<U>(.+?)</U>", "\\[U\\]$1\\[/U\\]");
htmlMap.put("<SPAN STYLE='text-decoration:underline;'>(.+?)</SPAN>", "\\[U\\]$1\\[/U\\]");
htmlMap.put("<SPAN STYLE=\"text-decoration:underline;\">(.+?)</SPAN>", "\\[U\\]$1\\[/U\\]");
// H TITLE
htmlMap.put("<H1>(.+?)</H1>", "\\[H1\\]$1\\[/H1\\]");
htmlMap.put("<H2>(.+?)</H2>", "\\[H2\\]$1\\[/H2\\]");
htmlMap.put("<H3>(.+?)</H3>", "\\[H3\\]$1\\[/H3\\]");
htmlMap.put("<H4>(.+?)</H4>", "\\[H4\\]$1\\[/H4\\]");
htmlMap.put("<H5>(.+?)</H5>", "\\[H5\\]$1\\[/H5\\]");
htmlMap.put("<H6>(.+?)</H6>", "\\[H6\\]$1\\[/H6\\]");
// BLOCKQUOTE
htmlMap.put("<BLOCKQUOTE>(.+?)</BLOCKQUOTE>", "\\[QUOTE\\]$1\\[/QUOTE\\]");
// P & ALIGNS
htmlMap.put("<P>(.+?)</P>", "\\[P\\](.+?)\\[/P\\]");
htmlMap.put("<P STYLE='text-indent:(.+?)px;line-height:(.+?)%;'>(.+?)</P>", "\\[P=$1,$2\\]$3\\[/P\\]");
htmlMap.put("<DIV ALIGN='CENTER'>(.+?)</DIV>", "\\[CENTER\\]$1\\[/CENTER\\]");
htmlMap.put("<DIV ALIGN=\"CENTER\">(.+?)</DIV>", "\\[CENTER\\]$1\\[/CENTER\\]");
htmlMap.put("<P ALIGN='CENTER'>(.+?)</P>", "\\[CENTER\\]$1\\[/CENTER\\]");
htmlMap.put("<P ALIGN=\"CENTER\">(.+?)</P>", "\\[CENTER\\]$1\\[/CENTER\\]");
htmlMap.put("<DIV ALIGN='(.+?)'>(.+?)", "\\[ALIGN=$1\\]$2\\[/ALIGN\\]");
htmlMap.put("<DIV ALIGN=\"(.+?)\">(.+?)", "\\[ALIGN=$1\\]$2\\[/ALIGN\\]");
// FONTS
htmlMap.put("<SPAN STYLE='color:(.+?);'>(.+?)</SPAN>", "\\[COLOR=$1\\]$2\\[/COLOR\\]");
htmlMap.put("<SPAN STYLE=\"color:(.+?);\">(.+?)</SPAN>", "\\[COLOR=$1\\]$2\\[/COLOR\\]");
htmlMap.put("<SPAN STYLE='font-size:(.+?);'>(.+?)</SPAN>", "\\[SIZE=$1\\]$2\\[/SIZE\\]");
htmlMap.put("<SPAN STYLE=\"font-size:(.+?);\">(.+?)</SPAN>", "\\[SIZE=$1\\]$2\\[/SIZE\\]");
htmlMap.put("<FONT COLOR=\"(.+?);\">(.+?)</SPAN>", "\\[COLOR=$1\\]$2\\[/COLOR\\]");
htmlMap.put("<FONT COLOR='(.+?);'>(.+?)</SPAN>", "\\[COLOR=$1\\]$2\\[/COLOR\\]");
htmlMap.put("<FONT FACE=\"(.+?);\">(.+?)</SPAN>", "$2");
htmlMap.put("<FONT FACE='(.+?);'>(.+?)</SPAN>", "$2]");
htmlMap.put("<FONT FACE='(.+?);' COLOR=\"(.+?);\">(.+?)</SPAN>", "\\[COLOR=$2\\]$3\\[/COLOR\\]");
htmlMap.put("<FONT FACE='(.+?);' COLOR='(.+?);'>(.+?)</SPAN>", "\\[COLOR=$2\\]$3\\[/COLOR\\]");
htmlMap.put("<FONT COLOR=\"(.+?);\" FACE=\"(.+?)\">(.+?)</SPAN>", "\\[COLOR=$1\\]$3\\[/COLOR\\]");
htmlMap.put("<FONT COLOR='(.+?);' FACE='(.+?);'>(.+?)</SPAN>", "\\[COLOR=$1\\]$3\\[/COLOR\\]");
// IMAGES
htmlMap.put("<IMG SRC='(.+?)' />", "\\[IMG\\]$1\\[/IMG\\]");
htmlMap.put("<IMG WIDTH='(.+?)' HEIGHT='(.+?)' SRC='(.+?)' />", "\\[IMG=$1,$2\\]$3\\[/IMG\\]");
// LINKS & MAILS
htmlMap.put("<A HREF='mailto:(.+?)'>(.+?)</A>", "\\[EMAIL=$1\\]$2\\[/EMAIL\\]");;
htmlMap.put("<A HREF=\"mailto:(.+?)\">(.+?)</A>", "\\[EMAIL=$1\\]$2\\[/EMAIL\\]");;
htmlMap.put("<A HREF='(.+?)'>(.+?)</A>", "\\[URL=$1\\]$2\\[/URL\\]");
htmlMap.put("<A HREF=\"(.+?)\">(.+?)</A>", "\\[URL=$1\\]$2\\[/URL\\]");
// VIDEOS
htmlMap.put("<OBJECT WIDTH='(.+?)' HEIGHT='(.+?)'><PARAM NAME='(.+?)' VALUE='HTTP://WWW.YOUTUBE.COM/V/(.+?)'></PARAM><EMBED SRC='http://www.youtube.com/v/(.+?)' TYPE='(.+?)' WIDTH='(.+?)' HEIGHT='(.+?)'></EMBED></OBJECT>", "\\[YOUTUBE\\]$4\\[/YOUTUBE\\]");
htmlMap.put("<OBJECT WIDTH=\"(.+?)\" HEIGHT=\"(.+?)\"><PARAM NAME=\"(.+?)\" VALUE=\"HTTP://WWW.YOUTUBE.COM/V/(.+?)\"></PARAM><EMBED SRC=\"http://www.youtube.com/v/(.+?)\" TYPE=\"(.+?)\" WIDTH=\"(.+?)\" HEIGHT=\"(.+?)\"></EMBED></OBJECT>", "\\[YOUTUBE\\]$4\\[/YOUTUBE\\]");
htmlMap.put("<VIDEO SRC='(.+?)' />", "\\[VIDEO\\]$1\\[/VIDEO\\]");
htmlMap.put("<VIDEO SRC=\"(.+?)\" />", "\\[VIDEO\\]$1\\[/VIDEO\\]");
return htmlMap;
}
public static Map<String, String> getBBcodeMap()
{
Map<String, String> bbMap = new HashMap<String, String>();
/* lowercase */
bbMap.put("\n", "<br />");
bbMap.put("\\[b\\](.+?)\\[/b\\]", "<strong>$1</strong>");
bbMap.put("\\[i\\](.+?)\\[/i\\]", "<i>$1</i>");
bbMap.put("\\[u\\](.+?)\\[/u\\]", "<u>$1</u>");
bbMap.put("\\[h1\\](.+?)\\[/h1\\]", "<h1>$1</h1>");
bbMap.put("\\[h2\\](.+?)\\[/h2\\]", "<h2>$1</h2>");
bbMap.put("\\[h3\\](.+?)\\[/h3\\]", "<h3>$1</h3>");
bbMap.put("\\[h4\\](.+?)\\[/h4\\]", "<h4>$1</h4>");
bbMap.put("\\[h5\\](.+?)\\[/h5\\]", "<h5>$1</h5>");
bbMap.put("\\[h6\\](.+?)\\[/h6\\]", "<h6>$1</h6>");
bbMap.put("\\[quote\\](.+?)\\[/quote\\]", "<blockquote>$1</blockquote>");
bbMap.put("\\[p\\](.+?)\\[/p\\]", "<p>$1</p>");
bbMap.put("\\[p=(.+?),(.+?)\\](.+?)\\[/p\\]", "<p style=\"text-indent:$1px;line-height:$2%;\">$3</p>");
bbMap.put("\\[center\\](.+?)\\[/center\\]", "<div align=\"center\">$1");
bbMap.put("\\[align=(.+?)\\](.+?)\\[/align\\]", "<div align=\"$1\">$2");
bbMap.put("\\[color=(.+?)\\](.+?)\\[/color\\]", "<span style=\"color:$1;\">$2</span>");
bbMap.put("\\[size=(.+?)\\](.+?)\\[/size\\]", "<span style=\"font-size:$1;\">$2</span>");
bbMap.put("\\[img\\](.+?)\\[/img\\]", "<img src=\"$1\" />");
bbMap.put("\\[img=(.+?),(.+?)\\](.+?)\\[/img\\]", "<img width=\"$1\" height=\"$2\" src=\"$3\" />");
bbMap.put("\\[email\\](.+?)\\[/email\\]", "<a href=\"mailto:$1\">$1</a>");
bbMap.put("\\[email=(.+?)\\](.+?)\\[/email\\]", "<a href=\"mailto:$1\">$2</a>");
bbMap.put("\\[url\\](.+?)\\[/url\\]", "<a href=\"$1\">$1</a>");
bbMap.put("\\[url=(.+?)\\](.+?)\\[/url\\]", "<a href=\"$1\">$2</a>");
bbMap.put("\\[youtube\\](.+?)\\[/youtube\\]", "<object width=\"640\" height=\"380\"><param name=\"movie\" value=\"http://www.youtube.com/v/$1\"></param><embed src=\"http://www.youtube.com/v/$1\" type=\"application/x-shockwave-flash\" width=\"640\" height=\"380\"></embed></object>");
bbMap.put("\\[video\\](.+?)\\[/video\\]", "<video src=\"$1\" />");
/* UPPERCASE */
bbMap.put("\\[B\\](.+?)\\[/B\\]", "<STRONG>$1</STRONG>");
bbMap.put("\\[I\\](.+?)\\[/I\\]", "<I>$1</I>");
bbMap.put("\\[U\\](.+?)\\[/U\\]", "<U>$1</U>");
bbMap.put("\\[H1\\](.+?)\\[/H1\\]", "<H1>$1</H1>");
bbMap.put("\\[H2\\](.+?)\\[/H2\\]", "<H2>$1</H2>");
bbMap.put("\\[H3\\](.+?)\\[/H3\\]", "<H3>$1</H3>");
bbMap.put("\\[H4\\](.+?)\\[/H4\\]", "<H4>$1</H4>");
bbMap.put("\\[H5\\](.+?)\\[/H5\\]", "<H5>$1</H5>");
bbMap.put("\\[H6\\](.+?)\\[/H6\\]", "<H6>$1</H6>");
bbMap.put("\\[QUOTE\\](.+?)\\[/QUOTE\\]", "<BLOCKQUOTE>$1</BLOCKQUOTE>");
bbMap.put("\\[P\\](.+?)\\[/P\\]", "<P>$1</P>");
bbMap.put("\\[P=(.+?),(.+?)\\](.+?)\\[/P\\]", "<P STYLE=\"TEXT-INDENT:$1PX;LINE-HEIGHT:$2%;\">$3</P>");
bbMap.put("\\[CENTER\\](.+?)\\[/CENTER\\]", "<DIV ALIGN=\"CENTER\">$1");
bbMap.put("\\[ALIGN=(.+?)\\](.+?)\\[/ALIGN\\]", "<DIV ALIGN=\"$1\">$2");
bbMap.put("\\[COLOR=(.+?)\\](.+?)\\[/COLOR\\]", "<SPAN STYLE=\"COLOR:$1;\">$2</SPAN>");
bbMap.put("\\[SIZE=(.+?)\\](.+?)\\[/SIZE\\]", "<SPAN STYLE=\"FONT-SIZE:$1;\">$2</SPAN>");
bbMap.put("\\[IMG\\](.+?)\\[/IMG\\]", "<IMG SRC=\"$1\" />");
bbMap.put("\\[IMG=(.+?),(.+?)\\](.+?)\\[/IMG\\]", "<IMG WIDTH=\"$1\" HEIGHT=\"$2\" SRC=\"$3\" />");
bbMap.put("\\[EMAIL\\](.+?)\\[/EMAIL\\]", "<A HREF=\"MAILTO:$1\">$1</A>");
bbMap.put("\\[EMAIL=(.+?)\\](.+?)\\[/EMAIL\\]", "<A HREF=\"MAILTO:$1\">$2</A>");
bbMap.put("\\[URL\\](.+?)\\[/URL\\]", "<A HREF=\"$1\">$1</A>");
bbMap.put("\\[URL=(.+?)\\](.+?)\\[/URL\\]", "<A HREF=\"$1\">$2</A>");
bbMap.put("\\[YOUTUBE\\](.+?)\\[/YOUTUBE\\]", "<OBJECT WIDTH=\"640\" HEIGHT=\"380\"><PARAM NAME=\"MOVIE\" VALUE=\"HTTP://WWW.YOUTUBE.COM/V/$1\"></PARAM><EMBED SRC=\"HTTP://WWW.YOUTUBE.COM/V/$1\" TYPE=\"APPLICATION/X-SHOCKWAVE-FLASH\" WIDTH=\"640\" HEIGHT=\"380\"></EMBED></OBJECT>");
bbMap.put("\\[VIDEO\\](.+?)\\[/VIDEO\\]", "<VIDEO SRC=\"$1\" />");
return bbMap;
}
}
| true | true |
public static Map<String, String> getHTMLMap()
{
Map<String, String> htmlMap = new HashMap<String, String>();
/* lowcase */
// br
htmlMap.put("<br />", "\n");
htmlMap.put("<br>", "\n");
// hr
htmlMap.put("<hr />", "[hr]");
htmlMap.put("<hr>", "[hr]");
// strong
htmlMap.put("<strong>(.+?)</strong>", "\\[b\\]$1\\[/b\\]");
htmlMap.put("<b>(.+?)</b>", "\\[b\\]$1\\[/b\\]");
// italic
htmlMap.put("<i>(.+?)</i>", "\\[i\\]$1\\[/i\\]");
htmlMap.put("<span style='font-style:italic;'>(.+?)</span>", "\\[i\\]$1\\[/i\\]");
htmlMap.put("<span style=\"font-style:italic;\">(.+?)</span>", "\\[i\\]$1\\[/i\\]");
// underline
htmlMap.put("<u>(.+?)</u>", "\\[u\\]$1\\[/u\\]");
htmlMap.put("<span style='text-decoration:underline;'>(.+?)</span>", "\\[u\\]$1\\[/u\\]");
htmlMap.put("<span style=\"text-decoration:underline;\">(.+?)</span>", "\\[u\\]$1\\[/u\\]");
// h title
htmlMap.put("<h1>(.+?)</h1>", "\\[h1\\]$1\\[/h1\\]");
htmlMap.put("<h2>(.+?)</h2>", "\\[h2\\]$1\\[/h2\\]");
htmlMap.put("<h3>(.+?)</h3>", "\\[h3\\]$1\\[/h3\\]");
htmlMap.put("<h4>(.+?)</h4>", "\\[h4\\]$1\\[/h4\\]");
htmlMap.put("<h5>(.+?)</h5>", "\\[h5\\]$1\\[/h5\\]");
htmlMap.put("<h6>(.+?)</h6>", "\\[h6\\]$1\\[/h6\\]");
// blockquote
htmlMap.put("<blockquote>(.+?)</blockquote>", "\\[quote\\]$1\\[/quote\\]");
// p & aligns
htmlMap.put("<p>(.+?)</p>", "\\[p\\](.+?)\\[/p\\]");
htmlMap.put("<p style='text-indent:(.+?)px;line-height:(.+?)%;'>(.+?)</p>", "\\[p=$1,$2\\]$3\\[/p\\]");
htmlMap.put("<div align='center'>(.+?)</div>", "\\[center\\]$1\\[/center\\]");
htmlMap.put("<div align=\"center\">(.+?)</div>", "\\[center\\]$1\\[/center\\]");
htmlMap.put("<p align='center'>(.+?)</p>", "\\[center\\]$1\\[/center\\]");
htmlMap.put("<p align=\"center\">(.+?)</p>", "\\[center\\]$1\\[/center\\]");
htmlMap.put("<div align='(.+?)'>(.+?)", "\\[align=$1\\]$2\\[/align\\]");
htmlMap.put("<div align=\"(.+?)\">(.+?)", "\\[align=$1\\]$2\\[/align\\]");
// fonts
htmlMap.put("<span style='color:(.+?);'>(.+?)</span>", "\\[color=$1\\]$2\\[/color\\]");
htmlMap.put("<span style=\"color:(.+?);\">(.+?)</span>", "\\[color=$1\\]$2\\[/color\\]");
htmlMap.put("<span style='font-size:(.+?);'>(.+?)</span>", "\\[size=$1\\]$2\\[/size\\]");
htmlMap.put("<span style=\"font-size:(.+?);\">(.+?)</span>", "\\[size=$1\\]$2\\[/size\\]");
htmlMap.put("<font color=\"(.+?);\">(.+?)</span>", "\\[color=$1\\]$2\\[/color\\]");
htmlMap.put("<font color='(.+?);'>(.+?)</span>", "\\[color=$1\\]$2\\[/color\\]");
htmlMap.put("<font face=\"(.+?);\">(.+?)</span>", "$2");
htmlMap.put("<font face='(.+?);'>(.+?)</span>", "$2]");
htmlMap.put("<font face='(.+?);' color=\"(.+?);\">(.+?)</span>", "\\[color=$2\\]$3\\[/color\\]");
htmlMap.put("<font face='(.+?);' color='(.+?);'>(.+?)</span>", "\\[color=$2\\]$3\\[/color\\]");
htmlMap.put("<font color=\"(.+?);\" face=\"(.+?)\">(.+?)</span>", "\\[color=$1\\]$3\\[/color\\]");
htmlMap.put("<font color='(.+?);' face='(.+?);'>(.+?)</span>", "\\[color=$1\\]$3\\[/color\\]");
// images
htmlMap.put("<img src='(.+?)' />", "\\[img\\]$1\\[/img\\]");
htmlMap.put("<img width='(.+?)' height='(.+?)' src='(.+?)' />", "\\[img=$1,$2\\]$3\\[/img\\]");
// links & mails
htmlMap.put("<a href='mailto:(.+?)'>(.+?)</a>", "\\[email=$1\\]$2\\[/email\\]");;
htmlMap.put("<a href=\"mailto:(.+?)\">(.+?)</a>", "\\[email=$1\\]$2\\[/email\\]");;
htmlMap.put("<a href='(.+?)'>(.+?)</a>", "\\[url=$1\"\\]$2\\[/url\\]");
htmlMap.put("<a href=\"(.+?)\">(.+?)</a>", "\\[url=$1\"\\]$2\\[/url\\]");
// videos
htmlMap.put("<object width='(.+?)' height='(.+?)'><param name='(.+?)' value='http://www.youtube.com/v/(.+?)'></param><embed src='http://www.youtube.com/v/(.+?)' type='(.+?)' width='(.+?)' height='(.+?)'></embed></object>", "\\[youtube\\]$4\\[/youtube\\]");
htmlMap.put("<object width=\"(.+?)\" height=\"(.+?)\"><param name=\"(.+?)\" value=\"http://www.youtube.com/v/(.+?)\"></param><embed src=\"http://www.youtube.com/v/(.+?)\" type=\"(.+?)\" width=\"(.+?)\" height=\"(.+?)\"></embed></object>", "\\[youtube\\]$4\\[/youtube\\]");
htmlMap.put("<video src='(.+?)' />", "\\[video\\]$1\\[/video\\]");
htmlMap.put("<video src=\"(.+?)\" />", "\\[video\\]$1\\[/video\\]");
/* UPPERCASE */
// BR
htmlMap.put("<BR />", "\n");
htmlMap.put("<BR>", "\n");
// HR
htmlMap.put("<HR>", "[HR]");
htmlMap.put("<HR />", "[HR]");
// STRONG
htmlMap.put("<STRONG>(.+?)</STRONG>", "\\[B\\]$1\\[/B\\]");
htmlMap.put("<B>(.+?)</B>", "\\[B\\]$1\\[/B\\]");
// ITALIC
htmlMap.put("<I>(.+?)</I>", "\\[I\\]$1\\[/I\\]");
htmlMap.put("<SPAN STYLE='font-style:italic;'>(.+?)</SPAN>", "\\[I\\]$1\\[/I\\]");
htmlMap.put("<SPAN STYLE=\"font-style:italic;\">(.+?)</SPAN>", "\\[I\\]$1\\[/I\\]");
// UNDERLINE
htmlMap.put("<U>(.+?)</U>", "\\[U\\]$1\\[/U\\]");
htmlMap.put("<SPAN STYLE='text-decoration:underline;'>(.+?)</SPAN>", "\\[U\\]$1\\[/U\\]");
htmlMap.put("<SPAN STYLE=\"text-decoration:underline;\">(.+?)</SPAN>", "\\[U\\]$1\\[/U\\]");
// H TITLE
htmlMap.put("<H1>(.+?)</H1>", "\\[H1\\]$1\\[/H1\\]");
htmlMap.put("<H2>(.+?)</H2>", "\\[H2\\]$1\\[/H2\\]");
htmlMap.put("<H3>(.+?)</H3>", "\\[H3\\]$1\\[/H3\\]");
htmlMap.put("<H4>(.+?)</H4>", "\\[H4\\]$1\\[/H4\\]");
htmlMap.put("<H5>(.+?)</H5>", "\\[H5\\]$1\\[/H5\\]");
htmlMap.put("<H6>(.+?)</H6>", "\\[H6\\]$1\\[/H6\\]");
// BLOCKQUOTE
htmlMap.put("<BLOCKQUOTE>(.+?)</BLOCKQUOTE>", "\\[QUOTE\\]$1\\[/QUOTE\\]");
// P & ALIGNS
htmlMap.put("<P>(.+?)</P>", "\\[P\\](.+?)\\[/P\\]");
htmlMap.put("<P STYLE='text-indent:(.+?)px;line-height:(.+?)%;'>(.+?)</P>", "\\[P=$1,$2\\]$3\\[/P\\]");
htmlMap.put("<DIV ALIGN='CENTER'>(.+?)</DIV>", "\\[CENTER\\]$1\\[/CENTER\\]");
htmlMap.put("<DIV ALIGN=\"CENTER\">(.+?)</DIV>", "\\[CENTER\\]$1\\[/CENTER\\]");
htmlMap.put("<P ALIGN='CENTER'>(.+?)</P>", "\\[CENTER\\]$1\\[/CENTER\\]");
htmlMap.put("<P ALIGN=\"CENTER\">(.+?)</P>", "\\[CENTER\\]$1\\[/CENTER\\]");
htmlMap.put("<DIV ALIGN='(.+?)'>(.+?)", "\\[ALIGN=$1\\]$2\\[/ALIGN\\]");
htmlMap.put("<DIV ALIGN=\"(.+?)\">(.+?)", "\\[ALIGN=$1\\]$2\\[/ALIGN\\]");
// FONTS
htmlMap.put("<SPAN STYLE='color:(.+?);'>(.+?)</SPAN>", "\\[COLOR=$1\\]$2\\[/COLOR\\]");
htmlMap.put("<SPAN STYLE=\"color:(.+?);\">(.+?)</SPAN>", "\\[COLOR=$1\\]$2\\[/COLOR\\]");
htmlMap.put("<SPAN STYLE='font-size:(.+?);'>(.+?)</SPAN>", "\\[SIZE=$1\\]$2\\[/SIZE\\]");
htmlMap.put("<SPAN STYLE=\"font-size:(.+?);\">(.+?)</SPAN>", "\\[SIZE=$1\\]$2\\[/SIZE\\]");
htmlMap.put("<FONT COLOR=\"(.+?);\">(.+?)</SPAN>", "\\[COLOR=$1\\]$2\\[/COLOR\\]");
htmlMap.put("<FONT COLOR='(.+?);'>(.+?)</SPAN>", "\\[COLOR=$1\\]$2\\[/COLOR\\]");
htmlMap.put("<FONT FACE=\"(.+?);\">(.+?)</SPAN>", "$2");
htmlMap.put("<FONT FACE='(.+?);'>(.+?)</SPAN>", "$2]");
htmlMap.put("<FONT FACE='(.+?);' COLOR=\"(.+?);\">(.+?)</SPAN>", "\\[COLOR=$2\\]$3\\[/COLOR\\]");
htmlMap.put("<FONT FACE='(.+?);' COLOR='(.+?);'>(.+?)</SPAN>", "\\[COLOR=$2\\]$3\\[/COLOR\\]");
htmlMap.put("<FONT COLOR=\"(.+?);\" FACE=\"(.+?)\">(.+?)</SPAN>", "\\[COLOR=$1\\]$3\\[/COLOR\\]");
htmlMap.put("<FONT COLOR='(.+?);' FACE='(.+?);'>(.+?)</SPAN>", "\\[COLOR=$1\\]$3\\[/COLOR\\]");
// IMAGES
htmlMap.put("<IMG SRC='(.+?)' />", "\\[IMG\\]$1\\[/IMG\\]");
htmlMap.put("<IMG WIDTH='(.+?)' HEIGHT='(.+?)' SRC='(.+?)' />", "\\[IMG=$1,$2\\]$3\\[/IMG\\]");
// LINKS & MAILS
htmlMap.put("<A HREF='mailto:(.+?)'>(.+?)</A>", "\\[EMAIL=$1\\]$2\\[/EMAIL\\]");;
htmlMap.put("<A HREF=\"mailto:(.+?)\">(.+?)</A>", "\\[EMAIL=$1\\]$2\\[/EMAIL\\]");;
htmlMap.put("<A HREF='(.+?)'>(.+?)</A>", "\\[URL=$1\\]$2\\[/URL\\]");
htmlMap.put("<A HREF=\"(.+?)\">(.+?)</A>", "\\[URL=$1\\]$2\\[/URL\\]");
// VIDEOS
htmlMap.put("<OBJECT WIDTH='(.+?)' HEIGHT='(.+?)'><PARAM NAME='(.+?)' VALUE='HTTP://WWW.YOUTUBE.COM/V/(.+?)'></PARAM><EMBED SRC='http://www.youtube.com/v/(.+?)' TYPE='(.+?)' WIDTH='(.+?)' HEIGHT='(.+?)'></EMBED></OBJECT>", "\\[YOUTUBE\\]$4\\[/YOUTUBE\\]");
htmlMap.put("<OBJECT WIDTH=\"(.+?)\" HEIGHT=\"(.+?)\"><PARAM NAME=\"(.+?)\" VALUE=\"HTTP://WWW.YOUTUBE.COM/V/(.+?)\"></PARAM><EMBED SRC=\"http://www.youtube.com/v/(.+?)\" TYPE=\"(.+?)\" WIDTH=\"(.+?)\" HEIGHT=\"(.+?)\"></EMBED></OBJECT>", "\\[YOUTUBE\\]$4\\[/YOUTUBE\\]");
htmlMap.put("<VIDEO SRC='(.+?)' />", "\\[VIDEO\\]$1\\[/VIDEO\\]");
htmlMap.put("<VIDEO SRC=\"(.+?)\" />", "\\[VIDEO\\]$1\\[/VIDEO\\]");
return htmlMap;
}
|
public static Map<String, String> getHTMLMap()
{
Map<String, String> htmlMap = new HashMap<String, String>();
/* lowcase */
// br
htmlMap.put("<br />", "\n");
htmlMap.put("<br>", "\n");
// hr
htmlMap.put("<hr />", "[hr]");
htmlMap.put("<hr>", "[hr]");
// strong
htmlMap.put("<strong>(.+?)</strong>", "\\[b\\]$1\\[/b\\]");
htmlMap.put("<b>(.+?)</b>", "\\[b\\]$1\\[/b\\]");
// italic
htmlMap.put("<i>(.+?)</i>", "\\[i\\]$1\\[/i\\]");
htmlMap.put("<span style='font-style:italic;'>(.+?)</span>", "\\[i\\]$1\\[/i\\]");
htmlMap.put("<span style=\"font-style:italic;\">(.+?)</span>", "\\[i\\]$1\\[/i\\]");
// underline
htmlMap.put("<u>(.+?)</u>", "\\[u\\]$1\\[/u\\]");
htmlMap.put("<span style='text-decoration:underline;'>(.+?)</span>", "\\[u\\]$1\\[/u\\]");
htmlMap.put("<span style=\"text-decoration:underline;\">(.+?)</span>", "\\[u\\]$1\\[/u\\]");
// h title
htmlMap.put("<h1>(.+?)</h1>", "\\[h1\\]$1\\[/h1\\]");
htmlMap.put("<h2>(.+?)</h2>", "\\[h2\\]$1\\[/h2\\]");
htmlMap.put("<h3>(.+?)</h3>", "\\[h3\\]$1\\[/h3\\]");
htmlMap.put("<h4>(.+?)</h4>", "\\[h4\\]$1\\[/h4\\]");
htmlMap.put("<h5>(.+?)</h5>", "\\[h5\\]$1\\[/h5\\]");
htmlMap.put("<h6>(.+?)</h6>", "\\[h6\\]$1\\[/h6\\]");
// blockquote
htmlMap.put("<blockquote>(.+?)</blockquote>", "\\[quote\\]$1\\[/quote\\]");
// p & aligns
htmlMap.put("<p>(.+?)</p>", "\\[p\\](.+?)\\[/p\\]");
htmlMap.put("<p style='text-indent:(.+?)px;line-height:(.+?)%;'>(.+?)</p>", "\\[p=$1,$2\\]$3\\[/p\\]");
htmlMap.put("<div align='center'>(.+?)</div>", "\\[center\\]$1\\[/center\\]");
htmlMap.put("<div align=\"center\">(.+?)</div>", "\\[center\\]$1\\[/center\\]");
htmlMap.put("<p align='center'>(.+?)</p>", "\\[center\\]$1\\[/center\\]");
htmlMap.put("<p align=\"center\">(.+?)</p>", "\\[center\\]$1\\[/center\\]");
htmlMap.put("<div align='(.+?)'>(.+?)", "\\[align=$1\\]$2\\[/align\\]");
htmlMap.put("<div align=\"(.+?)\">(.+?)", "\\[align=$1\\]$2\\[/align\\]");
// fonts
htmlMap.put("<span style='color:(.+?);'>(.+?)</span>", "\\[color=$1\\]$2\\[/color\\]");
htmlMap.put("<span style=\"color:(.+?);\">(.+?)</span>", "\\[color=$1\\]$2\\[/color\\]");
htmlMap.put("<span style='font-size:(.+?);'>(.+?)</span>", "\\[size=$1\\]$2\\[/size\\]");
htmlMap.put("<span style=\"font-size:(.+?);\">(.+?)</span>", "\\[size=$1\\]$2\\[/size\\]");
htmlMap.put("<font color=\"(.+?);\">(.+?)</span>", "\\[color=$1\\]$2\\[/color\\]");
htmlMap.put("<font color='(.+?);'>(.+?)</span>", "\\[color=$1\\]$2\\[/color\\]");
htmlMap.put("<font face=\"(.+?);\">(.+?)</span>", "$2");
htmlMap.put("<font face='(.+?);'>(.+?)</span>", "$2]");
htmlMap.put("<font face='(.+?);' color=\"(.+?);\">(.+?)</span>", "\\[color=$2\\]$3\\[/color\\]");
htmlMap.put("<font face='(.+?);' color='(.+?);'>(.+?)</span>", "\\[color=$2\\]$3\\[/color\\]");
htmlMap.put("<font color=\"(.+?);\" face=\"(.+?)\">(.+?)</span>", "\\[color=$1\\]$3\\[/color\\]");
htmlMap.put("<font color='(.+?);' face='(.+?);'>(.+?)</span>", "\\[color=$1\\]$3\\[/color\\]");
// images
htmlMap.put("<img src='(.+?)' />", "\\[img\\]$1\\[/img\\]");
htmlMap.put("<img width='(.+?)' height='(.+?)' src='(.+?)' />", "\\[img=$1,$2\\]$3\\[/img\\]");
// links & mails
htmlMap.put("<a href='mailto:(.+?)'>(.+?)</a>", "\\[email=$1\\]$2\\[/email\\]");;
htmlMap.put("<a href=\"mailto:(.+?)\">(.+?)</a>", "\\[email=$1\\]$2\\[/email\\]");;
htmlMap.put("<a href='(.+?)'>(.+?)</a>", "\\[url=$1\\]$2\\[/url\\]");
htmlMap.put("<a href=\"(.+?)\">(.+?)</a>", "\\[url=$1\"\\]$2\\[/url\\]");
// videos
htmlMap.put("<object width='(.+?)' height='(.+?)'><param name='(.+?)' value='http://www.youtube.com/v/(.+?)'></param><embed src='http://www.youtube.com/v/(.+?)' type='(.+?)' width='(.+?)' height='(.+?)'></embed></object>", "\\[youtube\\]$4\\[/youtube\\]");
htmlMap.put("<object width=\"(.+?)\" height=\"(.+?)\"><param name=\"(.+?)\" value=\"http://www.youtube.com/v/(.+?)\"></param><embed src=\"http://www.youtube.com/v/(.+?)\" type=\"(.+?)\" width=\"(.+?)\" height=\"(.+?)\"></embed></object>", "\\[youtube\\]$4\\[/youtube\\]");
htmlMap.put("<video src='(.+?)' />", "\\[video\\]$1\\[/video\\]");
htmlMap.put("<video src=\"(.+?)\" />", "\\[video\\]$1\\[/video\\]");
/* UPPERCASE */
// BR
htmlMap.put("<BR />", "\n");
htmlMap.put("<BR>", "\n");
// HR
htmlMap.put("<HR>", "[HR]");
htmlMap.put("<HR />", "[HR]");
// STRONG
htmlMap.put("<STRONG>(.+?)</STRONG>", "\\[B\\]$1\\[/B\\]");
htmlMap.put("<B>(.+?)</B>", "\\[B\\]$1\\[/B\\]");
// ITALIC
htmlMap.put("<I>(.+?)</I>", "\\[I\\]$1\\[/I\\]");
htmlMap.put("<SPAN STYLE='font-style:italic;'>(.+?)</SPAN>", "\\[I\\]$1\\[/I\\]");
htmlMap.put("<SPAN STYLE=\"font-style:italic;\">(.+?)</SPAN>", "\\[I\\]$1\\[/I\\]");
// UNDERLINE
htmlMap.put("<U>(.+?)</U>", "\\[U\\]$1\\[/U\\]");
htmlMap.put("<SPAN STYLE='text-decoration:underline;'>(.+?)</SPAN>", "\\[U\\]$1\\[/U\\]");
htmlMap.put("<SPAN STYLE=\"text-decoration:underline;\">(.+?)</SPAN>", "\\[U\\]$1\\[/U\\]");
// H TITLE
htmlMap.put("<H1>(.+?)</H1>", "\\[H1\\]$1\\[/H1\\]");
htmlMap.put("<H2>(.+?)</H2>", "\\[H2\\]$1\\[/H2\\]");
htmlMap.put("<H3>(.+?)</H3>", "\\[H3\\]$1\\[/H3\\]");
htmlMap.put("<H4>(.+?)</H4>", "\\[H4\\]$1\\[/H4\\]");
htmlMap.put("<H5>(.+?)</H5>", "\\[H5\\]$1\\[/H5\\]");
htmlMap.put("<H6>(.+?)</H6>", "\\[H6\\]$1\\[/H6\\]");
// BLOCKQUOTE
htmlMap.put("<BLOCKQUOTE>(.+?)</BLOCKQUOTE>", "\\[QUOTE\\]$1\\[/QUOTE\\]");
// P & ALIGNS
htmlMap.put("<P>(.+?)</P>", "\\[P\\](.+?)\\[/P\\]");
htmlMap.put("<P STYLE='text-indent:(.+?)px;line-height:(.+?)%;'>(.+?)</P>", "\\[P=$1,$2\\]$3\\[/P\\]");
htmlMap.put("<DIV ALIGN='CENTER'>(.+?)</DIV>", "\\[CENTER\\]$1\\[/CENTER\\]");
htmlMap.put("<DIV ALIGN=\"CENTER\">(.+?)</DIV>", "\\[CENTER\\]$1\\[/CENTER\\]");
htmlMap.put("<P ALIGN='CENTER'>(.+?)</P>", "\\[CENTER\\]$1\\[/CENTER\\]");
htmlMap.put("<P ALIGN=\"CENTER\">(.+?)</P>", "\\[CENTER\\]$1\\[/CENTER\\]");
htmlMap.put("<DIV ALIGN='(.+?)'>(.+?)", "\\[ALIGN=$1\\]$2\\[/ALIGN\\]");
htmlMap.put("<DIV ALIGN=\"(.+?)\">(.+?)", "\\[ALIGN=$1\\]$2\\[/ALIGN\\]");
// FONTS
htmlMap.put("<SPAN STYLE='color:(.+?);'>(.+?)</SPAN>", "\\[COLOR=$1\\]$2\\[/COLOR\\]");
htmlMap.put("<SPAN STYLE=\"color:(.+?);\">(.+?)</SPAN>", "\\[COLOR=$1\\]$2\\[/COLOR\\]");
htmlMap.put("<SPAN STYLE='font-size:(.+?);'>(.+?)</SPAN>", "\\[SIZE=$1\\]$2\\[/SIZE\\]");
htmlMap.put("<SPAN STYLE=\"font-size:(.+?);\">(.+?)</SPAN>", "\\[SIZE=$1\\]$2\\[/SIZE\\]");
htmlMap.put("<FONT COLOR=\"(.+?);\">(.+?)</SPAN>", "\\[COLOR=$1\\]$2\\[/COLOR\\]");
htmlMap.put("<FONT COLOR='(.+?);'>(.+?)</SPAN>", "\\[COLOR=$1\\]$2\\[/COLOR\\]");
htmlMap.put("<FONT FACE=\"(.+?);\">(.+?)</SPAN>", "$2");
htmlMap.put("<FONT FACE='(.+?);'>(.+?)</SPAN>", "$2]");
htmlMap.put("<FONT FACE='(.+?);' COLOR=\"(.+?);\">(.+?)</SPAN>", "\\[COLOR=$2\\]$3\\[/COLOR\\]");
htmlMap.put("<FONT FACE='(.+?);' COLOR='(.+?);'>(.+?)</SPAN>", "\\[COLOR=$2\\]$3\\[/COLOR\\]");
htmlMap.put("<FONT COLOR=\"(.+?);\" FACE=\"(.+?)\">(.+?)</SPAN>", "\\[COLOR=$1\\]$3\\[/COLOR\\]");
htmlMap.put("<FONT COLOR='(.+?);' FACE='(.+?);'>(.+?)</SPAN>", "\\[COLOR=$1\\]$3\\[/COLOR\\]");
// IMAGES
htmlMap.put("<IMG SRC='(.+?)' />", "\\[IMG\\]$1\\[/IMG\\]");
htmlMap.put("<IMG WIDTH='(.+?)' HEIGHT='(.+?)' SRC='(.+?)' />", "\\[IMG=$1,$2\\]$3\\[/IMG\\]");
// LINKS & MAILS
htmlMap.put("<A HREF='mailto:(.+?)'>(.+?)</A>", "\\[EMAIL=$1\\]$2\\[/EMAIL\\]");;
htmlMap.put("<A HREF=\"mailto:(.+?)\">(.+?)</A>", "\\[EMAIL=$1\\]$2\\[/EMAIL\\]");;
htmlMap.put("<A HREF='(.+?)'>(.+?)</A>", "\\[URL=$1\\]$2\\[/URL\\]");
htmlMap.put("<A HREF=\"(.+?)\">(.+?)</A>", "\\[URL=$1\\]$2\\[/URL\\]");
// VIDEOS
htmlMap.put("<OBJECT WIDTH='(.+?)' HEIGHT='(.+?)'><PARAM NAME='(.+?)' VALUE='HTTP://WWW.YOUTUBE.COM/V/(.+?)'></PARAM><EMBED SRC='http://www.youtube.com/v/(.+?)' TYPE='(.+?)' WIDTH='(.+?)' HEIGHT='(.+?)'></EMBED></OBJECT>", "\\[YOUTUBE\\]$4\\[/YOUTUBE\\]");
htmlMap.put("<OBJECT WIDTH=\"(.+?)\" HEIGHT=\"(.+?)\"><PARAM NAME=\"(.+?)\" VALUE=\"HTTP://WWW.YOUTUBE.COM/V/(.+?)\"></PARAM><EMBED SRC=\"http://www.youtube.com/v/(.+?)\" TYPE=\"(.+?)\" WIDTH=\"(.+?)\" HEIGHT=\"(.+?)\"></EMBED></OBJECT>", "\\[YOUTUBE\\]$4\\[/YOUTUBE\\]");
htmlMap.put("<VIDEO SRC='(.+?)' />", "\\[VIDEO\\]$1\\[/VIDEO\\]");
htmlMap.put("<VIDEO SRC=\"(.+?)\" />", "\\[VIDEO\\]$1\\[/VIDEO\\]");
return htmlMap;
}
|
diff --git a/biz.aQute.bndlib/src/aQute/bnd/osgi/Descriptors.java b/biz.aQute.bndlib/src/aQute/bnd/osgi/Descriptors.java
index 683f96d2d..4fb9f6371 100644
--- a/biz.aQute.bndlib/src/aQute/bnd/osgi/Descriptors.java
+++ b/biz.aQute.bndlib/src/aQute/bnd/osgi/Descriptors.java
@@ -1,567 +1,567 @@
package aQute.bnd.osgi;
import java.util.*;
import aQute.libg.generics.*;
public class Descriptors {
Map<String,TypeRef> typeRefCache = Create.map();
Map<String,Descriptor> descriptorCache = Create.map();
Map<String,PackageRef> packageCache = Create.map();
// MUST BE BEFORE PRIMITIVES, THEY USE THE DEFAULT PACKAGE!!
final static PackageRef DEFAULT_PACKAGE = new PackageRef();
final static PackageRef PRIMITIVE_PACKAGE = new PackageRef();
final static TypeRef VOID = new ConcreteRef("V", "void", PRIMITIVE_PACKAGE);
final static TypeRef BOOLEAN = new ConcreteRef("Z", "boolean", PRIMITIVE_PACKAGE);
final static TypeRef BYTE = new ConcreteRef("B", "byte", PRIMITIVE_PACKAGE);
final static TypeRef CHAR = new ConcreteRef("C", "char", PRIMITIVE_PACKAGE);
final static TypeRef SHORT = new ConcreteRef("S", "short", PRIMITIVE_PACKAGE);
final static TypeRef INTEGER = new ConcreteRef("I", "int", PRIMITIVE_PACKAGE);
final static TypeRef LONG = new ConcreteRef("J", "long", PRIMITIVE_PACKAGE);
final static TypeRef DOUBLE = new ConcreteRef("D", "double", PRIMITIVE_PACKAGE);
final static TypeRef FLOAT = new ConcreteRef("F", "float", PRIMITIVE_PACKAGE);
{
packageCache.put("", DEFAULT_PACKAGE);
}
public interface TypeRef extends Comparable<TypeRef> {
String getBinary();
String getFQN();
String getPath();
boolean isPrimitive();
TypeRef getComponentTypeRef();
TypeRef getClassRef();
PackageRef getPackageRef();
String getShortName();
boolean isJava();
boolean isObject();
String getSourcePath();
String getDottedOnly();
}
public static class PackageRef implements Comparable<PackageRef> {
final String binaryName;
final String fqn;
final boolean java;
PackageRef(String binaryName) {
this.binaryName = fqnToBinary(binaryName);
this.fqn = binaryToFQN(binaryName);
this.java = this.fqn.startsWith("java."); // &&
// !this.fqn.equals("java.sql)"
// For some reason I excluded java.sql but the classloader will
// delegate anyway. So lost the understanding why I did it??
}
PackageRef() {
this.binaryName = "";
this.fqn = ".";
this.java = false;
}
public PackageRef getDuplicate() {
return new PackageRef(binaryName + Constants.DUPLICATE_MARKER);
}
public String getFQN() {
return fqn;
}
public String getBinary() {
return binaryName;
}
public String getPath() {
return binaryName;
}
public boolean isJava() {
return java;
}
@Override
public String toString() {
return fqn;
}
boolean isDefaultPackage() {
return this.fqn.equals(".");
}
boolean isPrimitivePackage() {
return this == PRIMITIVE_PACKAGE;
}
public int compareTo(PackageRef other) {
return fqn.compareTo(other.fqn);
}
@Override
public boolean equals(Object o) {
assert o instanceof PackageRef;
return o == this;
}
@Override
public int hashCode() {
return super.hashCode();
}
/**
* Decide if the package is a metadata package.
*
* @param pack
* @return
*/
public boolean isMetaData() {
if (isDefaultPackage())
return true;
for (int i = 0; i < Constants.METAPACKAGES.length; i++) {
if (fqn.startsWith(Constants.METAPACKAGES[i]))
return true;
}
return false;
}
}
// We "intern" the
private static class ConcreteRef implements TypeRef {
final String binaryName;
final String fqn;
final boolean primitive;
final PackageRef packageRef;
ConcreteRef(PackageRef packageRef, String binaryName) {
if (packageRef.getFQN().length() < 2)
System.err.println("in default pack? " + binaryName);
this.binaryName = binaryName;
this.fqn = binaryToFQN(binaryName);
this.primitive = false;
this.packageRef = packageRef;
}
ConcreteRef(String binaryName, String fqn, PackageRef pref) {
this.binaryName = binaryName;
this.fqn = fqn;
this.primitive = true;
this.packageRef = pref;
}
public String getBinary() {
return binaryName;
}
public String getPath() {
return binaryName + ".class";
}
public String getSourcePath() {
return binaryName + ".java";
}
public String getFQN() {
return fqn;
}
public String getDottedOnly() {
return fqn.replace('$', '.');
}
public boolean isPrimitive() {
return primitive;
}
public TypeRef getComponentTypeRef() {
return null;
}
public TypeRef getClassRef() {
return this;
}
public PackageRef getPackageRef() {
return packageRef;
}
public String getShortName() {
int n = binaryName.lastIndexOf('/');
return binaryName.substring(n + 1);
}
public boolean isJava() {
return packageRef.isJava();
}
@Override
public String toString() {
return fqn;
}
public boolean isObject() {
return fqn.equals("java.lang.Object");
}
@Override
public boolean equals(Object other) {
assert other instanceof TypeRef;
return this == other;
}
public int compareTo(TypeRef other) {
if (this == other)
return 0;
return fqn.compareTo(other.getFQN());
}
@Override
public int hashCode() {
return super.hashCode();
}
}
private static class ArrayRef implements TypeRef {
final TypeRef component;
ArrayRef(TypeRef component) {
this.component = component;
}
public String getBinary() {
return "[" + component.getBinary();
}
public String getFQN() {
return component.getFQN() + "[]";
}
public String getPath() {
return component.getPath();
}
public String getSourcePath() {
return component.getSourcePath();
}
public boolean isPrimitive() {
return false;
}
public TypeRef getComponentTypeRef() {
return component;
}
public TypeRef getClassRef() {
return component.getClassRef();
}
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != getClass())
return false;
return component.equals(((ArrayRef) other).component);
}
public PackageRef getPackageRef() {
return component.getPackageRef();
}
public String getShortName() {
return component.getShortName() + "[]";
}
public boolean isJava() {
return component.isJava();
}
@Override
public String toString() {
return component.toString() + "[]";
}
public boolean isObject() {
return false;
}
public String getDottedOnly() {
return component.getDottedOnly();
}
public int compareTo(TypeRef other) {
if (this == other)
return 0;
return getFQN().compareTo(other.getFQN());
}
@Override
public int hashCode() {
return super.hashCode();
}
}
public TypeRef getTypeRef(String binaryClassName) {
assert !binaryClassName.endsWith(".class");
TypeRef ref = typeRefCache.get(binaryClassName);
if (ref != null)
return ref;
if (binaryClassName.startsWith("[")) {
ref = getTypeRef(binaryClassName.substring(1));
ref = new ArrayRef(ref);
} else {
- if (binaryClassName.length() >= 1) {
+ if (binaryClassName.length() == 1) {
switch (binaryClassName.charAt(0)) {
case 'V' :
return VOID;
case 'B' :
return BYTE;
case 'C' :
return CHAR;
case 'I' :
return INTEGER;
case 'S' :
return SHORT;
case 'D' :
return DOUBLE;
case 'F' :
return FLOAT;
case 'J' :
return LONG;
case 'Z' :
return BOOLEAN;
- case 'L' :
- binaryClassName = binaryClassName.substring(1, binaryClassName.length() - 1);
- break;
}
// falls trough for other 1 letter class names
}
+ if (binaryClassName.startsWith("L")) {
+ binaryClassName = binaryClassName.substring(1, binaryClassName.length() - 1);
+ }
ref = typeRefCache.get(binaryClassName);
if (ref != null)
return ref;
PackageRef pref;
int n = binaryClassName.lastIndexOf('/');
if (n < 0)
pref = DEFAULT_PACKAGE;
else
pref = getPackageRef(binaryClassName.substring(0, n));
ref = new ConcreteRef(pref, binaryClassName);
}
typeRefCache.put(binaryClassName, ref);
return ref;
}
public PackageRef getPackageRef(String binaryPackName) {
if (binaryPackName.indexOf('.') >= 0) {
binaryPackName = binaryPackName.replace('.', '/');
}
PackageRef ref = packageCache.get(binaryPackName);
if (ref != null)
return ref;
ref = new PackageRef(binaryPackName);
packageCache.put(binaryPackName, ref);
return ref;
}
public Descriptor getDescriptor(String descriptor) {
Descriptor d = descriptorCache.get(descriptor);
if (d != null)
return d;
d = new Descriptor(descriptor);
descriptorCache.put(descriptor, d);
return d;
}
public class Descriptor {
final TypeRef type;
final TypeRef[] prototype;
final String descriptor;
Descriptor(String descriptor) {
this.descriptor = descriptor;
int index = 0;
List<TypeRef> types = Create.list();
if (descriptor.charAt(index) == '(') {
index++;
while (descriptor.charAt(index) != ')') {
index = parse(types, descriptor, index);
}
index++; // skip )
prototype = types.toArray(new TypeRef[types.size()]);
types.clear();
} else
prototype = null;
index = parse(types, descriptor, index);
type = types.get(0);
}
int parse(List<TypeRef> types, String descriptor, int index) {
char c;
StringBuilder sb = new StringBuilder();
while ((c = descriptor.charAt(index++)) == '[') {
sb.append('[');
}
switch (c) {
case 'L' :
while ((c = descriptor.charAt(index++)) != ';') {
// TODO
sb.append(c);
}
break;
case 'V' :
case 'B' :
case 'C' :
case 'I' :
case 'S' :
case 'D' :
case 'F' :
case 'J' :
case 'Z' :
sb.append(c);
break;
default :
throw new IllegalArgumentException("Invalid type in descriptor: " + c + " from " + descriptor + "["
+ index + "]");
}
types.add(getTypeRef(sb.toString()));
return index;
}
public TypeRef getType() {
return type;
}
public TypeRef[] getPrototype() {
return prototype;
}
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != getClass())
return false;
return Arrays.equals(prototype, ((Descriptor) other).prototype) && type == ((Descriptor) other).type;
}
@Override
public int hashCode() {
return prototype == null ? type.hashCode() : type.hashCode() ^ Arrays.hashCode(prototype);
}
@Override
public String toString() {
return descriptor;
}
}
/**
* Return the short name of a FQN
*/
public static String getShortName(String fqn) {
assert fqn.indexOf('/') < 0;
int n = fqn.lastIndexOf('.');
if (n >= 0) {
return fqn.substring(n + 1);
}
return fqn;
}
public static String binaryToFQN(String binary) {
StringBuilder sb = new StringBuilder();
for (int i = 0, l = binary.length(); i < l; i++) {
char c = binary.charAt(i);
if (c == '/')
sb.append('.');
else
sb.append(c);
}
String result = sb.toString();
assert result.length() > 0;
return result;
}
public static String fqnToBinary(String binary) {
return binary.replace('.', '/');
}
public static String getPackage(String binaryNameOrFqn) {
int n = binaryNameOrFqn.lastIndexOf('/');
if (n >= 0)
return binaryNameOrFqn.substring(0, n).replace('/', '.');
n = binaryNameOrFqn.lastIndexOf(".");
if (n >= 0)
return binaryNameOrFqn.substring(0, n);
return ".";
}
public static String fqnToPath(String s) {
return fqnToBinary(s) + ".class";
}
public TypeRef getTypeRefFromFQN(String fqn) {
if (fqn.equals("boolean"))
return BOOLEAN;
if (fqn.equals("byte"))
return BOOLEAN;
if (fqn.equals("char"))
return CHAR;
if (fqn.equals("short"))
return SHORT;
if (fqn.equals("int"))
return INTEGER;
if (fqn.equals("long"))
return LONG;
if (fqn.equals("float"))
return FLOAT;
if (fqn.equals("double"))
return DOUBLE;
return getTypeRef(fqnToBinary(fqn));
}
public TypeRef getTypeRefFromPath(String path) {
assert path.endsWith(".class");
return getTypeRef(path.substring(0, path.length() - 6));
}
}
| false | true |
public TypeRef getTypeRef(String binaryClassName) {
assert !binaryClassName.endsWith(".class");
TypeRef ref = typeRefCache.get(binaryClassName);
if (ref != null)
return ref;
if (binaryClassName.startsWith("[")) {
ref = getTypeRef(binaryClassName.substring(1));
ref = new ArrayRef(ref);
} else {
if (binaryClassName.length() >= 1) {
switch (binaryClassName.charAt(0)) {
case 'V' :
return VOID;
case 'B' :
return BYTE;
case 'C' :
return CHAR;
case 'I' :
return INTEGER;
case 'S' :
return SHORT;
case 'D' :
return DOUBLE;
case 'F' :
return FLOAT;
case 'J' :
return LONG;
case 'Z' :
return BOOLEAN;
case 'L' :
binaryClassName = binaryClassName.substring(1, binaryClassName.length() - 1);
break;
}
// falls trough for other 1 letter class names
}
ref = typeRefCache.get(binaryClassName);
if (ref != null)
return ref;
PackageRef pref;
int n = binaryClassName.lastIndexOf('/');
if (n < 0)
pref = DEFAULT_PACKAGE;
else
pref = getPackageRef(binaryClassName.substring(0, n));
ref = new ConcreteRef(pref, binaryClassName);
}
typeRefCache.put(binaryClassName, ref);
return ref;
}
|
public TypeRef getTypeRef(String binaryClassName) {
assert !binaryClassName.endsWith(".class");
TypeRef ref = typeRefCache.get(binaryClassName);
if (ref != null)
return ref;
if (binaryClassName.startsWith("[")) {
ref = getTypeRef(binaryClassName.substring(1));
ref = new ArrayRef(ref);
} else {
if (binaryClassName.length() == 1) {
switch (binaryClassName.charAt(0)) {
case 'V' :
return VOID;
case 'B' :
return BYTE;
case 'C' :
return CHAR;
case 'I' :
return INTEGER;
case 'S' :
return SHORT;
case 'D' :
return DOUBLE;
case 'F' :
return FLOAT;
case 'J' :
return LONG;
case 'Z' :
return BOOLEAN;
}
// falls trough for other 1 letter class names
}
if (binaryClassName.startsWith("L")) {
binaryClassName = binaryClassName.substring(1, binaryClassName.length() - 1);
}
ref = typeRefCache.get(binaryClassName);
if (ref != null)
return ref;
PackageRef pref;
int n = binaryClassName.lastIndexOf('/');
if (n < 0)
pref = DEFAULT_PACKAGE;
else
pref = getPackageRef(binaryClassName.substring(0, n));
ref = new ConcreteRef(pref, binaryClassName);
}
typeRefCache.put(binaryClassName, ref);
return ref;
}
|
diff --git a/test/regression/src/test/java/org/jacorb/test/common/launch/Launcher.java b/test/regression/src/test/java/org/jacorb/test/common/launch/Launcher.java
index 6cb044926..b1af1e288 100644
--- a/test/regression/src/test/java/org/jacorb/test/common/launch/Launcher.java
+++ b/test/regression/src/test/java/org/jacorb/test/common/launch/Launcher.java
@@ -1,261 +1,258 @@
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2012 Gerald Brose / The JacORB Team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.jacorb.test.common.launch;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.jacorb.test.common.TestUtils;
/**
* Launches a JacORB process by direct invocation of a JVM
* with appropriate arguments.
*
*/
public class Launcher
{
protected static boolean assertsEnabled;
static
{
assertsEnabled = false;
assert assertsEnabled = true; // Intentional side effect!!!
}
protected File jacorbHome;
protected String classpath;
protected Properties properties;
protected boolean useCoverage;
protected String[] vmArgs;
protected String mainClass;
protected String[] args;
private List<String> command;
private String javaHome;
private String javaCommand;
public void setArgs(String[] args)
{
this.args = args;
}
public void setClasspath(String classpath)
{
this.classpath = classpath;
}
public void setMainClass(String mainClass)
{
this.mainClass = mainClass;
}
public void setProperties(Properties properties)
{
this.properties = properties;
}
public void setUseCoverage(boolean useCoverage)
{
this.useCoverage = useCoverage;
}
public void setVmArgs(String[] vmArgs)
{
this.vmArgs = vmArgs;
}
public void setJacorbHome(File jacorbHome)
{
TestUtils.log("using JacORB home: " + jacorbHome);
this.jacorbHome = jacorbHome;
}
protected String getPropertyWithDefault(Properties props, String name, String defaultValue)
{
return props.getProperty(name, System.getProperty(name, defaultValue));
}
private List<String> propsToArgList(Properties props)
{
List<String> result = new ArrayList<String>();
if (props == null) return result;
for (Iterator<Object> i = props.keySet().iterator(); i.hasNext();)
{
String key = (String)i.next();
String value = props.getProperty(key);
result.add ("-D" + key + "=" + value);
}
return result;
}
public void init()
{
command = buildCMDLine(jacorbHome, useCoverage, classpath, properties, mainClass, args);
}
public Process launch()
{
final Runtime rt = Runtime.getRuntime();
try
{
String[] cmd = (command.toArray (new String[command.size()]));
StringBuffer buff = new StringBuffer();
for (int i = 0; i < cmd.length; i++)
{
buff.append(cmd[i]);
buff.append(' ');
}
TestUtils.log("[DirectLauncher] launch: " + buff);
Process proc = rt.exec(cmd);
return proc;
}
catch (IOException ex)
{
throw new RuntimeException(ex);
}
}
private List<String> buildCMDLine(File jacorbHome, boolean coverage, String classpath,
Properties props, String mainClass, String[] args)
{
javaHome = getPropertyWithDefault(props, "jacorb.java.home", System.getProperty("java.home"));
final String jvm = getPropertyWithDefault(props, "jacorb.jvm", "/bin/java");
javaCommand = javaHome + jvm;
final List<String> cmdList = new ArrayList<String>();
cmdList.add (javaCommand);
if (assertsEnabled)
{
cmdList.add("-ea");
}
- if (jacorbHome != null)
- {
- cmdList.add(new BootClasspathBuilder(jacorbHome, coverage).getBootClasspath());
- }
+ cmdList.add("-Xbootclasspath:" + System.getProperty("sun.boot.class.path"));
if (classpath != null && classpath.length() > 0)
{
cmdList.add ("-classpath");
cmdList.add (classpath);
}
if (props != null)
{
if (! "".equals (getMaxHeapSize(props)))
{
cmdList.add ("-Xmx" + getMaxHeapSize(props));
}
cmdList.addAll (propsToArgList(props));
}
if (jacorbHome != null)
{
cmdList.add ("-Djacorb.home=" + jacorbHome);
}
if (TestUtils.isWindows())
{
try
{
cmdList.add ("-DSystemRoot=" + TestUtils.systemRoot());
}
catch (RuntimeException e)
{
System.out.println("WARNING: caught RuntimeException when reading SystemRoot: " + e.getMessage());
}
catch (IOException e)
{
System.out.println("WARNING: caught IOException when reading SystemRoot: " + e.getMessage());
}
}
cmdList.add (mainClass);
if (args != null)
{
cmdList.addAll (Arrays.asList(args));
}
return cmdList;
}
private String getMaxHeapSize(Properties props)
{
return getPropertyWithDefault(props, "jacorb.test.maxheapsize", "");
}
public String getLauncherDetails(String prefix)
{
try
{
final String javaVersionCommand = javaCommand + " -version";
Process proc = Runtime.getRuntime().exec(javaVersionCommand);
try
{
InputStream inputStream = proc.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
StringBuffer buffer = new StringBuffer();
while((line = reader.readLine()) != null)
{
buffer.append(prefix);
buffer.append(line);
buffer.append('\n');
}
return buffer.toString();
}
finally
{
proc.destroy();
}
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}
}
| true | true |
private List<String> buildCMDLine(File jacorbHome, boolean coverage, String classpath,
Properties props, String mainClass, String[] args)
{
javaHome = getPropertyWithDefault(props, "jacorb.java.home", System.getProperty("java.home"));
final String jvm = getPropertyWithDefault(props, "jacorb.jvm", "/bin/java");
javaCommand = javaHome + jvm;
final List<String> cmdList = new ArrayList<String>();
cmdList.add (javaCommand);
if (assertsEnabled)
{
cmdList.add("-ea");
}
if (jacorbHome != null)
{
cmdList.add(new BootClasspathBuilder(jacorbHome, coverage).getBootClasspath());
}
if (classpath != null && classpath.length() > 0)
{
cmdList.add ("-classpath");
cmdList.add (classpath);
}
if (props != null)
{
if (! "".equals (getMaxHeapSize(props)))
{
cmdList.add ("-Xmx" + getMaxHeapSize(props));
}
cmdList.addAll (propsToArgList(props));
}
if (jacorbHome != null)
{
cmdList.add ("-Djacorb.home=" + jacorbHome);
}
if (TestUtils.isWindows())
{
try
{
cmdList.add ("-DSystemRoot=" + TestUtils.systemRoot());
}
catch (RuntimeException e)
{
System.out.println("WARNING: caught RuntimeException when reading SystemRoot: " + e.getMessage());
}
catch (IOException e)
{
System.out.println("WARNING: caught IOException when reading SystemRoot: " + e.getMessage());
}
}
cmdList.add (mainClass);
if (args != null)
{
cmdList.addAll (Arrays.asList(args));
}
return cmdList;
}
|
private List<String> buildCMDLine(File jacorbHome, boolean coverage, String classpath,
Properties props, String mainClass, String[] args)
{
javaHome = getPropertyWithDefault(props, "jacorb.java.home", System.getProperty("java.home"));
final String jvm = getPropertyWithDefault(props, "jacorb.jvm", "/bin/java");
javaCommand = javaHome + jvm;
final List<String> cmdList = new ArrayList<String>();
cmdList.add (javaCommand);
if (assertsEnabled)
{
cmdList.add("-ea");
}
cmdList.add("-Xbootclasspath:" + System.getProperty("sun.boot.class.path"));
if (classpath != null && classpath.length() > 0)
{
cmdList.add ("-classpath");
cmdList.add (classpath);
}
if (props != null)
{
if (! "".equals (getMaxHeapSize(props)))
{
cmdList.add ("-Xmx" + getMaxHeapSize(props));
}
cmdList.addAll (propsToArgList(props));
}
if (jacorbHome != null)
{
cmdList.add ("-Djacorb.home=" + jacorbHome);
}
if (TestUtils.isWindows())
{
try
{
cmdList.add ("-DSystemRoot=" + TestUtils.systemRoot());
}
catch (RuntimeException e)
{
System.out.println("WARNING: caught RuntimeException when reading SystemRoot: " + e.getMessage());
}
catch (IOException e)
{
System.out.println("WARNING: caught IOException when reading SystemRoot: " + e.getMessage());
}
}
cmdList.add (mainClass);
if (args != null)
{
cmdList.addAll (Arrays.asList(args));
}
return cmdList;
}
|
diff --git a/Server/src/battleships/server/Session.java b/Server/src/battleships/server/Session.java
index b2e3669..eccb737 100644
--- a/Server/src/battleships/server/Session.java
+++ b/Server/src/battleships/server/Session.java
@@ -1,266 +1,266 @@
package battleships.server;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
import battleships.game.Coordinate;
import battleships.game.Navy;
import battleships.game.ServerAI;
import battleships.game.Ship;
import battleships.game.Validator;
import battleships.message.FinishedMessage;
import battleships.message.HitMessage;
import battleships.message.Message;
import battleships.message.NavyMessage;
import battleships.message.Shot;
import battleships.message.ValidationMessage;
/**
* A game session object.
* @author Magnus Hedlund
* */
public class Session implements Runnable{
private final static int PLAYER0 =0, PLAYER1=1, SUBMARINES=5, DESTROYERS=3, AIRCRAFT_CARRIERS=1;
private Player[] player = new Player[2];
private boolean[] navyValid = new boolean[2];
private Navy[] navy = new Navy[2];
private int currentPlayer=PLAYER0, otherPlayer=PLAYER1;
private boolean isHit=false;
private boolean isSunk=false;
private boolean grantTurn=false;
private boolean finished=false;
private ServerAI serverAI=null;
public Session(Player first, Player second){
player[PLAYER0]=first;
player[PLAYER1]=second;
}
public Session(Player first){
player[PLAYER0]=first;
serverAI = new ServerAI(5,3,1);
}
/**
* Runs the game.
* */
@Override
public void run() {
System.out.println("Run");
/* listen and validate Navy objects*/
while(!navyValid[PLAYER0] && !navyValid[PLAYER1]){
System.out.println("In Whileloop");
if(!navyValid[PLAYER0]){
boolean isValid = readAndValidate(PLAYER0);
navyValid[PLAYER0]=isValid;
if(isValid){System.out.println("validated navy 1");}
player[PLAYER0].sendMessage(new ValidationMessage(isValid));
}
//only validate if the other player is real
if(player[PLAYER1]==null){ //no real opponent
navyValid[PLAYER1]=true; //skip validation of server Navy
navy[PLAYER1]=serverAI.getNavy();
System.out.println("server already valid");
}
else if(!navyValid[PLAYER1]){
System.out.println("validating navy 2");
boolean isValid = readAndValidate(PLAYER1);
navyValid[PLAYER1]=isValid;
if(isValid){System.out.println("validated navy 2");}
player[PLAYER1].sendMessage(new ValidationMessage(isValid));
}
}
System.out.println("left validation loop");
//let first player shoot
player[currentPlayer].sendMessage(new NavyMessage(navy[currentPlayer], true));
enterGameLoop();
}//run end
/**
* Listening for NavyMessage and verifies the Navy object.
*
* */
private boolean readAndValidate(int playerNumber){
Validator validator = new Validator(SUBMARINES,DESTROYERS,AIRCRAFT_CARRIERS);
Message msg = readMessage(player[playerNumber]);
if(msg.getType().equals("NavyMessage")){
System.out.println("We have a navy");
NavyMessage navMsg = (NavyMessage)msg;
if(navMsg.getNavy().allSet()){
System.out.println("allSet");
}
if(validator.validateNavy(navMsg.getNavy())){
System.out.println("it�s valid");
navy[playerNumber]=navMsg.getNavy();
return true;
}
else{
System.out.println("it�s not valid");
return false;
}
}
else{
System.out.println("We don�t have a navy");
return false;
}
}
/**
* The game loop. Read messages/getshots and evaluate. Messages are sent to clients(not to the ServerAI)
* */
private void enterGameLoop(){
boolean loop=true;
Coordinate shotCoordinate=null;
Ship hitShip=null;
while(loop){
//reset
isHit=false;
isSunk=false;
grantTurn=false;
finished=false;
hitShip=null;
shotCoordinate=null;
//Read message
if(player[currentPlayer]!=null){ //an actual player
Message msg = readMessage(player[currentPlayer]);
Shot shotMsg=null;
if(msg.getType().equals("Shot")){
System.out.println("received Shot");
shotMsg = (Shot)msg;
shotCoordinate = shotMsg.getCoordinate();
}
}
else { //get shot coordinate from ServerAI
if(serverAI!=null){
shotCoordinate = serverAI.shoot();
System.out.println("server generated shot");
}
}
// do we have a Coordinate?
if(shotCoordinate!=null){
- System.out.println("X: "+Integer.toString(shotCoordinate.getX())+" Y: "+Integer.toString(shotCoordinate.getX()));
+ System.out.println("X: "+Integer.toString(shotCoordinate.getX())+" Y: "+Integer.toString(shotCoordinate.getY()));
// shoot the other players navy
hitShip=navy[otherPlayer].shot(shotCoordinate);
//a hit
if(hitShip!=null){
isHit=true;
System.out.println(hitShip.getName());
if(!hitShip.isSunk()){
hitShip=null; //don�t send Ship unless sunk
}
else{
System.out.println("sunk");
isSunk=true;
// check if won
if(navy[otherPlayer].allGone()){
finished=true;
}
}
}
// no hit
else{
System.out.println("Let the other one fire");
//if miss let the other one fire
grantTurn=true;
}
if(finished){
if(player[currentPlayer]!=null){
player[currentPlayer].sendMessage(new FinishedMessage(true, navy[currentPlayer]));
}
//send hitMessage to otherPlayer
if(player[otherPlayer]!=null){
player[otherPlayer].sendMessage(new FinishedMessage(false, navy[otherPlayer]));
}
loop=false;
}
else{
//send hitMessage to currentPlayer
if(player[currentPlayer]!=null){
player[currentPlayer].sendMessage(new HitMessage(isHit, shotCoordinate, isSunk, hitShip));
}
//send NavyMessage to otherPlayer
if(player[otherPlayer]!=null){
player[otherPlayer].sendMessage(new NavyMessage(navy[otherPlayer], grantTurn));
}
}
//if otherPlayer was granted next turn, Switch player
if(grantTurn){
System.out.println("Switching player");
switchPlayer();
}
}
else{ //the message received was of wrong type
if(player[currentPlayer]!=null){
player[currentPlayer].sendMessage(new ValidationMessage(false));
}
}
}//while end
}
/**
*
* Switch positions of the currentPlayer and otherPlayer
*
* */
private void switchPlayer(){
otherPlayer=currentPlayer;
if(currentPlayer==PLAYER0){
currentPlayer=PLAYER1;
}
else{
currentPlayer=PLAYER0;
}
}
private Message readMessage(Player p){
Message msg=null;
while(msg==null){
try{
msg=p.readMessage();
if(msg==null){
Thread.sleep(500);
}
else{
System.out.println("Got a message: "+msg.getType());
}
}catch(Exception e){
}
}
return msg;
}
}
| true | true |
private void enterGameLoop(){
boolean loop=true;
Coordinate shotCoordinate=null;
Ship hitShip=null;
while(loop){
//reset
isHit=false;
isSunk=false;
grantTurn=false;
finished=false;
hitShip=null;
shotCoordinate=null;
//Read message
if(player[currentPlayer]!=null){ //an actual player
Message msg = readMessage(player[currentPlayer]);
Shot shotMsg=null;
if(msg.getType().equals("Shot")){
System.out.println("received Shot");
shotMsg = (Shot)msg;
shotCoordinate = shotMsg.getCoordinate();
}
}
else { //get shot coordinate from ServerAI
if(serverAI!=null){
shotCoordinate = serverAI.shoot();
System.out.println("server generated shot");
}
}
// do we have a Coordinate?
if(shotCoordinate!=null){
System.out.println("X: "+Integer.toString(shotCoordinate.getX())+" Y: "+Integer.toString(shotCoordinate.getX()));
// shoot the other players navy
hitShip=navy[otherPlayer].shot(shotCoordinate);
//a hit
if(hitShip!=null){
isHit=true;
System.out.println(hitShip.getName());
if(!hitShip.isSunk()){
hitShip=null; //don�t send Ship unless sunk
}
else{
System.out.println("sunk");
isSunk=true;
// check if won
if(navy[otherPlayer].allGone()){
finished=true;
}
}
}
// no hit
else{
System.out.println("Let the other one fire");
//if miss let the other one fire
grantTurn=true;
}
if(finished){
if(player[currentPlayer]!=null){
player[currentPlayer].sendMessage(new FinishedMessage(true, navy[currentPlayer]));
}
//send hitMessage to otherPlayer
if(player[otherPlayer]!=null){
player[otherPlayer].sendMessage(new FinishedMessage(false, navy[otherPlayer]));
}
loop=false;
}
else{
//send hitMessage to currentPlayer
if(player[currentPlayer]!=null){
player[currentPlayer].sendMessage(new HitMessage(isHit, shotCoordinate, isSunk, hitShip));
}
//send NavyMessage to otherPlayer
if(player[otherPlayer]!=null){
player[otherPlayer].sendMessage(new NavyMessage(navy[otherPlayer], grantTurn));
}
}
//if otherPlayer was granted next turn, Switch player
if(grantTurn){
System.out.println("Switching player");
switchPlayer();
}
}
else{ //the message received was of wrong type
if(player[currentPlayer]!=null){
player[currentPlayer].sendMessage(new ValidationMessage(false));
}
}
}//while end
}
|
private void enterGameLoop(){
boolean loop=true;
Coordinate shotCoordinate=null;
Ship hitShip=null;
while(loop){
//reset
isHit=false;
isSunk=false;
grantTurn=false;
finished=false;
hitShip=null;
shotCoordinate=null;
//Read message
if(player[currentPlayer]!=null){ //an actual player
Message msg = readMessage(player[currentPlayer]);
Shot shotMsg=null;
if(msg.getType().equals("Shot")){
System.out.println("received Shot");
shotMsg = (Shot)msg;
shotCoordinate = shotMsg.getCoordinate();
}
}
else { //get shot coordinate from ServerAI
if(serverAI!=null){
shotCoordinate = serverAI.shoot();
System.out.println("server generated shot");
}
}
// do we have a Coordinate?
if(shotCoordinate!=null){
System.out.println("X: "+Integer.toString(shotCoordinate.getX())+" Y: "+Integer.toString(shotCoordinate.getY()));
// shoot the other players navy
hitShip=navy[otherPlayer].shot(shotCoordinate);
//a hit
if(hitShip!=null){
isHit=true;
System.out.println(hitShip.getName());
if(!hitShip.isSunk()){
hitShip=null; //don�t send Ship unless sunk
}
else{
System.out.println("sunk");
isSunk=true;
// check if won
if(navy[otherPlayer].allGone()){
finished=true;
}
}
}
// no hit
else{
System.out.println("Let the other one fire");
//if miss let the other one fire
grantTurn=true;
}
if(finished){
if(player[currentPlayer]!=null){
player[currentPlayer].sendMessage(new FinishedMessage(true, navy[currentPlayer]));
}
//send hitMessage to otherPlayer
if(player[otherPlayer]!=null){
player[otherPlayer].sendMessage(new FinishedMessage(false, navy[otherPlayer]));
}
loop=false;
}
else{
//send hitMessage to currentPlayer
if(player[currentPlayer]!=null){
player[currentPlayer].sendMessage(new HitMessage(isHit, shotCoordinate, isSunk, hitShip));
}
//send NavyMessage to otherPlayer
if(player[otherPlayer]!=null){
player[otherPlayer].sendMessage(new NavyMessage(navy[otherPlayer], grantTurn));
}
}
//if otherPlayer was granted next turn, Switch player
if(grantTurn){
System.out.println("Switching player");
switchPlayer();
}
}
else{ //the message received was of wrong type
if(player[currentPlayer]!=null){
player[currentPlayer].sendMessage(new ValidationMessage(false));
}
}
}//while end
}
|
diff --git a/modules/jetty/src/main/java/org/mortbay/jetty/servlet/Dispatcher.java b/modules/jetty/src/main/java/org/mortbay/jetty/servlet/Dispatcher.java
index 302d2d5df..8acb2741b 100644
--- a/modules/jetty/src/main/java/org/mortbay/jetty/servlet/Dispatcher.java
+++ b/modules/jetty/src/main/java/org/mortbay/jetty/servlet/Dispatcher.java
@@ -1,517 +1,517 @@
// ========================================================================
// Copyright 199-2004 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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.mortbay.jetty.servlet;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.HttpConnection;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.handler.ContextHandler;
import org.mortbay.util.Attributes;
import org.mortbay.util.LazyList;
import org.mortbay.util.MultiMap;
import org.mortbay.util.UrlEncoded;
/* ------------------------------------------------------------ */
/** Servlet RequestDispatcher.
*
* @author Greg Wilkins (gregw)
*/
public class Dispatcher implements RequestDispatcher
{
/** Dispatch include attribute names */
public final static String __INCLUDE_JETTY="org.mortbay.jetty.included";
public final static String __INCLUDE_PREFIX="javax.servlet.include.";
public final static String __INCLUDE_REQUEST_URI= "javax.servlet.include.request_uri";
public final static String __INCLUDE_CONTEXT_PATH= "javax.servlet.include.context_path";
public final static String __INCLUDE_SERVLET_PATH= "javax.servlet.include.servlet_path";
public final static String __INCLUDE_PATH_INFO= "javax.servlet.include.path_info";
public final static String __INCLUDE_QUERY_STRING= "javax.servlet.include.query_string";
/** Dispatch include attribute names */
public final static String __FORWARD_JETTY="org.mortbay.jetty.forwarded";
public final static String __FORWARD_PREFIX="javax.servlet.forward.";
public final static String __FORWARD_REQUEST_URI= "javax.servlet.forward.request_uri";
public final static String __FORWARD_CONTEXT_PATH= "javax.servlet.forward.context_path";
public final static String __FORWARD_SERVLET_PATH= "javax.servlet.forward.servlet_path";
public final static String __FORWARD_PATH_INFO= "javax.servlet.forward.path_info";
public final static String __FORWARD_QUERY_STRING= "javax.servlet.forward.query_string";
/** JSP attributes */
public final static String __JSP_FILE="org.apache.catalina.jsp_file";
/* ------------------------------------------------------------ */
/** Dispatch type from name
*/
public static int type(String type)
{
if ("request".equalsIgnoreCase(type))
return Handler.REQUEST;
if ("forward".equalsIgnoreCase(type))
return Handler.FORWARD;
if ("include".equalsIgnoreCase(type))
return Handler.INCLUDE;
if ("error".equalsIgnoreCase(type))
return Handler.ERROR;
throw new IllegalArgumentException(type);
}
/* ------------------------------------------------------------ */
private ContextHandler _contextHandler;
private String _uri;
private String _path;
private String _dQuery;
private String _named;
/* ------------------------------------------------------------ */
/**
* @param contextHandler
* @param uriInContext
* @param pathInContext
* @param query
*/
public Dispatcher(ContextHandler contextHandler, String uri, String pathInContext, String query)
{
_contextHandler=contextHandler;
_uri=uri;
_path=pathInContext;
_dQuery=query;
}
/* ------------------------------------------------------------ */
/** Constructor.
* @param servletHandler
* @param name
*/
public Dispatcher(ContextHandler contextHandler,String name)
throws IllegalStateException
{
_contextHandler=contextHandler;
_named=name;
}
/* ------------------------------------------------------------ */
/*
* @see javax.servlet.RequestDispatcher#forward(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
*/
public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
forward(request, response, Handler.FORWARD);
}
/* ------------------------------------------------------------ */
/*
* @see javax.servlet.RequestDispatcher#forward(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
*/
public void error(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
forward(request, response, Handler.ERROR);
}
/* ------------------------------------------------------------ */
/*
* @see javax.servlet.RequestDispatcher#include(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
*/
public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
Request base_request=(request instanceof Request)?((Request)request):HttpConnection.getCurrentConnection().getRequest();
request.removeAttribute(__JSP_FILE); // TODO remove when glassfish 1044 is fixed
// TODO - allow stream or writer????
Attributes old_attr=base_request.getAttributes();
MultiMap old_params=base_request.getParameters();
try
{
base_request.getConnection().include();
if (_named!=null)
_contextHandler.handle(_named, (HttpServletRequest)request, (HttpServletResponse)response, Handler.INCLUDE);
else
{
String query=_dQuery;
if (query!=null)
{
MultiMap parameters=new MultiMap();
UrlEncoded.decodeTo(query,parameters,request.getCharacterEncoding());
if (old_params!=null && old_params.size()>0)
{
// Merge parameters.
Iterator iter = old_params.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry entry = (Map.Entry)iter.next();
String name=(String)entry.getKey();
Object values=entry.getValue();
for (int i=0;i<LazyList.size(values);i++)
parameters.add(name, LazyList.get(values, i));
}
}
base_request.setParameters(parameters);
}
IncludeAttributes attr = new IncludeAttributes(old_attr);
attr._requestURI=_uri;
attr._contextPath=_contextHandler.getContextPath();
attr._servletPath=null; // set by ServletHandler
attr._pathInfo=_path;
attr._query=query;
base_request.setAttributes(attr);
_contextHandler.handle(_named==null?_path:_named, (HttpServletRequest)request, (HttpServletResponse)response, Handler.INCLUDE);
}
}
finally
{
base_request.setAttributes(old_attr);
base_request.getConnection().included();
base_request.setParameters(old_params);
}
}
/* ------------------------------------------------------------ */
/*
* @see javax.servlet.RequestDispatcher#forward(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
*/
protected void forward(ServletRequest request, ServletResponse response, int dispatch) throws ServletException, IOException
{
Request base_request=(request instanceof Request)?((Request)request):HttpConnection.getCurrentConnection().getRequest();
response.resetBuffer();
request.removeAttribute(__JSP_FILE); // TODO remove when glassfish 1044 is fixed
String old_uri=base_request.getRequestURI();
String old_context_path=base_request.getContextPath();
String old_servlet_path=base_request.getServletPath();
String old_path_info=base_request.getPathInfo();
String old_query=base_request.getQueryString();
Attributes old_attr=base_request.getAttributes();
MultiMap old_params=base_request.getParameters();
try
{
if (_named!=null)
_contextHandler.handle(_named, (HttpServletRequest)request, (HttpServletResponse)response, dispatch);
else
{
String query=_dQuery;
if (query!=null)
{
MultiMap parameters=new MultiMap();
UrlEncoded.decodeTo(query,parameters,request.getCharacterEncoding());
if (old_params!=null && old_params.size()>0)
{
// Merge parameters.
Iterator iter = old_params.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry entry = (Map.Entry)iter.next();
String name=(String)entry.getKey();
Object values=entry.getValue();
for (int i=0;i<LazyList.size(values);i++)
parameters.add(name, LazyList.get(values, i));
}
}
if (old_query!=null && old_query.length()>0)
query=query+"&"+old_query;
base_request.setParameters(parameters);
base_request.setQueryString(query);
}
ForwardAttributes attr = new ForwardAttributes(old_attr);
- attr._requestURI=base_request.getRequestURI();
- attr._contextPath=base_request.getContextPath();
- attr._servletPath=base_request.getServletPath();
- attr._pathInfo=base_request.getPathInfo();
- attr._query=base_request.getQueryString();
+ attr._requestURI=old_uri;
+ attr._contextPath=old_context_path;
+ attr._servletPath=old_servlet_path;
+ attr._pathInfo=old_path_info;
+ attr._query=old_query;
base_request.setRequestURI(_uri);
base_request.setContextPath(_contextHandler.getContextPath());
base_request.setAttributes(attr);
base_request.setQueryString(query);
_contextHandler.handle(_path, (HttpServletRequest)request, (HttpServletResponse)response, dispatch);
if (base_request.getConnection().getResponse().isWriting())
{
try {response.getWriter().close();}
catch(IllegalStateException e) { response.getOutputStream().close(); }
}
else
{
try {response.getOutputStream().close();}
catch(IllegalStateException e) { response.getWriter().close(); }
}
}
}
finally
{
base_request.setRequestURI(old_uri);
base_request.setContextPath(old_context_path);
base_request.setServletPath(old_servlet_path);
base_request.setPathInfo(old_path_info);
base_request.setAttributes(old_attr);
base_request.setParameters(old_params);
base_request.setQueryString(old_query);
}
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
private class ForwardAttributes implements Attributes
{
Attributes _attr;
String _requestURI;
String _contextPath;
String _servletPath;
String _pathInfo;
String _query;
ForwardAttributes(Attributes attributes)
{
_attr=attributes;
}
/* ------------------------------------------------------------ */
public Object getAttribute(String key)
{
if (Dispatcher.this._named==null)
{
if (key.equals(__FORWARD_PATH_INFO)) return _pathInfo;
if (key.equals(__FORWARD_REQUEST_URI)) return _requestURI;
if (key.equals(__FORWARD_SERVLET_PATH)) return _servletPath;
if (key.equals(__FORWARD_CONTEXT_PATH)) return _contextPath;
if (key.equals(__FORWARD_QUERY_STRING)) return _query;
}
if (key.startsWith(__INCLUDE_PREFIX))
return null;
if (key.equals(__FORWARD_JETTY))
return Boolean.TRUE;
return _attr.getAttribute(key);
}
/* ------------------------------------------------------------ */
public Enumeration getAttributeNames()
{
HashSet set=new HashSet();
Enumeration e=_attr.getAttributeNames();
while(e.hasMoreElements())
{
String name=(String)e.nextElement();
if (!name.startsWith(__INCLUDE_PREFIX) &&
!name.startsWith(__FORWARD_PREFIX))
set.add(name);
}
if (_named==null)
{
if (_pathInfo!=null)
set.add(__FORWARD_PATH_INFO);
else
set.remove(__FORWARD_PATH_INFO);
set.add(__FORWARD_REQUEST_URI);
set.add(__FORWARD_SERVLET_PATH);
set.add(__FORWARD_CONTEXT_PATH);
if (_query!=null)
set.add(__FORWARD_QUERY_STRING);
else
set.remove(__FORWARD_QUERY_STRING);
}
return Collections.enumeration(set);
}
/* ------------------------------------------------------------ */
public void setAttribute(String key, Object value)
{
if (_named==null && key.startsWith("javax.servlet."))
{
if (key.equals(__FORWARD_PATH_INFO)) _pathInfo=(String)value;
else if (key.equals(__FORWARD_REQUEST_URI)) _requestURI=(String)value;
else if (key.equals(__FORWARD_SERVLET_PATH)) _servletPath=(String)value;
else if (key.equals(__FORWARD_CONTEXT_PATH)) _contextPath=(String)value;
else if (key.equals(__FORWARD_QUERY_STRING)) _query=(String)value;
else if (value==null)
_attr.removeAttribute(key);
else
_attr.setAttribute(key,value);
}
else if (value==null)
_attr.removeAttribute(key);
else
_attr.setAttribute(key,value);
}
/* ------------------------------------------------------------ */
public String toString()
{
return "FORWARD+"+_attr.toString();
}
/* ------------------------------------------------------------ */
public void clearAttributes()
{
throw new IllegalStateException();
}
/* ------------------------------------------------------------ */
public void removeAttribute(String name)
{
setAttribute(name,null);
}
}
private class IncludeAttributes implements Attributes
{
Attributes _attr;
String _requestURI;
String _contextPath;
String _servletPath;
String _pathInfo;
String _query;
IncludeAttributes(Attributes attributes)
{
_attr=attributes;
}
/* ------------------------------------------------------------ */
public Object getAttribute(String key)
{
if (Dispatcher.this._named==null)
{
if (key.equals(__INCLUDE_PATH_INFO)) return _pathInfo;
if (key.equals(__INCLUDE_SERVLET_PATH)) return _servletPath;
if (key.equals(__INCLUDE_CONTEXT_PATH)) return _contextPath;
if (key.equals(__INCLUDE_QUERY_STRING)) return _query;
if (key.equals(__INCLUDE_REQUEST_URI)) return _requestURI;
}
else
{
if (key.startsWith(__INCLUDE_PREFIX))
return null;
}
if (key.startsWith(__FORWARD_PREFIX))
return null;
if (key.equals(__INCLUDE_JETTY))
return Boolean.TRUE;
return _attr.getAttribute(key);
}
/* ------------------------------------------------------------ */
public Enumeration getAttributeNames()
{
HashSet set=new HashSet();
Enumeration e=_attr.getAttributeNames();
while(e.hasMoreElements())
{
String name=(String)e.nextElement();
if (!name.startsWith(__INCLUDE_PREFIX) &&
!name.startsWith(__FORWARD_PREFIX))
set.add(name);
}
if (_named==null)
{
if (_pathInfo!=null)
set.add(__INCLUDE_PATH_INFO);
else
set.remove(__INCLUDE_PATH_INFO);
set.add(__INCLUDE_REQUEST_URI);
set.add(__INCLUDE_SERVLET_PATH);
set.add(__INCLUDE_CONTEXT_PATH);
if (_query!=null)
set.add(__INCLUDE_QUERY_STRING);
else
set.remove(__INCLUDE_QUERY_STRING);
}
return Collections.enumeration(set);
}
/* ------------------------------------------------------------ */
public void setAttribute(String key, Object value)
{
if (_named==null && key.startsWith("javax.servlet."))
{
if (key.equals(__INCLUDE_PATH_INFO)) _pathInfo=(String)value;
else if (key.equals(__INCLUDE_REQUEST_URI)) _requestURI=(String)value;
else if (key.equals(__INCLUDE_SERVLET_PATH)) _servletPath=(String)value;
else if (key.equals(__INCLUDE_CONTEXT_PATH)) _contextPath=(String)value;
else if (key.equals(__INCLUDE_QUERY_STRING)) _query=(String)value;
else if (value==null)
_attr.removeAttribute(key);
else
_attr.setAttribute(key,value);
}
else if (value==null)
_attr.removeAttribute(key);
else
_attr.setAttribute(key,value);
}
/* ------------------------------------------------------------ */
public String toString()
{
return "INCLUDE+"+_attr.toString();
}
/* ------------------------------------------------------------ */
public void clearAttributes()
{
throw new IllegalStateException();
}
/* ------------------------------------------------------------ */
public void removeAttribute(String name)
{
setAttribute(name,null);
}
}
};
| true | true |
protected void forward(ServletRequest request, ServletResponse response, int dispatch) throws ServletException, IOException
{
Request base_request=(request instanceof Request)?((Request)request):HttpConnection.getCurrentConnection().getRequest();
response.resetBuffer();
request.removeAttribute(__JSP_FILE); // TODO remove when glassfish 1044 is fixed
String old_uri=base_request.getRequestURI();
String old_context_path=base_request.getContextPath();
String old_servlet_path=base_request.getServletPath();
String old_path_info=base_request.getPathInfo();
String old_query=base_request.getQueryString();
Attributes old_attr=base_request.getAttributes();
MultiMap old_params=base_request.getParameters();
try
{
if (_named!=null)
_contextHandler.handle(_named, (HttpServletRequest)request, (HttpServletResponse)response, dispatch);
else
{
String query=_dQuery;
if (query!=null)
{
MultiMap parameters=new MultiMap();
UrlEncoded.decodeTo(query,parameters,request.getCharacterEncoding());
if (old_params!=null && old_params.size()>0)
{
// Merge parameters.
Iterator iter = old_params.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry entry = (Map.Entry)iter.next();
String name=(String)entry.getKey();
Object values=entry.getValue();
for (int i=0;i<LazyList.size(values);i++)
parameters.add(name, LazyList.get(values, i));
}
}
if (old_query!=null && old_query.length()>0)
query=query+"&"+old_query;
base_request.setParameters(parameters);
base_request.setQueryString(query);
}
ForwardAttributes attr = new ForwardAttributes(old_attr);
attr._requestURI=base_request.getRequestURI();
attr._contextPath=base_request.getContextPath();
attr._servletPath=base_request.getServletPath();
attr._pathInfo=base_request.getPathInfo();
attr._query=base_request.getQueryString();
base_request.setRequestURI(_uri);
base_request.setContextPath(_contextHandler.getContextPath());
base_request.setAttributes(attr);
base_request.setQueryString(query);
_contextHandler.handle(_path, (HttpServletRequest)request, (HttpServletResponse)response, dispatch);
if (base_request.getConnection().getResponse().isWriting())
{
try {response.getWriter().close();}
catch(IllegalStateException e) { response.getOutputStream().close(); }
}
else
{
try {response.getOutputStream().close();}
catch(IllegalStateException e) { response.getWriter().close(); }
}
}
}
finally
{
base_request.setRequestURI(old_uri);
base_request.setContextPath(old_context_path);
base_request.setServletPath(old_servlet_path);
base_request.setPathInfo(old_path_info);
base_request.setAttributes(old_attr);
base_request.setParameters(old_params);
base_request.setQueryString(old_query);
}
}
|
protected void forward(ServletRequest request, ServletResponse response, int dispatch) throws ServletException, IOException
{
Request base_request=(request instanceof Request)?((Request)request):HttpConnection.getCurrentConnection().getRequest();
response.resetBuffer();
request.removeAttribute(__JSP_FILE); // TODO remove when glassfish 1044 is fixed
String old_uri=base_request.getRequestURI();
String old_context_path=base_request.getContextPath();
String old_servlet_path=base_request.getServletPath();
String old_path_info=base_request.getPathInfo();
String old_query=base_request.getQueryString();
Attributes old_attr=base_request.getAttributes();
MultiMap old_params=base_request.getParameters();
try
{
if (_named!=null)
_contextHandler.handle(_named, (HttpServletRequest)request, (HttpServletResponse)response, dispatch);
else
{
String query=_dQuery;
if (query!=null)
{
MultiMap parameters=new MultiMap();
UrlEncoded.decodeTo(query,parameters,request.getCharacterEncoding());
if (old_params!=null && old_params.size()>0)
{
// Merge parameters.
Iterator iter = old_params.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry entry = (Map.Entry)iter.next();
String name=(String)entry.getKey();
Object values=entry.getValue();
for (int i=0;i<LazyList.size(values);i++)
parameters.add(name, LazyList.get(values, i));
}
}
if (old_query!=null && old_query.length()>0)
query=query+"&"+old_query;
base_request.setParameters(parameters);
base_request.setQueryString(query);
}
ForwardAttributes attr = new ForwardAttributes(old_attr);
attr._requestURI=old_uri;
attr._contextPath=old_context_path;
attr._servletPath=old_servlet_path;
attr._pathInfo=old_path_info;
attr._query=old_query;
base_request.setRequestURI(_uri);
base_request.setContextPath(_contextHandler.getContextPath());
base_request.setAttributes(attr);
base_request.setQueryString(query);
_contextHandler.handle(_path, (HttpServletRequest)request, (HttpServletResponse)response, dispatch);
if (base_request.getConnection().getResponse().isWriting())
{
try {response.getWriter().close();}
catch(IllegalStateException e) { response.getOutputStream().close(); }
}
else
{
try {response.getOutputStream().close();}
catch(IllegalStateException e) { response.getWriter().close(); }
}
}
}
finally
{
base_request.setRequestURI(old_uri);
base_request.setContextPath(old_context_path);
base_request.setServletPath(old_servlet_path);
base_request.setPathInfo(old_path_info);
base_request.setAttributes(old_attr);
base_request.setParameters(old_params);
base_request.setQueryString(old_query);
}
}
|
diff --git a/steps/wordcount/src/test/java/net/sf/okapi/steps/wordcount/WordCountTest.java b/steps/wordcount/src/test/java/net/sf/okapi/steps/wordcount/WordCountTest.java
index 1a0aef3f6..ee8e56f82 100644
--- a/steps/wordcount/src/test/java/net/sf/okapi/steps/wordcount/WordCountTest.java
+++ b/steps/wordcount/src/test/java/net/sf/okapi/steps/wordcount/WordCountTest.java
@@ -1,22 +1,22 @@
package net.sf.okapi.steps.wordcount;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class WordCountTest {
@Before
public void setUp() throws Exception {
}
@Test
public void testStatics() {
assertEquals(5, WordCounter.getCount("Test word count is correct.", "en"));
assertEquals(9, WordCounter.getCount("The quick (\"brown\") fox can't jump 32.3 feet, right?", "en"));
- assertEquals(9, WordCounter.getCount("The quick (�brown�) fox can�t jump 32.3 feet, right?", "en"));
+ assertEquals(9, WordCounter.getCount("The quick (\u201Cbrown\u201D) fox can\u2019t jump 32.3 feet, right?", "en"));
}
}
| true | true |
public void testStatics() {
assertEquals(5, WordCounter.getCount("Test word count is correct.", "en"));
assertEquals(9, WordCounter.getCount("The quick (\"brown\") fox can't jump 32.3 feet, right?", "en"));
assertEquals(9, WordCounter.getCount("The quick (�brown�) fox can�t jump 32.3 feet, right?", "en"));
}
|
public void testStatics() {
assertEquals(5, WordCounter.getCount("Test word count is correct.", "en"));
assertEquals(9, WordCounter.getCount("The quick (\"brown\") fox can't jump 32.3 feet, right?", "en"));
assertEquals(9, WordCounter.getCount("The quick (\u201Cbrown\u201D) fox can\u2019t jump 32.3 feet, right?", "en"));
}
|
diff --git a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OpenALAudio.java b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OpenALAudio.java
index ca1c3e3be..4d81f0c68 100644
--- a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OpenALAudio.java
+++ b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OpenALAudio.java
@@ -1,321 +1,321 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.backends.openal;
import static org.lwjgl.openal.AL10.AL_BUFFER;
import static org.lwjgl.openal.AL10.AL_NO_ERROR;
import static org.lwjgl.openal.AL10.AL_ORIENTATION;
import static org.lwjgl.openal.AL10.AL_PAUSED;
import static org.lwjgl.openal.AL10.AL_PLAYING;
import static org.lwjgl.openal.AL10.AL_POSITION;
import static org.lwjgl.openal.AL10.AL_SOURCE_STATE;
import static org.lwjgl.openal.AL10.AL_STOPPED;
import static org.lwjgl.openal.AL10.AL_VELOCITY;
import static org.lwjgl.openal.AL10.alDeleteSources;
import static org.lwjgl.openal.AL10.alGenSources;
import static org.lwjgl.openal.AL10.alGetError;
import static org.lwjgl.openal.AL10.alGetSourcei;
import static org.lwjgl.openal.AL10.alListener;
import static org.lwjgl.openal.AL10.alSourceStop;
import static org.lwjgl.openal.AL10.alSourcei;
import java.nio.FloatBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.openal.AL;
import org.lwjgl.openal.AL10;
import org.lwjgl.openal.AL11;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.audio.AudioDevice;
import com.badlogic.gdx.audio.AudioRecorder;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.IntArray;
import com.badlogic.gdx.utils.IntMap;
import com.badlogic.gdx.utils.LongMap;
import com.badlogic.gdx.utils.ObjectMap;
/** @author Nathan Sweet */
public class OpenALAudio implements Audio {
private final int deviceBufferSize;
private final int deviceBufferCount;
private IntArray idleSources, allSources;
private LongMap<Integer> soundIdToSource;
private IntMap<Long> sourceToSoundId;
private long nextSoundId = 0;
private ObjectMap<String, Class<? extends OpenALSound>> extensionToSoundClass = new ObjectMap();
private ObjectMap<String, Class<? extends OpenALMusic>> extensionToMusicClass = new ObjectMap();
Array<OpenALMusic> music = new Array(false, 1, OpenALMusic.class);
boolean noDevice = false;
public OpenALAudio () {
this(16, 512, 9);
}
- public OpenALAudio (int simultaneousSources, int deviceBufferSize, int deviceBufferCount) {
+ public OpenALAudio (int simultaneousSources, int deviceBufferCount, int deviceBufferSize) {
this.deviceBufferSize = deviceBufferSize;
this.deviceBufferCount = deviceBufferCount;
registerSound("ogg", Ogg.Sound.class);
registerMusic("ogg", Ogg.Music.class);
registerSound("wav", Wav.Sound.class);
registerMusic("wav", Wav.Music.class);
registerSound("mp3", Mp3.Sound.class);
registerMusic("mp3", Mp3.Music.class);
try {
AL.create();
} catch (LWJGLException ex) {
noDevice = true;
ex.printStackTrace();
return;
}
allSources = new IntArray(false, simultaneousSources);
for (int i = 0; i < simultaneousSources; i++) {
int sourceID = alGenSources();
if (alGetError() != AL_NO_ERROR) break;
allSources.add(sourceID);
}
idleSources = new IntArray(allSources);
soundIdToSource = new LongMap<Integer>();
sourceToSoundId = new IntMap<Long>();
FloatBuffer orientation = (FloatBuffer)BufferUtils.createFloatBuffer(6)
.put(new float[] {0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f}).flip();
alListener(AL_ORIENTATION, orientation);
FloatBuffer velocity = (FloatBuffer)BufferUtils.createFloatBuffer(3).put(new float[] {0.0f, 0.0f, 0.0f}).flip();
alListener(AL_VELOCITY, velocity);
FloatBuffer position = (FloatBuffer)BufferUtils.createFloatBuffer(3).put(new float[] {0.0f, 0.0f, 0.0f}).flip();
alListener(AL_POSITION, position);
}
public void registerSound (String extension, Class<? extends OpenALSound> soundClass) {
if (extension == null) throw new IllegalArgumentException("extension cannot be null.");
if (soundClass == null) throw new IllegalArgumentException("soundClass cannot be null.");
extensionToSoundClass.put(extension, soundClass);
}
public void registerMusic (String extension, Class<? extends OpenALMusic> musicClass) {
if (extension == null) throw new IllegalArgumentException("extension cannot be null.");
if (musicClass == null) throw new IllegalArgumentException("musicClass cannot be null.");
extensionToMusicClass.put(extension, musicClass);
}
public OpenALSound newSound (FileHandle file) {
if (file == null) throw new IllegalArgumentException("file cannot be null.");
Class<? extends OpenALSound> soundClass = extensionToSoundClass.get(file.extension());
if (soundClass == null) throw new GdxRuntimeException("Unknown file extension for sound: " + file);
try {
return soundClass.getConstructor(new Class[] {OpenALAudio.class, FileHandle.class}).newInstance(this, file);
} catch (Exception ex) {
throw new GdxRuntimeException("Error creating sound " + soundClass.getName() + " for file: " + file, ex);
}
}
public OpenALMusic newMusic (FileHandle file) {
if (file == null) throw new IllegalArgumentException("file cannot be null.");
Class<? extends OpenALMusic> musicClass = extensionToMusicClass.get(file.extension());
if (musicClass == null) throw new GdxRuntimeException("Unknown file extension for music: " + file);
try {
return musicClass.getConstructor(new Class[] {OpenALAudio.class, FileHandle.class}).newInstance(this, file);
} catch (Exception ex) {
throw new GdxRuntimeException("Error creating music " + musicClass.getName() + " for file: " + file, ex);
}
}
int obtainSource (boolean isMusic) {
if (noDevice) return 0;
for (int i = 0, n = idleSources.size; i < n; i++) {
int sourceId = idleSources.get(i);
int state = alGetSourcei(sourceId, AL_SOURCE_STATE);
if (state != AL_PLAYING && state != AL_PAUSED) {
if (isMusic) {
idleSources.removeIndex(i);
} else {
if (sourceToSoundId.containsKey(sourceId)) {
long soundId = sourceToSoundId.get(sourceId);
sourceToSoundId.remove(sourceId);
soundIdToSource.remove(soundId);
}
long soundId = nextSoundId++;
sourceToSoundId.put(sourceId, soundId);
soundIdToSource.put(soundId, sourceId);
}
alSourceStop(sourceId);
alSourcei(sourceId, AL_BUFFER, 0);
AL10.alSourcef(sourceId, AL10.AL_GAIN, 1);
AL10.alSourcef(sourceId, AL10.AL_PITCH, 1);
AL10.alSource3f(sourceId, AL10.AL_POSITION, 0, 0, 0);
return sourceId;
}
}
return -1;
}
void freeSource (int sourceID) {
if (noDevice) return;
alSourceStop(sourceID);
alSourcei(sourceID, AL_BUFFER, 0);
if (sourceToSoundId.containsKey(sourceID)) {
long soundId = sourceToSoundId.remove(sourceID);
soundIdToSource.remove(soundId);
}
idleSources.add(sourceID);
}
void freeBuffer (int bufferID) {
if (noDevice) return;
for (int i = 0, n = idleSources.size; i < n; i++) {
int sourceID = idleSources.get(i);
if (alGetSourcei(sourceID, AL_BUFFER) == bufferID) {
if (sourceToSoundId.containsKey(sourceID)) {
long soundId = sourceToSoundId.remove(sourceID);
soundIdToSource.remove(soundId);
}
alSourceStop(sourceID);
alSourcei(sourceID, AL_BUFFER, 0);
}
}
}
void stopSourcesWithBuffer (int bufferID) {
if (noDevice) return;
for (int i = 0, n = idleSources.size; i < n; i++) {
int sourceID = idleSources.get(i);
if (alGetSourcei(sourceID, AL_BUFFER) == bufferID) {
if (sourceToSoundId.containsKey(sourceID)) {
long soundId = sourceToSoundId.remove(sourceID);
soundIdToSource.remove(soundId);
}
alSourceStop(sourceID);
}
}
}
public void update () {
if (noDevice) return;
for (int i = 0; i < music.size; i++)
music.items[i].update();
}
public long getSoundId (int sourceId) {
if (!sourceToSoundId.containsKey(sourceId)) return -1;
return sourceToSoundId.get(sourceId);
}
public void stopSound (long soundId) {
if (!soundIdToSource.containsKey(soundId)) return;
int sourceId = soundIdToSource.get(soundId);
alSourceStop(sourceId);
}
public void setSoundGain (long soundId, float volume) {
if (!soundIdToSource.containsKey(soundId)) return;
int sourceId = soundIdToSource.get(soundId);
AL10.alSourcef(sourceId, AL10.AL_GAIN, volume);
}
public void setSoundLooping (long soundId, boolean looping) {
if (!soundIdToSource.containsKey(soundId)) return;
int sourceId = soundIdToSource.get(soundId);
alSourcei(sourceId, AL10.AL_LOOPING, looping ? AL10.AL_TRUE : AL10.AL_FALSE);
}
public void setSoundPitch (long soundId, float pitch) {
if (!soundIdToSource.containsKey(soundId)) return;
int sourceId = soundIdToSource.get(soundId);
AL10.alSourcef(sourceId, AL10.AL_PITCH, pitch);
}
public void setSoundPan (long soundId, float pan, float volume) {
if (!soundIdToSource.containsKey(soundId)) return;
int sourceId = soundIdToSource.get(soundId);
AL10.alSource3f(sourceId, AL10.AL_POSITION, pan, 0, 0);
}
public void dispose () {
if (noDevice) return;
for (int i = 0, n = allSources.size; i < n; i++) {
int sourceID = allSources.get(i);
int state = alGetSourcei(sourceID, AL_SOURCE_STATE);
if (state != AL_STOPPED) alSourceStop(sourceID);
alDeleteSources(sourceID);
}
sourceToSoundId.clear();
soundIdToSource.clear();
AL.destroy();
while (AL.isCreated()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}
public AudioDevice newAudioDevice (int sampleRate, final boolean isMono) {
if (noDevice) return new AudioDevice() {
@Override
public void writeSamples (float[] samples, int offset, int numSamples) {
}
@Override
public void writeSamples (short[] samples, int offset, int numSamples) {
}
@Override
public void setVolume (float volume) {
}
@Override
public boolean isMono () {
return isMono;
}
@Override
public int getLatency () {
return 0;
}
@Override
public void dispose () {
}
};
return new OpenALAudioDevice(this, sampleRate, isMono, deviceBufferSize, deviceBufferCount);
}
public AudioRecorder newAudioRecorder (int samplingRate, boolean isMono) {
if (noDevice) return new AudioRecorder() {
@Override
public void read (short[] samples, int offset, int numSamples) {
}
@Override
public void dispose () {
}
};
return new JavaSoundAudioRecorder(samplingRate, isMono);
}
}
| true | true |
public OpenALAudio (int simultaneousSources, int deviceBufferSize, int deviceBufferCount) {
this.deviceBufferSize = deviceBufferSize;
this.deviceBufferCount = deviceBufferCount;
registerSound("ogg", Ogg.Sound.class);
registerMusic("ogg", Ogg.Music.class);
registerSound("wav", Wav.Sound.class);
registerMusic("wav", Wav.Music.class);
registerSound("mp3", Mp3.Sound.class);
registerMusic("mp3", Mp3.Music.class);
try {
AL.create();
} catch (LWJGLException ex) {
noDevice = true;
ex.printStackTrace();
return;
}
allSources = new IntArray(false, simultaneousSources);
for (int i = 0; i < simultaneousSources; i++) {
int sourceID = alGenSources();
if (alGetError() != AL_NO_ERROR) break;
allSources.add(sourceID);
}
idleSources = new IntArray(allSources);
soundIdToSource = new LongMap<Integer>();
sourceToSoundId = new IntMap<Long>();
FloatBuffer orientation = (FloatBuffer)BufferUtils.createFloatBuffer(6)
.put(new float[] {0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f}).flip();
alListener(AL_ORIENTATION, orientation);
FloatBuffer velocity = (FloatBuffer)BufferUtils.createFloatBuffer(3).put(new float[] {0.0f, 0.0f, 0.0f}).flip();
alListener(AL_VELOCITY, velocity);
FloatBuffer position = (FloatBuffer)BufferUtils.createFloatBuffer(3).put(new float[] {0.0f, 0.0f, 0.0f}).flip();
alListener(AL_POSITION, position);
}
|
public OpenALAudio (int simultaneousSources, int deviceBufferCount, int deviceBufferSize) {
this.deviceBufferSize = deviceBufferSize;
this.deviceBufferCount = deviceBufferCount;
registerSound("ogg", Ogg.Sound.class);
registerMusic("ogg", Ogg.Music.class);
registerSound("wav", Wav.Sound.class);
registerMusic("wav", Wav.Music.class);
registerSound("mp3", Mp3.Sound.class);
registerMusic("mp3", Mp3.Music.class);
try {
AL.create();
} catch (LWJGLException ex) {
noDevice = true;
ex.printStackTrace();
return;
}
allSources = new IntArray(false, simultaneousSources);
for (int i = 0; i < simultaneousSources; i++) {
int sourceID = alGenSources();
if (alGetError() != AL_NO_ERROR) break;
allSources.add(sourceID);
}
idleSources = new IntArray(allSources);
soundIdToSource = new LongMap<Integer>();
sourceToSoundId = new IntMap<Long>();
FloatBuffer orientation = (FloatBuffer)BufferUtils.createFloatBuffer(6)
.put(new float[] {0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f}).flip();
alListener(AL_ORIENTATION, orientation);
FloatBuffer velocity = (FloatBuffer)BufferUtils.createFloatBuffer(3).put(new float[] {0.0f, 0.0f, 0.0f}).flip();
alListener(AL_VELOCITY, velocity);
FloatBuffer position = (FloatBuffer)BufferUtils.createFloatBuffer(3).put(new float[] {0.0f, 0.0f, 0.0f}).flip();
alListener(AL_POSITION, position);
}
|
diff --git a/tlandroidapp/src/org/opensourcetlapp/tl/SearchFragment.java b/tlandroidapp/src/org/opensourcetlapp/tl/SearchFragment.java
index c7ce0fe..7eeb55b 100644
--- a/tlandroidapp/src/org/opensourcetlapp/tl/SearchFragment.java
+++ b/tlandroidapp/src/org/opensourcetlapp/tl/SearchFragment.java
@@ -1,195 +1,198 @@
package org.opensourcetlapp.tl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.opensourcetlapp.tl.Adapters.MyPostsAdapter;
import org.opensourcetlapp.tl.Structs.PostInfo;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
public class SearchFragment extends ListFragment implements Runnable {
EditText search;
Fragment instance;
ProgressBar progressBar;
SearchHandler handler;
ArrayList<PostInfo> postInfoList = new ArrayList<PostInfo>();
int page = 1;
private boolean mInstanceAlreadySaved;
private Bundle mSavedOutState;
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("search", postInfoList);
mInstanceAlreadySaved = true;
}
public void run() {
try {
TagNode response = TLLib.TagNodeFromURLSearch(new HtmlCleaner(),search.getText().toString(),handler,getActivity());
Object[] tableResults = null;
Object[] nodeList = null;
try {
tableResults = response.evaluateXPath("//table[@width=748]/tbody");
nodeList = ((TagNode)tableResults[tableResults.length - 2]).evaluateXPath("//tr[position()>1]");
TagNode n;
for (Object o : nodeList){
n = (TagNode)o;
if (n.evaluateXPath("./td[3]").length > 0) {
TagNode topicStarter = (TagNode)(n.evaluateXPath("./td[3]"))[0];
TagNode replies = (TagNode)(n.evaluateXPath("./td[4]"))[0];
TagNode lastMessage = (TagNode)(n.evaluateXPath("./td[6]"))[0];
Object [] resourceList = (n.evaluateXPath("./td[2]/a"));
TagNode topic = (TagNode)resourceList[0];
TagNode lastPost = (TagNode)resourceList[resourceList.length-1];
TagNode topicURL = (TagNode)resourceList[0];
String topicURLString = topicURL.getAttributeByName("href");
PostInfo postInfo = new PostInfo();
if (topicStarter.getChildren().iterator().hasNext())
postInfo.topicStarterString = HtmlTools.unescapeHtml(topicStarter.getChildren().iterator().next().toString());
if (replies.getChildren().iterator().hasNext())
postInfo.repliesString = HtmlTools.unescapeHtml(replies.getChildren().iterator().next().toString());
postInfo.lastMessageString = HtmlTools.unescapeHtml(lastMessage.getChildren().get(0).toString());
postInfo.lastMessageString += " " + HtmlTools.unescapeHtml(lastMessage.getChildren().get(2).toString());
postInfo.topicURL = topicURLString;
if (topic.getChildren().iterator().hasNext())
postInfo.topicString = HtmlTools.unescapeHtml(topic.getChildren().iterator().next().toString());
postInfoList.add(postInfo);
}
}
} catch (XPatherException e) {
Log.d("SearchFragment", "couldn't retrieve results tables");
e.printStackTrace();
+ } catch (ArrayIndexOutOfBoundsException e) {
+ Log.d("SearchFragment", "no results table");
+ e.printStackTrace();
}
handler.sendEmptyMessage(0);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onResume() {
super.onResume();
if (!postInfoList.isEmpty())
getListView().setAdapter(new MyPostsAdapter(postInfoList, getActivity()));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (null == savedInstanceState && null != mSavedOutState) {
savedInstanceState = mSavedOutState;
}
mInstanceAlreadySaved = false;
if (savedInstanceState != null) {
postInfoList = savedInstanceState.getParcelableArrayList("search");
}
instance = this;
View view = inflater.inflate(R.layout.search, container,false);
search = (EditText)view.findViewById(R.id.search);
progressBar = (ProgressBar)view.findViewById(R.id.progressBar);
search.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
postInfoList = new ArrayList<PostInfo>();
progressBar.setVisibility(View.VISIBLE);
handler = new SearchHandler(progressBar);
page = 1;
new Thread((Runnable)instance).start();
return true;
}
return false;
}
});
return view;
}
public class SearchHandler extends Handler {
private ProgressBar bar;
public SearchHandler(ProgressBar bar) {
this.bar = bar;
}
@Override
public void handleMessage(Message msg) {
if (msg.what == 0 ) {
getListView().setAdapter(new MyPostsAdapter(postInfoList, getActivity()));
bar.setVisibility(View.INVISIBLE);
} else {
super.handleMessage(msg);
}
}
}
@Override
public void onStop()
{
if (!mInstanceAlreadySaved)
{
mSavedOutState = new Bundle();
onSaveInstanceState( mSavedOutState );
}
super.onStop();
}
public void onListItemClick(ListView l, View v, int position, long id) {
PostInfo postInfo = postInfoList.get((int) id);
String postURL = "/forum/"+postInfo.topicURL;
String postTopic = postInfo.topicString;
boolean postLocked = postInfo.locked;
Intent intent = new Intent().setClass(getActivity(), ShowThread.class);
intent.putExtra("postURL", postURL);
intent.putExtra("postTopic", postTopic);
intent.putExtra("postLocked", false);
startActivity(intent);
}
}
| true | true |
public void run() {
try {
TagNode response = TLLib.TagNodeFromURLSearch(new HtmlCleaner(),search.getText().toString(),handler,getActivity());
Object[] tableResults = null;
Object[] nodeList = null;
try {
tableResults = response.evaluateXPath("//table[@width=748]/tbody");
nodeList = ((TagNode)tableResults[tableResults.length - 2]).evaluateXPath("//tr[position()>1]");
TagNode n;
for (Object o : nodeList){
n = (TagNode)o;
if (n.evaluateXPath("./td[3]").length > 0) {
TagNode topicStarter = (TagNode)(n.evaluateXPath("./td[3]"))[0];
TagNode replies = (TagNode)(n.evaluateXPath("./td[4]"))[0];
TagNode lastMessage = (TagNode)(n.evaluateXPath("./td[6]"))[0];
Object [] resourceList = (n.evaluateXPath("./td[2]/a"));
TagNode topic = (TagNode)resourceList[0];
TagNode lastPost = (TagNode)resourceList[resourceList.length-1];
TagNode topicURL = (TagNode)resourceList[0];
String topicURLString = topicURL.getAttributeByName("href");
PostInfo postInfo = new PostInfo();
if (topicStarter.getChildren().iterator().hasNext())
postInfo.topicStarterString = HtmlTools.unescapeHtml(topicStarter.getChildren().iterator().next().toString());
if (replies.getChildren().iterator().hasNext())
postInfo.repliesString = HtmlTools.unescapeHtml(replies.getChildren().iterator().next().toString());
postInfo.lastMessageString = HtmlTools.unescapeHtml(lastMessage.getChildren().get(0).toString());
postInfo.lastMessageString += " " + HtmlTools.unescapeHtml(lastMessage.getChildren().get(2).toString());
postInfo.topicURL = topicURLString;
if (topic.getChildren().iterator().hasNext())
postInfo.topicString = HtmlTools.unescapeHtml(topic.getChildren().iterator().next().toString());
postInfoList.add(postInfo);
}
}
} catch (XPatherException e) {
Log.d("SearchFragment", "couldn't retrieve results tables");
e.printStackTrace();
}
handler.sendEmptyMessage(0);
} catch (IOException e) {
e.printStackTrace();
}
}
|
public void run() {
try {
TagNode response = TLLib.TagNodeFromURLSearch(new HtmlCleaner(),search.getText().toString(),handler,getActivity());
Object[] tableResults = null;
Object[] nodeList = null;
try {
tableResults = response.evaluateXPath("//table[@width=748]/tbody");
nodeList = ((TagNode)tableResults[tableResults.length - 2]).evaluateXPath("//tr[position()>1]");
TagNode n;
for (Object o : nodeList){
n = (TagNode)o;
if (n.evaluateXPath("./td[3]").length > 0) {
TagNode topicStarter = (TagNode)(n.evaluateXPath("./td[3]"))[0];
TagNode replies = (TagNode)(n.evaluateXPath("./td[4]"))[0];
TagNode lastMessage = (TagNode)(n.evaluateXPath("./td[6]"))[0];
Object [] resourceList = (n.evaluateXPath("./td[2]/a"));
TagNode topic = (TagNode)resourceList[0];
TagNode lastPost = (TagNode)resourceList[resourceList.length-1];
TagNode topicURL = (TagNode)resourceList[0];
String topicURLString = topicURL.getAttributeByName("href");
PostInfo postInfo = new PostInfo();
if (topicStarter.getChildren().iterator().hasNext())
postInfo.topicStarterString = HtmlTools.unescapeHtml(topicStarter.getChildren().iterator().next().toString());
if (replies.getChildren().iterator().hasNext())
postInfo.repliesString = HtmlTools.unescapeHtml(replies.getChildren().iterator().next().toString());
postInfo.lastMessageString = HtmlTools.unescapeHtml(lastMessage.getChildren().get(0).toString());
postInfo.lastMessageString += " " + HtmlTools.unescapeHtml(lastMessage.getChildren().get(2).toString());
postInfo.topicURL = topicURLString;
if (topic.getChildren().iterator().hasNext())
postInfo.topicString = HtmlTools.unescapeHtml(topic.getChildren().iterator().next().toString());
postInfoList.add(postInfo);
}
}
} catch (XPatherException e) {
Log.d("SearchFragment", "couldn't retrieve results tables");
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
Log.d("SearchFragment", "no results table");
e.printStackTrace();
}
handler.sendEmptyMessage(0);
} catch (IOException e) {
e.printStackTrace();
}
}
|
diff --git a/src/com/sonyericsson/chkbugreport/ps/PSScanner.java b/src/com/sonyericsson/chkbugreport/ps/PSScanner.java
index cb3707d..69750f4 100644
--- a/src/com/sonyericsson/chkbugreport/ps/PSScanner.java
+++ b/src/com/sonyericsson/chkbugreport/ps/PSScanner.java
@@ -1,178 +1,178 @@
/*
* Copyright (C) 2011 Sony Ericsson Mobile Communications AB
* Copyright (C) 2012 Sony Mobile Communications AB
*
* This file is part of ChkBugReport.
*
* ChkBugReport 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.
*
* ChkBugReport 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 ChkBugReport. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sonyericsson.chkbugreport.ps;
import com.sonyericsson.chkbugreport.BugReportModule;
import com.sonyericsson.chkbugreport.ProcessRecord;
import com.sonyericsson.chkbugreport.Section;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PSScanner {
private BugReportModule mBr;
private static final String HEADER_1 = "USER PID PPID VSIZE RSS PCY WCHAN PC NAME";
private static final Pattern PATTERN_1 = Pattern.compile("([a-z0-9_]+) *([0-9]+) *([0-9]+) *([0-9]+) *([0-9]+) *(fg|bg|un)? ([0-9-a-f]{8}) ([0-9-a-f]{8}) (.) (.*)");
private static final String HEADER_2 = "USER PID PPID VSIZE RSS PRIO NICE RTPRI SCHED PCY WCHAN PC NAME";
private static final Pattern PATTERN_2 = Pattern.compile("([a-z0-9_]+) *([0-9]+) *([0-9]+) *([0-9]+) *([0-9]+) *([0-9-]+) *([0-9-]+) *([0-9-]+) *([0-9-]+) *(fg|bg|un)? ([0-9-a-f]{8}) ([0-9-a-f]{8}) (.) (.*)");
public PSScanner(BugReportModule br) {
mBr = br;
}
public PSRecords run() {
PSRecords ret = readPS(Section.PROCESSES_AND_THREADS);
if (ret == null) {
ret = readPS(Section.PROCESSES);
}
return ret;
}
private PSRecords readPS(String sectionName) {
Section ps = mBr.findSection(sectionName);
if (ps == null) {
mBr.printErr(3, "Cannot find section: " + sectionName + " (ignoring it)");
return null;
}
// Process the PS section
PSRecords ret = new PSRecords();
Pattern p = null;
int lineIdx = 0, idxPid = -1, idxPPid = -1, idxPcy = -1, idxName = -1, idxNice = -1;
- for (int tries = 0; tries < 10; tries++) {
+ for (int tries = 0; tries < 10 && lineIdx < ps.getLineCount(); tries++) {
String buff = ps.getLine(lineIdx++);
if (buff.equals(HEADER_1)) {
p = PATTERN_1;
idxPid = 2;
idxPPid = 3;
idxPcy = 6;
idxName = 10;
break;
}
if (buff.equals(HEADER_2)) {
p = PATTERN_2;
idxPid = 2;
idxPPid = 3;
idxNice = 7;
idxPcy = 10;
idxName = 14;
break;
}
}
if (p == null) {
mBr.printErr(4, "Could not find header in ps output");
return null;
}
// Now read and process every line
int pidZygote = -1;
int cnt = ps.getLineCount();
for (int i = lineIdx; i < cnt; i++) {
String buff = ps.getLine(i);
if (buff.startsWith("[")) break;
Matcher m = p.matcher(buff);
if (!m.matches()) {
mBr.printErr(4, "Error parsing line: " + buff);
continue;
}
int pid = -1;
if (idxPid >= 0) {
String sPid = m.group(idxPid);
try {
pid = Integer.parseInt(sPid);
} catch (NumberFormatException nfe) {
mBr.printErr(4, "Error parsing pid from: " + sPid);
break;
}
}
// Extract ppid
int ppid = -1;
if (idxPPid >= 0) {
String sPid = m.group(idxPPid);
try {
ppid = Integer.parseInt(sPid);
} catch (NumberFormatException nfe) {
mBr.printErr(4, "Error parsing ppid from: " + sPid);
break;
}
}
// Extract nice
int nice = PSRecord.NICE_UNKNOWN;
if (idxNice >= 0) {
String sNice = m.group(idxNice);
try {
nice = Integer.parseInt(sNice);
} catch (NumberFormatException nfe) {
mBr.printErr(4, "Error parsing nice from: " + sNice);
break;
}
}
// Extract scheduler policy
int pcy = PSRecord.PCY_UNKNOWN;
if (idxPcy >= 0) {
String sPcy = m.group(idxPcy);
if ("fg".equals(sPcy)) {
pcy = PSRecord.PCY_NORMAL;
} else if ("bg".equals(sPcy)) {
pcy = PSRecord.PCY_BATCH;
} else if ("un".equals(sPcy)) {
pcy = PSRecord.PCY_FIFO;
} else {
pcy = PSRecord.PCY_OTHER;
}
}
// Exctract name
String name = "";
if (idxName >= 0) {
name = m.group(idxName);
}
// Fix the name
ret.put(pid, new PSRecord(pid, ppid, nice, pcy, name));
// Check if we should create a ProcessRecord for this
if (pidZygote == -1 && name.equals("zygote")) {
pidZygote = pid;
}
ProcessRecord pr = mBr.getProcessRecord(pid, true, false);
pr.suggestName(name, 10);
}
// Build tree structure as well
for (PSRecord psr : ret) {
int ppid = psr.mPPid;
PSRecord parent = ret.getPSRecord(ppid);
if (parent == null) {
parent = ret.getPSTree();
}
parent.mChildren.add(psr);
psr.mParent = parent;
}
return ret;
}
}
| true | true |
private PSRecords readPS(String sectionName) {
Section ps = mBr.findSection(sectionName);
if (ps == null) {
mBr.printErr(3, "Cannot find section: " + sectionName + " (ignoring it)");
return null;
}
// Process the PS section
PSRecords ret = new PSRecords();
Pattern p = null;
int lineIdx = 0, idxPid = -1, idxPPid = -1, idxPcy = -1, idxName = -1, idxNice = -1;
for (int tries = 0; tries < 10; tries++) {
String buff = ps.getLine(lineIdx++);
if (buff.equals(HEADER_1)) {
p = PATTERN_1;
idxPid = 2;
idxPPid = 3;
idxPcy = 6;
idxName = 10;
break;
}
if (buff.equals(HEADER_2)) {
p = PATTERN_2;
idxPid = 2;
idxPPid = 3;
idxNice = 7;
idxPcy = 10;
idxName = 14;
break;
}
}
if (p == null) {
mBr.printErr(4, "Could not find header in ps output");
return null;
}
// Now read and process every line
int pidZygote = -1;
int cnt = ps.getLineCount();
for (int i = lineIdx; i < cnt; i++) {
String buff = ps.getLine(i);
if (buff.startsWith("[")) break;
Matcher m = p.matcher(buff);
if (!m.matches()) {
mBr.printErr(4, "Error parsing line: " + buff);
continue;
}
int pid = -1;
if (idxPid >= 0) {
String sPid = m.group(idxPid);
try {
pid = Integer.parseInt(sPid);
} catch (NumberFormatException nfe) {
mBr.printErr(4, "Error parsing pid from: " + sPid);
break;
}
}
// Extract ppid
int ppid = -1;
if (idxPPid >= 0) {
String sPid = m.group(idxPPid);
try {
ppid = Integer.parseInt(sPid);
} catch (NumberFormatException nfe) {
mBr.printErr(4, "Error parsing ppid from: " + sPid);
break;
}
}
// Extract nice
int nice = PSRecord.NICE_UNKNOWN;
if (idxNice >= 0) {
String sNice = m.group(idxNice);
try {
nice = Integer.parseInt(sNice);
} catch (NumberFormatException nfe) {
mBr.printErr(4, "Error parsing nice from: " + sNice);
break;
}
}
// Extract scheduler policy
int pcy = PSRecord.PCY_UNKNOWN;
if (idxPcy >= 0) {
String sPcy = m.group(idxPcy);
if ("fg".equals(sPcy)) {
pcy = PSRecord.PCY_NORMAL;
} else if ("bg".equals(sPcy)) {
pcy = PSRecord.PCY_BATCH;
} else if ("un".equals(sPcy)) {
pcy = PSRecord.PCY_FIFO;
} else {
pcy = PSRecord.PCY_OTHER;
}
}
// Exctract name
String name = "";
if (idxName >= 0) {
name = m.group(idxName);
}
// Fix the name
ret.put(pid, new PSRecord(pid, ppid, nice, pcy, name));
// Check if we should create a ProcessRecord for this
if (pidZygote == -1 && name.equals("zygote")) {
pidZygote = pid;
}
ProcessRecord pr = mBr.getProcessRecord(pid, true, false);
pr.suggestName(name, 10);
}
// Build tree structure as well
for (PSRecord psr : ret) {
int ppid = psr.mPPid;
PSRecord parent = ret.getPSRecord(ppid);
if (parent == null) {
parent = ret.getPSTree();
}
parent.mChildren.add(psr);
psr.mParent = parent;
}
return ret;
}
|
private PSRecords readPS(String sectionName) {
Section ps = mBr.findSection(sectionName);
if (ps == null) {
mBr.printErr(3, "Cannot find section: " + sectionName + " (ignoring it)");
return null;
}
// Process the PS section
PSRecords ret = new PSRecords();
Pattern p = null;
int lineIdx = 0, idxPid = -1, idxPPid = -1, idxPcy = -1, idxName = -1, idxNice = -1;
for (int tries = 0; tries < 10 && lineIdx < ps.getLineCount(); tries++) {
String buff = ps.getLine(lineIdx++);
if (buff.equals(HEADER_1)) {
p = PATTERN_1;
idxPid = 2;
idxPPid = 3;
idxPcy = 6;
idxName = 10;
break;
}
if (buff.equals(HEADER_2)) {
p = PATTERN_2;
idxPid = 2;
idxPPid = 3;
idxNice = 7;
idxPcy = 10;
idxName = 14;
break;
}
}
if (p == null) {
mBr.printErr(4, "Could not find header in ps output");
return null;
}
// Now read and process every line
int pidZygote = -1;
int cnt = ps.getLineCount();
for (int i = lineIdx; i < cnt; i++) {
String buff = ps.getLine(i);
if (buff.startsWith("[")) break;
Matcher m = p.matcher(buff);
if (!m.matches()) {
mBr.printErr(4, "Error parsing line: " + buff);
continue;
}
int pid = -1;
if (idxPid >= 0) {
String sPid = m.group(idxPid);
try {
pid = Integer.parseInt(sPid);
} catch (NumberFormatException nfe) {
mBr.printErr(4, "Error parsing pid from: " + sPid);
break;
}
}
// Extract ppid
int ppid = -1;
if (idxPPid >= 0) {
String sPid = m.group(idxPPid);
try {
ppid = Integer.parseInt(sPid);
} catch (NumberFormatException nfe) {
mBr.printErr(4, "Error parsing ppid from: " + sPid);
break;
}
}
// Extract nice
int nice = PSRecord.NICE_UNKNOWN;
if (idxNice >= 0) {
String sNice = m.group(idxNice);
try {
nice = Integer.parseInt(sNice);
} catch (NumberFormatException nfe) {
mBr.printErr(4, "Error parsing nice from: " + sNice);
break;
}
}
// Extract scheduler policy
int pcy = PSRecord.PCY_UNKNOWN;
if (idxPcy >= 0) {
String sPcy = m.group(idxPcy);
if ("fg".equals(sPcy)) {
pcy = PSRecord.PCY_NORMAL;
} else if ("bg".equals(sPcy)) {
pcy = PSRecord.PCY_BATCH;
} else if ("un".equals(sPcy)) {
pcy = PSRecord.PCY_FIFO;
} else {
pcy = PSRecord.PCY_OTHER;
}
}
// Exctract name
String name = "";
if (idxName >= 0) {
name = m.group(idxName);
}
// Fix the name
ret.put(pid, new PSRecord(pid, ppid, nice, pcy, name));
// Check if we should create a ProcessRecord for this
if (pidZygote == -1 && name.equals("zygote")) {
pidZygote = pid;
}
ProcessRecord pr = mBr.getProcessRecord(pid, true, false);
pr.suggestName(name, 10);
}
// Build tree structure as well
for (PSRecord psr : ret) {
int ppid = psr.mPPid;
PSRecord parent = ret.getPSRecord(ppid);
if (parent == null) {
parent = ret.getPSTree();
}
parent.mChildren.add(psr);
psr.mParent = parent;
}
return ret;
}
|
diff --git a/com/nijikokun/bukkit/General/iListen.java b/com/nijikokun/bukkit/General/iListen.java
index d62e058..95384e3 100644
--- a/com/nijikokun/bukkit/General/iListen.java
+++ b/com/nijikokun/bukkit/General/iListen.java
@@ -1,797 +1,797 @@
package com.nijikokun.bukkit.General;
import com.nijikokun.bukkit.Permissions.Permissions;
import com.nijikokun.bukkit.iConomy.iConomy;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;
import org.bukkit.World;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.plugin.InvalidDescriptionException;
import org.bukkit.plugin.InvalidPluginException;
import org.bukkit.plugin.Plugin;
import net.minecraft.server.WorldServer;
import org.bukkit.Location;
import org.bukkit.craftbukkit.CraftWorld;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
* General 1.1 & Code from iConomy 2.x
* Coded while listening to Avenged Sevenfold - A little piece of heaven <3
* Copyright (C) 2011 Nijikokun <[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 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/>.
*/
/**
* iListen.java
* <br /><br />
* Listens for calls from hMod, and reacts accordingly.
*
* @author Nijikokun <[email protected]>
*/
public class iListen extends PlayerListener {
private static final Logger log = Logger.getLogger("Minecraft");
private ArrayList<String> lines = new ArrayList<String>();
/*
* Miscellaneous things required.
*/
public Misc Misc = new Misc();
public HashMap<Player, String> AFK = new HashMap<Player, String>();
public List<String> Commands = new ArrayList<String>();
public static General plugin;
public WorldServer server;
public iListen(General instance) {
plugin = instance;
}
private Location spawn(Player player) {
double x = (server.m + 0.5D);
double y = server.e(this.server.m, this.server.o) + 1.5D;
double z = server.o + 0.5D;
float rotX = 0.0F;
float rotY = 0.0F;
return new Location(player.getWorld(), x, y, z, rotX, rotY);
}
public long getTime() {
return plugin.getServer().getTime();
}
public long getRelativeTime() {
return (getTime() % 24000);
}
public long getStartTime() {
return (getTime()-getRelativeTime());
}
public void setTime(long time) {
plugin.getServer().setTime(time);
}
private void setRelativeTime(long time) {
long margin = (time-getTime()) % 24000;
if (margin < 0) {
margin += 24000;
}
plugin.getServer().setTime(getTime()+margin);
}
protected boolean teleport(String who, String to) {
Player destination = Misc.playerMatch(to);
if (who.equalsIgnoreCase("*")) {
Player[] players = plugin.getServer().getOnlinePlayers();
for (Player player : players) {
if (!player.equals(destination)) {
player.teleportTo(destination.getLocation());
}
}
return true;
} else if (who.contains(",")) {
String[] players = who.split(",");
for (String name : players) {
Player player = Misc.playerMatch(name);
if ((player == null) || (destination == null)) {
continue;
} else {
if (!player.equals(destination)) {
player.teleportTo(destination.getLocation());
}
}
}
return true;
} else {
Player player = Misc.playerMatch(who);
if ((player == null) || (destination == null)) {
return false;
} else {
player.teleportTo(destination.getLocation());
return true;
}
}
}
private String getDirection(double degrees) {
if (0 <= degrees && degrees < 22.5) {
return "N";
} else if (22.5 <= degrees && degrees < 67.5) {
return "NE";
} else if (67.5 <= degrees && degrees < 112.5) {
return "E";
} else if (112.5 <= degrees && degrees < 157.5) {
return "SE";
} else if (157.5 <= degrees && degrees < 202.5) {
return "S";
} else if (202.5 <= degrees && degrees < 247.5) {
return "SW";
} else if (247.5 <= degrees && degrees < 292.5) {
return "W";
} else if (292.5 <= degrees && degrees < 337.5) {
return "NW";
} else if (337.5 <= degrees && degrees < 360.0) {
return "N";
} else {
return "ERR";
}
}
public boolean isAFK(Player player) {
return AFK.containsKey(player);
}
public void AFK(Player player, String message) {
AFK.put(player, message);
}
public void unAFK(Player player) {
AFK.remove(player);
}
public String[] readMotd() {
ArrayList<String> motd = new ArrayList<String>();
try {
BufferedReader in = new BufferedReader(new FileReader(plugin.getDataFolder() + File.separator + "general.motd"));
String str;
while ((str = in.readLine()) != null) {
motd.add(str);
}
in.close();
} catch (IOException e) { }
return motd.toArray(new String[]{});
}
public String[] read_commands() {
try {
BufferedReader in = new BufferedReader(new FileReader(plugin.getDataFolder() + File.separator + "general.help"));
String str;
while ((str = in.readLine()) != null) {
if(!lines.contains(str)) {
lines.add(str);
} else {
continue;
}
}
in.close();
} catch (IOException e) { }
return lines.toArray(new String[]{});
}
public void print_commands(int page) {
String[] commands = read_commands();
int amount = 0;
if (page > 0) {
amount = (page - 1) * 7;
} else {
amount = 0;
}
Messaging.send("&dHelp &f(&dPage &f" + (page != 0 ? page : "1") + "&d of&f " + (int)Math.ceil((double)commands.length/7D) + "&d) [] = required, () = optional:");
try {
for (int i = amount; i < amount + 7; i++) {
if (commands.length > i) {
Messaging.send(commands[i]);
}
}
} catch (NumberFormatException ex) {
Messaging.send("&cNot a valid page number.");
}
}
public void register_command(String command, String help) {
if(!Commands.contains(command.replace("|", "&5|&f") + help)) {
Commands.add(command.replace("|", "&5|&f") + help);
}
}
public void register_custom_command(String command) {
if(!Commands.contains(command)) {
Commands.add(command);
}
}
public void save_command(String command, String help) {
if(!Commands.contains(command + " &5-&3 " + help)) {
Commands.add(command + " &5-&3 " + help);
}
}
public void save_custom_command(String command) {
if(!Commands.contains(command)) {
Commands.add(command);
}
}
public void remove_command(String command, String help) {
if(Commands.contains(command.replace("|", "&5|&f") + " &5-&3 " + help)) {
Commands.remove(command.replace("|", "&5|&f") + " &5-&3 " + help);
} else {
// General.log.info("Help command registry does not contain "+command+" to remove!");
}
}
public void remove_custom_command(String command_line) {
if(Commands.contains(command_line)) {
Commands.remove(command_line);
} else {
// General.log.info("Help command registry does not contain "+command_line+" to remove!");
}
}
@Override
public void onPlayerJoin(PlayerEvent event) {
Player player = event.getPlayer();
String[] motd = readMotd();
if(motd == null || motd.length < 1) { return; }
String location = (int)player.getLocation().getX() +"x, " + (int)player.getLocation().getY() +"y, " + (int)player.getLocation().getZ() +"z";
String ip = player.getAddress().getAddress().getHostAddress();
String balance = "";
Plugin test = plugin.getServer().getPluginManager().getPlugin("iConomy");
if(test != null) {
iConomy iConomy = (iConomy)test;
balance = iConomy.db.get_balance(player.getName()) + " " + iConomy.currency;
}
for(String line : motd) {
Messaging.send(
player,
Messaging.argument(
line,
new String[]{
"+dname,+d", "+name,+n", "+location,+l", "+health,+h", "+ip", "+balance", "+online"
},
new String[]{
player.getDisplayName(),
player.getName(),
location,
Misc.string(player.getHealth()),
ip,
balance,
Misc.string(plugin.getServer().getOnlinePlayers().length)
}
)
);
}
}
/**
* Commands sent from in game to us.
*
* @param player The player who sent the command.
* @param split The input line split by spaces.
* @return <code>boolean</code> - True denotes that the command existed, false the command doesn't.
*/
@Override
public void onPlayerCommand(PlayerChatEvent event) {
String[] split = event.getMessage().split(" ");
Player player = event.getPlayer();
World world = player.getWorld();
server = ((CraftWorld)world).getHandle();
Messaging.save(player);
String base = split[0];
if((!event.isCancelled()) && Misc.isEither(base, "/help", "/?")) {
int page = 0;
if (split.length >= 2) {
try {
page = Integer.parseInt(split[1]);
} catch (NumberFormatException ex) {
Messaging.send("&cNot a valid page number."); event.setCancelled(true);
return;
}
}
print_commands(page); event.setCancelled(true);
}
if((!event.isCancelled()) && Misc.is(base, "/setspawn")) {
if (!General.Permissions.Security.permission(player, "general.spawn.set")) {
return;
}
server.m = (int)Math.ceil(player.getLocation().getX());
server.o = (int)Math.ceil(player.getLocation().getZ());
Messaging.send("&eSpawn position changed to where you are standing.");
}
if(Misc.is(base, "/spawn")) {
if (!General.Permissions.Security.permission(player, "general.spawn")) {
return;
}
player.teleportTo(spawn(player));
}
if((!event.isCancelled()) && Misc.is(base, "/motd")) {
String[] motd = readMotd();
if(motd == null || motd.length < 1) { return; }
String location = (int)player.getLocation().getX() +"x, " + (int)player.getLocation().getY() +"y, " + (int)player.getLocation().getZ() +"z";
String ip = player.getAddress().getAddress().getHostAddress();
String balance = "";
Plugin test = plugin.getServer().getPluginManager().getPlugin("iConomy");
if(test != null) {
iConomy iConomy = (iConomy)test;
balance = iConomy.db.get_balance(player.getName()) + " " + iConomy.currency;
}
for(String line : motd) {
Messaging.send(
player,
Messaging.argument(
line,
new String[]{
"+dname,+d", "+name,+n", "+location,+l", "+health,+h", "+ip", "+balance", "+online"
},
new String[]{
player.getDisplayName(),
player.getName(),
location,
Misc.string(player.getHealth()),
ip,
balance,
Misc.string(plugin.getServer().getOnlinePlayers().length)
}
)
);
}
}
if(Misc.isEither(base, "/tp", "/teleport")) {
if (!General.Permissions.Security.permission(player, "general.teleport")) {
return;
}
if (split.length == 2) {
String to = split[1];
if (to.equalsIgnoreCase("*")) {
Messaging.send("&cIncorrect usage of wildchar *");
} else if (to.contains(",")) {
Messaging.send("&cIncorrect usage of multiple players.");
} else {
if (!teleport(player.getName(), to)) {
Messaging.send("&cCannot find destination player: &f" + to);
}
}
} else if (split.length == 3) {
String who = split[1];
String to = split[2];
if (to.equalsIgnoreCase("*")) {
Messaging.send("&cIncorrect usage of wildchar *");
} else if (to.contains(",")) {
Messaging.send("&cIncorrect usage of multiple players.");
} else {
if (!teleport(who, to)) {
Messaging.send("&cCould not teleport " + who + " to " + to + ".");
}
}
} else {
Messaging.send("&c------ &f/tp help&c ------");
Messaging.send("&c/tp [player] &f-&c Teleport to a player");
Messaging.send("&c/tp [player] [to] &f-&c Teleport player to another player");
Messaging.send("&c/tp [player,...] [to] &f-&c Teleport players to another player");
Messaging.send("&c/tp * [to] &f-&c Teleport everyone to another player");
}
}
if(Misc.isEither(base, "/s", "/tphere")) {
if (!General.Permissions.Security.permission(player, "general.teleport.here")) {
return;
}
- if (split.length < 1) {
+ if (split.length < 2) {
Messaging.send("&cCorrect usage is:&f /s [player] &cor&f /tphere [player]");
return;
}
Player who = Misc.playerMatch(split[1]);
- if (player != null) {
+ if (who != null) {
if (who.getName().equalsIgnoreCase(player.getName())) {
Messaging.send("&cWow look at that! You teleported yourself to yourself!");
return;
}
log.info(player.getName() + " teleported " + who.getName() + " to their self.");
who.teleportTo(player.getLocation());
} else {
Messaging.send("&cCan't find user " + split[1] + ".");
}
}
if((!event.isCancelled()) && Misc.is(base, "/getpos")) {
Messaging.send("Pos X: " + player.getLocation().getX() + " Y: " + player.getLocation().getY() + " Z: " + player.getLocation().getZ());
Messaging.send("Rotation: " + player.getLocation().getYaw() + " Pitch: " + player.getLocation().getPitch());
double degreeRotation = ((player.getLocation().getYaw() - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
Messaging.send("Compass: " + getDirection(degreeRotation) + " (" + (Math.round(degreeRotation * 10) / 10.0) + ")");
}
if(Misc.is(base, "/compass")) {
double degreeRotation = ((player.getLocation().getYaw() - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
Messaging.send("&cCompass: " + getDirection(degreeRotation));
}
if(Misc.isEither(base, "/afk", "/away")) {
if ((AFK != null || !AFK.isEmpty()) && isAFK(player)) {
Messaging.send("&7You have been marked as back.");
unAFK(player);
} else {
Messaging.send("&7You are now currently marked as away.");
String reason = "AFK";
if(split.length >= 2) {
reason = Misc.combineSplit(1, split, " ");
}
AFK(player, reason);
}
}
if(Misc.isEither(base, "/msg", "/tell")) {
if (split.length < 3) {
Messaging.send("&cCorrect usage is: /msg [player] [message]");
event.setCancelled(true);
return;
}
Player who = Misc.playerMatch(split[1]);
if (who != null) {
if (who.getName().equals(player.getName())) {
Messaging.send("&cYou can't message yourself!");
event.setCancelled(true);
return;
}
Messaging.send("(MSG) <" + player.getName() + "> " + Misc.combineSplit(2, split, " "));
Messaging.send(who, "(MSG) <" + player.getName() + "> " + Misc.combineSplit(2, split, " "));
if (isAFK(who)) {
Messaging.send("&7This player is currently away.");
Messaging.send("&7Reason: " + AFK.get(player));
}
} else {
Messaging.send("&cCouldn't find player " + split[1]);
}
}
if(Misc.isEither(base, "/i", "/give")) {
if (!General.Permissions.Security.permission(player, "general.items")) {
return;
}
if (split.length < 2) {
Messaging.send("&cCorrect usage is: /i [item|player](:type) [item|amount] (amount)"); return;
}
int itemId = 0;
int amount = 1;
int dataType = -1;
Player who = null;
try {
if(split[1].contains(":")) {
String[] data = split[1].split(":");
try {
dataType = Integer.valueOf(data[1]);
} catch (NumberFormatException e) { dataType = -1; }
itemId = Items.validate(data[0]);
} else {
itemId = Items.validate(split[1]);
}
if(itemId == -1) {
who = Misc.playerMatch(split[1]);
}
} catch(NumberFormatException e) {
who = Misc.playerMatch(split[1]);
}
if((itemId == 0 || itemId == -1) && who != null) {
String i = split[2];
if(i.contains(":")) {
String[] data = i.split(":");
try {
dataType = Integer.valueOf(data[1]);
} catch (NumberFormatException e) { dataType = -1; }
i = data[0];
}
itemId = Items.validate(i);
if(dataType == -1) {
dataType = Items.validateGrabType(i);
}
}
if(itemId == -1 || itemId == 0) {
Messaging.send("&cInvalid item."); return;
}
if(dataType != -1) {
if(!Items.validateType(itemId, dataType)) {
Messaging.send("&f"+dataType+"&c is not a valid data type for &f"+Items.name(itemId)+"&c."); return;
}
}
if(split.length >= 3 && who == null) {
try {
amount = Integer.valueOf(split[2]);
} catch(NumberFormatException e) { amount = 1; }
} else if (split.length >= 4) {
if(who != null) {
try {
amount = Integer.valueOf(split[3]);
} catch(NumberFormatException e) { amount = 1; }
} else {
who = Misc.playerMatch(split[3]);
}
}
if(who == null) {
who = player;
}
int slot = who.getInventory().firstEmpty();
if(dataType != -1) {
if(slot < 0) {
who.getWorld().dropItem(who.getLocation(), new ItemStack(itemId, amount, ((byte)dataType)));
} else {
who.getInventory().addItem(new ItemStack(itemId, amount, ((byte)dataType)));
}
} else {
if(slot < 0) {
who.getWorld().dropItem(who.getLocation(), new ItemStack(itemId, amount));
} else {
who.getInventory().addItem(new ItemStack(itemId, amount));
}
}
if(who.getName().equals(player.getName())) {
Messaging.send(who, "&2Enjoy! Giving &f"+amount+"&2 of &f"+Items.name(itemId)+"&2.");
} else {
Messaging.send(who, "&2Enjoy the gift! &f"+amount+"&2 of &f"+Items.name(itemId)+"&2. c:!");
}
event.setCancelled(true);
}
if(Misc.is(base, "/time")) {
if (!General.Permissions.Security.permission(player, "general.time")) {
return;
}
long time = getTime();
long timeRelative = getRelativeTime();
long timeStart = getStartTime();
if(split.length < 2) {
int hours = (int)((time / 1000+8) % 24);
int minutes = (((int)(time % 1000)) / 1000) * 60;
Messaging.send("&cTime: "+hours+":"+minutes);
} else if (split.length == 2) {
String command = split[1];
if (Misc.is(command, "help")) {
Messaging.send("&c-------- /time help --------");
Messaging.send("&c/time &f-&c Shows relative time");
Messaging.send("&c/time day &f-&c Turns time to day");
Messaging.send("&c/time night &f-&c Turns time to night");
Messaging.send("&c/time raw &f-&c Shows raw time");
Messaging.send("&c/time =13000 &f-&c Sets raw time");
Messaging.send("&c/time +500 &f-&c Adds to raw time");
Messaging.send("&c/time -500 &f-&c Subtracts from raw time");
Messaging.send("&c/time 12 &f-&c Set relative time");
} else if (Misc.is(command, "day")) {
setTime(timeStart);
} else if (Misc.is(command, "night")) {
setTime(timeStart+13000);
} else if (Misc.is(command, "raw")) {
Messaging.send("&cRaw: " + time);
} else if (command.startsWith("=")) {
try {
setTime(Long.parseLong(command.substring(1)));
} catch(NumberFormatException ex) { }
} else if (command.startsWith("+")) {
try {
setTime(time+Long.parseLong(command.substring(1)));
} catch(NumberFormatException ex) { }
} else if (command.startsWith("-")) {
try {
setTime(time-Long.parseLong(command.substring(1)));
} catch(NumberFormatException ex) { }
} else {
try {
timeRelative = (Integer.parseInt(command)*1000-8000+24000)%24000;
setTime(timeStart + timeRelative);
} catch(NumberFormatException ex) { }
}
} else {
Messaging.send("&cCorrect usage is: /time [day|night|raw|([=|+|-]time)] (rawtime)");
Messaging.send("&c/time &f-&c Shows relative time");
Messaging.send("&c/time day &f-&c Turns time to day");
Messaging.send("&c/time night &f-&c Turns time to night");
Messaging.send("&c/time raw &f-&c Shows raw time");
Messaging.send("&c/time =13000 &f-&c Sets raw time");
Messaging.send("&c/time +500 &f-&c Adds to raw time");
Messaging.send("&c/time -500 &f-&c Subtracts from raw time");
Messaging.send("&c/time 12 &f-&c Set relative time");
}
return;
}
if(Misc.isEither(base, "/playerlist", "/online") || Misc.is(base, "/who")) {
if(split.length == 2) {
if (!General.Permissions.Security.permission(player, "general.player-info")) {
return;
}
Player lookup = Misc.playerMatch(split[1]);
String name = lookup.getName();
String displayName = lookup.getDisplayName();
String bar = "";
String location = "";
if(General.health) {
int health = lookup.getHealth();
int length = 10;
int bars = Math.round(health/2);
int remainder = length-bars;
String hb_color = ((bars >= 7) ? "&2" : ((bars < 7 && bars >= 3) ? "&e" : ((bars < 3) ? "&c" : "&2")));
bar = " &f["+ hb_color + Misc.repeat('|', bars) + "&7" + Misc.repeat('|', remainder) + "&f]";
}
if(General.coords) {
int x = (int)lookup.getLocation().getX();
int y = (int)lookup.getLocation().getY();
int z = (int)lookup.getLocation().getZ();
location = x+"x, "+y+"y, "+z+"z";
}
Messaging.send("&f------------------------------------------------");
Messaging.send("&e Player &f["+name+"/"+displayName+"]&e Info:");
Messaging.send("&f------------------------------------------------");
Messaging.send("&6 Username: &f" + name + ((General.health) ? bar : ""));
if(General.coords) {
Messaging.send("&6 -&e Location: &f" + location);
}
Messaging.send("&6 -&e Status: &f" + ((isAFK(lookup)) ? "AFK ("+AFK.get(lookup)+")" : "Around."));
Messaging.send("&f------------------------------------------------");
} else {
ArrayList<Player> olist = new ArrayList<Player>();
Player[] players = new Player[]{};
for(Player p : plugin.getServer().getOnlinePlayers()) {
if(p == null || !p.isOnline()) { continue; } else {
olist.add(p);
}
}
// Cast it to something empty to prevent nulls / empties
players = olist.toArray(players);
if(players.length <= 1 || olist.isEmpty()) {
Messaging.send("&ePlayer list (1):");
Messaging.send("&f - Just you.");
Messaging.send(" ");
} else {
int online = players.length;
ArrayList<String> list = new ArrayList<String>();
String currently = "";
int on = 0, perLine = 5, i = 1;
for(Player current : players) {
if(current == null) { ++on; continue; }
if(i == perLine) { list.add(currently); currently = ""; i = 1; }
currently += (on >= online) ? current.getName() : current.getName() + ", ";
++on; ++i;
}
// Guess list was smaller than 5.
if(list.isEmpty()) {
list.add(currently);
}
Messaging.send("&ePlayers list ("+on+"):");
for(String line : list) {
Messaging.send(line);
}
Messaging.send(" ");
}
}
}
}
}
| false | true |
public void onPlayerCommand(PlayerChatEvent event) {
String[] split = event.getMessage().split(" ");
Player player = event.getPlayer();
World world = player.getWorld();
server = ((CraftWorld)world).getHandle();
Messaging.save(player);
String base = split[0];
if((!event.isCancelled()) && Misc.isEither(base, "/help", "/?")) {
int page = 0;
if (split.length >= 2) {
try {
page = Integer.parseInt(split[1]);
} catch (NumberFormatException ex) {
Messaging.send("&cNot a valid page number."); event.setCancelled(true);
return;
}
}
print_commands(page); event.setCancelled(true);
}
if((!event.isCancelled()) && Misc.is(base, "/setspawn")) {
if (!General.Permissions.Security.permission(player, "general.spawn.set")) {
return;
}
server.m = (int)Math.ceil(player.getLocation().getX());
server.o = (int)Math.ceil(player.getLocation().getZ());
Messaging.send("&eSpawn position changed to where you are standing.");
}
if(Misc.is(base, "/spawn")) {
if (!General.Permissions.Security.permission(player, "general.spawn")) {
return;
}
player.teleportTo(spawn(player));
}
if((!event.isCancelled()) && Misc.is(base, "/motd")) {
String[] motd = readMotd();
if(motd == null || motd.length < 1) { return; }
String location = (int)player.getLocation().getX() +"x, " + (int)player.getLocation().getY() +"y, " + (int)player.getLocation().getZ() +"z";
String ip = player.getAddress().getAddress().getHostAddress();
String balance = "";
Plugin test = plugin.getServer().getPluginManager().getPlugin("iConomy");
if(test != null) {
iConomy iConomy = (iConomy)test;
balance = iConomy.db.get_balance(player.getName()) + " " + iConomy.currency;
}
for(String line : motd) {
Messaging.send(
player,
Messaging.argument(
line,
new String[]{
"+dname,+d", "+name,+n", "+location,+l", "+health,+h", "+ip", "+balance", "+online"
},
new String[]{
player.getDisplayName(),
player.getName(),
location,
Misc.string(player.getHealth()),
ip,
balance,
Misc.string(plugin.getServer().getOnlinePlayers().length)
}
)
);
}
}
if(Misc.isEither(base, "/tp", "/teleport")) {
if (!General.Permissions.Security.permission(player, "general.teleport")) {
return;
}
if (split.length == 2) {
String to = split[1];
if (to.equalsIgnoreCase("*")) {
Messaging.send("&cIncorrect usage of wildchar *");
} else if (to.contains(",")) {
Messaging.send("&cIncorrect usage of multiple players.");
} else {
if (!teleport(player.getName(), to)) {
Messaging.send("&cCannot find destination player: &f" + to);
}
}
} else if (split.length == 3) {
String who = split[1];
String to = split[2];
if (to.equalsIgnoreCase("*")) {
Messaging.send("&cIncorrect usage of wildchar *");
} else if (to.contains(",")) {
Messaging.send("&cIncorrect usage of multiple players.");
} else {
if (!teleport(who, to)) {
Messaging.send("&cCould not teleport " + who + " to " + to + ".");
}
}
} else {
Messaging.send("&c------ &f/tp help&c ------");
Messaging.send("&c/tp [player] &f-&c Teleport to a player");
Messaging.send("&c/tp [player] [to] &f-&c Teleport player to another player");
Messaging.send("&c/tp [player,...] [to] &f-&c Teleport players to another player");
Messaging.send("&c/tp * [to] &f-&c Teleport everyone to another player");
}
}
if(Misc.isEither(base, "/s", "/tphere")) {
if (!General.Permissions.Security.permission(player, "general.teleport.here")) {
return;
}
if (split.length < 1) {
Messaging.send("&cCorrect usage is:&f /s [player] &cor&f /tphere [player]");
return;
}
Player who = Misc.playerMatch(split[1]);
if (player != null) {
if (who.getName().equalsIgnoreCase(player.getName())) {
Messaging.send("&cWow look at that! You teleported yourself to yourself!");
return;
}
log.info(player.getName() + " teleported " + who.getName() + " to their self.");
who.teleportTo(player.getLocation());
} else {
Messaging.send("&cCan't find user " + split[1] + ".");
}
}
if((!event.isCancelled()) && Misc.is(base, "/getpos")) {
Messaging.send("Pos X: " + player.getLocation().getX() + " Y: " + player.getLocation().getY() + " Z: " + player.getLocation().getZ());
Messaging.send("Rotation: " + player.getLocation().getYaw() + " Pitch: " + player.getLocation().getPitch());
double degreeRotation = ((player.getLocation().getYaw() - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
Messaging.send("Compass: " + getDirection(degreeRotation) + " (" + (Math.round(degreeRotation * 10) / 10.0) + ")");
}
if(Misc.is(base, "/compass")) {
double degreeRotation = ((player.getLocation().getYaw() - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
Messaging.send("&cCompass: " + getDirection(degreeRotation));
}
if(Misc.isEither(base, "/afk", "/away")) {
if ((AFK != null || !AFK.isEmpty()) && isAFK(player)) {
Messaging.send("&7You have been marked as back.");
unAFK(player);
} else {
Messaging.send("&7You are now currently marked as away.");
String reason = "AFK";
if(split.length >= 2) {
reason = Misc.combineSplit(1, split, " ");
}
AFK(player, reason);
}
}
if(Misc.isEither(base, "/msg", "/tell")) {
if (split.length < 3) {
Messaging.send("&cCorrect usage is: /msg [player] [message]");
event.setCancelled(true);
return;
}
Player who = Misc.playerMatch(split[1]);
if (who != null) {
if (who.getName().equals(player.getName())) {
Messaging.send("&cYou can't message yourself!");
event.setCancelled(true);
return;
}
Messaging.send("(MSG) <" + player.getName() + "> " + Misc.combineSplit(2, split, " "));
Messaging.send(who, "(MSG) <" + player.getName() + "> " + Misc.combineSplit(2, split, " "));
if (isAFK(who)) {
Messaging.send("&7This player is currently away.");
Messaging.send("&7Reason: " + AFK.get(player));
}
} else {
Messaging.send("&cCouldn't find player " + split[1]);
}
}
if(Misc.isEither(base, "/i", "/give")) {
if (!General.Permissions.Security.permission(player, "general.items")) {
return;
}
if (split.length < 2) {
Messaging.send("&cCorrect usage is: /i [item|player](:type) [item|amount] (amount)"); return;
}
int itemId = 0;
int amount = 1;
int dataType = -1;
Player who = null;
try {
if(split[1].contains(":")) {
String[] data = split[1].split(":");
try {
dataType = Integer.valueOf(data[1]);
} catch (NumberFormatException e) { dataType = -1; }
itemId = Items.validate(data[0]);
} else {
itemId = Items.validate(split[1]);
}
if(itemId == -1) {
who = Misc.playerMatch(split[1]);
}
} catch(NumberFormatException e) {
who = Misc.playerMatch(split[1]);
}
if((itemId == 0 || itemId == -1) && who != null) {
String i = split[2];
if(i.contains(":")) {
String[] data = i.split(":");
try {
dataType = Integer.valueOf(data[1]);
} catch (NumberFormatException e) { dataType = -1; }
i = data[0];
}
itemId = Items.validate(i);
if(dataType == -1) {
dataType = Items.validateGrabType(i);
}
}
if(itemId == -1 || itemId == 0) {
Messaging.send("&cInvalid item."); return;
}
if(dataType != -1) {
if(!Items.validateType(itemId, dataType)) {
Messaging.send("&f"+dataType+"&c is not a valid data type for &f"+Items.name(itemId)+"&c."); return;
}
}
if(split.length >= 3 && who == null) {
try {
amount = Integer.valueOf(split[2]);
} catch(NumberFormatException e) { amount = 1; }
} else if (split.length >= 4) {
if(who != null) {
try {
amount = Integer.valueOf(split[3]);
} catch(NumberFormatException e) { amount = 1; }
} else {
who = Misc.playerMatch(split[3]);
}
}
if(who == null) {
who = player;
}
int slot = who.getInventory().firstEmpty();
if(dataType != -1) {
if(slot < 0) {
who.getWorld().dropItem(who.getLocation(), new ItemStack(itemId, amount, ((byte)dataType)));
} else {
who.getInventory().addItem(new ItemStack(itemId, amount, ((byte)dataType)));
}
} else {
if(slot < 0) {
who.getWorld().dropItem(who.getLocation(), new ItemStack(itemId, amount));
} else {
who.getInventory().addItem(new ItemStack(itemId, amount));
}
}
if(who.getName().equals(player.getName())) {
Messaging.send(who, "&2Enjoy! Giving &f"+amount+"&2 of &f"+Items.name(itemId)+"&2.");
} else {
Messaging.send(who, "&2Enjoy the gift! &f"+amount+"&2 of &f"+Items.name(itemId)+"&2. c:!");
}
event.setCancelled(true);
}
if(Misc.is(base, "/time")) {
if (!General.Permissions.Security.permission(player, "general.time")) {
return;
}
long time = getTime();
long timeRelative = getRelativeTime();
long timeStart = getStartTime();
if(split.length < 2) {
int hours = (int)((time / 1000+8) % 24);
int minutes = (((int)(time % 1000)) / 1000) * 60;
Messaging.send("&cTime: "+hours+":"+minutes);
} else if (split.length == 2) {
String command = split[1];
if (Misc.is(command, "help")) {
Messaging.send("&c-------- /time help --------");
Messaging.send("&c/time &f-&c Shows relative time");
Messaging.send("&c/time day &f-&c Turns time to day");
Messaging.send("&c/time night &f-&c Turns time to night");
Messaging.send("&c/time raw &f-&c Shows raw time");
Messaging.send("&c/time =13000 &f-&c Sets raw time");
Messaging.send("&c/time +500 &f-&c Adds to raw time");
Messaging.send("&c/time -500 &f-&c Subtracts from raw time");
Messaging.send("&c/time 12 &f-&c Set relative time");
} else if (Misc.is(command, "day")) {
setTime(timeStart);
} else if (Misc.is(command, "night")) {
setTime(timeStart+13000);
} else if (Misc.is(command, "raw")) {
Messaging.send("&cRaw: " + time);
} else if (command.startsWith("=")) {
try {
setTime(Long.parseLong(command.substring(1)));
} catch(NumberFormatException ex) { }
} else if (command.startsWith("+")) {
try {
setTime(time+Long.parseLong(command.substring(1)));
} catch(NumberFormatException ex) { }
} else if (command.startsWith("-")) {
try {
setTime(time-Long.parseLong(command.substring(1)));
} catch(NumberFormatException ex) { }
} else {
try {
timeRelative = (Integer.parseInt(command)*1000-8000+24000)%24000;
setTime(timeStart + timeRelative);
} catch(NumberFormatException ex) { }
}
} else {
Messaging.send("&cCorrect usage is: /time [day|night|raw|([=|+|-]time)] (rawtime)");
Messaging.send("&c/time &f-&c Shows relative time");
Messaging.send("&c/time day &f-&c Turns time to day");
Messaging.send("&c/time night &f-&c Turns time to night");
Messaging.send("&c/time raw &f-&c Shows raw time");
Messaging.send("&c/time =13000 &f-&c Sets raw time");
Messaging.send("&c/time +500 &f-&c Adds to raw time");
Messaging.send("&c/time -500 &f-&c Subtracts from raw time");
Messaging.send("&c/time 12 &f-&c Set relative time");
}
return;
}
if(Misc.isEither(base, "/playerlist", "/online") || Misc.is(base, "/who")) {
if(split.length == 2) {
if (!General.Permissions.Security.permission(player, "general.player-info")) {
return;
}
Player lookup = Misc.playerMatch(split[1]);
String name = lookup.getName();
String displayName = lookup.getDisplayName();
String bar = "";
String location = "";
if(General.health) {
int health = lookup.getHealth();
int length = 10;
int bars = Math.round(health/2);
int remainder = length-bars;
String hb_color = ((bars >= 7) ? "&2" : ((bars < 7 && bars >= 3) ? "&e" : ((bars < 3) ? "&c" : "&2")));
bar = " &f["+ hb_color + Misc.repeat('|', bars) + "&7" + Misc.repeat('|', remainder) + "&f]";
}
if(General.coords) {
int x = (int)lookup.getLocation().getX();
int y = (int)lookup.getLocation().getY();
int z = (int)lookup.getLocation().getZ();
location = x+"x, "+y+"y, "+z+"z";
}
Messaging.send("&f------------------------------------------------");
Messaging.send("&e Player &f["+name+"/"+displayName+"]&e Info:");
Messaging.send("&f------------------------------------------------");
Messaging.send("&6 Username: &f" + name + ((General.health) ? bar : ""));
if(General.coords) {
Messaging.send("&6 -&e Location: &f" + location);
}
Messaging.send("&6 -&e Status: &f" + ((isAFK(lookup)) ? "AFK ("+AFK.get(lookup)+")" : "Around."));
Messaging.send("&f------------------------------------------------");
} else {
ArrayList<Player> olist = new ArrayList<Player>();
Player[] players = new Player[]{};
for(Player p : plugin.getServer().getOnlinePlayers()) {
if(p == null || !p.isOnline()) { continue; } else {
olist.add(p);
}
}
// Cast it to something empty to prevent nulls / empties
players = olist.toArray(players);
if(players.length <= 1 || olist.isEmpty()) {
Messaging.send("&ePlayer list (1):");
Messaging.send("&f - Just you.");
Messaging.send(" ");
} else {
int online = players.length;
ArrayList<String> list = new ArrayList<String>();
String currently = "";
int on = 0, perLine = 5, i = 1;
for(Player current : players) {
if(current == null) { ++on; continue; }
if(i == perLine) { list.add(currently); currently = ""; i = 1; }
currently += (on >= online) ? current.getName() : current.getName() + ", ";
++on; ++i;
}
// Guess list was smaller than 5.
if(list.isEmpty()) {
list.add(currently);
}
Messaging.send("&ePlayers list ("+on+"):");
for(String line : list) {
Messaging.send(line);
}
Messaging.send(" ");
}
}
}
}
|
public void onPlayerCommand(PlayerChatEvent event) {
String[] split = event.getMessage().split(" ");
Player player = event.getPlayer();
World world = player.getWorld();
server = ((CraftWorld)world).getHandle();
Messaging.save(player);
String base = split[0];
if((!event.isCancelled()) && Misc.isEither(base, "/help", "/?")) {
int page = 0;
if (split.length >= 2) {
try {
page = Integer.parseInt(split[1]);
} catch (NumberFormatException ex) {
Messaging.send("&cNot a valid page number."); event.setCancelled(true);
return;
}
}
print_commands(page); event.setCancelled(true);
}
if((!event.isCancelled()) && Misc.is(base, "/setspawn")) {
if (!General.Permissions.Security.permission(player, "general.spawn.set")) {
return;
}
server.m = (int)Math.ceil(player.getLocation().getX());
server.o = (int)Math.ceil(player.getLocation().getZ());
Messaging.send("&eSpawn position changed to where you are standing.");
}
if(Misc.is(base, "/spawn")) {
if (!General.Permissions.Security.permission(player, "general.spawn")) {
return;
}
player.teleportTo(spawn(player));
}
if((!event.isCancelled()) && Misc.is(base, "/motd")) {
String[] motd = readMotd();
if(motd == null || motd.length < 1) { return; }
String location = (int)player.getLocation().getX() +"x, " + (int)player.getLocation().getY() +"y, " + (int)player.getLocation().getZ() +"z";
String ip = player.getAddress().getAddress().getHostAddress();
String balance = "";
Plugin test = plugin.getServer().getPluginManager().getPlugin("iConomy");
if(test != null) {
iConomy iConomy = (iConomy)test;
balance = iConomy.db.get_balance(player.getName()) + " " + iConomy.currency;
}
for(String line : motd) {
Messaging.send(
player,
Messaging.argument(
line,
new String[]{
"+dname,+d", "+name,+n", "+location,+l", "+health,+h", "+ip", "+balance", "+online"
},
new String[]{
player.getDisplayName(),
player.getName(),
location,
Misc.string(player.getHealth()),
ip,
balance,
Misc.string(plugin.getServer().getOnlinePlayers().length)
}
)
);
}
}
if(Misc.isEither(base, "/tp", "/teleport")) {
if (!General.Permissions.Security.permission(player, "general.teleport")) {
return;
}
if (split.length == 2) {
String to = split[1];
if (to.equalsIgnoreCase("*")) {
Messaging.send("&cIncorrect usage of wildchar *");
} else if (to.contains(",")) {
Messaging.send("&cIncorrect usage of multiple players.");
} else {
if (!teleport(player.getName(), to)) {
Messaging.send("&cCannot find destination player: &f" + to);
}
}
} else if (split.length == 3) {
String who = split[1];
String to = split[2];
if (to.equalsIgnoreCase("*")) {
Messaging.send("&cIncorrect usage of wildchar *");
} else if (to.contains(",")) {
Messaging.send("&cIncorrect usage of multiple players.");
} else {
if (!teleport(who, to)) {
Messaging.send("&cCould not teleport " + who + " to " + to + ".");
}
}
} else {
Messaging.send("&c------ &f/tp help&c ------");
Messaging.send("&c/tp [player] &f-&c Teleport to a player");
Messaging.send("&c/tp [player] [to] &f-&c Teleport player to another player");
Messaging.send("&c/tp [player,...] [to] &f-&c Teleport players to another player");
Messaging.send("&c/tp * [to] &f-&c Teleport everyone to another player");
}
}
if(Misc.isEither(base, "/s", "/tphere")) {
if (!General.Permissions.Security.permission(player, "general.teleport.here")) {
return;
}
if (split.length < 2) {
Messaging.send("&cCorrect usage is:&f /s [player] &cor&f /tphere [player]");
return;
}
Player who = Misc.playerMatch(split[1]);
if (who != null) {
if (who.getName().equalsIgnoreCase(player.getName())) {
Messaging.send("&cWow look at that! You teleported yourself to yourself!");
return;
}
log.info(player.getName() + " teleported " + who.getName() + " to their self.");
who.teleportTo(player.getLocation());
} else {
Messaging.send("&cCan't find user " + split[1] + ".");
}
}
if((!event.isCancelled()) && Misc.is(base, "/getpos")) {
Messaging.send("Pos X: " + player.getLocation().getX() + " Y: " + player.getLocation().getY() + " Z: " + player.getLocation().getZ());
Messaging.send("Rotation: " + player.getLocation().getYaw() + " Pitch: " + player.getLocation().getPitch());
double degreeRotation = ((player.getLocation().getYaw() - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
Messaging.send("Compass: " + getDirection(degreeRotation) + " (" + (Math.round(degreeRotation * 10) / 10.0) + ")");
}
if(Misc.is(base, "/compass")) {
double degreeRotation = ((player.getLocation().getYaw() - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
Messaging.send("&cCompass: " + getDirection(degreeRotation));
}
if(Misc.isEither(base, "/afk", "/away")) {
if ((AFK != null || !AFK.isEmpty()) && isAFK(player)) {
Messaging.send("&7You have been marked as back.");
unAFK(player);
} else {
Messaging.send("&7You are now currently marked as away.");
String reason = "AFK";
if(split.length >= 2) {
reason = Misc.combineSplit(1, split, " ");
}
AFK(player, reason);
}
}
if(Misc.isEither(base, "/msg", "/tell")) {
if (split.length < 3) {
Messaging.send("&cCorrect usage is: /msg [player] [message]");
event.setCancelled(true);
return;
}
Player who = Misc.playerMatch(split[1]);
if (who != null) {
if (who.getName().equals(player.getName())) {
Messaging.send("&cYou can't message yourself!");
event.setCancelled(true);
return;
}
Messaging.send("(MSG) <" + player.getName() + "> " + Misc.combineSplit(2, split, " "));
Messaging.send(who, "(MSG) <" + player.getName() + "> " + Misc.combineSplit(2, split, " "));
if (isAFK(who)) {
Messaging.send("&7This player is currently away.");
Messaging.send("&7Reason: " + AFK.get(player));
}
} else {
Messaging.send("&cCouldn't find player " + split[1]);
}
}
if(Misc.isEither(base, "/i", "/give")) {
if (!General.Permissions.Security.permission(player, "general.items")) {
return;
}
if (split.length < 2) {
Messaging.send("&cCorrect usage is: /i [item|player](:type) [item|amount] (amount)"); return;
}
int itemId = 0;
int amount = 1;
int dataType = -1;
Player who = null;
try {
if(split[1].contains(":")) {
String[] data = split[1].split(":");
try {
dataType = Integer.valueOf(data[1]);
} catch (NumberFormatException e) { dataType = -1; }
itemId = Items.validate(data[0]);
} else {
itemId = Items.validate(split[1]);
}
if(itemId == -1) {
who = Misc.playerMatch(split[1]);
}
} catch(NumberFormatException e) {
who = Misc.playerMatch(split[1]);
}
if((itemId == 0 || itemId == -1) && who != null) {
String i = split[2];
if(i.contains(":")) {
String[] data = i.split(":");
try {
dataType = Integer.valueOf(data[1]);
} catch (NumberFormatException e) { dataType = -1; }
i = data[0];
}
itemId = Items.validate(i);
if(dataType == -1) {
dataType = Items.validateGrabType(i);
}
}
if(itemId == -1 || itemId == 0) {
Messaging.send("&cInvalid item."); return;
}
if(dataType != -1) {
if(!Items.validateType(itemId, dataType)) {
Messaging.send("&f"+dataType+"&c is not a valid data type for &f"+Items.name(itemId)+"&c."); return;
}
}
if(split.length >= 3 && who == null) {
try {
amount = Integer.valueOf(split[2]);
} catch(NumberFormatException e) { amount = 1; }
} else if (split.length >= 4) {
if(who != null) {
try {
amount = Integer.valueOf(split[3]);
} catch(NumberFormatException e) { amount = 1; }
} else {
who = Misc.playerMatch(split[3]);
}
}
if(who == null) {
who = player;
}
int slot = who.getInventory().firstEmpty();
if(dataType != -1) {
if(slot < 0) {
who.getWorld().dropItem(who.getLocation(), new ItemStack(itemId, amount, ((byte)dataType)));
} else {
who.getInventory().addItem(new ItemStack(itemId, amount, ((byte)dataType)));
}
} else {
if(slot < 0) {
who.getWorld().dropItem(who.getLocation(), new ItemStack(itemId, amount));
} else {
who.getInventory().addItem(new ItemStack(itemId, amount));
}
}
if(who.getName().equals(player.getName())) {
Messaging.send(who, "&2Enjoy! Giving &f"+amount+"&2 of &f"+Items.name(itemId)+"&2.");
} else {
Messaging.send(who, "&2Enjoy the gift! &f"+amount+"&2 of &f"+Items.name(itemId)+"&2. c:!");
}
event.setCancelled(true);
}
if(Misc.is(base, "/time")) {
if (!General.Permissions.Security.permission(player, "general.time")) {
return;
}
long time = getTime();
long timeRelative = getRelativeTime();
long timeStart = getStartTime();
if(split.length < 2) {
int hours = (int)((time / 1000+8) % 24);
int minutes = (((int)(time % 1000)) / 1000) * 60;
Messaging.send("&cTime: "+hours+":"+minutes);
} else if (split.length == 2) {
String command = split[1];
if (Misc.is(command, "help")) {
Messaging.send("&c-------- /time help --------");
Messaging.send("&c/time &f-&c Shows relative time");
Messaging.send("&c/time day &f-&c Turns time to day");
Messaging.send("&c/time night &f-&c Turns time to night");
Messaging.send("&c/time raw &f-&c Shows raw time");
Messaging.send("&c/time =13000 &f-&c Sets raw time");
Messaging.send("&c/time +500 &f-&c Adds to raw time");
Messaging.send("&c/time -500 &f-&c Subtracts from raw time");
Messaging.send("&c/time 12 &f-&c Set relative time");
} else if (Misc.is(command, "day")) {
setTime(timeStart);
} else if (Misc.is(command, "night")) {
setTime(timeStart+13000);
} else if (Misc.is(command, "raw")) {
Messaging.send("&cRaw: " + time);
} else if (command.startsWith("=")) {
try {
setTime(Long.parseLong(command.substring(1)));
} catch(NumberFormatException ex) { }
} else if (command.startsWith("+")) {
try {
setTime(time+Long.parseLong(command.substring(1)));
} catch(NumberFormatException ex) { }
} else if (command.startsWith("-")) {
try {
setTime(time-Long.parseLong(command.substring(1)));
} catch(NumberFormatException ex) { }
} else {
try {
timeRelative = (Integer.parseInt(command)*1000-8000+24000)%24000;
setTime(timeStart + timeRelative);
} catch(NumberFormatException ex) { }
}
} else {
Messaging.send("&cCorrect usage is: /time [day|night|raw|([=|+|-]time)] (rawtime)");
Messaging.send("&c/time &f-&c Shows relative time");
Messaging.send("&c/time day &f-&c Turns time to day");
Messaging.send("&c/time night &f-&c Turns time to night");
Messaging.send("&c/time raw &f-&c Shows raw time");
Messaging.send("&c/time =13000 &f-&c Sets raw time");
Messaging.send("&c/time +500 &f-&c Adds to raw time");
Messaging.send("&c/time -500 &f-&c Subtracts from raw time");
Messaging.send("&c/time 12 &f-&c Set relative time");
}
return;
}
if(Misc.isEither(base, "/playerlist", "/online") || Misc.is(base, "/who")) {
if(split.length == 2) {
if (!General.Permissions.Security.permission(player, "general.player-info")) {
return;
}
Player lookup = Misc.playerMatch(split[1]);
String name = lookup.getName();
String displayName = lookup.getDisplayName();
String bar = "";
String location = "";
if(General.health) {
int health = lookup.getHealth();
int length = 10;
int bars = Math.round(health/2);
int remainder = length-bars;
String hb_color = ((bars >= 7) ? "&2" : ((bars < 7 && bars >= 3) ? "&e" : ((bars < 3) ? "&c" : "&2")));
bar = " &f["+ hb_color + Misc.repeat('|', bars) + "&7" + Misc.repeat('|', remainder) + "&f]";
}
if(General.coords) {
int x = (int)lookup.getLocation().getX();
int y = (int)lookup.getLocation().getY();
int z = (int)lookup.getLocation().getZ();
location = x+"x, "+y+"y, "+z+"z";
}
Messaging.send("&f------------------------------------------------");
Messaging.send("&e Player &f["+name+"/"+displayName+"]&e Info:");
Messaging.send("&f------------------------------------------------");
Messaging.send("&6 Username: &f" + name + ((General.health) ? bar : ""));
if(General.coords) {
Messaging.send("&6 -&e Location: &f" + location);
}
Messaging.send("&6 -&e Status: &f" + ((isAFK(lookup)) ? "AFK ("+AFK.get(lookup)+")" : "Around."));
Messaging.send("&f------------------------------------------------");
} else {
ArrayList<Player> olist = new ArrayList<Player>();
Player[] players = new Player[]{};
for(Player p : plugin.getServer().getOnlinePlayers()) {
if(p == null || !p.isOnline()) { continue; } else {
olist.add(p);
}
}
// Cast it to something empty to prevent nulls / empties
players = olist.toArray(players);
if(players.length <= 1 || olist.isEmpty()) {
Messaging.send("&ePlayer list (1):");
Messaging.send("&f - Just you.");
Messaging.send(" ");
} else {
int online = players.length;
ArrayList<String> list = new ArrayList<String>();
String currently = "";
int on = 0, perLine = 5, i = 1;
for(Player current : players) {
if(current == null) { ++on; continue; }
if(i == perLine) { list.add(currently); currently = ""; i = 1; }
currently += (on >= online) ? current.getName() : current.getName() + ", ";
++on; ++i;
}
// Guess list was smaller than 5.
if(list.isEmpty()) {
list.add(currently);
}
Messaging.send("&ePlayers list ("+on+"):");
for(String line : list) {
Messaging.send(line);
}
Messaging.send(" ");
}
}
}
}
|
diff --git a/client/src/es/deusto/weblab/client/comm/CommonCommunication.java b/client/src/es/deusto/weblab/client/comm/CommonCommunication.java
index 4bd37fc39..6de5823c3 100644
--- a/client/src/es/deusto/weblab/client/comm/CommonCommunication.java
+++ b/client/src/es/deusto/weblab/client/comm/CommonCommunication.java
@@ -1,262 +1,265 @@
/*
* Copyright (C) 2005-2009 University of Deusto
* All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution.
*
* This software consists of contributions made by many individuals,
* listed below:
*
* Author: Pablo Orduña <[email protected]>
* Jaime Irurzun <[email protected]>
*
*/
package es.deusto.weblab.client.comm;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.user.client.DOM;
import es.deusto.weblab.client.comm.callbacks.ISessionIdCallback;
import es.deusto.weblab.client.comm.callbacks.IUserInformationCallback;
import es.deusto.weblab.client.comm.callbacks.IVoidCallback;
import es.deusto.weblab.client.comm.callbacks.IWebLabAsyncCallback;
import es.deusto.weblab.client.comm.exceptions.CommunicationException;
import es.deusto.weblab.client.comm.exceptions.SerializationException;
import es.deusto.weblab.client.comm.exceptions.WebLabServerException;
import es.deusto.weblab.client.comm.exceptions.core.SessionNotFoundException;
import es.deusto.weblab.client.comm.exceptions.login.InvalidCredentialsException;
import es.deusto.weblab.client.comm.exceptions.login.LoginException;
import es.deusto.weblab.client.configuration.IConfigurationManager;
import es.deusto.weblab.client.dto.SessionID;
import es.deusto.weblab.client.dto.users.User;
public abstract class CommonCommunication implements ICommonCommunication {
public static final String WEBLAB_LOGIN_SERVICE_URL_PROPERTY = "weblab.service.login.url";
public static final String DEFAULT_WEBLAB_LOGIN_SERVICE_URL = "/weblab/login/json/";
public static final String WEBLAB_SERVICE_URL_PROPERTY = "weblab.service.url";
public static final String DEFAULT_WEBLAB_SERVICE_URL = "/weblab/json/";
protected final IConfigurationManager configurationManager;
protected ICommonSerializer serializer;
protected CommonCommunication(IConfigurationManager configurationManager){
this.configurationManager = configurationManager;
this.serializer = this.createSerializer();
}
protected abstract ICommonSerializer createSerializer();
protected void setSerializer(ICommonSerializer serializer){
this.serializer = serializer;
}
private String getServiceUrl(){
return this.configurationManager.getProperty(
CommonCommunication.WEBLAB_SERVICE_URL_PROPERTY,
CommonCommunication.DEFAULT_WEBLAB_SERVICE_URL
);
}
/**
* Performs a request. The request is sent to the server, and when finished,
* its result is returned through a callback.
* @param requestSerialized The request to be performed, already serialized.
* @param failureCallback Callback to invoke if the request fails.
* @param rci Callback to invoke when the request finishes.
*/
public void performRequest(String requestSerialized, IWebLabAsyncCallback failureCallback, RequestCallback rci){
final RequestBuilder rb = this.createRequestBuilder(RequestBuilder.POST, this.getServiceUrl());
try {
rb.sendRequest(requestSerialized, rci);
} catch (final RequestException e) {
failureCallback.onFailure(new CommunicationException(e.getMessage(), e));
}
}
private String getLoginServiceUrl(){
return this.configurationManager.getProperty(
CommonCommunication.WEBLAB_LOGIN_SERVICE_URL_PROPERTY,
CommonCommunication.DEFAULT_WEBLAB_LOGIN_SERVICE_URL
);
}
// For testing purposes
protected RequestBuilder createRequestBuilder(RequestBuilder.Method method, String url){
return new RequestBuilder(method, url);
}
private void performLoginRequest(String requestSerialized,
IWebLabAsyncCallback failureCallback, RequestCallback rci) {
final RequestBuilder rb = this.createRequestBuilder(RequestBuilder.POST, this.getLoginServiceUrl());
try {
rb.sendRequest(requestSerialized, rci);
} catch (final RequestException e) {
failureCallback.onFailure(new CommunicationException(e.getMessage(), e));
}
}
private class LoginRequestCallback extends WebLabRequestCallback{
private final ISessionIdCallback sessionIdCallback;
private final String username;
private final String password;
public LoginRequestCallback(ISessionIdCallback sessionIdCallback, String username, String password){
super(sessionIdCallback);
this.sessionIdCallback = sessionIdCallback;
this.username = username;
this.password = password;
}
@Override
public void onSuccessResponseReceived(String response) {
SessionID sessionId;
try {
sessionId = CommonCommunication.this.serializer.parseLoginResponse(response);
} catch (final SerializationException e) {
- this.sessionIdCallback.onFailure(e);
+ if(response.contains("503 for URL"))
+ this.sessionIdCallback.onFailure(new SerializationException("Is the WebLab-Deusto server down? Got an " + e.getMessage(), e));
+ else
+ this.sessionIdCallback.onFailure(e);
return;
} catch (final InvalidCredentialsException e) {
this.sessionIdCallback.onFailure(e);
return;
} catch (final LoginException e) {
this.sessionIdCallback.onFailure(e);
return;
} catch (final WebLabServerException e) {
this.sessionIdCallback.onFailure(e);
return;
}
this.launchBrowserPasswordManager();
this.sessionIdCallback.onSuccess(sessionId);
}
private void launchBrowserPasswordManager() {
final Element usernameField = DOM.getElementById("hiddenUsername");
final Element passwordField = DOM.getElementById("hiddenPassword");
final Element submitField = DOM.getElementById("hiddenLoginFormSubmitButton");
if(usernameField == null || passwordField == null || submitField == null)
return;
if(usernameField instanceof InputElement)
((InputElement)usernameField).setValue(this.username);
else return;
if(passwordField instanceof InputElement)
((InputElement)passwordField).setValue(this.password);
else return;
if(submitField instanceof InputElement)
((InputElement)submitField).click();
}
}
@Override
public void login(String username, String password, ISessionIdCallback callback) {
String requestSerialized;
try {
requestSerialized = this.serializer.serializeLoginRequest(username, password);
} catch (final SerializationException e1) {
callback.onFailure(e1);
return;
}
this.performLoginRequest(
requestSerialized,
callback,
new LoginRequestCallback(callback, username, password)
);
}
private class LogoutRequestCallback extends WebLabRequestCallback{
private final IVoidCallback voidCallback;
public LogoutRequestCallback(IVoidCallback voidCallback){
super(voidCallback);
this.voidCallback = voidCallback;
}
@Override
public void onSuccessResponseReceived(String response) {
try {
CommonCommunication.this.serializer.parseLogoutResponse(response);
} catch (final SerializationException e) {
this.voidCallback.onFailure(e);
return;
} catch (final WebLabServerException e) {
this.voidCallback.onFailure(e);
return;
}
this.voidCallback.onSuccess();
}
}
@Override
public void logout(SessionID sessionId, IVoidCallback callback) {
String requestSerialized;
try {
requestSerialized = this.serializer.serializeLogoutRequest(sessionId);
} catch (final SerializationException e1) {
callback.onFailure(e1);
return;
}
this.performRequest(
requestSerialized,
callback,
new LogoutRequestCallback(callback)
);
}
private class UserInformationRequestCallback extends WebLabRequestCallback{
private final IUserInformationCallback userInformationCallback;
public UserInformationRequestCallback(IUserInformationCallback userInformationCallback){
super(userInformationCallback);
this.userInformationCallback = userInformationCallback;
}
@Override
public void onSuccessResponseReceived(String response) {
User user;
try {
user = CommonCommunication.this.serializer.parseGetUserInformationResponse(response);
} catch (final SerializationException e) {
this.userInformationCallback.onFailure(e);
return;
} catch (final SessionNotFoundException e) {
this.userInformationCallback.onFailure(e);
return;
} catch (final WebLabServerException e) {
this.userInformationCallback.onFailure(e);
return;
}
this.userInformationCallback.onSuccess(user);
}
}
@Override
public void getUserInformation(SessionID sessionId, IUserInformationCallback callback) {
String requestSerialized;
try {
requestSerialized = this.serializer.serializeGetUserInformationRequest(sessionId);
} catch (final SerializationException e1) {
callback.onFailure(e1);
return;
}
this.performRequest(
requestSerialized,
callback,
new UserInformationRequestCallback(callback)
);
}
}
| true | true |
public void onSuccessResponseReceived(String response) {
SessionID sessionId;
try {
sessionId = CommonCommunication.this.serializer.parseLoginResponse(response);
} catch (final SerializationException e) {
this.sessionIdCallback.onFailure(e);
return;
} catch (final InvalidCredentialsException e) {
this.sessionIdCallback.onFailure(e);
return;
} catch (final LoginException e) {
this.sessionIdCallback.onFailure(e);
return;
} catch (final WebLabServerException e) {
this.sessionIdCallback.onFailure(e);
return;
}
this.launchBrowserPasswordManager();
this.sessionIdCallback.onSuccess(sessionId);
}
|
public void onSuccessResponseReceived(String response) {
SessionID sessionId;
try {
sessionId = CommonCommunication.this.serializer.parseLoginResponse(response);
} catch (final SerializationException e) {
if(response.contains("503 for URL"))
this.sessionIdCallback.onFailure(new SerializationException("Is the WebLab-Deusto server down? Got an " + e.getMessage(), e));
else
this.sessionIdCallback.onFailure(e);
return;
} catch (final InvalidCredentialsException e) {
this.sessionIdCallback.onFailure(e);
return;
} catch (final LoginException e) {
this.sessionIdCallback.onFailure(e);
return;
} catch (final WebLabServerException e) {
this.sessionIdCallback.onFailure(e);
return;
}
this.launchBrowserPasswordManager();
this.sessionIdCallback.onSuccess(sessionId);
}
|
diff --git a/src/geotools/src/main/java/org/geogit/geotools/porcelain/PGImport.java b/src/geotools/src/main/java/org/geogit/geotools/porcelain/PGImport.java
index 9f14b39d..bab28207 100644
--- a/src/geotools/src/main/java/org/geogit/geotools/porcelain/PGImport.java
+++ b/src/geotools/src/main/java/org/geogit/geotools/porcelain/PGImport.java
@@ -1,116 +1,119 @@
/* Copyright (c) 2011 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the LGPL 2.1 license, available at the root
* application directory.
*/
package org.geogit.geotools.porcelain;
import java.net.ConnectException;
import java.sql.Connection;
import org.geogit.cli.CLICommand;
import org.geogit.cli.GeogitCLI;
import org.geogit.geotools.plumbing.GeoToolsOpException;
import org.geogit.geotools.plumbing.ImportOp;
import org.geotools.data.DataStore;
import org.geotools.jdbc.JDBCDataStore;
import org.opengis.util.ProgressListener;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
/**
* Imports one or more tables from a PostGIS database.
*
* PostGIS CLI proxy for {@link ImportOp}
*
* @see ImportOp
*/
@Parameters(commandNames = "import", commandDescription = "Import PostGIS database")
public class PGImport extends AbstractPGCommand implements CLICommand {
/**
* If this is set, only this table will be imported.
*/
@Parameter(names = { "--table", "-t" }, description = "Table to import.")
public String table = "";
/**
* If this is set, all tables will be imported.
*/
@Parameter(names = "--all", description = "Import all tables.")
public boolean all = false;
/**
* Executes the import command using the provided options.
*
* @param cli
* @see org.geogit.cli.AbstractPGCommand#runInternal(org.geogit.cli.GeogitCLI)
*/
@Override
protected void runInternal(GeogitCLI cli) throws Exception {
if (cli.getGeogit() == null) {
cli.getConsole().println("Not a geogit repository: " + cli.getPlatform().pwd());
return;
}
DataStore dataStore = null;
try {
dataStore = getDataStore();
} catch (ConnectException e) {
cli.getConsole().println("Unable to connect using the specified database parameters.");
cli.getConsole().flush();
return;
}
try {
if (dataStore instanceof JDBCDataStore) {
Connection con = null;
try {
con = ((JDBCDataStore) dataStore).getDataSource().getConnection();
} catch (Exception e) {
throw new ConnectException();
}
((JDBCDataStore) dataStore).closeSafe(con);
}
cli.getConsole().println("Importing from database " + commonArgs.database);
ProgressListener progressListener = cli.getProgressListener();
cli.getGeogit().command(ImportOp.class).setAll(all).setTable(table)
.setDataStore(dataStore).setProgressListener(progressListener).call();
cli.getConsole().println("Import successful.");
} catch (GeoToolsOpException e) {
switch (e.statusCode) {
+ case TABLE_NOT_DEFINED:
+ cli.getConsole().println("You need to specify a table or use the --all option.");
+ break;
case ALL_AND_TABLE_DEFINED:
cli.getConsole().println("Specify --all or --table, both cannot be set.");
break;
case NO_FEATURES_FOUND:
cli.getConsole().println("No features were found in the database.");
break;
case TABLE_NOT_FOUND:
cli.getConsole().println("Could not find the specified table.");
break;
case UNABLE_TO_GET_NAMES:
cli.getConsole().println("Unable to get feature types from the database.");
break;
case UNABLE_TO_GET_FEATURES:
cli.getConsole().println("Unable to get features from the database.");
break;
case UNABLE_TO_INSERT:
cli.getConsole().println("Unable to insert features into the working tree.");
break;
default:
break;
}
} catch (ConnectException e) {
cli.getConsole().println("Unable to connect using the specified database parameters.");
} finally {
dataStore.dispose();
cli.getConsole().flush();
}
}
}
| true | true |
protected void runInternal(GeogitCLI cli) throws Exception {
if (cli.getGeogit() == null) {
cli.getConsole().println("Not a geogit repository: " + cli.getPlatform().pwd());
return;
}
DataStore dataStore = null;
try {
dataStore = getDataStore();
} catch (ConnectException e) {
cli.getConsole().println("Unable to connect using the specified database parameters.");
cli.getConsole().flush();
return;
}
try {
if (dataStore instanceof JDBCDataStore) {
Connection con = null;
try {
con = ((JDBCDataStore) dataStore).getDataSource().getConnection();
} catch (Exception e) {
throw new ConnectException();
}
((JDBCDataStore) dataStore).closeSafe(con);
}
cli.getConsole().println("Importing from database " + commonArgs.database);
ProgressListener progressListener = cli.getProgressListener();
cli.getGeogit().command(ImportOp.class).setAll(all).setTable(table)
.setDataStore(dataStore).setProgressListener(progressListener).call();
cli.getConsole().println("Import successful.");
} catch (GeoToolsOpException e) {
switch (e.statusCode) {
case ALL_AND_TABLE_DEFINED:
cli.getConsole().println("Specify --all or --table, both cannot be set.");
break;
case NO_FEATURES_FOUND:
cli.getConsole().println("No features were found in the database.");
break;
case TABLE_NOT_FOUND:
cli.getConsole().println("Could not find the specified table.");
break;
case UNABLE_TO_GET_NAMES:
cli.getConsole().println("Unable to get feature types from the database.");
break;
case UNABLE_TO_GET_FEATURES:
cli.getConsole().println("Unable to get features from the database.");
break;
case UNABLE_TO_INSERT:
cli.getConsole().println("Unable to insert features into the working tree.");
break;
default:
break;
}
} catch (ConnectException e) {
cli.getConsole().println("Unable to connect using the specified database parameters.");
} finally {
dataStore.dispose();
cli.getConsole().flush();
}
}
|
protected void runInternal(GeogitCLI cli) throws Exception {
if (cli.getGeogit() == null) {
cli.getConsole().println("Not a geogit repository: " + cli.getPlatform().pwd());
return;
}
DataStore dataStore = null;
try {
dataStore = getDataStore();
} catch (ConnectException e) {
cli.getConsole().println("Unable to connect using the specified database parameters.");
cli.getConsole().flush();
return;
}
try {
if (dataStore instanceof JDBCDataStore) {
Connection con = null;
try {
con = ((JDBCDataStore) dataStore).getDataSource().getConnection();
} catch (Exception e) {
throw new ConnectException();
}
((JDBCDataStore) dataStore).closeSafe(con);
}
cli.getConsole().println("Importing from database " + commonArgs.database);
ProgressListener progressListener = cli.getProgressListener();
cli.getGeogit().command(ImportOp.class).setAll(all).setTable(table)
.setDataStore(dataStore).setProgressListener(progressListener).call();
cli.getConsole().println("Import successful.");
} catch (GeoToolsOpException e) {
switch (e.statusCode) {
case TABLE_NOT_DEFINED:
cli.getConsole().println("You need to specify a table or use the --all option.");
break;
case ALL_AND_TABLE_DEFINED:
cli.getConsole().println("Specify --all or --table, both cannot be set.");
break;
case NO_FEATURES_FOUND:
cli.getConsole().println("No features were found in the database.");
break;
case TABLE_NOT_FOUND:
cli.getConsole().println("Could not find the specified table.");
break;
case UNABLE_TO_GET_NAMES:
cli.getConsole().println("Unable to get feature types from the database.");
break;
case UNABLE_TO_GET_FEATURES:
cli.getConsole().println("Unable to get features from the database.");
break;
case UNABLE_TO_INSERT:
cli.getConsole().println("Unable to insert features into the working tree.");
break;
default:
break;
}
} catch (ConnectException e) {
cli.getConsole().println("Unable to connect using the specified database parameters.");
} finally {
dataStore.dispose();
cli.getConsole().flush();
}
}
|
diff --git a/src/btwmod/chat/mod_Chat.java b/src/btwmod/chat/mod_Chat.java
index 179e7f6..6348f8d 100644
--- a/src/btwmod/chat/mod_Chat.java
+++ b/src/btwmod/chat/mod_Chat.java
@@ -1,136 +1,138 @@
package btwmod.chat;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import btwmods.CommandsAPI;
import btwmods.IMod;
import btwmods.PlayerAPI;
import btwmods.Util;
import btwmods.io.Settings;
import btwmods.player.IPlayerChatListener;
import btwmods.player.PlayerChatEvent;
public class mod_Chat implements IMod, IPlayerChatListener {
public String globalMessageFormat = "<%1$s> %2$s";
public Set<String> bannedColors = new HashSet<String>();
public Set<String> bannedUsers = new HashSet<String>();
private Settings data = null;
private Map<String, String> colorLookup = new HashMap<String, String>();
private CommandChatColor commandChatColor;
@Override
public String getName() {
return "Chat";
}
@Override
public void init(Settings settings, Settings data) throws Exception {
this.data = data;
String bannedUsers = settings.get("bannedUsers");
- for (String bannedUser : bannedUsers.split("[,; ]+"))
- this.bannedUsers.add(bannedUser.toLowerCase().trim());
+ if (bannedUsers != null)
+ for (String bannedUser : bannedUsers.split("[,; ]+"))
+ this.bannedUsers.add(bannedUser.toLowerCase().trim());
String bannedColors = settings.get("bannedColors");
- for (String bannedColor : bannedColors.split("[,; ]+"))
- this.bannedColors.add(bannedColor.toLowerCase().trim());
+ if (bannedColors != null)
+ for (String bannedColor : bannedColors.split("[,; ]+"))
+ this.bannedColors.add(bannedColor.toLowerCase().trim());
//addColor("black", Util.COLOR_BLACK);
//addColor("navy", Util.COLOR_NAVY);
addColor("green", Util.COLOR_GREEN);
addColor("teal", Util.COLOR_TEAL);
addColor("maroon", Util.COLOR_MAROON);
addColor("purple", Util.COLOR_PURPLE);
addColor("gold", Util.COLOR_GOLD);
addColor("silver", Util.COLOR_SILVER);
addColor("grey", Util.COLOR_GREY);
addColor("blue", Util.COLOR_BLUE);
addColor("lime", Util.COLOR_LIME);
addColor("aqua", Util.COLOR_AQUA);
addColor("red", Util.COLOR_RED);
addColor("pink", Util.COLOR_PINK);
addColor("yellow", Util.COLOR_YELLOW);
addColor("white", Util.COLOR_WHITE);
PlayerAPI.addListener(this);
CommandsAPI.registerCommand(commandChatColor = new CommandChatColor(this), this);
}
private void addColor(String color, String colorCode) {
if (!bannedColors.contains(color)) {
colorLookup.put(color, colorCode);
}
}
@Override
public void unload() throws Exception {
PlayerAPI.removeListener(this);
CommandsAPI.unregisterCommand(commandChatColor);
}
@Override
public IMod getMod() {
return this;
}
public boolean setPlayerColor(String username, String color) throws IOException {
if (color.equalsIgnoreCase("off") || color.equalsIgnoreCase("white") || isBannedUser(username)) {
data.removeKey(username.toLowerCase(), "color");
return true;
}
else if (isValidColor(color)) {
data.set(username.toLowerCase(), "color", color.toLowerCase());
data.saveSettings();
return true;
}
return false;
}
public String getPlayerColor(String username) {
return data.get(username.toLowerCase(), "color");
}
public String getColorChar(String color) {
return colorLookup.get(color.toLowerCase());
}
public boolean isValidColor(String color) {
return color.equalsIgnoreCase("off") || colorLookup.containsKey(color.toLowerCase());
}
public String[] getColors() {
return colorLookup.keySet().toArray(new String[colorLookup.size()]);
}
public boolean isBannedUser(String username) {
return bannedUsers.contains(username.toLowerCase().trim());
}
@Override
public void onPlayerChatAction(PlayerChatEvent event) {
if (event.type == PlayerChatEvent.TYPE.GLOBAL) {
// Attempt to get the user's setting.
String color = data.get(event.player.username.toLowerCase(), "color");
// Convert the setting to a color.
if (color != null)
color = getColorChar(color);
event.setMessage(String.format(globalMessageFormat,
color == null
? event.player.username
: color + event.player.username + Util.COLOR_WHITE,
event.getMessage()
));
event.sendAsGlobalMessage();
}
}
}
| false | true |
public void init(Settings settings, Settings data) throws Exception {
this.data = data;
String bannedUsers = settings.get("bannedUsers");
for (String bannedUser : bannedUsers.split("[,; ]+"))
this.bannedUsers.add(bannedUser.toLowerCase().trim());
String bannedColors = settings.get("bannedColors");
for (String bannedColor : bannedColors.split("[,; ]+"))
this.bannedColors.add(bannedColor.toLowerCase().trim());
//addColor("black", Util.COLOR_BLACK);
//addColor("navy", Util.COLOR_NAVY);
addColor("green", Util.COLOR_GREEN);
addColor("teal", Util.COLOR_TEAL);
addColor("maroon", Util.COLOR_MAROON);
addColor("purple", Util.COLOR_PURPLE);
addColor("gold", Util.COLOR_GOLD);
addColor("silver", Util.COLOR_SILVER);
addColor("grey", Util.COLOR_GREY);
addColor("blue", Util.COLOR_BLUE);
addColor("lime", Util.COLOR_LIME);
addColor("aqua", Util.COLOR_AQUA);
addColor("red", Util.COLOR_RED);
addColor("pink", Util.COLOR_PINK);
addColor("yellow", Util.COLOR_YELLOW);
addColor("white", Util.COLOR_WHITE);
PlayerAPI.addListener(this);
CommandsAPI.registerCommand(commandChatColor = new CommandChatColor(this), this);
}
|
public void init(Settings settings, Settings data) throws Exception {
this.data = data;
String bannedUsers = settings.get("bannedUsers");
if (bannedUsers != null)
for (String bannedUser : bannedUsers.split("[,; ]+"))
this.bannedUsers.add(bannedUser.toLowerCase().trim());
String bannedColors = settings.get("bannedColors");
if (bannedColors != null)
for (String bannedColor : bannedColors.split("[,; ]+"))
this.bannedColors.add(bannedColor.toLowerCase().trim());
//addColor("black", Util.COLOR_BLACK);
//addColor("navy", Util.COLOR_NAVY);
addColor("green", Util.COLOR_GREEN);
addColor("teal", Util.COLOR_TEAL);
addColor("maroon", Util.COLOR_MAROON);
addColor("purple", Util.COLOR_PURPLE);
addColor("gold", Util.COLOR_GOLD);
addColor("silver", Util.COLOR_SILVER);
addColor("grey", Util.COLOR_GREY);
addColor("blue", Util.COLOR_BLUE);
addColor("lime", Util.COLOR_LIME);
addColor("aqua", Util.COLOR_AQUA);
addColor("red", Util.COLOR_RED);
addColor("pink", Util.COLOR_PINK);
addColor("yellow", Util.COLOR_YELLOW);
addColor("white", Util.COLOR_WHITE);
PlayerAPI.addListener(this);
CommandsAPI.registerCommand(commandChatColor = new CommandChatColor(this), this);
}
|
diff --git a/grails/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java b/grails/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
index 0eff6efd0..0d196426c 100644
--- a/grails/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
+++ b/grails/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
@@ -1,318 +1,319 @@
/*
* Copyright 2004-2005 the original author or authors.
*
* 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.codehaus.groovy.grails.web.metaclass;
import grails.util.JSonBuilder;
import grails.util.OpenRicoBuilder;
import groovy.lang.*;
import groovy.text.Template;
import groovy.xml.StreamingMarkupBuilder;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.grails.commons.ControllerArtefactHandler;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.commons.metaclass.AbstractDynamicMethodInvocation;
import org.codehaus.groovy.grails.web.pages.GSPResponseWriter;
import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Allows rendering of text, views, and templates to the response
*
* @author Graeme Rocher
* @since 0.2
*
* Created: Oct 27, 2005
*/
public class RenderDynamicMethod extends AbstractDynamicMethodInvocation {
public static final String METHOD_SIGNATURE = "render";
public static final Pattern METHOD_PATTERN = Pattern.compile('^'+METHOD_SIGNATURE+'$');
public static final String ARGUMENT_TEXT = "text";
public static final String ARGUMENT_CONTENT_TYPE = "contentType";
public static final String ARGUMENT_ENCODING = "encoding";
public static final String ARGUMENT_VIEW = "view";
public static final String ARGUMENT_MODEL = "model";
public static final String ARGUMENT_TEMPLATE = "template";
public static final String ARGUMENT_BEAN = "bean";
public static final String ARGUMENT_COLLECTION = "collection";
public static final String ARGUMENT_BUILDER = "builder";
public static final String ARGUMENT_VAR = "var";
private static final String DEFAULT_ARGUMENT = "it";
private static final String BUILDER_TYPE_RICO = "rico";
private static final String BUILDER_TYPE_JSON = "json";
private static final String ARGUMENT_TO = "to";
private static final int BUFFER_SIZE = 8192;
public RenderDynamicMethod() {
super(METHOD_PATTERN);
}
public Object invoke(Object target, String methodName, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
GrailsApplication application = webRequest.getAttributes().getGrailsApplication();
HttpServletRequest request = webRequest.getCurrentRequest();
HttpServletResponse response = webRequest.getCurrentResponse();
boolean renderView = true;
GroovyObject controller = (GroovyObject)target;
- response.setContentType("text/html");
+ if(response.getContentType() == null)
+ response.setContentType("text/html");
if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) {
try {
response.getWriter().write(arguments[0].toString());
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
else if(arguments[0] instanceof Closure) {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
Writer out;
if(argMap.containsKey(ARGUMENT_TO)) {
out = (Writer)argMap.get(ARGUMENT_TO);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
String contentType = argMap.get(ARGUMENT_CONTENT_TYPE).toString();
String encoding = argMap.get(ARGUMENT_ENCODING).toString();
response.setContentType(contentType + ";charset=" + encoding);
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
response.setContentType(argMap.get(ARGUMENT_CONTENT_TYPE).toString());
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else {
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
webRequest.setOut(out);
if(arguments[arguments.length - 1] instanceof Closure) {
if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] });
}
else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER)) || isJSONResponse(response)){
JSonBuilder jsonBuilder;
try{
jsonBuilder = new JSonBuilder(response);
renderView = false;
}catch(IOException e){
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] });
}
else {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(out);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
}
else if(arguments[arguments.length - 1] instanceof String) {
try {
out.write((String)arguments[arguments.length - 1]);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
try {
out.write(text);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_VIEW)) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
GrailsControllerClass controllerClass = (GrailsControllerClass) application.getArtefact(ControllerArtefactHandler.TYPE,
target.getClass().getName());
if(controllerClass == null && webRequest.getControllerName() != null) {
controllerClass = (GrailsControllerClass)application.getArtefactByLogicalPropertyName(ControllerArtefactHandler.TYPE, webRequest.getControllerName());
}
String viewUri;
if(viewName.indexOf('/') > -1) {
if(!viewName.startsWith("/")) {
viewName = '/' + viewName;
}
viewUri = viewName;
}
else {
viewUri = controllerClass.getViewByName(viewName);
}
Map model;
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
model = (Map)modelObject;
}
else if(controllerClass.getClazz().isInstance(target)) {
model = new BeanMap(target);
}
else {
model = new HashMap();
}
controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) );
}
else if(argMap.containsKey(ARGUMENT_TEMPLATE)) {
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String var = (String)argMap.get(ARGUMENT_VAR);
// get the template uri
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES);
String templateUri = attrs.getTemplateUri(templateName,request);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
try {
Template t = engine.createTemplate(templateUri);
if(t == null) {
throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found.");
}
Map binding = new HashMap();
if(argMap.containsKey(ARGUMENT_BEAN)) {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, argMap.get(ARGUMENT_BEAN));
Writable w = t.make(binding);
w.writeTo(out);
}
else if(argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
if(colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, colObject);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else if(argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL));
w.writeTo(out);
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
renderView = false;
}
catch(GroovyRuntimeException gre) {
throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre);
}
catch(IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex);
}
}
else {
try {
out.write(DefaultGroovyMethods.inspect(arguments[0]));
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error obtaining response writer: " + e.getMessage(), e);
}
}
try {
if(!renderView) out.flush();
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
webRequest.setRenderView(renderView);
return null;
}
private boolean isJSONResponse(HttpServletResponse response) {
return response.getContentType() != null && response.getContentType().indexOf("text/json")>-1;
}
}
| true | true |
public Object invoke(Object target, String methodName, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
GrailsApplication application = webRequest.getAttributes().getGrailsApplication();
HttpServletRequest request = webRequest.getCurrentRequest();
HttpServletResponse response = webRequest.getCurrentResponse();
boolean renderView = true;
GroovyObject controller = (GroovyObject)target;
response.setContentType("text/html");
if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) {
try {
response.getWriter().write(arguments[0].toString());
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
else if(arguments[0] instanceof Closure) {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
Writer out;
if(argMap.containsKey(ARGUMENT_TO)) {
out = (Writer)argMap.get(ARGUMENT_TO);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
String contentType = argMap.get(ARGUMENT_CONTENT_TYPE).toString();
String encoding = argMap.get(ARGUMENT_ENCODING).toString();
response.setContentType(contentType + ";charset=" + encoding);
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
response.setContentType(argMap.get(ARGUMENT_CONTENT_TYPE).toString());
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else {
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
webRequest.setOut(out);
if(arguments[arguments.length - 1] instanceof Closure) {
if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] });
}
else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER)) || isJSONResponse(response)){
JSonBuilder jsonBuilder;
try{
jsonBuilder = new JSonBuilder(response);
renderView = false;
}catch(IOException e){
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] });
}
else {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(out);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
}
else if(arguments[arguments.length - 1] instanceof String) {
try {
out.write((String)arguments[arguments.length - 1]);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
try {
out.write(text);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_VIEW)) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
GrailsControllerClass controllerClass = (GrailsControllerClass) application.getArtefact(ControllerArtefactHandler.TYPE,
target.getClass().getName());
if(controllerClass == null && webRequest.getControllerName() != null) {
controllerClass = (GrailsControllerClass)application.getArtefactByLogicalPropertyName(ControllerArtefactHandler.TYPE, webRequest.getControllerName());
}
String viewUri;
if(viewName.indexOf('/') > -1) {
if(!viewName.startsWith("/")) {
viewName = '/' + viewName;
}
viewUri = viewName;
}
else {
viewUri = controllerClass.getViewByName(viewName);
}
Map model;
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
model = (Map)modelObject;
}
else if(controllerClass.getClazz().isInstance(target)) {
model = new BeanMap(target);
}
else {
model = new HashMap();
}
controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) );
}
else if(argMap.containsKey(ARGUMENT_TEMPLATE)) {
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String var = (String)argMap.get(ARGUMENT_VAR);
// get the template uri
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES);
String templateUri = attrs.getTemplateUri(templateName,request);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
try {
Template t = engine.createTemplate(templateUri);
if(t == null) {
throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found.");
}
Map binding = new HashMap();
if(argMap.containsKey(ARGUMENT_BEAN)) {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, argMap.get(ARGUMENT_BEAN));
Writable w = t.make(binding);
w.writeTo(out);
}
else if(argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
if(colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, colObject);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else if(argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL));
w.writeTo(out);
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
renderView = false;
}
catch(GroovyRuntimeException gre) {
throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre);
}
catch(IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex);
}
}
else {
try {
out.write(DefaultGroovyMethods.inspect(arguments[0]));
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error obtaining response writer: " + e.getMessage(), e);
}
}
try {
if(!renderView) out.flush();
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
webRequest.setRenderView(renderView);
return null;
}
|
public Object invoke(Object target, String methodName, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
GrailsApplication application = webRequest.getAttributes().getGrailsApplication();
HttpServletRequest request = webRequest.getCurrentRequest();
HttpServletResponse response = webRequest.getCurrentResponse();
boolean renderView = true;
GroovyObject controller = (GroovyObject)target;
if(response.getContentType() == null)
response.setContentType("text/html");
if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) {
try {
response.getWriter().write(arguments[0].toString());
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
else if(arguments[0] instanceof Closure) {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
Writer out;
if(argMap.containsKey(ARGUMENT_TO)) {
out = (Writer)argMap.get(ARGUMENT_TO);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
String contentType = argMap.get(ARGUMENT_CONTENT_TYPE).toString();
String encoding = argMap.get(ARGUMENT_ENCODING).toString();
response.setContentType(contentType + ";charset=" + encoding);
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
response.setContentType(argMap.get(ARGUMENT_CONTENT_TYPE).toString());
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else {
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
webRequest.setOut(out);
if(arguments[arguments.length - 1] instanceof Closure) {
if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] });
}
else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER)) || isJSONResponse(response)){
JSonBuilder jsonBuilder;
try{
jsonBuilder = new JSonBuilder(response);
renderView = false;
}catch(IOException e){
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] });
}
else {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(out);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
}
else if(arguments[arguments.length - 1] instanceof String) {
try {
out.write((String)arguments[arguments.length - 1]);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
try {
out.write(text);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_VIEW)) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
GrailsControllerClass controllerClass = (GrailsControllerClass) application.getArtefact(ControllerArtefactHandler.TYPE,
target.getClass().getName());
if(controllerClass == null && webRequest.getControllerName() != null) {
controllerClass = (GrailsControllerClass)application.getArtefactByLogicalPropertyName(ControllerArtefactHandler.TYPE, webRequest.getControllerName());
}
String viewUri;
if(viewName.indexOf('/') > -1) {
if(!viewName.startsWith("/")) {
viewName = '/' + viewName;
}
viewUri = viewName;
}
else {
viewUri = controllerClass.getViewByName(viewName);
}
Map model;
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
model = (Map)modelObject;
}
else if(controllerClass.getClazz().isInstance(target)) {
model = new BeanMap(target);
}
else {
model = new HashMap();
}
controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) );
}
else if(argMap.containsKey(ARGUMENT_TEMPLATE)) {
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String var = (String)argMap.get(ARGUMENT_VAR);
// get the template uri
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES);
String templateUri = attrs.getTemplateUri(templateName,request);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
try {
Template t = engine.createTemplate(templateUri);
if(t == null) {
throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found.");
}
Map binding = new HashMap();
if(argMap.containsKey(ARGUMENT_BEAN)) {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, argMap.get(ARGUMENT_BEAN));
Writable w = t.make(binding);
w.writeTo(out);
}
else if(argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
if(colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, colObject);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else if(argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL));
w.writeTo(out);
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
renderView = false;
}
catch(GroovyRuntimeException gre) {
throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre);
}
catch(IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex);
}
}
else {
try {
out.write(DefaultGroovyMethods.inspect(arguments[0]));
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error obtaining response writer: " + e.getMessage(), e);
}
}
try {
if(!renderView) out.flush();
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
webRequest.setRenderView(renderView);
return null;
}
|
diff --git a/webapp/src/main/java/org/vaadin/tori/thread/ThreadViewImpl.java b/webapp/src/main/java/org/vaadin/tori/thread/ThreadViewImpl.java
index bdf9019d..df8c406f 100644
--- a/webapp/src/main/java/org/vaadin/tori/thread/ThreadViewImpl.java
+++ b/webapp/src/main/java/org/vaadin/tori/thread/ThreadViewImpl.java
@@ -1,524 +1,525 @@
package org.vaadin.tori.thread;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.vaadin.tori.ToriApplication;
import org.vaadin.tori.ToriNavigator;
import org.vaadin.tori.component.FloatingBar;
import org.vaadin.tori.component.FloatingBar.DisplayEvent;
import org.vaadin.tori.component.FloatingBar.FloatingAlignment;
import org.vaadin.tori.component.FloatingBar.HideEvent;
import org.vaadin.tori.component.FloatingBar.VisibilityListener;
import org.vaadin.tori.component.HeadingLabel;
import org.vaadin.tori.component.HeadingLabel.HeadingLevel;
import org.vaadin.tori.component.LazyLayout;
import org.vaadin.tori.component.NewThreadComponent;
import org.vaadin.tori.component.NewThreadComponent.NewThreadListener;
import org.vaadin.tori.component.PanicComponent;
import org.vaadin.tori.component.ReplyComponent;
import org.vaadin.tori.component.ReplyComponent.ReplyListener;
import org.vaadin.tori.component.post.PostComponent;
import org.vaadin.tori.data.entity.Category;
import org.vaadin.tori.data.entity.DiscussionThread;
import org.vaadin.tori.data.entity.Post;
import org.vaadin.tori.exception.DataSourceException;
import org.vaadin.tori.mvp.AbstractView;
import com.ocpsoft.pretty.time.PrettyTime;
import com.vaadin.event.FieldEvents;
import com.vaadin.event.FieldEvents.FocusEvent;
import com.vaadin.event.LayoutEvents.LayoutClickEvent;
import com.vaadin.event.LayoutEvents.LayoutClickListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Label.ContentMode;
import com.vaadin.ui.Notification;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
@SuppressWarnings("serial")
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "SE_BAD_FIELD_STORE", justification = "We're ignoring serialization")
public class ThreadViewImpl extends AbstractView<ThreadView, ThreadPresenter>
implements ThreadView {
private static final int RENDER_DELAY_MILLIS = 1000;
private static final int RENDER_DISTANCE_PX = 1000;
private static final String PLACEHOLDER_WIDTH = "100%";
private static final String PLACEHOLDER_HEIGHT = "300px";
/** The amount of posts to preload from the beginning and the end. */
private static final int PRELOAD_THRESHHOLD = 4;
private CssLayout layout;
private final ReplyListener replyListener = new ReplyListener() {
@Override
public void submit(final String rawBody) {
if (!rawBody.trim().isEmpty()) {
try {
getPresenter().sendReply(rawBody);
} catch (final DataSourceException e) {
getRoot().showNotification(
DataSourceException.BORING_GENERIC_ERROR_MESSAGE);
}
}
}
};
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "SE_BAD_FIELD", justification = "We don't care about serialization")
private final Map<Post, PostComponent> postsToComponents = new HashMap<Post, PostComponent>();
private final LazyLayout postsLayout;
// private final CssLayout postsLayout;
private ReplyComponent reply;
private NewThreadComponent newThreadComponent;
public ThreadViewImpl() {
setStyleName("threadview");
// postsLayout = new CssLayout();
postsLayout = new LazyLayout();
postsLayout.setRenderDistance(RENDER_DISTANCE_PX);
postsLayout.setPlaceholderSize(PLACEHOLDER_HEIGHT, PLACEHOLDER_WIDTH);
postsLayout.setRenderDelay(RENDER_DELAY_MILLIS);
}
@Override
protected Component createCompositionRoot() {
return layout = new CssLayout();
}
@Override
public void initView() {
layout.setWidth("100%");
}
@Override
protected ThreadPresenter createPresenter() {
final ToriApplication app = ToriApplication.getCurrent();
return new ThreadPresenter(app.getDataSource(),
app.getAuthorizationService());
}
/**
* @return returns <code>null</code> if the visitor has entered an invalid
* URL or a new thread is being created.
*/
@CheckForNull
@Override
public DiscussionThread getCurrentThread() {
return getPresenter().getCurrentThread();
}
/**
* @return <code>null</code> if the visitor has entered an invalid URL.
*/
@CheckForNull
@Override
public Category getCurrentCategory() {
return getPresenter().getCurrentCategory();
}
@Override
public void displayPosts(final List<Post> posts,
@NonNull final DiscussionThread currentThread) {
layout.removeAllComponents();
postsLayout.removeAllComponents();
layout.addComponent(postsLayout);
for (int i = 0; i < posts.size(); i++) {
final Post post = posts.get(i);
final PostComponent c = newPostComponent(post);
if (i < PRELOAD_THRESHHOLD || i > posts.size() - PRELOAD_THRESHHOLD) {
postsLayout.addComponentEagerly(c);
} else {
postsLayout.addComponent(c);
}
if (i == 0) {
// create the floating summary bar for the first post
final FloatingBar summaryBar = getSummaryBar(post, c);
summaryBar.setScrollComponent(c);
summaryBar.setAlignment(FloatingAlignment.TOP);
layout.addComponent(summaryBar);
}
}
if (getPresenter().userMayReply()) {
final Label spacer = new Label("<span class=\"eof\">eof</span>",
ContentMode.XHTML);
spacer.setStyleName("spacer");
layout.addComponent(spacer);
reply = new ReplyComponent(replyListener, getPresenter()
.getFormattingSyntax(), "Post Reply");
reply.setUserMayAddFiles(getPresenter().userMayAddFiles());
reply.setMaxFileSize(getPresenter().getMaxFileSize());
layout.addComponent(reply);
final FloatingBar quickReplyBar = getQuickReplyBar(reply);
quickReplyBar.setScrollComponent(reply);
quickReplyBar.setAlignment(FloatingAlignment.BOTTOM);
layout.addComponent(quickReplyBar);
}
final Label bottomSpacer = new Label("");
bottomSpacer.setStyleName("spacer");
layout.addComponent(bottomSpacer);
}
private PostComponent newPostComponent(final Post post) {
final PostComponent c = new PostComponent(post, getPresenter());
postsToComponents.put(post, c);
// main component permissions
if (getPresenter().userMayReportPosts()) {
c.enableReporting();
}
if (getPresenter().userMayEdit(post)) {
c.enableEditing();
}
if (getPresenter().userMayQuote(post)) {
c.enableQuoting();
}
if (getPresenter().userMayVote()) {
try {
c.enableUpDownVoting(getPresenter().getPostVote(post));
} catch (final DataSourceException e) {
// NOP - everything's logged.
}
}
// context menu permissions
try {
if (getPresenter().userCanFollowThread()) {
c.enableThreadFollowing();
}
if (getPresenter().userCanUnFollowThread()) {
c.enableThreadUnFollowing();
}
} catch (final DataSourceException e) {
// NOP - everything's logged. If you can't follow, you can't
// unfollow either.
}
if (getPresenter().userMayBan()) {
c.enableBanning();
}
if (getPresenter().userMayDelete(post)) {
c.enableDeleting();
}
return c;
}
private PostComponent newPostSummaryComponent(final Post post) {
final PostComponent c = new PostComponent(post, getPresenter());
c.addStyleName("summary");
return c;
}
private Component getThreadSummary(final Post firstPost) {
final DiscussionThread thread = getPresenter().getCurrentThread();
if (thread == null) {
return new Label("No thread selected");
}
final VerticalLayout summaryLayout = new VerticalLayout();
summaryLayout.setWidth(966.0f, Unit.PIXELS);
summaryLayout.addStyleName("threadSummary");
final PostComponent postSummary = newPostSummaryComponent(firstPost);
postSummary.setVisible(false);
final String topicXhtml = String
.format("Thread: <strong>%s</strong> started by <strong>%s</strong> %s",
thread.getTopic(), firstPost.getAuthor()
.getDisplayedName(), new PrettyTime()
.format(firstPost.getTime()));
final Label topicLabel = new Label(topicXhtml, ContentMode.XHTML);
topicLabel.setWidth(null);
final String showPostContentCaption = "Show post content";
final String hidePostContentCaption = "Hide post content";
final String collapsedStyle = "collapsed";
final Label showOrHideLabel = new Label(showPostContentCaption);
showOrHideLabel.setStyleName("show-or-hide");
showOrHideLabel.addStyleName(collapsedStyle);
showOrHideLabel.setWidth(null);
summaryLayout.addListener(new LayoutClickListener() {
@Override
public void layoutClick(final LayoutClickEvent event) {
postSummary.setVisible(!postSummary.isVisible());
showOrHideLabel.setValue(postSummary.isVisible() ? hidePostContentCaption
: showPostContentCaption);
if (postSummary.isVisible()) {
showOrHideLabel.removeStyleName(collapsedStyle);
} else {
showOrHideLabel.addStyleName(collapsedStyle);
}
}
});
final CssLayout topRow = new CssLayout();
topRow.addStyleName("topRow");
topRow.setWidth("100%");
topRow.setMargin(true);
topRow.addComponent(topicLabel);
topRow.addComponent(showOrHideLabel);
summaryLayout.addComponent(topRow);
summaryLayout.addComponent(postSummary);
return summaryLayout;
}
private FloatingBar getSummaryBar(final Post post,
final PostComponent originalPost) {
final FloatingBar bar = new FloatingBar();
bar.addStyleName("threadSummaryBar");
bar.setContent(getThreadSummary(post));
return bar;
}
private FloatingBar getQuickReplyBar(
final ReplyComponent mirroredReplyComponent) {
final ReplyComponent quickReply = new ReplyComponent(replyListener,
getPresenter().getFormattingSyntax(), "Quick Reply",
"Your reply...");
// Using the TextArea of the ReplyComponent as the property data source
// to keep the two editors in sync.
quickReply.getInput().setPropertyDataSource(
mirroredReplyComponent.getInput());
quickReply.setCompactMode(true);
quickReply.setCollapsible(true);
quickReply.getInput().addListener(new FieldEvents.FocusListener() {
@Override
public void focus(final FocusEvent event) {
quickReply.setCompactMode(false);
}
});
quickReply.setWidth(966.0f, Unit.PIXELS);
final FloatingBar bar = new FloatingBar();
bar.addStyleName("quickReply");
bar.setAlignment(FloatingAlignment.BOTTOM);
bar.setContent(quickReply);
bar.addListener(new VisibilityListener() {
@Override
public void onHide(final HideEvent event) {
// FIXME re-implement
// quickReply.getInput().blur();
}
@Override
public void onDisplay(final DisplayEvent event) {
// FIXME re-implement
// mirroredReplyComponent.getInput().blur();
}
});
return bar;
}
@Override
public void displayThreadNotFoundError(final String threadIdString) {
getRoot().showNotification("No thread found for " + threadIdString,
Notification.TYPE_ERROR_MESSAGE);
}
@Override
protected void navigationTo(final String[] arguments) {
try {
super.getPresenter().handleArguments(arguments);
} catch (final DataSourceException e) {
panic();
}
}
@Override
public void confirmPostReported() {
getRoot().showNotification("Post is reported!");
}
@Override
public void confirmBanned() {
getRoot().showNotification("User is banned");
reloadPage();
}
@Override
public void confirmFollowingThread() {
getRoot().showNotification("Following thread");
swapFollowingMenus();
}
@Override
public void confirmUnFollowingThread() {
getRoot().showNotification("Not following thread anymore");
swapFollowingMenus();
}
private void swapFollowingMenus() {
for (final PostComponent c : postsToComponents.values()) {
c.swapFollowingMenu();
}
}
@Override
public void confirmPostDeleted() {
getRoot().showNotification("Post deleted");
reloadPage();
}
/**
* Resets and redraws the view.
*
* @deprecated Now with the {@link LazyLayout} this <em>really really</em>
* should be avoided. Use incremental changes instead whenever
* humanly possible, please!
*/
@Deprecated
private void reloadPage() {
try {
getPresenter().resetView();
} catch (final DataSourceException e) {
panic();
}
}
@Override
public void refreshScores(final Post post, final long newScore) {
postsToComponents.get(post).refreshScores(newScore);
}
@Override
public void confirmReplyPostedAndShowIt(final Post newPost) {
postsLayout.addComponentEagerly(newPostComponent(newPost));
}
@Override
public void displayUserCanNotReply() {
getRoot().showNotification(
"Unfortunately, you are not allowed to reply to this thread.");
}
@Override
public void displayUserCanNotEdit() {
getRoot().showNotification(
"Unfortunately, you are not allowed to edit this post.");
}
@Override
public void redirectToDashboard() {
getNavigator().navigateTo(
ToriNavigator.ApplicationView.DASHBOARD.getUrl());
}
@Override
public void displayNewThreadFormFor(final Category category) {
layout.removeAllComponents();
final HeadingLabel heading = new HeadingLabel("Start a New Thread",
HeadingLevel.H2);
layout.addComponent(heading);
getRoot().scrollIntoView(heading);
final HorizontalLayout topicLayout = new HorizontalLayout();
topicLayout.setSpacing(true);
topicLayout.setMargin(true, false, true, false);
topicLayout.setWidth("50em");
topicLayout.setStyleName("newthread");
layout.addComponent(topicLayout);
- final HeadingLabel topicLabel = new HeadingLabel("Topic:",
+ final HeadingLabel topicLabel = new HeadingLabel("Topic",
HeadingLevel.H3);
topicLabel.addStyleName("topiclabel");
- topicLabel.setWidth("140px");
+ topicLabel.setWidth("153px");
topicLayout.addComponent(topicLabel);
final TextField topicField = new TextField();
topicField.setStyleName("topicfield");
topicField.setWidth("100%");
topicLayout.addComponent(topicField);
topicLayout.setExpandRatio(topicField, 1.0f);
+ topicField.focus();
newThreadComponent = new NewThreadComponent(new NewThreadListener() {
@Override
public void submit(final String rawBody) {
String errorMessages = "";
final String topic = topicField.getValue();
if (topic.isEmpty()) {
errorMessages += "You need a topic<br/>";
}
if (rawBody.isEmpty()) {
errorMessages += "You need a thread body<br/>";
}
if (errorMessages.isEmpty()) {
try {
final DiscussionThread createdThread = getPresenter()
.createNewThread(category, topic, rawBody);
getNavigator().navigateTo(
ToriNavigator.ApplicationView.THREADS.getUrl()
+ "/" + createdThread.getId());
} catch (final DataSourceException e) {
getRoot()
.showNotification(
DataSourceException.BORING_GENERIC_ERROR_MESSAGE);
}
} else {
getRoot().showNotification(errorMessages,
Notification.TYPE_HUMANIZED_MESSAGE);
}
}
}, ToriApplication.getCurrent().getPostFormatter()
.getFormattingSyntaxXhtml());
newThreadComponent.setUserMayAddFiles(getPresenter().userMayAddFiles());
newThreadComponent.setMaxFileSize(getPresenter().getMaxFileSize());
layout.addComponent(newThreadComponent);
}
@Override
public void panic() {
layout.removeAllComponents();
layout.addComponent(new PanicComponent());
}
@Override
public void appendToReply(final String textToAppend) {
reply.insertIntoMessage(textToAppend);
}
@Override
public void refresh(final Post post) {
final PostComponent oldComponent = postsToComponents.get(post);
final PostComponent newComponent = newPostComponent(post);
postsToComponents.put(post, newComponent);
postsLayout.replaceComponent(oldComponent, newComponent);
}
@Override
public void updateAttachmentList(
final LinkedHashMap<String, byte[]> attachments) {
if (reply != null) {
reply.updateAttachmentList(attachments);
}
if (newThreadComponent != null) {
newThreadComponent.updateAttachmentList(attachments);
}
}
}
| false | true |
public void displayNewThreadFormFor(final Category category) {
layout.removeAllComponents();
final HeadingLabel heading = new HeadingLabel("Start a New Thread",
HeadingLevel.H2);
layout.addComponent(heading);
getRoot().scrollIntoView(heading);
final HorizontalLayout topicLayout = new HorizontalLayout();
topicLayout.setSpacing(true);
topicLayout.setMargin(true, false, true, false);
topicLayout.setWidth("50em");
topicLayout.setStyleName("newthread");
layout.addComponent(topicLayout);
final HeadingLabel topicLabel = new HeadingLabel("Topic:",
HeadingLevel.H3);
topicLabel.addStyleName("topiclabel");
topicLabel.setWidth("140px");
topicLayout.addComponent(topicLabel);
final TextField topicField = new TextField();
topicField.setStyleName("topicfield");
topicField.setWidth("100%");
topicLayout.addComponent(topicField);
topicLayout.setExpandRatio(topicField, 1.0f);
newThreadComponent = new NewThreadComponent(new NewThreadListener() {
@Override
public void submit(final String rawBody) {
String errorMessages = "";
final String topic = topicField.getValue();
if (topic.isEmpty()) {
errorMessages += "You need a topic<br/>";
}
if (rawBody.isEmpty()) {
errorMessages += "You need a thread body<br/>";
}
if (errorMessages.isEmpty()) {
try {
final DiscussionThread createdThread = getPresenter()
.createNewThread(category, topic, rawBody);
getNavigator().navigateTo(
ToriNavigator.ApplicationView.THREADS.getUrl()
+ "/" + createdThread.getId());
} catch (final DataSourceException e) {
getRoot()
.showNotification(
DataSourceException.BORING_GENERIC_ERROR_MESSAGE);
}
} else {
getRoot().showNotification(errorMessages,
Notification.TYPE_HUMANIZED_MESSAGE);
}
}
}, ToriApplication.getCurrent().getPostFormatter()
.getFormattingSyntaxXhtml());
newThreadComponent.setUserMayAddFiles(getPresenter().userMayAddFiles());
newThreadComponent.setMaxFileSize(getPresenter().getMaxFileSize());
layout.addComponent(newThreadComponent);
}
|
public void displayNewThreadFormFor(final Category category) {
layout.removeAllComponents();
final HeadingLabel heading = new HeadingLabel("Start a New Thread",
HeadingLevel.H2);
layout.addComponent(heading);
getRoot().scrollIntoView(heading);
final HorizontalLayout topicLayout = new HorizontalLayout();
topicLayout.setSpacing(true);
topicLayout.setMargin(true, false, true, false);
topicLayout.setWidth("50em");
topicLayout.setStyleName("newthread");
layout.addComponent(topicLayout);
final HeadingLabel topicLabel = new HeadingLabel("Topic",
HeadingLevel.H3);
topicLabel.addStyleName("topiclabel");
topicLabel.setWidth("153px");
topicLayout.addComponent(topicLabel);
final TextField topicField = new TextField();
topicField.setStyleName("topicfield");
topicField.setWidth("100%");
topicLayout.addComponent(topicField);
topicLayout.setExpandRatio(topicField, 1.0f);
topicField.focus();
newThreadComponent = new NewThreadComponent(new NewThreadListener() {
@Override
public void submit(final String rawBody) {
String errorMessages = "";
final String topic = topicField.getValue();
if (topic.isEmpty()) {
errorMessages += "You need a topic<br/>";
}
if (rawBody.isEmpty()) {
errorMessages += "You need a thread body<br/>";
}
if (errorMessages.isEmpty()) {
try {
final DiscussionThread createdThread = getPresenter()
.createNewThread(category, topic, rawBody);
getNavigator().navigateTo(
ToriNavigator.ApplicationView.THREADS.getUrl()
+ "/" + createdThread.getId());
} catch (final DataSourceException e) {
getRoot()
.showNotification(
DataSourceException.BORING_GENERIC_ERROR_MESSAGE);
}
} else {
getRoot().showNotification(errorMessages,
Notification.TYPE_HUMANIZED_MESSAGE);
}
}
}, ToriApplication.getCurrent().getPostFormatter()
.getFormattingSyntaxXhtml());
newThreadComponent.setUserMayAddFiles(getPresenter().userMayAddFiles());
newThreadComponent.setMaxFileSize(getPresenter().getMaxFileSize());
layout.addComponent(newThreadComponent);
}
|
diff --git a/lbImpl/src/org/LexGrid/LexBIG/Impl/loaders/LexGridMultiLoaderImpl.java b/lbImpl/src/org/LexGrid/LexBIG/Impl/loaders/LexGridMultiLoaderImpl.java
index b08569b14..c95904c77 100644
--- a/lbImpl/src/org/LexGrid/LexBIG/Impl/loaders/LexGridMultiLoaderImpl.java
+++ b/lbImpl/src/org/LexGrid/LexBIG/Impl/loaders/LexGridMultiLoaderImpl.java
@@ -1,251 +1,251 @@
package org.LexGrid.LexBIG.Impl.loaders;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import org.LexGrid.LexBIG.DataModel.Core.AbsoluteCodingSchemeVersionReference;
import org.LexGrid.LexBIG.DataModel.InterfaceElements.ExtensionDescription;
import org.LexGrid.LexBIG.DataModel.InterfaceElements.LoadStatus;
import org.LexGrid.LexBIG.DataModel.InterfaceElements.types.ProcessState;
import org.LexGrid.LexBIG.Exceptions.LBException;
import org.LexGrid.LexBIG.Exceptions.LBInvocationException;
import org.LexGrid.LexBIG.Exceptions.LBParameterException;
import org.LexGrid.LexBIG.Extensions.Load.LexGrid_Loader;
import org.LexGrid.LexBIG.Extensions.Load.options.OptionHolder;
import org.LexGrid.codingSchemes.CodingScheme;
import org.LexGrid.util.SimpleMemUsageReporter;
import org.LexGrid.util.SimpleMemUsageReporter.Snapshot;
import org.lexevs.dao.database.service.exception.CodingSchemeAlreadyLoadedException;
import org.lexevs.locator.LexEvsServiceLocator;
import org.lexevs.logging.messaging.impl.CachingMessageDirectorImpl;
import org.lexevs.system.service.SystemResourceService;
import edu.mayo.informatics.lexgrid.convert.directConversions.StreamingXMLToSQL;
import edu.mayo.informatics.lexgrid.convert.directConversions.LgXMLCommon.LexGridXMLProcessor;
import edu.mayo.informatics.lexgrid.convert.options.BooleanOption;
import edu.mayo.informatics.lexgrid.convert.utility.URNVersionPair;
public class LexGridMultiLoaderImpl extends BaseLoader implements LexGrid_Loader {
private static final long serialVersionUID = 5405545553067402760L;
public final static String name = "LexGrid_Loader";
private final static String description = "This loader loads LexGrid XML files into the LexGrid database.";
public final static String VALIDATE = "Validate";
private static boolean validate = true;
public LexGridMultiLoaderImpl() {
super();
}
public void LexGridMultiLoaderbaseLoad(boolean async)throws LBInvocationException {
setStatus(new LoadStatus());
getStatus().setState(ProcessState.PROCESSING);
getStatus().setStartTime(new Date(System.currentTimeMillis()));
setMd_(new CachingMessageDirectorImpl( new MessageDirector(getName(), getStatus())));
if (async) {
Thread conversion = new Thread(new DoConversion());
conversion.start();
} else {
new DoConversion().run();
}
}
/* (non-Javadoc)
* @see org.LexGrid.LexBIG.Extensions.Load.LexGrid_Loader#validate(java.net.URI, int)
*/
public void validate(URI uri, int validationLevel) throws LBParameterException {
throw new UnsupportedOperationException();
}
public void load(URI source, boolean stopOnErrors, boolean async) throws LBException {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.LexGrid.LexBIG.Extensions.Load.LexGrid_Loader#load(java.net.URI, boolean, boolean)
*/
public void load(URI uri) {
setResourceUri(uri);
try {
boolean async = this.getOptions().getBooleanOption(ASYNC_OPTION).getOptionValue();
LexGridMultiLoaderbaseLoad(async);
} catch (LBInvocationException e) {
throw new RuntimeException(e);
}
}
/* (non-Javadoc)
* @see org.LexGrid.LexBIG.Impl.loaders.BaseLoader#declareAllowedOptions(org.LexGrid.LexBIG.Extensions.Load.options.OptionHolder)
*/
@Override
protected OptionHolder declareAllowedOptions(OptionHolder holder) {
BooleanOption forceValidation = new BooleanOption(LexGridMultiLoaderImpl.VALIDATE, validate);
holder.getBooleanOptions().add(forceValidation);
return holder;
}
/* (non-Javadoc)
* @see org.LexGrid.LexBIG.Impl.loaders.BaseLoader#doLoad()
*/
@Override
protected URNVersionPair[] doLoad() throws CodingSchemeAlreadyLoadedException {
StreamingXMLToSQL loader = new StreamingXMLToSQL();
CodingScheme[] codingScheme = loader.load(
this.getResourceUri(),
this.getLogger(),
this.getOptions().getBooleanOption(LexGridMultiLoaderImpl.VALIDATE).getOptionValue());
this.getStatus().setState(ProcessState.COMPLETED);
this.getStatus().setErrorsLogged(false);
return this.constructVersionPairsFromCodingSchemes(codingScheme);
}
/* (non-Javadoc)
* @see org.LexGrid.LexBIG.Impl.Extensions.AbstractExtendable#buildExtensionDescription()
*/
@Override
protected ExtensionDescription buildExtensionDescription() {
ExtensionDescription temp = new ExtensionDescription();
temp.setExtensionBaseClass(LexGridMultiLoaderImpl.class.getInterfaces()[0].getName());
temp.setExtensionClass(LexGridMultiLoaderImpl.class.getName());
temp.setDescription(LexGridMultiLoaderImpl.description);
temp.setName(LexGridMultiLoaderImpl.name);
return temp;
}
private class DoConversion implements Runnable {
public void run() {
URNVersionPair[] locks = null;
try {
// Actually do the load
URNVersionPair[] loadedCodingSchemes = doLoad();
//Must be loading a value domain or picklist if this condition is true ... exit
if(loadedCodingSchemes[0].getUrn()== LexGridXMLProcessor.NO_SCHEME_URL
&& loadedCodingSchemes[0].getVersion()== LexGridXMLProcessor.NO_SCHEME_VERSION){return;}
setCodingSchemeReferences(urnVersionPairToAbsoluteCodingSchemeVersionReference(loadedCodingSchemes));
String[] codingSchemeNames = new String[loadedCodingSchemes.length];
for (int i = 0; i < loadedCodingSchemes.length; i++) {
codingSchemeNames[i] = loadedCodingSchemes[i].getUrn();
}
if (getStatus().getErrorsLogged() != null && !getStatus().getErrorsLogged().booleanValue()) {
getMd_().info("Finished loading the DB");
Snapshot snap = SimpleMemUsageReporter.snapshot();
getMd_().info("Read Time : " + SimpleMemUsageReporter.formatTimeDiff(snap.getTimeDelta(null))
+ " Heap Usage: " + SimpleMemUsageReporter.formatMemStat(snap.getHeapUsage())
+ " Heap Delta:" + SimpleMemUsageReporter.formatMemStat(snap.getHeapUsageDelta(null)));
//Pre-register to make this available before indexing.
if(isDoRegister()) {
register(loadedCodingSchemes);
}
doPostProcessing(getOptions(), getCodingSchemeReferences());
doTransitiveAndIndex(getCodingSchemeReferences());
getMd_().info("After Indexing");
snap = SimpleMemUsageReporter.snapshot();
getMd_().info("Read Time : " + SimpleMemUsageReporter.formatTimeDiff(snap.getTimeDelta(null))
+ " Heap Usage: " + SimpleMemUsageReporter.formatMemStat(snap.getHeapUsage())
+ " Heap Delta:" + SimpleMemUsageReporter.formatMemStat(snap.getHeapUsageDelta(null)));
getStatus().setState(ProcessState.COMPLETED);
getMd_().info("Load process completed without error");
//Register again (to set as INACTIVE)
if(isDoRegister()) {
register(loadedCodingSchemes);
}
}
} catch (CodingSchemeAlreadyLoadedException e) {
getStatus().setState(ProcessState.FAILED);
getMd_().fatal(e.getMessage());
} catch (Exception e) {
getStatus().setState(ProcessState.FAILED);
getMd_().fatal("Failed while running the conversion", e);
} finally {
- if (getStatus().getState() == null || getStatus().getState().equals(ProcessState.COMPLETED)) {
+ if (getStatus().getState() == null || !getStatus().getState().equals(ProcessState.COMPLETED)) {
getStatus().setState(ProcessState.FAILED);
try {
if (locks != null) {
for (int i = 0; i < locks.length; i++) {
unlock(locks[i]);
}
}
getLogger().warn("Load failed. Removing temporary resources...");
SystemResourceService service =
LexEvsServiceLocator.getInstance().getSystemResourceService();
for(AbsoluteCodingSchemeVersionReference ref : getCodingSchemeReferences()) {
service.removeCodingSchemeResourceFromSystem(ref.getCodingSchemeURN(), ref.getCodingSchemeVersion());
}
} catch (LBParameterException e) {
// do nothing - means that the requested delete item
// didn't exist.
} catch (Exception e) {
getLogger().warn("Problem removing temporary resources", e);
}
}
getStatus().setEndTime(new Date(System.currentTimeMillis()));
inUse = false;
}
}
}
/* (non-Javadoc)
* @see org.LexGrid.LexBIG.Extensions.Load.LexGrid_Loader#getSchemaURL()
*/
public URI getSchemaURL() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see org.LexGrid.LexBIG.Extensions.Load.LexGrid_Loader#getSchemaVersion()
*/
public String getSchemaVersion() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
public void finalize() throws Throwable {
getLogger().loadLogDebug("Freeing LexGridMultiLoaderImpl");
super.finalize();
}
/**
* @param args
*/
public static void main(String[] args){
LexGridMultiLoaderImpl loader = new LexGridMultiLoaderImpl();
loader.addBooleanOptionValue(LexGridMultiLoaderImpl.VALIDATE, validate);
URI uri = null;
try {
uri = new URI(args[0]);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loader.load(uri);
}
}
| true | true |
public void run() {
URNVersionPair[] locks = null;
try {
// Actually do the load
URNVersionPair[] loadedCodingSchemes = doLoad();
//Must be loading a value domain or picklist if this condition is true ... exit
if(loadedCodingSchemes[0].getUrn()== LexGridXMLProcessor.NO_SCHEME_URL
&& loadedCodingSchemes[0].getVersion()== LexGridXMLProcessor.NO_SCHEME_VERSION){return;}
setCodingSchemeReferences(urnVersionPairToAbsoluteCodingSchemeVersionReference(loadedCodingSchemes));
String[] codingSchemeNames = new String[loadedCodingSchemes.length];
for (int i = 0; i < loadedCodingSchemes.length; i++) {
codingSchemeNames[i] = loadedCodingSchemes[i].getUrn();
}
if (getStatus().getErrorsLogged() != null && !getStatus().getErrorsLogged().booleanValue()) {
getMd_().info("Finished loading the DB");
Snapshot snap = SimpleMemUsageReporter.snapshot();
getMd_().info("Read Time : " + SimpleMemUsageReporter.formatTimeDiff(snap.getTimeDelta(null))
+ " Heap Usage: " + SimpleMemUsageReporter.formatMemStat(snap.getHeapUsage())
+ " Heap Delta:" + SimpleMemUsageReporter.formatMemStat(snap.getHeapUsageDelta(null)));
//Pre-register to make this available before indexing.
if(isDoRegister()) {
register(loadedCodingSchemes);
}
doPostProcessing(getOptions(), getCodingSchemeReferences());
doTransitiveAndIndex(getCodingSchemeReferences());
getMd_().info("After Indexing");
snap = SimpleMemUsageReporter.snapshot();
getMd_().info("Read Time : " + SimpleMemUsageReporter.formatTimeDiff(snap.getTimeDelta(null))
+ " Heap Usage: " + SimpleMemUsageReporter.formatMemStat(snap.getHeapUsage())
+ " Heap Delta:" + SimpleMemUsageReporter.formatMemStat(snap.getHeapUsageDelta(null)));
getStatus().setState(ProcessState.COMPLETED);
getMd_().info("Load process completed without error");
//Register again (to set as INACTIVE)
if(isDoRegister()) {
register(loadedCodingSchemes);
}
}
} catch (CodingSchemeAlreadyLoadedException e) {
getStatus().setState(ProcessState.FAILED);
getMd_().fatal(e.getMessage());
} catch (Exception e) {
getStatus().setState(ProcessState.FAILED);
getMd_().fatal("Failed while running the conversion", e);
} finally {
if (getStatus().getState() == null || getStatus().getState().equals(ProcessState.COMPLETED)) {
getStatus().setState(ProcessState.FAILED);
try {
if (locks != null) {
for (int i = 0; i < locks.length; i++) {
unlock(locks[i]);
}
}
getLogger().warn("Load failed. Removing temporary resources...");
SystemResourceService service =
LexEvsServiceLocator.getInstance().getSystemResourceService();
for(AbsoluteCodingSchemeVersionReference ref : getCodingSchemeReferences()) {
service.removeCodingSchemeResourceFromSystem(ref.getCodingSchemeURN(), ref.getCodingSchemeVersion());
}
} catch (LBParameterException e) {
// do nothing - means that the requested delete item
// didn't exist.
} catch (Exception e) {
getLogger().warn("Problem removing temporary resources", e);
}
}
getStatus().setEndTime(new Date(System.currentTimeMillis()));
inUse = false;
}
}
|
public void run() {
URNVersionPair[] locks = null;
try {
// Actually do the load
URNVersionPair[] loadedCodingSchemes = doLoad();
//Must be loading a value domain or picklist if this condition is true ... exit
if(loadedCodingSchemes[0].getUrn()== LexGridXMLProcessor.NO_SCHEME_URL
&& loadedCodingSchemes[0].getVersion()== LexGridXMLProcessor.NO_SCHEME_VERSION){return;}
setCodingSchemeReferences(urnVersionPairToAbsoluteCodingSchemeVersionReference(loadedCodingSchemes));
String[] codingSchemeNames = new String[loadedCodingSchemes.length];
for (int i = 0; i < loadedCodingSchemes.length; i++) {
codingSchemeNames[i] = loadedCodingSchemes[i].getUrn();
}
if (getStatus().getErrorsLogged() != null && !getStatus().getErrorsLogged().booleanValue()) {
getMd_().info("Finished loading the DB");
Snapshot snap = SimpleMemUsageReporter.snapshot();
getMd_().info("Read Time : " + SimpleMemUsageReporter.formatTimeDiff(snap.getTimeDelta(null))
+ " Heap Usage: " + SimpleMemUsageReporter.formatMemStat(snap.getHeapUsage())
+ " Heap Delta:" + SimpleMemUsageReporter.formatMemStat(snap.getHeapUsageDelta(null)));
//Pre-register to make this available before indexing.
if(isDoRegister()) {
register(loadedCodingSchemes);
}
doPostProcessing(getOptions(), getCodingSchemeReferences());
doTransitiveAndIndex(getCodingSchemeReferences());
getMd_().info("After Indexing");
snap = SimpleMemUsageReporter.snapshot();
getMd_().info("Read Time : " + SimpleMemUsageReporter.formatTimeDiff(snap.getTimeDelta(null))
+ " Heap Usage: " + SimpleMemUsageReporter.formatMemStat(snap.getHeapUsage())
+ " Heap Delta:" + SimpleMemUsageReporter.formatMemStat(snap.getHeapUsageDelta(null)));
getStatus().setState(ProcessState.COMPLETED);
getMd_().info("Load process completed without error");
//Register again (to set as INACTIVE)
if(isDoRegister()) {
register(loadedCodingSchemes);
}
}
} catch (CodingSchemeAlreadyLoadedException e) {
getStatus().setState(ProcessState.FAILED);
getMd_().fatal(e.getMessage());
} catch (Exception e) {
getStatus().setState(ProcessState.FAILED);
getMd_().fatal("Failed while running the conversion", e);
} finally {
if (getStatus().getState() == null || !getStatus().getState().equals(ProcessState.COMPLETED)) {
getStatus().setState(ProcessState.FAILED);
try {
if (locks != null) {
for (int i = 0; i < locks.length; i++) {
unlock(locks[i]);
}
}
getLogger().warn("Load failed. Removing temporary resources...");
SystemResourceService service =
LexEvsServiceLocator.getInstance().getSystemResourceService();
for(AbsoluteCodingSchemeVersionReference ref : getCodingSchemeReferences()) {
service.removeCodingSchemeResourceFromSystem(ref.getCodingSchemeURN(), ref.getCodingSchemeVersion());
}
} catch (LBParameterException e) {
// do nothing - means that the requested delete item
// didn't exist.
} catch (Exception e) {
getLogger().warn("Problem removing temporary resources", e);
}
}
getStatus().setEndTime(new Date(System.currentTimeMillis()));
inUse = false;
}
}
|
diff --git a/src-nlp/org/seasr/meandre/components/nlp/openmary/OpenMaryClient.java b/src-nlp/org/seasr/meandre/components/nlp/openmary/OpenMaryClient.java
index 279bd10f..843021a9 100644
--- a/src-nlp/org/seasr/meandre/components/nlp/openmary/OpenMaryClient.java
+++ b/src-nlp/org/seasr/meandre/components/nlp/openmary/OpenMaryClient.java
@@ -1,202 +1,210 @@
/**
*
* University of Illinois/NCSA
* Open Source License
*
* Copyright (c) 2008, NCSA. All rights reserved.
*
* Developed by:
* The Automated Learning Group
* University of Illinois at Urbana-Champaign
* http://www.seasr.org
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal with 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:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimers.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimers in
* the documentation and/or other materials provided with the distribution.
*
* Neither the names of The Automated Learning Group, University of
* Illinois at Urbana-Champaign, nor the names of its contributors may
* be used to endorse or promote products derived from this Software
* without specific prior written permission.
*
* 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 CONTRIBUTORS 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 WITH THE SOFTWARE.
*
*/
package org.seasr.meandre.components.nlp.openmary;
import java.io.ByteArrayOutputStream;
import marytts.client.MaryClient;
import marytts.client.http.Address;
import org.meandre.annotations.Component;
import org.meandre.annotations.Component.FiringPolicy;
import org.meandre.annotations.Component.Licenses;
import org.meandre.annotations.ComponentInput;
import org.meandre.annotations.ComponentOutput;
import org.meandre.annotations.ComponentProperty;
import org.meandre.core.ComponentContext;
import org.meandre.core.ComponentContextProperties;
import org.seasr.datatypes.core.BasicDataTypesTools;
import org.seasr.datatypes.core.DataTypeParser;
import org.seasr.datatypes.core.Names;
import org.seasr.meandre.components.abstracts.AbstractExecutableComponent;
/**
*
* @author Boris Capitanu
*
*/
@Component(
creator = "Boris Capitanu",
description = "OpenMary client",
name = "OpenMary Client",
tags = "openmary, speech, audio",
firingPolicy = FiringPolicy.all,
rights = Licenses.UofINCSA,
baseURL = "meandre://seasr.org/components/foundry/",
dependency = {"protobuf-java-2.2.0.jar"}
)
public class OpenMaryClient extends AbstractExecutableComponent {
//------------------------------ INPUTS ------------------------------------------------------
@ComponentInput(
name = Names.PORT_TEXT,
description = "The input data" +
"<br>TYPE: java.lang.String" +
"<br>TYPE: org.seasr.datatypes.BasicDataTypes.Strings" +
"<br>TYPE: byte[]" +
"<br>TYPE: org.seasr.datatypes.BasicDataTypes.Bytes" +
"<br>TYPE: java.lang.Object"
)
protected static final String IN_TEXT = Names.PORT_TEXT;
//------------------------------ OUTPUTS -----------------------------------------------------
@ComponentOutput(
name = "bytes",
description = "The output data" +
"<br>TYPE: org.seasr.datatypes.BasicDataTypes.Bytes"
)
protected static final String OUT_BYTES = "bytes";
//------------------------------ PROPERTIES --------------------------------------------------
@ComponentProperty(
name = "server_hostname",
description = "The hostname for the OpenMary server",
defaultValue = "localhost"
)
protected static final String PROP_SERVER = "server_hostname";
@ComponentProperty(
name = "server_port",
description = "The port number for the OpenMary server",
defaultValue = "59125"
)
protected static final String PROP_PORT = "server_port";
@ComponentProperty(
name = "locale",
description = "Specifies the language of the domain",
defaultValue = "en-US"
)
protected static final String PROP_LOCALE = "locale";
@ComponentProperty(
name = "input_type",
description = "The input type. Can be one of:<br>" +
"TEXT<br>SIMPLEPHONEMES<br>APML<br>SSML<br>SABLE<br>PARTSOFSPEECH<br>PHONEMES<br>" +
"INTONATION<br>ALLOPHONES<br>PRAAT_TEXTGRID<br>REALISED_DURATIONS<br>REALISED_ACOUSTPARAMS<br>" +
"RAWMARYXML<br>TOKENS<br>WORDS<br>ACOUSTPARAMS",
defaultValue = "TEXT"
)
protected static final String PROP_INPUT_TYPE = "input_type";
@ComponentProperty(
name = "output_type",
description = "The output type. Can be one of:<br>" +
"PARTSOFSPEECH<br>PHONEMES<br>INTONATION<br>ALLOPHONES<br>PRAAT_TEXTGRID<br>" +
"REALISED_DURATIONS<br>REALISED_ACOUSTPARAMS<br>RAWMARYXML<br>TOKENS<br>WORDS<br>" +
"ACOUSTPARAMS<br>HALFPHONE_TARGETFEATURES<br>TARGETFEATURES<br>AUDIO",
defaultValue = "AUDIO"
)
protected static final String PROP_OUTPUT_TYPE = "output_type";
@ComponentProperty(
name = "audio_type",
description = "The audio type. Can be one of:<br>" +
"WAVE<br>AU<br>AIFF",
defaultValue = "WAVE"
)
protected static final String PROP_AUDIO_TYPE = "audio_type";
//--------------------------------------------------------------------------------------------
protected MaryClient _openMary = null;
protected String _serverHost;
protected int _serverPort;
protected String _locale;
protected String _inputType;
protected String _outputType;
protected String _audioType;
protected String _defaultVoiceName = null;
//--------------------------------------------------------------------------------------------
@Override
public void initializeCallBack(ComponentContextProperties ccp) throws Exception {
_serverHost = getPropertyOrDieTrying(PROP_SERVER, ccp);
_serverPort = Integer.parseInt(getPropertyOrDieTrying(PROP_PORT, ccp));
_locale = getPropertyOrDieTrying(PROP_LOCALE, ccp);
_inputType = getPropertyOrDieTrying(PROP_INPUT_TYPE, ccp);
_outputType = getPropertyOrDieTrying(PROP_OUTPUT_TYPE, ccp);
_audioType = getPropertyOrDieTrying(PROP_AUDIO_TYPE, ccp);
}
@Override
public void executeCallBack(ComponentContext cc) throws Exception {
// Delay initialization until execute() so that if we have an OpenMary server
// component, it has time to start during initialize() before we attempt
// to connect to it
if (_openMary == null)
_openMary = MaryClient.getMaryClient(new Address(_serverHost, _serverPort));
for (String text : DataTypeParser.parseAsString(cc.getDataComponentFromInput(IN_TEXT))) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
- _openMary.process(text, _inputType, _outputType, _locale, _audioType, _defaultVoiceName, baos);
+ try {
+ _openMary.process(text, _inputType, _outputType, _locale, _audioType, _defaultVoiceName, baos);
+ }
+ catch (Exception e) {
+ console.severe(e.getMessage());
+ console.severe("The failing text follows:");
+ console.severe(text);
+ throw e;
+ }
cc.pushDataComponentToOutput(OUT_BYTES, BasicDataTypesTools.byteArrayToBytes(baos.toByteArray()));
}
}
@Override
public void disposeCallBack(ComponentContextProperties ccp) throws Exception {
_openMary = null;
}
}
| true | true |
public void executeCallBack(ComponentContext cc) throws Exception {
// Delay initialization until execute() so that if we have an OpenMary server
// component, it has time to start during initialize() before we attempt
// to connect to it
if (_openMary == null)
_openMary = MaryClient.getMaryClient(new Address(_serverHost, _serverPort));
for (String text : DataTypeParser.parseAsString(cc.getDataComponentFromInput(IN_TEXT))) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
_openMary.process(text, _inputType, _outputType, _locale, _audioType, _defaultVoiceName, baos);
cc.pushDataComponentToOutput(OUT_BYTES, BasicDataTypesTools.byteArrayToBytes(baos.toByteArray()));
}
}
|
public void executeCallBack(ComponentContext cc) throws Exception {
// Delay initialization until execute() so that if we have an OpenMary server
// component, it has time to start during initialize() before we attempt
// to connect to it
if (_openMary == null)
_openMary = MaryClient.getMaryClient(new Address(_serverHost, _serverPort));
for (String text : DataTypeParser.parseAsString(cc.getDataComponentFromInput(IN_TEXT))) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
_openMary.process(text, _inputType, _outputType, _locale, _audioType, _defaultVoiceName, baos);
}
catch (Exception e) {
console.severe(e.getMessage());
console.severe("The failing text follows:");
console.severe(text);
throw e;
}
cc.pushDataComponentToOutput(OUT_BYTES, BasicDataTypesTools.byteArrayToBytes(baos.toByteArray()));
}
}
|
diff --git a/server/src/org/oryxeditor/server/MultiDownloader.java b/server/src/org/oryxeditor/server/MultiDownloader.java
index 63e83fff..cfabed5b 100644
--- a/server/src/org/oryxeditor/server/MultiDownloader.java
+++ b/server/src/org/oryxeditor/server/MultiDownloader.java
@@ -1,202 +1,202 @@
package org.oryxeditor.server;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* Copyright (c) 2007 Martin Czuchra.
*
* 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.
*/
/**
* This is a rewrite of the original download.php for usage in plugins that need
* to run in the Java environment.
*
* There is no distinction between GET and POST requests, since code relying on
* download.php behaviour would perform a POST to just request the download of
* one or more files from the server.
*
* @author Martin Czuchra
*/
public class MultiDownloader extends HttpServlet {
private static final long serialVersionUID = 544537395679618334L;
/**
* The GET request forwards to the performDownload method.
*/
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
this.performDownload(req, res);
}
/**
* The POST request forwards to the performDownload method.
*/
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
this.performDownload(req, res);
}
private void prepareHeaders(HttpServletResponse res, String mimetype,
String name) {
res.setHeader("Pragma", "public");
res.setHeader("Expires", "0");
res.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
res.addHeader("Cache-Control", "private");
res.setHeader("Content-Transfer-Encoding", "binary");
res.setHeader("Content-Type", mimetype);
res.setHeader("Content-Disposition", "attachment; filename=\"" + name
+ "\"");
}
/**
* Creates a zipfile consisting of filenames and contents provided in
* filenames and contents parameters, respectively. The resulting zip file
* is written into the whereTo stream.
*
* This method requires that the length of the filenames and contents array
* is equal and performs an assertion on this.
*
* @param filenames
* the array of filenames to be written into the zip file.
* @param contents
* the array of file contents to be written into the zipfile
* for the file that is at the same array position in the
* filenames array.
* @param whereTo
* the stream the zipfile should be written to.
* @throws IOException
* when something goes wrong.
*/
private void zip(String[] filenames, String[] contents, OutputStream whereTo)
throws IOException {
assert (filenames.length == contents.length);
// enclose the whereTo stream into a ZipOutputStream.
ZipOutputStream out = new ZipOutputStream(whereTo);
// iterate over all filenames.
for (int i = 0; i < filenames.length; i++) {
// add a new entry for the current filename, write the current
// content and close the entry again.
out.putNextEntry(new ZipEntry(filenames[i]));
out.write(contents[i].getBytes());
out.closeEntry();
}
// Complete the ZIP file
out.close();
}
/**
* Performs the actual download independently of the original HTTP method of
* the request. See in-method comments for details.
*
* @param req
* The original HttpServletRequest object.
* @param res
* The original HttpServletResponse object.
* @throws IOException
*/
private void performDownload(HttpServletRequest req, HttpServletResponse res)
throws IOException {
// if there is a parameter named "download_0", then, by convention,
// there are more than one files to be downloaded in a zip file.
if (req.getParameter("download_0") != null) {
// traverse all files that should be downloaded and that are
// embedded in the request. the content of each file is stored in
// content, the filename in name.
int i = 0;
String content, name;
Vector<String> contents = new Vector<String>(), names = new Vector<String>();
while ((content = req.getParameter("download_" + i)) != null) {
// get current name and increment file counter.
name = req.getParameter("file_" + i++);
// while collecting, write all current names and contents into
// the appropriate Vector objects.
contents.add(content);
names.add(name);
}
// init two arrays the vectors will be cast into.
String[] contentsArray = new String[contents.size()];
String[] namesArray = new String[names.size()];
// prepare the response headers and send the requested file to the
// client. mimetype and filename originally were hardcoded into
// download.php, so they are here, since code may rely on this.
this.prepareHeaders(res, "application/zip", "result.zip");
this.zip(names.toArray(namesArray),
contents.toArray(contentsArray), res.getOutputStream());
} else if (req.getParameter("download") != null) {
// branch for fetching of one file exactly. get the name and content
// of the file into the appropriate string variables.
String name = req.getParameter("file");
- String content = req.getParameter("content");
+ String content = req.getParameter("download");
// prepare headers, with empty mimetype (as download.php does), and
// send the content of the file back to the user.
this.prepareHeaders(res, "", name);
res.getWriter().write(content);
} else {
// when none of the above rules applies, inform the user that
// nothing remains to be done.
// TODO Find appropriate HTTP message here, no code relies on this.
res.getWriter().println("There is nothing to be downloaded.");
}
}
}
| true | true |
private void performDownload(HttpServletRequest req, HttpServletResponse res)
throws IOException {
// if there is a parameter named "download_0", then, by convention,
// there are more than one files to be downloaded in a zip file.
if (req.getParameter("download_0") != null) {
// traverse all files that should be downloaded and that are
// embedded in the request. the content of each file is stored in
// content, the filename in name.
int i = 0;
String content, name;
Vector<String> contents = new Vector<String>(), names = new Vector<String>();
while ((content = req.getParameter("download_" + i)) != null) {
// get current name and increment file counter.
name = req.getParameter("file_" + i++);
// while collecting, write all current names and contents into
// the appropriate Vector objects.
contents.add(content);
names.add(name);
}
// init two arrays the vectors will be cast into.
String[] contentsArray = new String[contents.size()];
String[] namesArray = new String[names.size()];
// prepare the response headers and send the requested file to the
// client. mimetype and filename originally were hardcoded into
// download.php, so they are here, since code may rely on this.
this.prepareHeaders(res, "application/zip", "result.zip");
this.zip(names.toArray(namesArray),
contents.toArray(contentsArray), res.getOutputStream());
} else if (req.getParameter("download") != null) {
// branch for fetching of one file exactly. get the name and content
// of the file into the appropriate string variables.
String name = req.getParameter("file");
String content = req.getParameter("content");
// prepare headers, with empty mimetype (as download.php does), and
// send the content of the file back to the user.
this.prepareHeaders(res, "", name);
res.getWriter().write(content);
} else {
// when none of the above rules applies, inform the user that
// nothing remains to be done.
// TODO Find appropriate HTTP message here, no code relies on this.
res.getWriter().println("There is nothing to be downloaded.");
}
}
|
private void performDownload(HttpServletRequest req, HttpServletResponse res)
throws IOException {
// if there is a parameter named "download_0", then, by convention,
// there are more than one files to be downloaded in a zip file.
if (req.getParameter("download_0") != null) {
// traverse all files that should be downloaded and that are
// embedded in the request. the content of each file is stored in
// content, the filename in name.
int i = 0;
String content, name;
Vector<String> contents = new Vector<String>(), names = new Vector<String>();
while ((content = req.getParameter("download_" + i)) != null) {
// get current name and increment file counter.
name = req.getParameter("file_" + i++);
// while collecting, write all current names and contents into
// the appropriate Vector objects.
contents.add(content);
names.add(name);
}
// init two arrays the vectors will be cast into.
String[] contentsArray = new String[contents.size()];
String[] namesArray = new String[names.size()];
// prepare the response headers and send the requested file to the
// client. mimetype and filename originally were hardcoded into
// download.php, so they are here, since code may rely on this.
this.prepareHeaders(res, "application/zip", "result.zip");
this.zip(names.toArray(namesArray),
contents.toArray(contentsArray), res.getOutputStream());
} else if (req.getParameter("download") != null) {
// branch for fetching of one file exactly. get the name and content
// of the file into the appropriate string variables.
String name = req.getParameter("file");
String content = req.getParameter("download");
// prepare headers, with empty mimetype (as download.php does), and
// send the content of the file back to the user.
this.prepareHeaders(res, "", name);
res.getWriter().write(content);
} else {
// when none of the above rules applies, inform the user that
// nothing remains to be done.
// TODO Find appropriate HTTP message here, no code relies on this.
res.getWriter().println("There is nothing to be downloaded.");
}
}
|
diff --git a/src/org/protege/editor/owl/ui/metrics/DLNameKeyPanel.java b/src/org/protege/editor/owl/ui/metrics/DLNameKeyPanel.java
index f5b2e2c2..3ddae8b1 100644
--- a/src/org/protege/editor/owl/ui/metrics/DLNameKeyPanel.java
+++ b/src/org/protege/editor/owl/ui/metrics/DLNameKeyPanel.java
@@ -1,145 +1,145 @@
package org.protege.editor.owl.ui.metrics;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.protege.editor.core.ui.util.ComponentFactory;
import org.protege.editor.owl.ui.OWLIcons;
/**
* Author: Matthew Horridge<br>
* The University Of Manchester<br>
* Medical Informatics Group<br>
* Date: 03-Oct-2006<br><br>
* <p/>
* [email protected]<br>
* www.cs.man.ac.uk/~horridgm<br><br>
*/
public class DLNameKeyPanel extends JPanel {
public DLNameKeyPanel() {
List<NameObject> box = new ArrayList<NameObject>();
addExplanation(OWLIcons.getIcon("AL.png"),
"Attributive language. This is the base language which allows:" + "<ul><li>Atomic negation (negation of concepts that do not appear on the left hand side of axioms)</li>" + "<li>Concept intersection</li>" + "<li>Universal restrictions</li>" + "<li>Limited existential quatification (restrictions that only have fillers " + "of Thing)</li></ul>",
box);
// addExplanation(OWLIcons.getIcon("F.png"), "Attributive language", box);
addExplanation(OWLIcons.getIcon("FLM.png"),
"A sub-langauge of AL, which is obtained by disallowing atomic negation",
box);
addExplanation(OWLIcons.getIcon("FLO.png"),
- "A sub-language of FLo, which is obtained by disallowing limited existential quantification",
+ "A sub-language of FL-, which is obtained by disallowing limited existential quantification",
box);
addExplanation(OWLIcons.getIcon("C.png"), "Complex concept negation", box);
addExplanation(OWLIcons.getIcon("S.png"), "An abbreviation for AL and C with transitive properties", box);
addExplanation(OWLIcons.getIcon("H.png"), "Role hierarchy (subproperties - rdfs:subPropertyOf)", box);
addExplanation(OWLIcons.getIcon("O.png"),
"Nominals. (Enumerated classes or object value restrictions - owl:oneOf, owl:hasValue)",
box);
addExplanation(OWLIcons.getIcon("I.png"), "Inverse properties", box);
addExplanation(OWLIcons.getIcon("N.png"),
"Cardinality restrictions (owl:Cardinality, owl:minCardianlity, owl:maxCardinality)",
box);
addExplanation(OWLIcons.getIcon("Q.png"), "Qualified cardinality restrictions (available in OWL 1.1)", box);
addExplanation(OWLIcons.getIcon("F.png"), "Functional properties", box);
addExplanation(OWLIcons.getIcon("E.png"),
"Full existential quantification (Existential restrictions that have fillers other that owl:Thing)",
box);
addExplanation(OWLIcons.getIcon("U.png"), "Concept union", box);
addExplanation(OWLIcons.getIcon("Datatype.png"), "Use of datatype properties, data values or datatypes", box);
setLayout(new BorderLayout());
JList l = new JList(box.toArray());
l.setCellRenderer(new DefaultListCellRenderer() {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list,
value,
index,
isSelected,
cellHasFocus);
NameObject nameObject = (NameObject) value;
label.setIcon(nameObject.getIcon());
label.setText(nameObject.getDesc());
label.setFont(new Font(label.getFont().getName(), Font.PLAIN, 12));
label.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0,
0,
1,
0,
Color.LIGHT_GRAY),
BorderFactory.createEmptyBorder(5, 2, 5, 2)));
return label;
}
});
l.setBackground(Color.WHITE);
JScrollPane sp = ComponentFactory.createScrollPane(l);
add(sp, BorderLayout.CENTER);
}
private class NameObject {
private Icon icon;
private String desc;
public NameObject(final Icon icon, String desc) {
this.icon = new Icon() {
public void paintIcon(Component c, Graphics g, int x, int y) {
icon.paintIcon(c, g, x, y);
}
public int getIconWidth() {
return 80;
}
public int getIconHeight() {
return icon.getIconHeight();
}
};
this.desc = "<html><body>" + desc + "</body></html>";
}
public Icon getIcon() {
return icon;
}
public String getDesc() {
return desc;
}
}
private void addExplanation(Icon icon, String description, List<NameObject> list) {
list.add(new NameObject(icon, description));
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setContentPane(new DLNameKeyPanel());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
| true | true |
public DLNameKeyPanel() {
List<NameObject> box = new ArrayList<NameObject>();
addExplanation(OWLIcons.getIcon("AL.png"),
"Attributive language. This is the base language which allows:" + "<ul><li>Atomic negation (negation of concepts that do not appear on the left hand side of axioms)</li>" + "<li>Concept intersection</li>" + "<li>Universal restrictions</li>" + "<li>Limited existential quatification (restrictions that only have fillers " + "of Thing)</li></ul>",
box);
// addExplanation(OWLIcons.getIcon("F.png"), "Attributive language", box);
addExplanation(OWLIcons.getIcon("FLM.png"),
"A sub-langauge of AL, which is obtained by disallowing atomic negation",
box);
addExplanation(OWLIcons.getIcon("FLO.png"),
"A sub-language of FLo, which is obtained by disallowing limited existential quantification",
box);
addExplanation(OWLIcons.getIcon("C.png"), "Complex concept negation", box);
addExplanation(OWLIcons.getIcon("S.png"), "An abbreviation for AL and C with transitive properties", box);
addExplanation(OWLIcons.getIcon("H.png"), "Role hierarchy (subproperties - rdfs:subPropertyOf)", box);
addExplanation(OWLIcons.getIcon("O.png"),
"Nominals. (Enumerated classes or object value restrictions - owl:oneOf, owl:hasValue)",
box);
addExplanation(OWLIcons.getIcon("I.png"), "Inverse properties", box);
addExplanation(OWLIcons.getIcon("N.png"),
"Cardinality restrictions (owl:Cardinality, owl:minCardianlity, owl:maxCardinality)",
box);
addExplanation(OWLIcons.getIcon("Q.png"), "Qualified cardinality restrictions (available in OWL 1.1)", box);
addExplanation(OWLIcons.getIcon("F.png"), "Functional properties", box);
addExplanation(OWLIcons.getIcon("E.png"),
"Full existential quantification (Existential restrictions that have fillers other that owl:Thing)",
box);
addExplanation(OWLIcons.getIcon("U.png"), "Concept union", box);
addExplanation(OWLIcons.getIcon("Datatype.png"), "Use of datatype properties, data values or datatypes", box);
setLayout(new BorderLayout());
JList l = new JList(box.toArray());
l.setCellRenderer(new DefaultListCellRenderer() {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list,
value,
index,
isSelected,
cellHasFocus);
NameObject nameObject = (NameObject) value;
label.setIcon(nameObject.getIcon());
label.setText(nameObject.getDesc());
label.setFont(new Font(label.getFont().getName(), Font.PLAIN, 12));
label.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0,
0,
1,
0,
Color.LIGHT_GRAY),
BorderFactory.createEmptyBorder(5, 2, 5, 2)));
return label;
}
});
l.setBackground(Color.WHITE);
JScrollPane sp = ComponentFactory.createScrollPane(l);
add(sp, BorderLayout.CENTER);
}
|
public DLNameKeyPanel() {
List<NameObject> box = new ArrayList<NameObject>();
addExplanation(OWLIcons.getIcon("AL.png"),
"Attributive language. This is the base language which allows:" + "<ul><li>Atomic negation (negation of concepts that do not appear on the left hand side of axioms)</li>" + "<li>Concept intersection</li>" + "<li>Universal restrictions</li>" + "<li>Limited existential quatification (restrictions that only have fillers " + "of Thing)</li></ul>",
box);
// addExplanation(OWLIcons.getIcon("F.png"), "Attributive language", box);
addExplanation(OWLIcons.getIcon("FLM.png"),
"A sub-langauge of AL, which is obtained by disallowing atomic negation",
box);
addExplanation(OWLIcons.getIcon("FLO.png"),
"A sub-language of FL-, which is obtained by disallowing limited existential quantification",
box);
addExplanation(OWLIcons.getIcon("C.png"), "Complex concept negation", box);
addExplanation(OWLIcons.getIcon("S.png"), "An abbreviation for AL and C with transitive properties", box);
addExplanation(OWLIcons.getIcon("H.png"), "Role hierarchy (subproperties - rdfs:subPropertyOf)", box);
addExplanation(OWLIcons.getIcon("O.png"),
"Nominals. (Enumerated classes or object value restrictions - owl:oneOf, owl:hasValue)",
box);
addExplanation(OWLIcons.getIcon("I.png"), "Inverse properties", box);
addExplanation(OWLIcons.getIcon("N.png"),
"Cardinality restrictions (owl:Cardinality, owl:minCardianlity, owl:maxCardinality)",
box);
addExplanation(OWLIcons.getIcon("Q.png"), "Qualified cardinality restrictions (available in OWL 1.1)", box);
addExplanation(OWLIcons.getIcon("F.png"), "Functional properties", box);
addExplanation(OWLIcons.getIcon("E.png"),
"Full existential quantification (Existential restrictions that have fillers other that owl:Thing)",
box);
addExplanation(OWLIcons.getIcon("U.png"), "Concept union", box);
addExplanation(OWLIcons.getIcon("Datatype.png"), "Use of datatype properties, data values or datatypes", box);
setLayout(new BorderLayout());
JList l = new JList(box.toArray());
l.setCellRenderer(new DefaultListCellRenderer() {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list,
value,
index,
isSelected,
cellHasFocus);
NameObject nameObject = (NameObject) value;
label.setIcon(nameObject.getIcon());
label.setText(nameObject.getDesc());
label.setFont(new Font(label.getFont().getName(), Font.PLAIN, 12));
label.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0,
0,
1,
0,
Color.LIGHT_GRAY),
BorderFactory.createEmptyBorder(5, 2, 5, 2)));
return label;
}
});
l.setBackground(Color.WHITE);
JScrollPane sp = ComponentFactory.createScrollPane(l);
add(sp, BorderLayout.CENTER);
}
|
diff --git a/core/src/visad/trunk/VisADGeometryArray.java b/core/src/visad/trunk/VisADGeometryArray.java
index b236640a6..22958c73f 100644
--- a/core/src/visad/trunk/VisADGeometryArray.java
+++ b/core/src/visad/trunk/VisADGeometryArray.java
@@ -1,557 +1,557 @@
//
// VisADGeometryArray.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2002 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library 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 visad;
import java.util.*;
/**
VisADGeometryArray stands in for j3d.GeometryArray
and is Serializable.<P>
*/
public abstract class VisADGeometryArray extends VisADSceneGraphObject
implements Cloneable {
public int vertexCount;
public int vertexFormat;
public float[] coordinates;
public float[] normals;
public byte[] colors;
public float[] texCoords;
// stuff for longitude
boolean any_longitude_rotate = false;
int longitude_axis = -1;
ScalarMap longitude_map = null;
CoordinateSystem longitude_cs = null;
float[][] longitude_coords = null;
public VisADGeometryArray() {
vertexCount = 0;
vertexFormat = 0;
coordinates = null;
normals = null;
colors = null;
texCoords = null;
}
/** eliminate any vectors or triangles crossing seams of
map projections, defined by display-side CoordinateSystems;
this default implementation does nothing */
public VisADGeometryArray adjustSeam(DataRenderer renderer)
throws VisADException {
CoordinateSystem coord_sys = renderer.getDisplayCoordinateSystem();
// WLH 13 March 2000
// if (coord_sys == null) return this;
if (coord_sys == null || coord_sys instanceof SphericalCoordinateSystem) {
return this;
}
return this;
}
/** like adjustLongitude, but rather than splitting vectors or
triangles, keep the VisADGeometryArray intact but possibly
move it in longitude (try to keep its centroid on the "main"
side of the seam) */
public VisADGeometryArray adjustLongitudeBulk(DataRenderer renderer)
throws VisADException {
float[] lons = getLongitudes(renderer, true); // bulk = true
return this;
}
/** split any vectors or triangles crossing crossing longitude
seams when Longitude is mapped to a Cartesian display axis;
default implementation: rotate if necessary, then return points */
public VisADGeometryArray adjustLongitude(DataRenderer renderer)
throws VisADException {
float[] lons = getLongitudes(renderer);
if (any_longitude_rotate) {
// some coordinates changed, so return VisADPointArray
VisADPointArray array = new VisADPointArray();
array.vertexCount = vertexCount;
array.coordinates = coordinates;
array.colors = colors;
return array;
}
else {
return this;
}
}
static float rotateOneLongitude(float lon, float base) {
if (lon == lon) {
float x = (lon - base) % 360.0f;
return (x + ((x < 0.0f) ? (360.0f + base) : base));
}
else {
return lon;
}
}
void rotateLongitudes(float[] lons, float base, boolean bulk)
throws VisADException {
boolean any = false;
// so rotate longitudes to base
if (bulk) {
float mean_lon = 0.0f;
int n = 0;
for (int i=0; i<vertexCount; i++) {
if (lons[i] == lons[i]) {
mean_lon += lons[i];
n++;
}
}
mean_lon = mean_lon / n;
float x = (mean_lon - base) % 360.0f;
x += (x < 0.0f) ? (360.0f + base) : base;
if (x != mean_lon) {
x = x - mean_lon;
any = true;
}
if (any) {
for (int i=0; i<vertexCount; i++) {
if (lons[i] == lons[i]) {
lons[i] += x;
}
}
}
}
else { // !bulk
for (int i=0; i<vertexCount; i++) {
if (lons[i] == lons[i]) {
float x = (lons[i] - base) % 360.0f;
x += (x < 0.0f) ? (360.0f + base) : base;
if (x != lons[i]) {
lons[i] = x;
any = true;
}
}
}
}
if (any) {
if (longitude_cs == null) {
float[] coords = longitude_map.scaleValues(lons);
for (int i=0; i<vertexCount; i++) {
coordinates[3 * i + longitude_axis] = coords[i];
}
}
else {
longitude_coords[longitude_axis] = longitude_map.scaleValues(lons);
float[][] coords = longitude_cs.toReference(longitude_coords);
int k = 0;
for (int i=0; i<vertexCount; i++) {
coordinates[k++] = coords[0][i];
coordinates[k++] = coords[1][i];
coordinates[k++] = coords[2][i];
}
}
any_longitude_rotate = true;
}
}
float[] getLongitudes(DataRenderer renderer)
throws VisADException {
return getLongitudes(renderer, false);
}
float[] getLongitudes(DataRenderer renderer, boolean bulk)
throws VisADException {
any_longitude_rotate = false;
longitude_map = null;
longitude_axis = -1;
longitude_cs = null;
longitude_coords = null;
Vector mapVector = renderer.getDisplay().getMapVector();
Enumeration maps = mapVector.elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (!RealType.Longitude.equals(map.getScalar())) continue;
// getCircular() true for Latitude, Longitude, CylAzimuth, etc
if (dreal.getCircular()) return null; // do nothing!
if (tuple != null &&
(tuple.equals(Display.DisplaySpatialCartesianTuple) ||
(tuple.getCoordinateSystem() != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)))) { // spatial
// System.out.println("getLongitudes: found a map from Longitude to a spatial axis");
// have found a map from Longitude to a spatial DisplayRealType
// other than Longitude or CylAzimuth
double[] map_range = map.getRange();
float map_min = (float) map_range[0];
float map_max = (float) map_range[1];
// System.out.println("map = " + map);
// System.out.println("map_min = " + map_min + " map_max = " + map_max);
// leave some information for getLongitudeRange
longitude_map = map;
longitude_axis = dreal.getTupleIndex();
longitude_cs = tuple.getCoordinateSystem(); // may be null
float[] lons = null;
if (longitude_cs == null) {
+ lons = new float[vertexCount];
for (int i=0; i<vertexCount; i++) {
- lons = new float[vertexCount];
lons[i] = coordinates[3 * i + longitude_axis];
}
}
else {
float[][] coords = new float[3][vertexCount];
int k = 0;
for (int i=0; i<vertexCount; i++) {
coords[0][i] = coordinates[k++];
coords[1][i] = coordinates[k++];
coords[2][i] = coordinates[k++];
}
longitude_coords = longitude_cs.fromReference(coords);
lons = longitude_coords[longitude_axis];
}
lons = longitude_map.inverseScaleValues(lons);
// get range of Longitude values
float lon_min = Float.MAX_VALUE;
// float lon_max = Float.MIN_VALUE;
float lon_max = -Float.MAX_VALUE;
for (int i=0; i<vertexCount; i++) {
if (lons[i] == lons[i]) {
// System.out.println("lons[" + i + "] = " + lons[i]);
if (lons[i] < lon_min) lon_min = lons[i];
if (lons[i] > lon_max) lon_max = lons[i];
}
}
// System.out.println("lon_min = " + lon_min + " lon_max = " + lon_max);
if (lon_min == Float.MAX_VALUE) {
longitude_coords = null;
return lons;
}
boolean any_rotate = false;
if (map_min == map_min && map_max == map_max) {
float map_delta = 0.1f * (map_max - map_min);
// System.out.println("map_delta = " + map_delta);
if ( ((map_min + map_delta) < lon_min &&
(map_max + map_delta) < lon_max) ||
(lon_min < (map_min - map_delta) &&
lon_max < (map_max - map_delta)) ) {
float new_lon_min = rotateOneLongitude(lon_min, map_min);
float new_lon_max = rotateOneLongitude(lon_max, map_min);
float dist_min =
(lon_min < map_min) ? (map_min - lon_min) :
(map_max < lon_min) ? (lon_min - map_max) : 0.0f;
float new_dist_min =
(new_lon_min < map_min) ? (map_min - new_lon_min) :
(map_max < new_lon_min) ? (new_lon_min - map_max) : 0.0f;
float dist_max =
(lon_max < map_min) ? (map_min - lon_max) :
(map_max < lon_max) ? (lon_max - map_max) : 0.0f;
float new_dist_max =
(new_lon_max < map_min) ? (map_min - new_lon_max) :
(map_max < new_lon_max) ? (new_lon_max - map_max) : 0.0f;
if ((new_dist_min + new_dist_max) < (dist_min + dist_max)) {
// actual longitudes are shifted significantly from map,
// so rotate longitudes to base at map_min
// System.out.println("rotateLongitudes to map_min " + map_min);
any_rotate = true;
rotateLongitudes(lons, map_min, bulk);
}
}
}
if (!any_rotate && (lon_min + 360.0f) < lon_max) {
// System.out.println("rotateLongitudes to lon_min " + lon_min);
rotateLongitudes(lons, lon_min, bulk);
}
/*
for (int i=0; i<vertexCount; i++) {
System.out.println("return lons[" + i + "] = " + lons[i]);
}
*/
longitude_coords = null;
return lons;
} // end if (tuple != null && ...
} // end while(maps.hasMoreElements())
int[] indices = renderer.getLatLonIndices();
if (indices[0] < 0 || indices[1] < 0) return null;
float[][] locs = new float[3][vertexCount];
int k = 0;
for (int i=0; i<vertexCount; i++) {
locs[0][i] = coordinates[k++];
locs[1][i] = coordinates[k++];
locs[2][i] = coordinates[k++];
}
float[][] latlons = renderer.earthToSpatial(locs, null);
longitude_coords = null;
return latlons[1];
}
// always called after getLongitudes()
float[] getLongitudeRange(float[] lons, int[] axis,
float[] coords) {
float[] lon_range = {Float.NaN, Float.NaN};
axis[0] = -1;
coords[0] = Float.NaN;
coords[1] = Float.NaN;
float lon_min = Float.MAX_VALUE;
// float lon_max = Float.MIN_VALUE;
float lon_max = -Float.MAX_VALUE;
for (int i=0; i<vertexCount; i++) {
if (lons[i] == lons[i]) {
if (lons[i] < lon_min) lon_min = lons[i];
if (lons[i] > lon_max) lon_max = lons[i];
}
}
// WLH 30 Dec 99
if ((lon_max - lon_min) < 1.0f) {
lon_max += 0.5f;
lon_min -= 0.5f;
}
if (lon_min <= lon_max) {
/* WLH 30 Dec 99
float delta = 1.0f; // allow a little slop in Longitudes
*/
float delta = (lon_max - lon_min) / 10.0f; // allow a little slop in Longitudes
if (delta > 1.0f) delta = 1.0f;
float x = (lon_min + delta) % 180.0f;
if (x < 0.0f) x += 180.0f;
float y = (lon_min + delta) - x;
if ((lon_max - delta) < y + 360.0f) {
lon_range[0] = y;
lon_range[1] = y + 360.0f;
}
else {
lon_range[0] = lon_min;
lon_range[1] = lon_min + 360.0f;
}
if (longitude_map != null && longitude_cs == null) {
float[] xcoords = longitude_map.scaleValues(lon_range);
coords[0] = xcoords[0];
coords[1] = xcoords[1];
axis[0] = longitude_axis;
}
else {
coords[0] = Float.NaN;
coords[1] = Float.NaN;
axis[0] = -1;
}
}
return lon_range;
}
public VisADGeometryArray removeMissing() {
VisADPointArray array = new VisADPointArray();
float[] coords = new float[coordinates.length];
int color_length = 3;
byte[] cols = null;
if (colors != null) {
cols = new byte[colors.length];
if (colors.length != coordinates.length) color_length = 4;
}
int k = 0;
int m = 0;
int j = 0;
boolean any_missing = false;
for (int i=0; i<coordinates.length; i+=3) {
if (coordinates[i] == coordinates[i] &&
coordinates[i+1] == coordinates[i+1] &&
coordinates[i+2] == coordinates[i+2]) {
coords[k] = coordinates[i];
coords[k+1] = coordinates[i+1];
coords[k+2] = coordinates[i+2];
if (colors != null) {
cols[m] = colors[j];
cols[m+1] = colors[j+1];
cols[m+2] = colors[j+2];
m += 3;
if (color_length == 4) {
cols[m++] = colors[j+3];
}
}
k += 3;
}
else { // missing coordinates values
any_missing = true;
}
j += color_length;
}
if (!any_missing) {
return this;
}
else {
array.coordinates = new float[k];
System.arraycopy(coords, 0, array.coordinates, 0, k);
if (colors != null) {
array.colors = new byte[m];
System.arraycopy(cols, 0, array.colors, 0, m);
}
return array;
}
}
static void merge(VisADGeometryArray[] arrays, VisADGeometryArray array)
throws VisADException {
if (arrays == null || arrays.length == 0 || array == null) return;
int n = arrays.length;
int count = 0;
boolean color_flag = false;
boolean normal_flag = false;
boolean texCoord_flag = false;
boolean any = false;
int vf = 0;
for (int i=0; i<n; i++) {
if (arrays[i] != null) {
color_flag = (arrays[i].colors != null);
normal_flag = (arrays[i].normals != null);
texCoord_flag = (arrays[i].texCoords != null);
vf = arrays[i].vertexFormat;
any = true;
}
}
if (!any) return;
for (int i=0; i<n; i++) {
if (arrays[i] == null) continue;
count += arrays[i].vertexCount;
if (color_flag != (arrays[i].colors != null) ||
normal_flag != (arrays[i].normals != null) ||
texCoord_flag != (arrays[i].texCoords != null)) {
throw new DisplayException("VisADGeometryArray.merge: formats don't match");
}
}
float[] coordinates = new float[3 * count];
byte[] colors = null;
float[] normals = null;
float[] texCoords = null;
if (color_flag) {
colors = new byte[3 * count];
}
if (normal_flag) {
normals = new float[3 * count];
}
if (texCoord_flag) {
texCoords = new float[3 * count];
}
int k = 0;
int kc = 0;
int kn = 0;
int kt = 0;
for (int i=0; i<n; i++) {
if (arrays[i] == null) continue;
float[] c = arrays[i].coordinates;
for (int j=0; j<3*arrays[i].vertexCount; j++) {
coordinates[k++] = c[j];
}
if (color_flag) {
byte[] b = arrays[i].colors;
for (int j=0; j<3*arrays[i].vertexCount; j++) {
colors[kc++] = b[j];
}
}
if (normal_flag) {
c = arrays[i].normals;
for (int j=0; j<3*arrays[i].vertexCount; j++) {
normals[kn++] = c[j];
}
}
if (texCoord_flag) {
c = arrays[i].texCoords;
for (int j=0; j<3*arrays[i].vertexCount; j++) {
texCoords[kt++] = c[j];
}
}
}
array.vertexCount = count;
array.coordinates = coordinates;
array.colors = colors;
array.normals = normals;
array.texCoords = texCoords;
array.vertexFormat = vf;
return;
}
public String toString() {
String string = "GeometryArray, vertexCount = " + vertexCount +
" vertexFormat = " + vertexFormat;
if (coordinates != null) {
string = string + "\n coordinates = " + floatArrayString(coordinates);
}
if (colors != null) {
string = string + "\n colors = " + byteArrayString(colors);
}
if (normals != null) {
string = string + "\n normals = " + floatArrayString(normals);
}
if (texCoords != null) {
string = string + "\n texCoords = " + floatArrayString(texCoords);
}
return string;
}
static String floatArrayString(float[] value) {
String string = "";
for (int i=0; i<value.length; i++) string = string + " " + value[i];
return string;
}
static String byteArrayString(byte[] value) {
String string = "";
for (int i=0; i<value.length; i++) string = string + " " + value[i];
return string;
}
public void copy(VisADGeometryArray array) {
array.vertexCount = vertexCount;
array.vertexFormat = vertexFormat;
if (coordinates != null) {
array.coordinates = new float[coordinates.length];
System.arraycopy(coordinates, 0, array.coordinates, 0,
coordinates.length);
}
if (normals != null) {
array.normals = new float[normals.length];
System.arraycopy(normals, 0, array.normals, 0,
normals.length);
}
if (colors != null) {
array.colors = new byte[colors.length];
System.arraycopy(colors, 0, array.colors, 0,
colors.length);
}
if (texCoords != null) {
array.texCoords = new float[texCoords.length];
System.arraycopy(texCoords, 0, array.texCoords, 0,
texCoords.length);
}
}
public abstract Object clone();
}
| false | true |
float[] getLongitudes(DataRenderer renderer, boolean bulk)
throws VisADException {
any_longitude_rotate = false;
longitude_map = null;
longitude_axis = -1;
longitude_cs = null;
longitude_coords = null;
Vector mapVector = renderer.getDisplay().getMapVector();
Enumeration maps = mapVector.elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (!RealType.Longitude.equals(map.getScalar())) continue;
// getCircular() true for Latitude, Longitude, CylAzimuth, etc
if (dreal.getCircular()) return null; // do nothing!
if (tuple != null &&
(tuple.equals(Display.DisplaySpatialCartesianTuple) ||
(tuple.getCoordinateSystem() != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)))) { // spatial
// System.out.println("getLongitudes: found a map from Longitude to a spatial axis");
// have found a map from Longitude to a spatial DisplayRealType
// other than Longitude or CylAzimuth
double[] map_range = map.getRange();
float map_min = (float) map_range[0];
float map_max = (float) map_range[1];
// System.out.println("map = " + map);
// System.out.println("map_min = " + map_min + " map_max = " + map_max);
// leave some information for getLongitudeRange
longitude_map = map;
longitude_axis = dreal.getTupleIndex();
longitude_cs = tuple.getCoordinateSystem(); // may be null
float[] lons = null;
if (longitude_cs == null) {
for (int i=0; i<vertexCount; i++) {
lons = new float[vertexCount];
lons[i] = coordinates[3 * i + longitude_axis];
}
}
else {
float[][] coords = new float[3][vertexCount];
int k = 0;
for (int i=0; i<vertexCount; i++) {
coords[0][i] = coordinates[k++];
coords[1][i] = coordinates[k++];
coords[2][i] = coordinates[k++];
}
longitude_coords = longitude_cs.fromReference(coords);
lons = longitude_coords[longitude_axis];
}
lons = longitude_map.inverseScaleValues(lons);
// get range of Longitude values
float lon_min = Float.MAX_VALUE;
// float lon_max = Float.MIN_VALUE;
float lon_max = -Float.MAX_VALUE;
for (int i=0; i<vertexCount; i++) {
if (lons[i] == lons[i]) {
// System.out.println("lons[" + i + "] = " + lons[i]);
if (lons[i] < lon_min) lon_min = lons[i];
if (lons[i] > lon_max) lon_max = lons[i];
}
}
// System.out.println("lon_min = " + lon_min + " lon_max = " + lon_max);
if (lon_min == Float.MAX_VALUE) {
longitude_coords = null;
return lons;
}
boolean any_rotate = false;
if (map_min == map_min && map_max == map_max) {
float map_delta = 0.1f * (map_max - map_min);
// System.out.println("map_delta = " + map_delta);
if ( ((map_min + map_delta) < lon_min &&
(map_max + map_delta) < lon_max) ||
(lon_min < (map_min - map_delta) &&
lon_max < (map_max - map_delta)) ) {
float new_lon_min = rotateOneLongitude(lon_min, map_min);
float new_lon_max = rotateOneLongitude(lon_max, map_min);
float dist_min =
(lon_min < map_min) ? (map_min - lon_min) :
(map_max < lon_min) ? (lon_min - map_max) : 0.0f;
float new_dist_min =
(new_lon_min < map_min) ? (map_min - new_lon_min) :
(map_max < new_lon_min) ? (new_lon_min - map_max) : 0.0f;
float dist_max =
(lon_max < map_min) ? (map_min - lon_max) :
(map_max < lon_max) ? (lon_max - map_max) : 0.0f;
float new_dist_max =
(new_lon_max < map_min) ? (map_min - new_lon_max) :
(map_max < new_lon_max) ? (new_lon_max - map_max) : 0.0f;
if ((new_dist_min + new_dist_max) < (dist_min + dist_max)) {
// actual longitudes are shifted significantly from map,
// so rotate longitudes to base at map_min
// System.out.println("rotateLongitudes to map_min " + map_min);
any_rotate = true;
rotateLongitudes(lons, map_min, bulk);
}
}
}
if (!any_rotate && (lon_min + 360.0f) < lon_max) {
// System.out.println("rotateLongitudes to lon_min " + lon_min);
rotateLongitudes(lons, lon_min, bulk);
}
/*
for (int i=0; i<vertexCount; i++) {
System.out.println("return lons[" + i + "] = " + lons[i]);
}
*/
longitude_coords = null;
return lons;
} // end if (tuple != null && ...
} // end while(maps.hasMoreElements())
int[] indices = renderer.getLatLonIndices();
if (indices[0] < 0 || indices[1] < 0) return null;
float[][] locs = new float[3][vertexCount];
int k = 0;
for (int i=0; i<vertexCount; i++) {
locs[0][i] = coordinates[k++];
locs[1][i] = coordinates[k++];
locs[2][i] = coordinates[k++];
}
float[][] latlons = renderer.earthToSpatial(locs, null);
longitude_coords = null;
return latlons[1];
}
|
float[] getLongitudes(DataRenderer renderer, boolean bulk)
throws VisADException {
any_longitude_rotate = false;
longitude_map = null;
longitude_axis = -1;
longitude_cs = null;
longitude_coords = null;
Vector mapVector = renderer.getDisplay().getMapVector();
Enumeration maps = mapVector.elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (!RealType.Longitude.equals(map.getScalar())) continue;
// getCircular() true for Latitude, Longitude, CylAzimuth, etc
if (dreal.getCircular()) return null; // do nothing!
if (tuple != null &&
(tuple.equals(Display.DisplaySpatialCartesianTuple) ||
(tuple.getCoordinateSystem() != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)))) { // spatial
// System.out.println("getLongitudes: found a map from Longitude to a spatial axis");
// have found a map from Longitude to a spatial DisplayRealType
// other than Longitude or CylAzimuth
double[] map_range = map.getRange();
float map_min = (float) map_range[0];
float map_max = (float) map_range[1];
// System.out.println("map = " + map);
// System.out.println("map_min = " + map_min + " map_max = " + map_max);
// leave some information for getLongitudeRange
longitude_map = map;
longitude_axis = dreal.getTupleIndex();
longitude_cs = tuple.getCoordinateSystem(); // may be null
float[] lons = null;
if (longitude_cs == null) {
lons = new float[vertexCount];
for (int i=0; i<vertexCount; i++) {
lons[i] = coordinates[3 * i + longitude_axis];
}
}
else {
float[][] coords = new float[3][vertexCount];
int k = 0;
for (int i=0; i<vertexCount; i++) {
coords[0][i] = coordinates[k++];
coords[1][i] = coordinates[k++];
coords[2][i] = coordinates[k++];
}
longitude_coords = longitude_cs.fromReference(coords);
lons = longitude_coords[longitude_axis];
}
lons = longitude_map.inverseScaleValues(lons);
// get range of Longitude values
float lon_min = Float.MAX_VALUE;
// float lon_max = Float.MIN_VALUE;
float lon_max = -Float.MAX_VALUE;
for (int i=0; i<vertexCount; i++) {
if (lons[i] == lons[i]) {
// System.out.println("lons[" + i + "] = " + lons[i]);
if (lons[i] < lon_min) lon_min = lons[i];
if (lons[i] > lon_max) lon_max = lons[i];
}
}
// System.out.println("lon_min = " + lon_min + " lon_max = " + lon_max);
if (lon_min == Float.MAX_VALUE) {
longitude_coords = null;
return lons;
}
boolean any_rotate = false;
if (map_min == map_min && map_max == map_max) {
float map_delta = 0.1f * (map_max - map_min);
// System.out.println("map_delta = " + map_delta);
if ( ((map_min + map_delta) < lon_min &&
(map_max + map_delta) < lon_max) ||
(lon_min < (map_min - map_delta) &&
lon_max < (map_max - map_delta)) ) {
float new_lon_min = rotateOneLongitude(lon_min, map_min);
float new_lon_max = rotateOneLongitude(lon_max, map_min);
float dist_min =
(lon_min < map_min) ? (map_min - lon_min) :
(map_max < lon_min) ? (lon_min - map_max) : 0.0f;
float new_dist_min =
(new_lon_min < map_min) ? (map_min - new_lon_min) :
(map_max < new_lon_min) ? (new_lon_min - map_max) : 0.0f;
float dist_max =
(lon_max < map_min) ? (map_min - lon_max) :
(map_max < lon_max) ? (lon_max - map_max) : 0.0f;
float new_dist_max =
(new_lon_max < map_min) ? (map_min - new_lon_max) :
(map_max < new_lon_max) ? (new_lon_max - map_max) : 0.0f;
if ((new_dist_min + new_dist_max) < (dist_min + dist_max)) {
// actual longitudes are shifted significantly from map,
// so rotate longitudes to base at map_min
// System.out.println("rotateLongitudes to map_min " + map_min);
any_rotate = true;
rotateLongitudes(lons, map_min, bulk);
}
}
}
if (!any_rotate && (lon_min + 360.0f) < lon_max) {
// System.out.println("rotateLongitudes to lon_min " + lon_min);
rotateLongitudes(lons, lon_min, bulk);
}
/*
for (int i=0; i<vertexCount; i++) {
System.out.println("return lons[" + i + "] = " + lons[i]);
}
*/
longitude_coords = null;
return lons;
} // end if (tuple != null && ...
} // end while(maps.hasMoreElements())
int[] indices = renderer.getLatLonIndices();
if (indices[0] < 0 || indices[1] < 0) return null;
float[][] locs = new float[3][vertexCount];
int k = 0;
for (int i=0; i<vertexCount; i++) {
locs[0][i] = coordinates[k++];
locs[1][i] = coordinates[k++];
locs[2][i] = coordinates[k++];
}
float[][] latlons = renderer.earthToSpatial(locs, null);
longitude_coords = null;
return latlons[1];
}
|
diff --git a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java
index f2a79bc7..ffd59f66 100644
--- a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java
+++ b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java
@@ -1,1725 +1,1725 @@
package gov.nih.nci.evs.browser.bean;
import java.util.*;
import java.net.URI;
import javax.faces.context.*;
import javax.faces.event.*;
import javax.faces.model.*;
import javax.servlet.http.*;
import org.LexGrid.concepts.*;
import org.LexGrid.LexBIG.DataModel.Core.*;
import org.LexGrid.LexBIG.Utility.Iterators.*;
import gov.nih.nci.evs.browser.utils.*;
import gov.nih.nci.evs.browser.properties.*;
import gov.nih.nci.evs.browser.common.*;
import gov.nih.nci.evs.searchlog.*;
import org.apache.log4j.*;
import org.LexGrid.LexBIG.caCore.interfaces.LexEVSDistributed;
import org.lexgrid.valuesets.LexEVSValueSetDefinitionServices;
import org.LexGrid.valueSets.ValueSetDefinition;
import org.LexGrid.commonTypes.Source;
/**
* <!-- LICENSE_TEXT_START -->
* Copyright 2008,2009 NGIT. This software was developed in conjunction
* with the National Cancer Institute, and so to the extent government
* employees are co-authors, any rights in such works shall be subject
* to Title 17 of the United States Code, section 105.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the disclaimer of Article 3,
* below. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* 2. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by NGIT and the National
* Cancer Institute." If no such end-user documentation is to be
* included, this acknowledgment shall appear in the software itself,
* wherever such third-party acknowledgments normally appear.
* 3. The names "The National Cancer Institute", "NCI" and "NGIT" must
* not be used to endorse or promote products derived from this software.
* 4. This license does not authorize the incorporation of this software
* into any third party proprietary programs. This license does not
* authorize the recipient to use any trademarks owned by either NCI
* or NGIT
* 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE
* DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE,
* NGIT, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* <!-- LICENSE_TEXT_END -->
*/
/**
* @author EVS Team
* @version 1.0
*
* Modification history Initial implementation [email protected]
*
*/
public class UserSessionBean extends Object {
private static Logger _logger = Logger.getLogger(UserSessionBean.class);
private static String _contains_warning_msg =
"(WARNING: Only a subset of results may appear due to current limits in the terminology server (see Known Issues on the Help page).)";
private String _selectedQuickLink = null;
private List _quickLinkList = null;
public List<SelectItem> _ontologyList = null;
public List<String> _ontologiesToSearchOn = null;
public String contextPath = null;
public UserSessionBean() {
_ontologiesToSearchOn = new ArrayList<String>();
contextPath = getContextPath();
}
public String getContextPath() {
if (contextPath == null) {
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
contextPath = request.getContextPath();
}
return contextPath;
}
public void setSelectedQuickLink(String selectedQuickLink) {
_selectedQuickLink = selectedQuickLink;
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
request.getSession().setAttribute("selectedQuickLink",
selectedQuickLink);
}
public String getSelectedQuickLink() {
return _selectedQuickLink;
}
public void quickLinkChanged(ValueChangeEvent event) {
if (event.getNewValue() == null)
return;
String newValue = (String) event.getNewValue();
// _logger.debug("quickLinkChanged; " + newValue);
setSelectedQuickLink(newValue);
HttpServletResponse response =
(HttpServletResponse) FacesContext.getCurrentInstance()
.getExternalContext().getResponse();
String targetURL = null;// "http://nciterms.nci.nih.gov/";
if (_selectedQuickLink.compareTo("NCI Terminology Browser") == 0) {
targetURL = "http://nciterms.nci.nih.gov/";
}
try {
response.sendRedirect(response.encodeRedirectURL(targetURL));
} catch (Exception ex) {
ex.printStackTrace();
// send error message
}
}
public List getQuickLinkList() {
_quickLinkList = new ArrayList();
_quickLinkList.add(new SelectItem("Quick Links"));
_quickLinkList.add(new SelectItem("NCI Terminology Browser"));
_quickLinkList.add(new SelectItem("NCI MetaThesaurus"));
_quickLinkList.add(new SelectItem("EVS Home"));
_quickLinkList.add(new SelectItem("NCI Terminology Resources"));
return _quickLinkList;
}
public String searchAction() {
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
String matchText = (String) request.getParameter("matchText");
if (matchText != null)
matchText = matchText.trim();
// [#19965] Error message is not displayed when Search Criteria is not
// proivded
if (matchText == null || matchText.length() == 0) {
String message = "Please enter a search string.";
request.getSession().setAttribute("message", message);
// request.getSession().removeAttribute("matchText");
request.removeAttribute("matchText");
return "message";
}
request.getSession().setAttribute("matchText", matchText);
String matchAlgorithm = (String) request.getParameter("algorithm");
String searchTarget = (String) request.getParameter("searchTarget");
request.getSession().setAttribute("searchTarget", searchTarget);
request.getSession().setAttribute("algorithm", matchAlgorithm);
boolean ranking = true;
String scheme = request.getParameter("scheme");
String searchaction_dictionary = request.getParameter("dictionary");
if (scheme == null) {
scheme = (String) request.getAttribute("scheme");
}
if (scheme == null) {
scheme = (String) request.getParameter("dictionary");
}
if (scheme == null) {
scheme = Constants.CODING_SCHEME_NAME;
}
String version = (String) request.getParameter("version");
if (version == null) {
version = DataUtils.getVocabularyVersionByTag(scheme, "PRODUCTION");
}
request.setAttribute("version", version);
_logger.debug("UserSessionBean scheme: " + scheme);
_logger.debug("searchAction version: " + version);
// KLO, 012610
if (searchTarget.compareTo("relationships") == 0
&& matchAlgorithm.compareTo("contains") == 0) {
String text = matchText.trim();
if (text.length() < NCItBrowserProperties
.getMinimumSearchStringLength()) {
String msg = Constants.ERROR_REQUIRE_MORE_SPECIFIC_QUERY_STRING;
request.getSession().setAttribute("message", msg);
request.getSession().setAttribute("vocabulary", scheme);
return "message";
}
}
request.getSession().setAttribute("ranking", Boolean.toString(ranking));
String source = (String) request.getParameter("source");
if (source == null) {
source = "ALL";
}
if (NCItBrowserProperties._debugOn) {
try {
_logger.debug(Utils.SEPARATOR);
_logger.debug("* criteria: " + matchText);
// _logger.debug("* matchType: " + matchtype);
_logger.debug("* source: " + source);
_logger.debug("* ranking: " + ranking);
// _logger.debug("* sortOption: " + sortOption);
} catch (Exception e) {
}
}
Vector schemes = new Vector();
schemes.add(scheme);
//String version = null;
Vector versions = new Vector();
versions.add(version);
String max_str = null;
int maxToReturn = -1;// 1000;
try {
max_str =
NCItBrowserProperties.getInstance().getProperty(
NCItBrowserProperties.MAXIMUM_RETURN);
maxToReturn = Integer.parseInt(max_str);
} catch (Exception ex) {
}
Utils.StopWatch stopWatch = new Utils.StopWatch();
Vector<org.LexGrid.concepts.Entity> v = null;
boolean excludeDesignation = true;
boolean designationOnly = false;
// check if this search has been performance previously through
// IteratorBeanManager
IteratorBeanManager iteratorBeanManager =
(IteratorBeanManager) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap()
.get("iteratorBeanManager");
if (iteratorBeanManager == null) {
iteratorBeanManager = new IteratorBeanManager();
FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap()
.put("iteratorBeanManager", iteratorBeanManager);
}
IteratorBean iteratorBean = null;
ResolvedConceptReferencesIterator iterator = null;
String key =
iteratorBeanManager.createIteratorKey(schemes, matchText,
searchTarget, matchAlgorithm, maxToReturn);
if (searchTarget.compareTo("names") == 0) {
if (iteratorBeanManager.containsIteratorBean(key)) {
iteratorBean = iteratorBeanManager.getIteratorBean(key);
iterator = iteratorBean.getIterator();
} else {
ResolvedConceptReferencesIteratorWrapper wrapper =
new SearchUtils()
.searchByName(schemes, versions, matchText, source,
matchAlgorithm, ranking, maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
if (iterator != null) {
iteratorBean = new IteratorBean(iterator);
iteratorBean.setKey(key);
iteratorBeanManager.addIteratorBean(iteratorBean);
}
}
}
} else if (searchTarget.compareTo("properties") == 0) {
if (iteratorBeanManager.containsIteratorBean(key)) {
iteratorBean = iteratorBeanManager.getIteratorBean(key);
iterator = iteratorBean.getIterator();
} else {
ResolvedConceptReferencesIteratorWrapper wrapper =
new SearchUtils().searchByProperties(schemes, versions,
matchText, source, matchAlgorithm, excludeDesignation,
ranking, maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
if (iterator != null) {
iteratorBean = new IteratorBean(iterator);
iteratorBean.setKey(key);
iteratorBeanManager.addIteratorBean(iteratorBean);
}
}
}
} else if (searchTarget.compareTo("relationships") == 0) {
designationOnly = true;
if (iteratorBeanManager.containsIteratorBean(key)) {
iteratorBean = iteratorBeanManager.getIteratorBean(key);
iterator = iteratorBean.getIterator();
} else {
ResolvedConceptReferencesIteratorWrapper wrapper =
new SearchUtils().searchByAssociations(schemes, versions,
matchText, source, matchAlgorithm, designationOnly,
ranking, maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
if (iterator != null) {
iteratorBean = new IteratorBean(iterator);
iteratorBean.setKey(key);
iteratorBeanManager.addIteratorBean(iteratorBean);
}
}
}
}
request.getSession().setAttribute("vocabulary", scheme);
request.getSession().removeAttribute("neighborhood_synonyms");
request.getSession().removeAttribute("neighborhood_atoms");
request.getSession().removeAttribute("concept");
request.getSession().removeAttribute("code");
request.getSession().removeAttribute("codeInNCI");
request.getSession().removeAttribute("AssociationTargetHashMap");
request.getSession().removeAttribute("type");
request.setAttribute("key", key);
System.out.println("(*************) setAttribute key: " + key);
if (iterator != null) {
// request.getSession().setAttribute("key", key);
//request.setAttribute("key", key);
//System.out.println("(*************) setAttribute key: " + key);
int numberRemaining = 0;
try {
numberRemaining = iterator.numberRemaining();
} catch (Exception ex) {
ex.printStackTrace();
}
int size = iteratorBean.getSize();
if (size > 1) {
request.getSession().setAttribute("search_results", v);
String match_size = Integer.toString(size);
request.getSession().setAttribute("match_size", match_size);
request.getSession().setAttribute("page_string", "1");
request.getSession().setAttribute("new_search", Boolean.TRUE);
request.getSession().setAttribute("dictionary", scheme);
_logger
.debug("UserSessionBean request.getSession().setAttribute dictionary: "
+ scheme);
return "search_results";
} else if (size == 1) {
request.getSession().setAttribute("singleton", "true");
request.getSession().setAttribute("dictionary", scheme);// Constants.CODING_SCHEME_NAME);
int pageNumber = 1;
List list = iteratorBean.getData(1);
ResolvedConceptReference ref =
(ResolvedConceptReference) list.get(0);
Entity c = null;
if (ref == null) {
String msg =
"Error: Null ResolvedConceptReference encountered.";
request.getSession().setAttribute("message", msg);
request.getSession().setAttribute("dictionary", scheme);
return "message";
} else {
if (ref.getConceptCode() == null) {
String message =
"Code has not been assigned to the concept matches with '"
+ matchText + "'";
_logger.warn("WARNING: " + message);
request.getSession().setAttribute("message", message);
request.getSession().setAttribute("dictionary", scheme);
return "message";
} else {
request.getSession().setAttribute("code",
ref.getConceptCode());
}
c = ref.getReferencedEntry();
if (c == null) {
c =
DataUtils.getConceptByCode(scheme, null, null, ref
.getConceptCode());
if (c == null) {
String message =
"Unable to find the concept with a code '"
+ ref.getConceptCode() + "'";
_logger.warn("WARNING: " + message);
request.getSession().setAttribute("message",
message);
request.getSession().setAttribute("dictionary",
scheme);
return "message";
}
} else {
request.getSession().setAttribute("code",
c.getEntityCode());
}
}
request.getSession().setAttribute("concept", c);
request.getSession().setAttribute("type", "properties");
request.getSession().setAttribute("new_search", Boolean.TRUE);
return "concept_details";
}
}
String message = "No match found.";
int minimumSearchStringLength =
NCItBrowserProperties.getMinimumSearchStringLength();
if (matchAlgorithm.compareTo(Constants.EXACT_SEARCH_ALGORITHM) == 0) {
message = Constants.ERROR_NO_MATCH_FOUND_TRY_OTHER_ALGORITHMS;
}
else if (matchAlgorithm.compareTo(Constants.STARTWITH_SEARCH_ALGORITHM) == 0
&& matchText.length() < minimumSearchStringLength) {
message = Constants.ERROR_ENCOUNTERED_TRY_NARROW_QUERY;
}
request.getSession().setAttribute("message", message);
request.getSession().setAttribute("dictionary", scheme);
return "message";
}
private String _selectedResultsPerPage = null;
private List _resultsPerPageList = null;
public static List getResultsPerPageValues() {
List resultsPerPageList = new ArrayList();
resultsPerPageList.add("10");
resultsPerPageList.add("25");
resultsPerPageList.add("50");
resultsPerPageList.add("75");
resultsPerPageList.add("100");
resultsPerPageList.add("250");
resultsPerPageList.add("500");
return resultsPerPageList;
}
public List getResultsPerPageList() {
_resultsPerPageList = new ArrayList();
_resultsPerPageList.add(new SelectItem("10"));
_resultsPerPageList.add(new SelectItem("25"));
_resultsPerPageList.add(new SelectItem("50"));
_resultsPerPageList.add(new SelectItem("75"));
_resultsPerPageList.add(new SelectItem("100"));
_resultsPerPageList.add(new SelectItem("250"));
_resultsPerPageList.add(new SelectItem("500"));
_selectedResultsPerPage =
((SelectItem) _resultsPerPageList.get(2)).getLabel(); // default to
// 50
return _resultsPerPageList;
}
public void setSelectedResultsPerPage(String selectedResultsPerPage) {
if (selectedResultsPerPage == null) {
System.out.println("(*) selectedResultsPerPage == null ??? ");
return;
}
_selectedResultsPerPage = selectedResultsPerPage;
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
request.getSession().setAttribute("selectedResultsPerPage",
selectedResultsPerPage);
System.out.println("(*) request.getSession().setAttribute selectedResultsPerPage " + selectedResultsPerPage);
}
public String getSelectedResultsPerPage() {
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
String s =
(String) request.getSession()
.getAttribute("selectedResultsPerPage");
if (s != null) {
_selectedResultsPerPage = s;
} else {
_selectedResultsPerPage = "50";
request.getSession().setAttribute("selectedResultsPerPage", "50");
}
return _selectedResultsPerPage;
}
public void resultsPerPageChanged(ValueChangeEvent event) {
if (event.getNewValue() == null) {
System.out.println("(*) UserSessionBean event.getNewValue() == null??? ");
return;
}
String newValue = (String) event.getNewValue();
System.out.println("(*) UserSessionBean resultsPerPageChanged newValue: " + newValue);
setSelectedResultsPerPage(newValue);
}
public String linkAction() {
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
return "";
}
private String _selectedAlgorithm = null;
private List _algorithmList = null;
public List getAlgorithmList() {
_algorithmList = new ArrayList();
_algorithmList.add(new SelectItem("exactMatch", "exactMatch"));
_algorithmList.add(new SelectItem("startsWith", "Begins With"));
_algorithmList.add(new SelectItem("contains", "Contains"));
_selectedAlgorithm = ((SelectItem) _algorithmList.get(0)).getLabel();
return _algorithmList;
}
public void algorithmChanged(ValueChangeEvent event) {
if (event.getNewValue() == null)
return;
String newValue = (String) event.getNewValue();
setSelectedAlgorithm(newValue);
}
public void setSelectedAlgorithm(String selectedAlgorithm) {
_selectedAlgorithm = selectedAlgorithm;
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
request.getSession().setAttribute("algorithm", selectedAlgorithm);
}
public String getSelectedAlgorithm() {
return _selectedAlgorithm;
}
public String contactUs() throws Exception {
String msg = "Your message was successfully sent.";
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
try {
String subject = request.getParameter("subject");
String message = request.getParameter("message");
String from = request.getParameter("emailaddress");
String recipients[] = MailUtils.getRecipients();
MailUtils.postMail(from, recipients, subject, message);
} catch (UserInputException e) {
msg = e.getMessage();
request.setAttribute("errorMsg", Utils.toHtml(msg));
request.setAttribute("errorType", "user");
return "error";
} catch (Exception e) {
msg = "System Error: Your message was not sent.\n";
msg += " (If possible, please contact NCI systems team.)\n";
msg += "\n";
msg += e.getMessage();
request.setAttribute("errorMsg", Utils.toHtml(msg));
request.setAttribute("errorType", "system");
e.printStackTrace();
return "error";
}
request.getSession().setAttribute("message", Utils.toHtml(msg));
return "message";
}
// //////////////////////////////////////////////////////////////////////////////////////////
// ontologies
public List getOntologiesToSearchOn() {
if (_ontologyList == null) {
_ontologyList = DataUtils.getOntologyList();
SelectItem item = (SelectItem) _ontologyList.get(0);
_ontologiesToSearchOn.add(item.getLabel());
} else if (_ontologiesToSearchOn.size() == 0) {
SelectItem item = (SelectItem) _ontologyList.get(0);
_ontologiesToSearchOn.add(item.getLabel());
}
return _ontologiesToSearchOn;
}
public List getOntologyList() {
if (_ontologyList == null) {
_ontologyList = DataUtils.getOntologyList();
}
return _ontologyList;
}
public void setOntologiesToSearchOn(List<String> newValue) {
_ontologiesToSearchOn = new ArrayList<String>();
for (int i = 0; i < newValue.size(); i++) {
Object obj = newValue.get(i);
_ontologiesToSearchOn.add((String) obj);
}
}
public void ontologiesToSearchOnChanged(ValueChangeEvent event) {
if (event.getNewValue() == null) {
return;
}
List newValue = (List) event.getNewValue();
setOntologiesToSearchOn(newValue);
}
public List<SelectItem> _ontologySelectionList = null;
public String _ontologyToSearchOn = null;
public List getOntologySelectionList() {
if (_ontologySelectionList != null)
return _ontologySelectionList;
List ontologies = getOntologyList();
_ontologySelectionList = new ArrayList<SelectItem>();
String label = "Switch to another vocabulary (select one)";
_ontologySelectionList.add(new SelectItem(label, label));
for (int i = 0; i < ontologies.size(); i++) {
SelectItem item = (SelectItem) _ontologyList.get(i);
_ontologySelectionList.add(item);
}
return _ontologySelectionList;
}
public void ontologySelectionChanged(ValueChangeEvent event) {
if (event.getNewValue() == null) {
// _logger.warn("ontologySelectionChanged; event.getNewValue() == null ");
return;
}
String newValue = (String) event.getNewValue();
HttpServletResponse response =
(HttpServletResponse) FacesContext.getCurrentInstance()
.getExternalContext().getResponse();
String targetURL = null;// "http://nciterms.nci.nih.gov/";
targetURL = "http://nciterms.nci.nih.gov/";
try {
response.sendRedirect(response.encodeRedirectURL(targetURL));
} catch (Exception ex) {
ex.printStackTrace();
}
}
public String getOntologyToSearchOn() {
if (_ontologySelectionList == null) {
_ontologySelectionList = getOntologySelectionList();
SelectItem item = (SelectItem) _ontologyList.get(1);
_ontologyToSearchOn = item.getLabel();
}
return _ontologyToSearchOn;
}
public void setOntologyToSearchOn(String newValue) {
_ontologyToSearchOn = newValue;
}
// //////////////////////////////////////////////////////////////////////////////////////
private String[] getSelectedVocabularies(String ontology_list_str) {
Vector v = DataUtils.parseData(ontology_list_str);
String[] ontology_list = new String[v.size()];
for (int i = 0; i < v.size(); i++) {
String s = (String) v.elementAt(i);
ontology_list[i] = s;
}
return ontology_list;
}
public String acceptLicenseAction() {
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
String dictionary = (String) request.getParameter("dictionary");
String code = (String) request.getParameter("code");
if (dictionary != null && code != null) {
LicenseBean licenseBean =
(LicenseBean) request.getSession().getAttribute("licenseBean");
if (licenseBean == null) {
licenseBean = new LicenseBean();
}
licenseBean.addLicenseAgreement(dictionary);
request.getSession().setAttribute("licenseBean", licenseBean);
Entity c =
DataUtils.getConceptByCode(dictionary, null, null, code);
request.getSession().setAttribute("code", code);
request.getSession().setAttribute("concept", c);
request.getSession().setAttribute("type", "properties");
return "concept_details";
} else {
String message = "Unidentifiable vocabulary name, or code";
request.getSession().setAttribute("warning", message);
return "message";
}
}
public String multipleSearchAction() {
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
String scheme = (String) request.getParameter("scheme");
String version = (String) request.getParameter("version");
String navigation_type = request.getParameter("nav_type");
- if (navigation_type == null) {
+ if (navigation_type == null || navigation_type.equals("null")) {
navigation_type = "terminologies";
}
// Called from license.jsp
LicenseBean licenseBean =
(LicenseBean) request.getSession().getAttribute("licenseBean");
if (scheme != null && version != null) {
if (licenseBean == null) {
licenseBean = new LicenseBean();
}
licenseBean.addLicenseAgreement(scheme);
request.getSession().setAttribute("licenseBean", licenseBean);
}
String matchText = (String) request.getParameter("matchText");
if (matchText != null) {
matchText = matchText.trim();
request.getSession().setAttribute("matchText", matchText);
} else {
matchText = (String) request.getSession().getAttribute("matchText");
}
String multiple_search_error =
(String) request.getSession().getAttribute(
"multiple_search_no_match_error");
request.getSession().removeAttribute("multiple_search_no_match_error");
String matchAlgorithm = (String) request.getParameter("algorithm");
request.getSession().setAttribute("algorithm", matchAlgorithm);
String searchTarget = (String) request.getParameter("searchTarget");
request.getSession().setAttribute("searchTarget", searchTarget);
String initial_search = (String) request.getParameter("initial_search");
String[] ontology_list = null;
if (navigation_type == null || navigation_type.compareTo("terminologies") == 0) {
ontology_list = request.getParameterValues("ontology_list");
}
List list = new ArrayList<String>();
String ontologiesToSearchOnStr = null;
String ontology_list_str = null;
List<String> ontologiesToSearchOn = null;
int knt = 0;
// process mappings
if (initial_search != null) { // from home page
/*
if (navigation_type.compareTo("mappings") == 0) {
String ontologyToSearchOn = request.getParameter("ontologyToSearchOn");
ontologiesToSearchOn = new ArrayList<String>();
ontology_list = new String[1];
ontology_list[0] = ontologyToSearchOn;
ontologiesToSearchOn.add(ontologyToSearchOn);
} else
*/
{
if (multiple_search_error != null) {
ontologiesToSearchOn = new ArrayList<String>();
ontologiesToSearchOnStr =
(String) request.getSession().getAttribute(
"ontologiesToSearchOn");
if (ontologiesToSearchOnStr != null) {
Vector ontologies_to_search_on =
DataUtils.parseData(ontologiesToSearchOnStr);
ontology_list = new String[ontologies_to_search_on.size()];
knt = ontologies_to_search_on.size();
for (int k = 0; k < ontologies_to_search_on.size(); k++) {
String s =
(String) ontologies_to_search_on.elementAt(k);
ontology_list[k] = s;
ontologiesToSearchOn.add(s);
}
}
}
}
if (ontology_list == null || ontology_list.length == 0) {
String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary.";
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().removeAttribute("ontologiesToSearchOn");
// String defaultOntologiesToSearchOnStr =
// ontologiesToSearchOnStr;
request.getSession().setAttribute(
"defaultOntologiesToSearchOnStr", "|");
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
} else {
ontologiesToSearchOn = new ArrayList<String>();
ontologiesToSearchOnStr = "|";
for (int i = 0; i < ontology_list.length; ++i) {
list.add(ontology_list[i]);
ontologiesToSearchOn.add(ontology_list[i]);
ontologiesToSearchOnStr =
ontologiesToSearchOnStr + ontology_list[i] + "|";
}
if (ontology_list_str == null) {
ontology_list_str = "";
for (int i = 0; i < ontology_list.length; ++i) {
ontology_list_str =
ontology_list_str + ontology_list[i];
if (i < ontology_list.length - 1) {
ontology_list_str = ontology_list_str + "|";
}
}
}
request.getSession().setAttribute("ontologiesToSearchOn",
ontologiesToSearchOnStr);
}
} else {
/*
if (navigation_type.compareTo("mappings") == 0) {
String ontologyToSearchOn = request.getParameter("ontologyToSearchOn");
ontologiesToSearchOn = new ArrayList<String>();
ontology_list = new String[1];
ontology_list[0] = ontologyToSearchOn;
ontologiesToSearchOn.add(ontologyToSearchOn);
} else
*/
{
ontologiesToSearchOn = new ArrayList<String>();
ontologiesToSearchOnStr =
(String) request.getSession().getAttribute(
"ontologiesToSearchOn");
if (ontologiesToSearchOnStr != null) {
Vector ontologies_to_search_on =
DataUtils.parseData(ontologiesToSearchOnStr);
ontology_list = new String[ontologies_to_search_on.size()];
knt = ontologies_to_search_on.size();
for (int k = 0; k < ontologies_to_search_on.size(); k++) {
String s = (String) ontologies_to_search_on.elementAt(k);
ontology_list[k] = s;
ontologiesToSearchOn.add(s);
}
}
}
}
String hide_ontology_list = "false";
// [#19965] Error message is not displayed when Search Criteria is not
// proivided
if (matchText == null || matchText.length() == 0) {
String message = Constants.ERROR_NO_SEARCH_STRING_ENTERED;
if (initial_search == null) {
hide_ontology_list = "true";
}
request.getSession().setAttribute("hide_ontology_list",
hide_ontology_list);
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
}
// KLO, 012610
else if (searchTarget.compareTo("relationships") == 0
&& matchAlgorithm.compareTo("contains") == 0) {
String text = matchText.trim();
if (text.length() < NCItBrowserProperties
.getMinimumSearchStringLength()) {
String msg = Constants.ERROR_REQUIRE_MORE_SPECIFIC_QUERY_STRING;
request.getSession().setAttribute("warning", msg);
request.getSession().setAttribute("message", msg);
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
}
}
boolean ranking = true;
String source = (String) request.getParameter("source");
if (source == null) {
source = "ALL";
}
if (NCItBrowserProperties._debugOn) {
try {
_logger.debug(Utils.SEPARATOR);
_logger.debug("* criteria: " + matchText);
_logger.debug("* source: " + source);
_logger.debug("* ranking: " + ranking);
_logger.debug("* ontology_list: ");
for (int i = 0; i < ontology_list.length; ++i) {
_logger.debug(" " + i + ") " + ontology_list[i]);
}
} catch (Exception e) {
}
}
if (ontology_list == null) {
ontology_list_str =
(String) request.getParameter("ontology_list_str"); // from
// multiple_search_results
// (hidden
// variable)
if (ontology_list_str != null) {
ontology_list = getSelectedVocabularies(ontology_list_str);
}
} else {
knt = ontology_list.length;
if (knt == 0) {
String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary.";
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().setAttribute("hide_ontology_list", "true");
request.getSession().removeAttribute("ontologiesToSearchOn");
// String defaultOntologiesToSearchOnStr =
// ontologiesToSearchOnStr;
request.getSession().setAttribute(
"defaultOntologiesToSearchOnStr", "|");
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
}
}
Vector schemes = new Vector();
Vector versions = new Vector();
ontologiesToSearchOn = new ArrayList<String>();
ontologiesToSearchOnStr = "|";
for (int i = 0; i < ontology_list.length; ++i) {
list.add(ontology_list[i]);
ontologiesToSearchOn.add(ontology_list[i]);
ontologiesToSearchOnStr =
ontologiesToSearchOnStr + ontology_list[i] + "|";
}
if (ontology_list_str == null) {
ontology_list_str = "";
for (int i = 0; i < ontology_list.length; ++i) {
ontology_list_str = ontology_list_str + ontology_list[i];
if (i < ontology_list.length - 1) {
ontology_list_str = ontology_list_str + "|";
}
}
}
scheme = null;
version = null;
String t = "";
if (ontologiesToSearchOn.size() == 0) {
String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary.";
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().removeAttribute("ontologiesToSearchOn");
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
} else {
request.getSession().setAttribute("ontologiesToSearchOn",
ontologiesToSearchOnStr);
// [#25270] Set "all but NCIm selected" as the default for the TB
// home page.
String defaultOntologiesToSearchOnStr = ontologiesToSearchOnStr;
request.getSession().setAttribute("defaultOntologiesToSearchOnStr",
defaultOntologiesToSearchOnStr);
for (int k = 0; k < ontologiesToSearchOn.size(); k++) {
String key = (String) list.get(k);
if (key != null) {
scheme = DataUtils.key2CodingSchemeName(key);
version = DataUtils.key2CodingSchemeVersion(key);
if (scheme != null) {
schemes.add(scheme);
// to be modified (handling of versions)
versions.add(version);
t = t + scheme + " (" + version + ")" + "\n";
boolean isLicensed =
LicenseBean.isLicensed(scheme, version);
if (licenseBean == null) {
licenseBean = new LicenseBean();
request.getSession().setAttribute("licenseBean",
licenseBean);
}
boolean accepted =
licenseBean.licenseAgreementAccepted(scheme);
if (isLicensed && !accepted) {
request.getSession().setAttribute("matchText",
matchText);
request.setAttribute("searchTarget", searchTarget);
request.setAttribute("algorithm", matchAlgorithm);
request.setAttribute("ontology_list_str",
ontology_list_str);
request.setAttribute("scheme", scheme);
request.setAttribute("version", version);
return "license";
}
} else {
_logger.warn("Unable to identify " + key);
}
}
}
}
String max_str = null;
int maxToReturn = -1;// 1000;
try {
max_str =
NCItBrowserProperties
.getProperty(NCItBrowserProperties.MAXIMUM_RETURN);
maxToReturn = Integer.parseInt(max_str);
} catch (Exception ex) {
// Do nothing
}
boolean designationOnly = false;
boolean excludeDesignation = true;
ResolvedConceptReferencesIterator iterator = null;
if (searchTarget.compareTo("names") == 0) {
long ms = System.currentTimeMillis();
long delay = 0;
_logger.debug("Calling SearchUtils().searchByName " + matchText);
ResolvedConceptReferencesIteratorWrapper wrapper =
new SearchUtils().searchByName(schemes, versions, matchText,
source, matchAlgorithm, ranking, maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
}
delay = System.currentTimeMillis() - ms;
_logger.debug("searchByName delay (millisec.): " + delay);
} else if (searchTarget.compareTo("properties") == 0) {
ResolvedConceptReferencesIteratorWrapper wrapper =
new SearchUtils().searchByProperties(schemes, versions,
matchText, source, matchAlgorithm, excludeDesignation,
ranking, maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
}
} else if (searchTarget.compareTo("relationships") == 0) {
designationOnly = true;
ResolvedConceptReferencesIteratorWrapper wrapper =
new SearchUtils().searchByAssociations(schemes, versions,
matchText, source, matchAlgorithm, designationOnly,
ranking, maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
}
}
request.getSession().setAttribute("vocabulary", scheme);
request.getSession().setAttribute("searchTarget", searchTarget);
request.getSession().setAttribute("algorithm", matchAlgorithm);
request.getSession().removeAttribute("neighborhood_synonyms");
request.getSession().removeAttribute("neighborhood_atoms");
request.getSession().removeAttribute("concept");
request.getSession().removeAttribute("code");
request.getSession().removeAttribute("codeInNCI");
request.getSession().removeAttribute("AssociationTargetHashMap");
request.getSession().removeAttribute("type");
if (iterator != null) {
IteratorBean iteratorBean =
(IteratorBean) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("iteratorBean");
if (iteratorBean == null) {
iteratorBean = new IteratorBean(iterator);
FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().put("iteratorBean", iteratorBean);
} else {
iteratorBean.setIterator(iterator);
}
int size = iteratorBean.getSize();
if (size == 1) {
int pageNumber = 1;
list = iteratorBean.getData(1);
ResolvedConceptReference ref =
(ResolvedConceptReference) list.get(0);
String coding_scheme = ref.getCodingSchemeName();
if (coding_scheme.compareToIgnoreCase("NCI Metathesaurus") == 0) {
String match_size = Integer.toString(size);
;// Integer.toString(v.size());
request.getSession().setAttribute("match_size", match_size);
request.getSession().setAttribute("page_string", "1");
request.getSession().setAttribute("new_search",
Boolean.TRUE);
// route to multiple_search_results.jsp
return "search_results";
}
request.getSession().setAttribute("singleton", "true");
request.getSession().setAttribute("dictionary", coding_scheme);
Entity c = null;
if (ref == null) {
String msg =
"Error: Null ResolvedConceptReference encountered.";
request.getSession().setAttribute("message", msg);
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "message";
} else {
c = ref.getReferencedEntry();
if (c == null) {
c =
DataUtils.getConceptByCode(coding_scheme, null,
null, ref.getConceptCode());
}
}
request.getSession().setAttribute("code", ref.getConceptCode());
request.getSession().setAttribute("concept", c);
request.getSession().setAttribute("type", "properties");
request.getSession().setAttribute("new_search", Boolean.TRUE);
request.setAttribute("algorithm", matchAlgorithm);
coding_scheme =
(String) DataUtils._localName2FormalNameHashMap
.get(coding_scheme);
String convertJSPString = HTTPUtils.convertJSPString(matchText);
request.getSession()
.setAttribute("matchText", convertJSPString);
request.setAttribute("dictionary", coding_scheme);
return "concept_details";
} else if (size > 0) {
String match_size = Integer.toString(size);
;// Integer.toString(v.size());
request.getSession().setAttribute("match_size", match_size);
request.getSession().setAttribute("page_string", "1");
request.getSession().setAttribute("new_search", Boolean.TRUE);
// route to multiple_search_results.jsp
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
_logger.debug("Start to render search_results ... ");
return "search_results";
}
}
int minimumSearchStringLength =
NCItBrowserProperties.getMinimumSearchStringLength();
if (ontologiesToSearchOn.size() == 0) {
request.getSession().removeAttribute("vocabulary");
} else if (ontologiesToSearchOn.size() == 1) {
String msg_scheme = (String) ontologiesToSearchOn.get(0);
request.getSession().setAttribute("vocabulary", msg_scheme);
} else {
request.getSession().removeAttribute("vocabulary");
}
String message = Constants.ERROR_NO_MATCH_FOUND;
if (matchAlgorithm.compareTo(Constants.EXACT_SEARCH_ALGORITHM) == 0) {
message = Constants.ERROR_NO_MATCH_FOUND_TRY_OTHER_ALGORITHMS;
}
else if (matchAlgorithm.compareTo(Constants.STARTWITH_SEARCH_ALGORITHM) == 0
&& matchText.length() < minimumSearchStringLength) {
message = Constants.ERROR_ENCOUNTERED_TRY_NARROW_QUERY;
}
hide_ontology_list = "false";
/*
* if (initial_search == null) { hide_ontology_list = "true"; }
*/
request.getSession().setAttribute("hide_ontology_list",
hide_ontology_list);
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().setAttribute("ontologiesToSearchOn",
ontologiesToSearchOnStr);
request.getSession().setAttribute("multiple_search_no_match_error",
"true");
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
}
public String acceptLicenseAgreement() {
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
// update LicenseBean
String dictionary = (String) request.getParameter("dictionary");
String version = (String) request.getParameter("version");
LicenseBean licenseBean =
(LicenseBean) request.getSession().getAttribute("licenseBean");
if (licenseBean == null) {
licenseBean = new LicenseBean();
}
licenseBean.addLicenseAgreement(dictionary);
request.getSession().setAttribute("licenseBean", licenseBean);
request.getSession().setAttribute("dictionary", dictionary);
request.getSession().setAttribute("scheme", dictionary);
request.getSession().setAttribute("version", version);
return "vocabulary_home";
}
public String advancedSearchAction() {
ResolvedConceptReferencesIteratorWrapper wrapper = null;
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
String scheme = (String) request.getParameter("dictionary");
String version = (String) request.getParameter("version");
System.out.println("advancedSearchAction version: " + version);
SearchStatusBean bean =
(SearchStatusBean) FacesContext.getCurrentInstance()
.getExternalContext().getRequestMap().get("searchStatusBean");
if (bean == null) {
bean = new SearchStatusBean(scheme, version);
request.setAttribute("searchStatusBean", bean);
}
String matchType = (String) request.getParameter("adv_search_type");
bean.setSearchType(matchType);
String matchAlgorithm =
(String) request.getParameter("adv_search_algorithm");
bean.setAlgorithm(matchAlgorithm);
String source = (String) request.getParameter("adv_search_source");
bean.setSelectedSource(source);
String selectSearchOption =
(String) request.getParameter("selectSearchOption");
bean.setSelectedSearchOption(selectSearchOption);
String selectProperty = (String) request.getParameter("selectProperty");
bean.setSelectedProperty(selectProperty);
String rel_search_association =
(String) request.getParameter("rel_search_association");
bean.setSelectedAssociation(rel_search_association);
String rel_search_rela =
(String) request.getParameter("rel_search_rela");
bean.setSelectedRELA(rel_search_rela);
FacesContext.getCurrentInstance().getExternalContext().getRequestMap()
.put("searchStatusBean", bean);
request.setAttribute("searchStatusBean", bean);
String searchTarget = (String) request.getParameter("searchTarget");
String matchText = (String) request.getParameter("matchText");
if (matchText == null || matchText.length() == 0) {
String message = "Please enter a search string.";
// request.getSession().setAttribute("message", message);
request.setAttribute("message", message);
return "message";
}
matchText = matchText.trim();
bean.setMatchText(matchText);
if (NCItBrowserProperties._debugOn) {
_logger.debug(Utils.SEPARATOR);
_logger.debug("* criteria: " + matchText);
_logger.debug("* source: " + source);
}
// String scheme = Constants.CODING_SCHEME_NAME;
Vector schemes = new Vector();
schemes.add(scheme);
String max_str = null;
int maxToReturn = -1;// 1000;
try {
max_str =
NCItBrowserProperties.getInstance().getProperty(
NCItBrowserProperties.MAXIMUM_RETURN);
maxToReturn = Integer.parseInt(max_str);
} catch (Exception ex) {
}
Utils.StopWatch stopWatch = new Utils.StopWatch();
Vector<org.LexGrid.concepts.Entity> v = null;
boolean excludeDesignation = true;
boolean designationOnly = false;
// check if this search has been performance previously through
// IteratorBeanManager
IteratorBeanManager iteratorBeanManager =
(IteratorBeanManager) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap()
.get("iteratorBeanManager");
if (iteratorBeanManager == null) {
iteratorBeanManager = new IteratorBeanManager();
FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap()
.put("iteratorBeanManager", iteratorBeanManager);
}
IteratorBean iteratorBean = null;
ResolvedConceptReferencesIterator iterator = null;
boolean ranking = true;
SearchFields searchFields = null;
String key = null;
String searchType = (String) request.getParameter("selectSearchOption");
_logger.debug("SearchUtils.java searchType: " + searchType);
if (searchType != null && searchType.compareTo("Property") == 0) {
/*
* _logger.debug("Advanced Search: "); _logger.debug("searchType: "
* + searchType); _logger.debug("matchText: " + matchText);
* _logger.debug("adv_search_algorithm: " + adv_search_algorithm);
* _logger.debug("adv_search_source: " + adv_search_source);
*/
String property_type =
(String) request.getParameter("selectPropertyType");
if (property_type != null && property_type.compareTo("ALL") == 0) {
property_type = null;
}
String property_name = selectProperty;
if (property_name != null) {
property_name = property_name.trim();
// if (property_name.length() == 0) property_name = null;
if (property_name.compareTo("ALL") == 0)
property_name = null;
}
searchFields =
SearchFields.setProperty(schemes, matchText, searchTarget,
property_type, property_name, source, matchAlgorithm,
maxToReturn);
key = searchFields.getKey();
_logger.debug("advancedSearchAction " + key);
if (iteratorBeanManager.containsIteratorBean(key)) {
iteratorBean = iteratorBeanManager.getIteratorBean(key);
iterator = iteratorBean.getIterator();
} else {
String[] property_types = null;
if (property_type != null)
property_types = new String[] { property_type };
String[] property_names = null;
if (property_name != null)
property_names = new String[] { property_name };
excludeDesignation = false;
wrapper =
new SearchUtils().searchByProperties(scheme, version,
matchText, property_types, property_names, source,
matchAlgorithm, excludeDesignation, ranking,
maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
}
if (iterator != null) {
iteratorBean = new IteratorBean(iterator);
iteratorBean.setKey(key);
iteratorBean.setMatchText(matchText);
iteratorBeanManager.addIteratorBean(iteratorBean);
}
}
} else if (searchType != null
&& searchType.compareTo("Relationship") == 0) {
if (rel_search_association != null
&& rel_search_association.compareTo("ALL") == 0)
rel_search_association = null;
if (rel_search_rela != null) {
rel_search_rela = rel_search_rela.trim();
if (rel_search_rela.length() == 0)
rel_search_rela = null;
}
/*
* String rel_search_direction = (String)
* request.getParameter("rel_search_direction");
*
* //boolean direction = false; int search_direction =
* Constants.SEARCH_BOTH_DIRECTION; if (rel_search_direction != null
* && rel_search_direction.compareTo("source") == 0) {
* search_direction = Constants.SEARCH_SOURCE; //direction = true; }
* else if (rel_search_direction != null &&
* rel_search_direction.compareTo("target") == 0) { search_direction
* = Constants.SEARCH_TARGET; //direction = true; }
*/
int search_direction = Constants.SEARCH_SOURCE;
_logger.debug("AdvancedSearchAction search_direction "
+ search_direction);
searchFields =
SearchFields.setRelationship(schemes, matchText, searchTarget,
rel_search_association, rel_search_rela, source,
matchAlgorithm, maxToReturn);
key = searchFields.getKey();
_logger.debug("AdvancedSearchAction key " + key);
if (iteratorBeanManager.containsIteratorBean(key)) {
iteratorBean = iteratorBeanManager.getIteratorBean(key);
iterator = iteratorBean.getIterator();
} else {
String[] associationsToNavigate = null;
String[] association_qualifier_names = null;
String[] association_qualifier_values = null;
if (rel_search_association != null) {
/*
associationsToNavigate =
new String[] { rel_search_association };
*/
String assocName = OntologyBean.convertAssociationName(scheme, null, rel_search_association);
//_logger.debug("Converting " + rel_search_association + " to " + assocName);
associationsToNavigate =
new String[] { assocName };
} else {
_logger.debug("(*) associationsToNavigate == null");
}
if (rel_search_rela != null) {
association_qualifier_names = new String[] { "rela" };
association_qualifier_values =
new String[] { rel_search_rela };
if (associationsToNavigate == null) {
Vector w = OntologyBean.getAssociationNames(scheme);
if (w == null || w.size() == 0) {
_logger
.warn("OntologyBean.getAssociationNames() returns null, or nothing???");
} else {
associationsToNavigate = new String[w.size()];
for (int i = 0; i < w.size(); i++) {
String nm = (String) w.elementAt(i);
associationsToNavigate[i] = nm;
}
}
}
} else {
_logger.warn("(*) qualifiers == null");
}
wrapper =
new SearchUtils().searchByAssociations(scheme, version,
matchText, associationsToNavigate,
association_qualifier_names,
association_qualifier_values, search_direction, source,
matchAlgorithm, excludeDesignation, ranking,
maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
}
if (iterator != null) {
iteratorBean = new IteratorBean(iterator);
iteratorBean.setKey(key);
iteratorBean.setMatchText(matchText);
iteratorBeanManager.addIteratorBean(iteratorBean);
}
}
} else if (searchType != null && searchType.compareTo("Name") == 0) {
searchFields =
SearchFields.setName(schemes, matchText, searchTarget, source,
matchAlgorithm, maxToReturn);
key = searchFields.getKey();
if (iteratorBeanManager.containsIteratorBean(key)) {
iteratorBean = iteratorBeanManager.getIteratorBean(key);
iterator = iteratorBean.getIterator();
} else {
wrapper =
new SearchUtils().searchByName(scheme, version, matchText,
source, matchAlgorithm, ranking, maxToReturn,
SearchUtils.NameSearchType.Name);
if (wrapper != null) {
iterator = wrapper.getIterator();
if (iterator != null) {
iteratorBean = new IteratorBean(iterator);
iteratorBean.setKey(key);
iteratorBean.setMatchText(matchText);
iteratorBeanManager.addIteratorBean(iteratorBean);
}
}
}
} else if (searchType != null && searchType.compareTo("Code") == 0) {
searchFields =
SearchFields.setCode(schemes, matchText, searchTarget, source,
matchAlgorithm, maxToReturn);
key = searchFields.getKey();
if (iteratorBeanManager.containsIteratorBean(key)) {
iteratorBean = iteratorBeanManager.getIteratorBean(key);
iterator = iteratorBean.getIterator();
} else {
/*
* wrapper = new SearchUtils().searchByName(scheme, version,
* matchText, source, matchAlgorithm, ranking, maxToReturn,
* SearchUtils.NameSearchType.Code);
*/
wrapper =
new SearchUtils().searchByCode(scheme, version, matchText,
source, matchAlgorithm, ranking, maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
if (iterator != null) {
iteratorBean = new IteratorBean(iterator);
iteratorBean.setKey(key);
iteratorBean.setMatchText(matchText);
iteratorBeanManager.addIteratorBean(iteratorBean);
}
}
}
}
request.setAttribute("key", key);
request.getSession().setAttribute("matchText", matchText);
request.getSession().removeAttribute("neighborhood_synonyms");
request.getSession().removeAttribute("neighborhood_atoms");
request.getSession().removeAttribute("concept");
request.getSession().removeAttribute("code");
request.getSession().removeAttribute("codeInNCI");
request.getSession().removeAttribute("AssociationTargetHashMap");
request.getSession().removeAttribute("type");
if (iterator != null) {
int size = iteratorBean.getSize();
_logger.debug("AdvancedSearchActon size: " + size);
// Write a search log entry
SearchLog.writeEntry(searchFields, size, HTTPUtils
.getRefererParmDecode(request));
if (size > 1) {
request.getSession().setAttribute("search_results", v);
String match_size = Integer.toString(size);
;// Integer.toString(v.size());
request.getSession().setAttribute("match_size", match_size);
request.getSession().setAttribute("page_string", "1");
request.setAttribute("version", version);
request.getSession().setAttribute("new_search", Boolean.TRUE);
return "search_results";
} else if (size == 1) {
request.getSession().setAttribute("singleton", "true");
request.getSession().setAttribute("dictionary", scheme);
// Concept c = (Concept) v.elementAt(0);
int pageNumber = 1;
List list = iteratorBean.getData(1);
ResolvedConceptReference ref =
(ResolvedConceptReference) list.get(0);
Entity c = null;
if (ref == null) {
String msg =
"Error: Null ResolvedConceptReference encountered.";
request.getSession().setAttribute("message", msg);
return "message";
} else {
c = ref.getReferencedEntry();
if (c == null) {
c =
DataUtils.getConceptByCode(scheme, null, null, ref
.getConceptCode());
}
}
request.getSession().setAttribute("code", ref.getConceptCode());
request.getSession().setAttribute("concept", c);
request.getSession().setAttribute("type", "properties");
request.getSession().setAttribute("version", version);
request.getSession().setAttribute("new_search", Boolean.TRUE);
return "concept_details";
}
}
String message = "No match found.";
if (matchAlgorithm.compareTo("exactMatch") == 0) {
message = Constants.ERROR_NO_MATCH_FOUND_TRY_OTHER_ALGORITHMS;
}
request.setAttribute("message", message);
return "no_match";
}
//resolveValueSetAction
public String resolveValueSetAction() {
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
return "resolve_value_set";
}
public String continueResolveValueSetAction() {
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
return "resolved_value_set";
}
public String exportValueSetAction() {
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
return "exported_value_set";
}
}
| true | true |
public String multipleSearchAction() {
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
String scheme = (String) request.getParameter("scheme");
String version = (String) request.getParameter("version");
String navigation_type = request.getParameter("nav_type");
if (navigation_type == null) {
navigation_type = "terminologies";
}
// Called from license.jsp
LicenseBean licenseBean =
(LicenseBean) request.getSession().getAttribute("licenseBean");
if (scheme != null && version != null) {
if (licenseBean == null) {
licenseBean = new LicenseBean();
}
licenseBean.addLicenseAgreement(scheme);
request.getSession().setAttribute("licenseBean", licenseBean);
}
String matchText = (String) request.getParameter("matchText");
if (matchText != null) {
matchText = matchText.trim();
request.getSession().setAttribute("matchText", matchText);
} else {
matchText = (String) request.getSession().getAttribute("matchText");
}
String multiple_search_error =
(String) request.getSession().getAttribute(
"multiple_search_no_match_error");
request.getSession().removeAttribute("multiple_search_no_match_error");
String matchAlgorithm = (String) request.getParameter("algorithm");
request.getSession().setAttribute("algorithm", matchAlgorithm);
String searchTarget = (String) request.getParameter("searchTarget");
request.getSession().setAttribute("searchTarget", searchTarget);
String initial_search = (String) request.getParameter("initial_search");
String[] ontology_list = null;
if (navigation_type == null || navigation_type.compareTo("terminologies") == 0) {
ontology_list = request.getParameterValues("ontology_list");
}
List list = new ArrayList<String>();
String ontologiesToSearchOnStr = null;
String ontology_list_str = null;
List<String> ontologiesToSearchOn = null;
int knt = 0;
// process mappings
if (initial_search != null) { // from home page
/*
if (navigation_type.compareTo("mappings") == 0) {
String ontologyToSearchOn = request.getParameter("ontologyToSearchOn");
ontologiesToSearchOn = new ArrayList<String>();
ontology_list = new String[1];
ontology_list[0] = ontologyToSearchOn;
ontologiesToSearchOn.add(ontologyToSearchOn);
} else
*/
{
if (multiple_search_error != null) {
ontologiesToSearchOn = new ArrayList<String>();
ontologiesToSearchOnStr =
(String) request.getSession().getAttribute(
"ontologiesToSearchOn");
if (ontologiesToSearchOnStr != null) {
Vector ontologies_to_search_on =
DataUtils.parseData(ontologiesToSearchOnStr);
ontology_list = new String[ontologies_to_search_on.size()];
knt = ontologies_to_search_on.size();
for (int k = 0; k < ontologies_to_search_on.size(); k++) {
String s =
(String) ontologies_to_search_on.elementAt(k);
ontology_list[k] = s;
ontologiesToSearchOn.add(s);
}
}
}
}
if (ontology_list == null || ontology_list.length == 0) {
String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary.";
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().removeAttribute("ontologiesToSearchOn");
// String defaultOntologiesToSearchOnStr =
// ontologiesToSearchOnStr;
request.getSession().setAttribute(
"defaultOntologiesToSearchOnStr", "|");
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
} else {
ontologiesToSearchOn = new ArrayList<String>();
ontologiesToSearchOnStr = "|";
for (int i = 0; i < ontology_list.length; ++i) {
list.add(ontology_list[i]);
ontologiesToSearchOn.add(ontology_list[i]);
ontologiesToSearchOnStr =
ontologiesToSearchOnStr + ontology_list[i] + "|";
}
if (ontology_list_str == null) {
ontology_list_str = "";
for (int i = 0; i < ontology_list.length; ++i) {
ontology_list_str =
ontology_list_str + ontology_list[i];
if (i < ontology_list.length - 1) {
ontology_list_str = ontology_list_str + "|";
}
}
}
request.getSession().setAttribute("ontologiesToSearchOn",
ontologiesToSearchOnStr);
}
} else {
/*
if (navigation_type.compareTo("mappings") == 0) {
String ontologyToSearchOn = request.getParameter("ontologyToSearchOn");
ontologiesToSearchOn = new ArrayList<String>();
ontology_list = new String[1];
ontology_list[0] = ontologyToSearchOn;
ontologiesToSearchOn.add(ontologyToSearchOn);
} else
*/
{
ontologiesToSearchOn = new ArrayList<String>();
ontologiesToSearchOnStr =
(String) request.getSession().getAttribute(
"ontologiesToSearchOn");
if (ontologiesToSearchOnStr != null) {
Vector ontologies_to_search_on =
DataUtils.parseData(ontologiesToSearchOnStr);
ontology_list = new String[ontologies_to_search_on.size()];
knt = ontologies_to_search_on.size();
for (int k = 0; k < ontologies_to_search_on.size(); k++) {
String s = (String) ontologies_to_search_on.elementAt(k);
ontology_list[k] = s;
ontologiesToSearchOn.add(s);
}
}
}
}
String hide_ontology_list = "false";
// [#19965] Error message is not displayed when Search Criteria is not
// proivided
if (matchText == null || matchText.length() == 0) {
String message = Constants.ERROR_NO_SEARCH_STRING_ENTERED;
if (initial_search == null) {
hide_ontology_list = "true";
}
request.getSession().setAttribute("hide_ontology_list",
hide_ontology_list);
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
}
// KLO, 012610
else if (searchTarget.compareTo("relationships") == 0
&& matchAlgorithm.compareTo("contains") == 0) {
String text = matchText.trim();
if (text.length() < NCItBrowserProperties
.getMinimumSearchStringLength()) {
String msg = Constants.ERROR_REQUIRE_MORE_SPECIFIC_QUERY_STRING;
request.getSession().setAttribute("warning", msg);
request.getSession().setAttribute("message", msg);
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
}
}
boolean ranking = true;
String source = (String) request.getParameter("source");
if (source == null) {
source = "ALL";
}
if (NCItBrowserProperties._debugOn) {
try {
_logger.debug(Utils.SEPARATOR);
_logger.debug("* criteria: " + matchText);
_logger.debug("* source: " + source);
_logger.debug("* ranking: " + ranking);
_logger.debug("* ontology_list: ");
for (int i = 0; i < ontology_list.length; ++i) {
_logger.debug(" " + i + ") " + ontology_list[i]);
}
} catch (Exception e) {
}
}
if (ontology_list == null) {
ontology_list_str =
(String) request.getParameter("ontology_list_str"); // from
// multiple_search_results
// (hidden
// variable)
if (ontology_list_str != null) {
ontology_list = getSelectedVocabularies(ontology_list_str);
}
} else {
knt = ontology_list.length;
if (knt == 0) {
String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary.";
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().setAttribute("hide_ontology_list", "true");
request.getSession().removeAttribute("ontologiesToSearchOn");
// String defaultOntologiesToSearchOnStr =
// ontologiesToSearchOnStr;
request.getSession().setAttribute(
"defaultOntologiesToSearchOnStr", "|");
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
}
}
Vector schemes = new Vector();
Vector versions = new Vector();
ontologiesToSearchOn = new ArrayList<String>();
ontologiesToSearchOnStr = "|";
for (int i = 0; i < ontology_list.length; ++i) {
list.add(ontology_list[i]);
ontologiesToSearchOn.add(ontology_list[i]);
ontologiesToSearchOnStr =
ontologiesToSearchOnStr + ontology_list[i] + "|";
}
if (ontology_list_str == null) {
ontology_list_str = "";
for (int i = 0; i < ontology_list.length; ++i) {
ontology_list_str = ontology_list_str + ontology_list[i];
if (i < ontology_list.length - 1) {
ontology_list_str = ontology_list_str + "|";
}
}
}
scheme = null;
version = null;
String t = "";
if (ontologiesToSearchOn.size() == 0) {
String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary.";
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().removeAttribute("ontologiesToSearchOn");
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
} else {
request.getSession().setAttribute("ontologiesToSearchOn",
ontologiesToSearchOnStr);
// [#25270] Set "all but NCIm selected" as the default for the TB
// home page.
String defaultOntologiesToSearchOnStr = ontologiesToSearchOnStr;
request.getSession().setAttribute("defaultOntologiesToSearchOnStr",
defaultOntologiesToSearchOnStr);
for (int k = 0; k < ontologiesToSearchOn.size(); k++) {
String key = (String) list.get(k);
if (key != null) {
scheme = DataUtils.key2CodingSchemeName(key);
version = DataUtils.key2CodingSchemeVersion(key);
if (scheme != null) {
schemes.add(scheme);
// to be modified (handling of versions)
versions.add(version);
t = t + scheme + " (" + version + ")" + "\n";
boolean isLicensed =
LicenseBean.isLicensed(scheme, version);
if (licenseBean == null) {
licenseBean = new LicenseBean();
request.getSession().setAttribute("licenseBean",
licenseBean);
}
boolean accepted =
licenseBean.licenseAgreementAccepted(scheme);
if (isLicensed && !accepted) {
request.getSession().setAttribute("matchText",
matchText);
request.setAttribute("searchTarget", searchTarget);
request.setAttribute("algorithm", matchAlgorithm);
request.setAttribute("ontology_list_str",
ontology_list_str);
request.setAttribute("scheme", scheme);
request.setAttribute("version", version);
return "license";
}
} else {
_logger.warn("Unable to identify " + key);
}
}
}
}
String max_str = null;
int maxToReturn = -1;// 1000;
try {
max_str =
NCItBrowserProperties
.getProperty(NCItBrowserProperties.MAXIMUM_RETURN);
maxToReturn = Integer.parseInt(max_str);
} catch (Exception ex) {
// Do nothing
}
boolean designationOnly = false;
boolean excludeDesignation = true;
ResolvedConceptReferencesIterator iterator = null;
if (searchTarget.compareTo("names") == 0) {
long ms = System.currentTimeMillis();
long delay = 0;
_logger.debug("Calling SearchUtils().searchByName " + matchText);
ResolvedConceptReferencesIteratorWrapper wrapper =
new SearchUtils().searchByName(schemes, versions, matchText,
source, matchAlgorithm, ranking, maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
}
delay = System.currentTimeMillis() - ms;
_logger.debug("searchByName delay (millisec.): " + delay);
} else if (searchTarget.compareTo("properties") == 0) {
ResolvedConceptReferencesIteratorWrapper wrapper =
new SearchUtils().searchByProperties(schemes, versions,
matchText, source, matchAlgorithm, excludeDesignation,
ranking, maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
}
} else if (searchTarget.compareTo("relationships") == 0) {
designationOnly = true;
ResolvedConceptReferencesIteratorWrapper wrapper =
new SearchUtils().searchByAssociations(schemes, versions,
matchText, source, matchAlgorithm, designationOnly,
ranking, maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
}
}
request.getSession().setAttribute("vocabulary", scheme);
request.getSession().setAttribute("searchTarget", searchTarget);
request.getSession().setAttribute("algorithm", matchAlgorithm);
request.getSession().removeAttribute("neighborhood_synonyms");
request.getSession().removeAttribute("neighborhood_atoms");
request.getSession().removeAttribute("concept");
request.getSession().removeAttribute("code");
request.getSession().removeAttribute("codeInNCI");
request.getSession().removeAttribute("AssociationTargetHashMap");
request.getSession().removeAttribute("type");
if (iterator != null) {
IteratorBean iteratorBean =
(IteratorBean) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("iteratorBean");
if (iteratorBean == null) {
iteratorBean = new IteratorBean(iterator);
FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().put("iteratorBean", iteratorBean);
} else {
iteratorBean.setIterator(iterator);
}
int size = iteratorBean.getSize();
if (size == 1) {
int pageNumber = 1;
list = iteratorBean.getData(1);
ResolvedConceptReference ref =
(ResolvedConceptReference) list.get(0);
String coding_scheme = ref.getCodingSchemeName();
if (coding_scheme.compareToIgnoreCase("NCI Metathesaurus") == 0) {
String match_size = Integer.toString(size);
;// Integer.toString(v.size());
request.getSession().setAttribute("match_size", match_size);
request.getSession().setAttribute("page_string", "1");
request.getSession().setAttribute("new_search",
Boolean.TRUE);
// route to multiple_search_results.jsp
return "search_results";
}
request.getSession().setAttribute("singleton", "true");
request.getSession().setAttribute("dictionary", coding_scheme);
Entity c = null;
if (ref == null) {
String msg =
"Error: Null ResolvedConceptReference encountered.";
request.getSession().setAttribute("message", msg);
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "message";
} else {
c = ref.getReferencedEntry();
if (c == null) {
c =
DataUtils.getConceptByCode(coding_scheme, null,
null, ref.getConceptCode());
}
}
request.getSession().setAttribute("code", ref.getConceptCode());
request.getSession().setAttribute("concept", c);
request.getSession().setAttribute("type", "properties");
request.getSession().setAttribute("new_search", Boolean.TRUE);
request.setAttribute("algorithm", matchAlgorithm);
coding_scheme =
(String) DataUtils._localName2FormalNameHashMap
.get(coding_scheme);
String convertJSPString = HTTPUtils.convertJSPString(matchText);
request.getSession()
.setAttribute("matchText", convertJSPString);
request.setAttribute("dictionary", coding_scheme);
return "concept_details";
} else if (size > 0) {
String match_size = Integer.toString(size);
;// Integer.toString(v.size());
request.getSession().setAttribute("match_size", match_size);
request.getSession().setAttribute("page_string", "1");
request.getSession().setAttribute("new_search", Boolean.TRUE);
// route to multiple_search_results.jsp
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
_logger.debug("Start to render search_results ... ");
return "search_results";
}
}
int minimumSearchStringLength =
NCItBrowserProperties.getMinimumSearchStringLength();
if (ontologiesToSearchOn.size() == 0) {
request.getSession().removeAttribute("vocabulary");
} else if (ontologiesToSearchOn.size() == 1) {
String msg_scheme = (String) ontologiesToSearchOn.get(0);
request.getSession().setAttribute("vocabulary", msg_scheme);
} else {
request.getSession().removeAttribute("vocabulary");
}
String message = Constants.ERROR_NO_MATCH_FOUND;
if (matchAlgorithm.compareTo(Constants.EXACT_SEARCH_ALGORITHM) == 0) {
message = Constants.ERROR_NO_MATCH_FOUND_TRY_OTHER_ALGORITHMS;
}
else if (matchAlgorithm.compareTo(Constants.STARTWITH_SEARCH_ALGORITHM) == 0
&& matchText.length() < minimumSearchStringLength) {
message = Constants.ERROR_ENCOUNTERED_TRY_NARROW_QUERY;
}
hide_ontology_list = "false";
/*
* if (initial_search == null) { hide_ontology_list = "true"; }
*/
request.getSession().setAttribute("hide_ontology_list",
hide_ontology_list);
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().setAttribute("ontologiesToSearchOn",
ontologiesToSearchOnStr);
request.getSession().setAttribute("multiple_search_no_match_error",
"true");
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
}
|
public String multipleSearchAction() {
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
String scheme = (String) request.getParameter("scheme");
String version = (String) request.getParameter("version");
String navigation_type = request.getParameter("nav_type");
if (navigation_type == null || navigation_type.equals("null")) {
navigation_type = "terminologies";
}
// Called from license.jsp
LicenseBean licenseBean =
(LicenseBean) request.getSession().getAttribute("licenseBean");
if (scheme != null && version != null) {
if (licenseBean == null) {
licenseBean = new LicenseBean();
}
licenseBean.addLicenseAgreement(scheme);
request.getSession().setAttribute("licenseBean", licenseBean);
}
String matchText = (String) request.getParameter("matchText");
if (matchText != null) {
matchText = matchText.trim();
request.getSession().setAttribute("matchText", matchText);
} else {
matchText = (String) request.getSession().getAttribute("matchText");
}
String multiple_search_error =
(String) request.getSession().getAttribute(
"multiple_search_no_match_error");
request.getSession().removeAttribute("multiple_search_no_match_error");
String matchAlgorithm = (String) request.getParameter("algorithm");
request.getSession().setAttribute("algorithm", matchAlgorithm);
String searchTarget = (String) request.getParameter("searchTarget");
request.getSession().setAttribute("searchTarget", searchTarget);
String initial_search = (String) request.getParameter("initial_search");
String[] ontology_list = null;
if (navigation_type == null || navigation_type.compareTo("terminologies") == 0) {
ontology_list = request.getParameterValues("ontology_list");
}
List list = new ArrayList<String>();
String ontologiesToSearchOnStr = null;
String ontology_list_str = null;
List<String> ontologiesToSearchOn = null;
int knt = 0;
// process mappings
if (initial_search != null) { // from home page
/*
if (navigation_type.compareTo("mappings") == 0) {
String ontologyToSearchOn = request.getParameter("ontologyToSearchOn");
ontologiesToSearchOn = new ArrayList<String>();
ontology_list = new String[1];
ontology_list[0] = ontologyToSearchOn;
ontologiesToSearchOn.add(ontologyToSearchOn);
} else
*/
{
if (multiple_search_error != null) {
ontologiesToSearchOn = new ArrayList<String>();
ontologiesToSearchOnStr =
(String) request.getSession().getAttribute(
"ontologiesToSearchOn");
if (ontologiesToSearchOnStr != null) {
Vector ontologies_to_search_on =
DataUtils.parseData(ontologiesToSearchOnStr);
ontology_list = new String[ontologies_to_search_on.size()];
knt = ontologies_to_search_on.size();
for (int k = 0; k < ontologies_to_search_on.size(); k++) {
String s =
(String) ontologies_to_search_on.elementAt(k);
ontology_list[k] = s;
ontologiesToSearchOn.add(s);
}
}
}
}
if (ontology_list == null || ontology_list.length == 0) {
String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary.";
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().removeAttribute("ontologiesToSearchOn");
// String defaultOntologiesToSearchOnStr =
// ontologiesToSearchOnStr;
request.getSession().setAttribute(
"defaultOntologiesToSearchOnStr", "|");
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
} else {
ontologiesToSearchOn = new ArrayList<String>();
ontologiesToSearchOnStr = "|";
for (int i = 0; i < ontology_list.length; ++i) {
list.add(ontology_list[i]);
ontologiesToSearchOn.add(ontology_list[i]);
ontologiesToSearchOnStr =
ontologiesToSearchOnStr + ontology_list[i] + "|";
}
if (ontology_list_str == null) {
ontology_list_str = "";
for (int i = 0; i < ontology_list.length; ++i) {
ontology_list_str =
ontology_list_str + ontology_list[i];
if (i < ontology_list.length - 1) {
ontology_list_str = ontology_list_str + "|";
}
}
}
request.getSession().setAttribute("ontologiesToSearchOn",
ontologiesToSearchOnStr);
}
} else {
/*
if (navigation_type.compareTo("mappings") == 0) {
String ontologyToSearchOn = request.getParameter("ontologyToSearchOn");
ontologiesToSearchOn = new ArrayList<String>();
ontology_list = new String[1];
ontology_list[0] = ontologyToSearchOn;
ontologiesToSearchOn.add(ontologyToSearchOn);
} else
*/
{
ontologiesToSearchOn = new ArrayList<String>();
ontologiesToSearchOnStr =
(String) request.getSession().getAttribute(
"ontologiesToSearchOn");
if (ontologiesToSearchOnStr != null) {
Vector ontologies_to_search_on =
DataUtils.parseData(ontologiesToSearchOnStr);
ontology_list = new String[ontologies_to_search_on.size()];
knt = ontologies_to_search_on.size();
for (int k = 0; k < ontologies_to_search_on.size(); k++) {
String s = (String) ontologies_to_search_on.elementAt(k);
ontology_list[k] = s;
ontologiesToSearchOn.add(s);
}
}
}
}
String hide_ontology_list = "false";
// [#19965] Error message is not displayed when Search Criteria is not
// proivided
if (matchText == null || matchText.length() == 0) {
String message = Constants.ERROR_NO_SEARCH_STRING_ENTERED;
if (initial_search == null) {
hide_ontology_list = "true";
}
request.getSession().setAttribute("hide_ontology_list",
hide_ontology_list);
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
}
// KLO, 012610
else if (searchTarget.compareTo("relationships") == 0
&& matchAlgorithm.compareTo("contains") == 0) {
String text = matchText.trim();
if (text.length() < NCItBrowserProperties
.getMinimumSearchStringLength()) {
String msg = Constants.ERROR_REQUIRE_MORE_SPECIFIC_QUERY_STRING;
request.getSession().setAttribute("warning", msg);
request.getSession().setAttribute("message", msg);
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
}
}
boolean ranking = true;
String source = (String) request.getParameter("source");
if (source == null) {
source = "ALL";
}
if (NCItBrowserProperties._debugOn) {
try {
_logger.debug(Utils.SEPARATOR);
_logger.debug("* criteria: " + matchText);
_logger.debug("* source: " + source);
_logger.debug("* ranking: " + ranking);
_logger.debug("* ontology_list: ");
for (int i = 0; i < ontology_list.length; ++i) {
_logger.debug(" " + i + ") " + ontology_list[i]);
}
} catch (Exception e) {
}
}
if (ontology_list == null) {
ontology_list_str =
(String) request.getParameter("ontology_list_str"); // from
// multiple_search_results
// (hidden
// variable)
if (ontology_list_str != null) {
ontology_list = getSelectedVocabularies(ontology_list_str);
}
} else {
knt = ontology_list.length;
if (knt == 0) {
String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary.";
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().setAttribute("hide_ontology_list", "true");
request.getSession().removeAttribute("ontologiesToSearchOn");
// String defaultOntologiesToSearchOnStr =
// ontologiesToSearchOnStr;
request.getSession().setAttribute(
"defaultOntologiesToSearchOnStr", "|");
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
}
}
Vector schemes = new Vector();
Vector versions = new Vector();
ontologiesToSearchOn = new ArrayList<String>();
ontologiesToSearchOnStr = "|";
for (int i = 0; i < ontology_list.length; ++i) {
list.add(ontology_list[i]);
ontologiesToSearchOn.add(ontology_list[i]);
ontologiesToSearchOnStr =
ontologiesToSearchOnStr + ontology_list[i] + "|";
}
if (ontology_list_str == null) {
ontology_list_str = "";
for (int i = 0; i < ontology_list.length; ++i) {
ontology_list_str = ontology_list_str + ontology_list[i];
if (i < ontology_list.length - 1) {
ontology_list_str = ontology_list_str + "|";
}
}
}
scheme = null;
version = null;
String t = "";
if (ontologiesToSearchOn.size() == 0) {
String message = Constants.ERROR_NO_VOCABULARY_SELECTED;// "Please select at least one vocabulary.";
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().removeAttribute("ontologiesToSearchOn");
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
} else {
request.getSession().setAttribute("ontologiesToSearchOn",
ontologiesToSearchOnStr);
// [#25270] Set "all but NCIm selected" as the default for the TB
// home page.
String defaultOntologiesToSearchOnStr = ontologiesToSearchOnStr;
request.getSession().setAttribute("defaultOntologiesToSearchOnStr",
defaultOntologiesToSearchOnStr);
for (int k = 0; k < ontologiesToSearchOn.size(); k++) {
String key = (String) list.get(k);
if (key != null) {
scheme = DataUtils.key2CodingSchemeName(key);
version = DataUtils.key2CodingSchemeVersion(key);
if (scheme != null) {
schemes.add(scheme);
// to be modified (handling of versions)
versions.add(version);
t = t + scheme + " (" + version + ")" + "\n";
boolean isLicensed =
LicenseBean.isLicensed(scheme, version);
if (licenseBean == null) {
licenseBean = new LicenseBean();
request.getSession().setAttribute("licenseBean",
licenseBean);
}
boolean accepted =
licenseBean.licenseAgreementAccepted(scheme);
if (isLicensed && !accepted) {
request.getSession().setAttribute("matchText",
matchText);
request.setAttribute("searchTarget", searchTarget);
request.setAttribute("algorithm", matchAlgorithm);
request.setAttribute("ontology_list_str",
ontology_list_str);
request.setAttribute("scheme", scheme);
request.setAttribute("version", version);
return "license";
}
} else {
_logger.warn("Unable to identify " + key);
}
}
}
}
String max_str = null;
int maxToReturn = -1;// 1000;
try {
max_str =
NCItBrowserProperties
.getProperty(NCItBrowserProperties.MAXIMUM_RETURN);
maxToReturn = Integer.parseInt(max_str);
} catch (Exception ex) {
// Do nothing
}
boolean designationOnly = false;
boolean excludeDesignation = true;
ResolvedConceptReferencesIterator iterator = null;
if (searchTarget.compareTo("names") == 0) {
long ms = System.currentTimeMillis();
long delay = 0;
_logger.debug("Calling SearchUtils().searchByName " + matchText);
ResolvedConceptReferencesIteratorWrapper wrapper =
new SearchUtils().searchByName(schemes, versions, matchText,
source, matchAlgorithm, ranking, maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
}
delay = System.currentTimeMillis() - ms;
_logger.debug("searchByName delay (millisec.): " + delay);
} else if (searchTarget.compareTo("properties") == 0) {
ResolvedConceptReferencesIteratorWrapper wrapper =
new SearchUtils().searchByProperties(schemes, versions,
matchText, source, matchAlgorithm, excludeDesignation,
ranking, maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
}
} else if (searchTarget.compareTo("relationships") == 0) {
designationOnly = true;
ResolvedConceptReferencesIteratorWrapper wrapper =
new SearchUtils().searchByAssociations(schemes, versions,
matchText, source, matchAlgorithm, designationOnly,
ranking, maxToReturn);
if (wrapper != null) {
iterator = wrapper.getIterator();
}
}
request.getSession().setAttribute("vocabulary", scheme);
request.getSession().setAttribute("searchTarget", searchTarget);
request.getSession().setAttribute("algorithm", matchAlgorithm);
request.getSession().removeAttribute("neighborhood_synonyms");
request.getSession().removeAttribute("neighborhood_atoms");
request.getSession().removeAttribute("concept");
request.getSession().removeAttribute("code");
request.getSession().removeAttribute("codeInNCI");
request.getSession().removeAttribute("AssociationTargetHashMap");
request.getSession().removeAttribute("type");
if (iterator != null) {
IteratorBean iteratorBean =
(IteratorBean) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("iteratorBean");
if (iteratorBean == null) {
iteratorBean = new IteratorBean(iterator);
FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().put("iteratorBean", iteratorBean);
} else {
iteratorBean.setIterator(iterator);
}
int size = iteratorBean.getSize();
if (size == 1) {
int pageNumber = 1;
list = iteratorBean.getData(1);
ResolvedConceptReference ref =
(ResolvedConceptReference) list.get(0);
String coding_scheme = ref.getCodingSchemeName();
if (coding_scheme.compareToIgnoreCase("NCI Metathesaurus") == 0) {
String match_size = Integer.toString(size);
;// Integer.toString(v.size());
request.getSession().setAttribute("match_size", match_size);
request.getSession().setAttribute("page_string", "1");
request.getSession().setAttribute("new_search",
Boolean.TRUE);
// route to multiple_search_results.jsp
return "search_results";
}
request.getSession().setAttribute("singleton", "true");
request.getSession().setAttribute("dictionary", coding_scheme);
Entity c = null;
if (ref == null) {
String msg =
"Error: Null ResolvedConceptReference encountered.";
request.getSession().setAttribute("message", msg);
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "message";
} else {
c = ref.getReferencedEntry();
if (c == null) {
c =
DataUtils.getConceptByCode(coding_scheme, null,
null, ref.getConceptCode());
}
}
request.getSession().setAttribute("code", ref.getConceptCode());
request.getSession().setAttribute("concept", c);
request.getSession().setAttribute("type", "properties");
request.getSession().setAttribute("new_search", Boolean.TRUE);
request.setAttribute("algorithm", matchAlgorithm);
coding_scheme =
(String) DataUtils._localName2FormalNameHashMap
.get(coding_scheme);
String convertJSPString = HTTPUtils.convertJSPString(matchText);
request.getSession()
.setAttribute("matchText", convertJSPString);
request.setAttribute("dictionary", coding_scheme);
return "concept_details";
} else if (size > 0) {
String match_size = Integer.toString(size);
;// Integer.toString(v.size());
request.getSession().setAttribute("match_size", match_size);
request.getSession().setAttribute("page_string", "1");
request.getSession().setAttribute("new_search", Boolean.TRUE);
// route to multiple_search_results.jsp
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
_logger.debug("Start to render search_results ... ");
return "search_results";
}
}
int minimumSearchStringLength =
NCItBrowserProperties.getMinimumSearchStringLength();
if (ontologiesToSearchOn.size() == 0) {
request.getSession().removeAttribute("vocabulary");
} else if (ontologiesToSearchOn.size() == 1) {
String msg_scheme = (String) ontologiesToSearchOn.get(0);
request.getSession().setAttribute("vocabulary", msg_scheme);
} else {
request.getSession().removeAttribute("vocabulary");
}
String message = Constants.ERROR_NO_MATCH_FOUND;
if (matchAlgorithm.compareTo(Constants.EXACT_SEARCH_ALGORITHM) == 0) {
message = Constants.ERROR_NO_MATCH_FOUND_TRY_OTHER_ALGORITHMS;
}
else if (matchAlgorithm.compareTo(Constants.STARTWITH_SEARCH_ALGORITHM) == 0
&& matchText.length() < minimumSearchStringLength) {
message = Constants.ERROR_ENCOUNTERED_TRY_NARROW_QUERY;
}
hide_ontology_list = "false";
/*
* if (initial_search == null) { hide_ontology_list = "true"; }
*/
request.getSession().setAttribute("hide_ontology_list",
hide_ontology_list);
request.getSession().setAttribute("warning", message);
request.getSession().setAttribute("message", message);
request.getSession().setAttribute("ontologiesToSearchOn",
ontologiesToSearchOnStr);
request.getSession().setAttribute("multiple_search_no_match_error",
"true");
request.getSession().setAttribute("matchText",
HTTPUtils.convertJSPString(matchText));
return "multiple_search";
}
|
diff --git a/library/src/com/nineoldandroids/view/animation/AnimatorProxy.java b/library/src/com/nineoldandroids/view/animation/AnimatorProxy.java
index 7ea410c..8136224 100644
--- a/library/src/com/nineoldandroids/view/animation/AnimatorProxy.java
+++ b/library/src/com/nineoldandroids/view/animation/AnimatorProxy.java
@@ -1,218 +1,218 @@
package com.nineoldandroids.view.animation;
import java.util.WeakHashMap;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Transformation;
/**
* A proxy class to allow for modifying post-3.0 view properties on all pre-3.0
* platforms. <strong>DO NOT</strong> wrap your views with this class if you
* are using {@code ObjectAnimator} as it will handle that itself.
*/
public final class AnimatorProxy extends Animation {
/** Whether or not the current running platform needs to be proxied. */
public static final boolean NEEDS_PROXY = Integer.valueOf(Build.VERSION.SDK).intValue() < Build.VERSION_CODES.HONEYCOMB;
private static final WeakHashMap<View, AnimatorProxy> PROXIES =
new WeakHashMap<View, AnimatorProxy>();
/**
* Create a proxy to allow for modifying post-3.0 view properties on all
* pre-3.0 platforms. <strong>DO NOT</strong> wrap your views if you are
* using {@code ObjectAnimator} as it will handle that itself.
*
* @param view View to wrap.
* @return Proxy to post-3.0 properties.
*/
public static AnimatorProxy wrap(View view) {
AnimatorProxy proxy = PROXIES.get(view);
if (proxy == null) {
proxy = new AnimatorProxy(view);
PROXIES.put(view, proxy);
}
return proxy;
}
private final View mView;
private final ViewGroup mViewParent;
private final Camera mCamera;
private boolean mHasPivot = false;
private float mAlpha = 1;
private float mPivotX = 0;
private float mPivotY = 0;
private float mRotationX = 0;
private float mRotationY = 0;
private float mRotationZ = 0;
private float mScaleX = 1;
private float mScaleY = 1;
private float mTranslationX = 0;
private float mTranslationY = 0;
private AnimatorProxy(View view) {
setDuration(0); //perform transformation immediately
setFillAfter(true); //persist transformation beyond duration
view.setAnimation(this);
mView = view;
mViewParent = (ViewGroup)view.getParent();
mCamera = new Camera();
}
public float getAlpha() {
return mAlpha;
}
public void setAlpha(float alpha) {
mAlpha = alpha;
mView.invalidate();
}
public float getPivotX() {
return mPivotX;
}
public void setPivotX(float pivotX) {
mHasPivot = true;
if (mPivotX != pivotX) {
mPivotX = pivotX;
mViewParent.invalidate();
}
}
public float getPivotY() {
return mPivotY;
}
public void setPivotY(float pivotY) {
mHasPivot = true;
if (mPivotY != pivotY) {
mPivotY = pivotY;
mViewParent.invalidate();
}
}
public float getRotation() {
return mRotationZ;
}
public void setRotation(float rotation) {
if (mRotationZ != rotation) {
mRotationZ = rotation;
mViewParent.invalidate();
}
}
public float getRotationX() {
return mRotationX;
}
public void setRotationX(float rotationX) {
if (mRotationX != rotationX) {
mRotationX = rotationX;
mViewParent.invalidate();
}
}
public float getRotationY() {
return mRotationY;
}
public void setRotationY(float rotationY) {
if (mRotationY != rotationY) {
mRotationY = rotationY;
mViewParent.invalidate();
}
}
public float getScaleX() {
return mScaleX;
}
public void setScaleX(float scaleX) {
if (mScaleX != scaleX) {
mScaleX = scaleX;
mViewParent.invalidate();
}
}
public float getScaleY() {
return mScaleY;
}
public void setScaleY(float scaleY) {
if (mScaleY != scaleY) {
mScaleY = scaleY;
mViewParent.invalidate();
}
}
public int getScrollX() {
return mView.getScrollX();
}
public void setScrollX(int value) {
mView.scrollTo(value, mView.getScrollY());
}
public int getScrollY() {
return mView.getScrollY();
}
public void setScrollY(int value) {
mView.scrollTo(mView.getScrollY(), value);
}
public float getTranslationX() {
return mTranslationX;
}
public void setTranslationX(float translationX) {
if (mTranslationX != translationX) {
mTranslationX = translationX;
mViewParent.invalidate();
}
}
public float getTranslationY() {
return mTranslationY;
}
public void setTranslationY(float translationY) {
if (mTranslationY != translationY) {
mTranslationY = translationY;
mViewParent.invalidate();
}
}
public float getX() {
return mView.getLeft() + mTranslationX;
}
public void setX(float x) {
setTranslationX(x - mView.getLeft());
}
public float getY() {
return mView.getTop() + mTranslationY;
}
public void setY(float y) {
setTranslationY(y - mView.getTop());
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
t.setAlpha(mAlpha);
final View view = mView;
final float w = view.getWidth();
final float h = view.getHeight();
final Matrix m = t.getMatrix();
final float rX = mRotationX;
final float rY = mRotationY;
final float rZ = mRotationZ;
if ((rX != 0) || (rY != 0) || (rZ != 0)) {
final Camera camera = mCamera;
final boolean hasPivot = mHasPivot;
final float pX = hasPivot ? mPivotX : w/2f;
final float pY = hasPivot ? mPivotY : h/2f;
camera.save();
camera.rotateX(rX);
camera.rotateY(rY);
camera.rotateZ(-rZ);
camera.getMatrix(m);
camera.restore();
m.preTranslate(-pX, -pY);
m.postTranslate(pX, pY);
}
final float sX = mScaleX;
final float sY = mScaleY;
- if ((sX != 0) || (sX != 0)) {
+ if ((sX != 0) || (sY != 0)) {
final float deltaSX = ((sX * w) - w) / 2f;
final float deltaSY = ((sY * h) - h) / 2f;
m.postScale(sX, sY);
m.postTranslate(-deltaSX, -deltaSY);
}
m.postTranslate(mTranslationX, mTranslationY);
}
}
| true | true |
protected void applyTransformation(float interpolatedTime, Transformation t) {
t.setAlpha(mAlpha);
final View view = mView;
final float w = view.getWidth();
final float h = view.getHeight();
final Matrix m = t.getMatrix();
final float rX = mRotationX;
final float rY = mRotationY;
final float rZ = mRotationZ;
if ((rX != 0) || (rY != 0) || (rZ != 0)) {
final Camera camera = mCamera;
final boolean hasPivot = mHasPivot;
final float pX = hasPivot ? mPivotX : w/2f;
final float pY = hasPivot ? mPivotY : h/2f;
camera.save();
camera.rotateX(rX);
camera.rotateY(rY);
camera.rotateZ(-rZ);
camera.getMatrix(m);
camera.restore();
m.preTranslate(-pX, -pY);
m.postTranslate(pX, pY);
}
final float sX = mScaleX;
final float sY = mScaleY;
if ((sX != 0) || (sX != 0)) {
final float deltaSX = ((sX * w) - w) / 2f;
final float deltaSY = ((sY * h) - h) / 2f;
m.postScale(sX, sY);
m.postTranslate(-deltaSX, -deltaSY);
}
m.postTranslate(mTranslationX, mTranslationY);
}
|
protected void applyTransformation(float interpolatedTime, Transformation t) {
t.setAlpha(mAlpha);
final View view = mView;
final float w = view.getWidth();
final float h = view.getHeight();
final Matrix m = t.getMatrix();
final float rX = mRotationX;
final float rY = mRotationY;
final float rZ = mRotationZ;
if ((rX != 0) || (rY != 0) || (rZ != 0)) {
final Camera camera = mCamera;
final boolean hasPivot = mHasPivot;
final float pX = hasPivot ? mPivotX : w/2f;
final float pY = hasPivot ? mPivotY : h/2f;
camera.save();
camera.rotateX(rX);
camera.rotateY(rY);
camera.rotateZ(-rZ);
camera.getMatrix(m);
camera.restore();
m.preTranslate(-pX, -pY);
m.postTranslate(pX, pY);
}
final float sX = mScaleX;
final float sY = mScaleY;
if ((sX != 0) || (sY != 0)) {
final float deltaSX = ((sX * w) - w) / 2f;
final float deltaSY = ((sY * h) - h) / 2f;
m.postScale(sX, sY);
m.postTranslate(-deltaSX, -deltaSY);
}
m.postTranslate(mTranslationX, mTranslationY);
}
|
diff --git a/src/org/geworkbench/parsers/SOFTSeriesParser.java b/src/org/geworkbench/parsers/SOFTSeriesParser.java
index db945a1e..d9b9be9f 100644
--- a/src/org/geworkbench/parsers/SOFTSeriesParser.java
+++ b/src/org/geworkbench/parsers/SOFTSeriesParser.java
@@ -1,382 +1,386 @@
package org.geworkbench.parsers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.SwingUtilities;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geworkbench.bison.datastructure.biocollections.microarrays.CSMicroarraySet;
import org.geworkbench.bison.datastructure.biocollections.microarrays.DSMicroarraySet;
import org.geworkbench.bison.datastructure.bioobjects.markers.CSExpressionMarker;
import org.geworkbench.bison.datastructure.bioobjects.markers.DSGeneMarker;
import org.geworkbench.bison.datastructure.bioobjects.markers.annotationparser.AnnotationParser;
import org.geworkbench.bison.datastructure.bioobjects.microarray.CSExpressionMarkerValue;
import org.geworkbench.bison.datastructure.bioobjects.microarray.CSMicroarray;
import org.geworkbench.util.AffyAnnotationUtil;
/**
* @author Nikhil
* @version $Id$
*/
public class SOFTSeriesParser {
static Log log = LogFactory.getLog(SOFTFileFormat.class);
private static final String commentSign1 = "#";
private static final String commentSign2 = "!";
private static final String commentSign3 = "^";
static final char ABSENT = 'A';
static final char PRESENT = 'P';
static final char MARGINAL = 'M';
static final char UNDEFINED = '\0';
transient private String errorMessage = null;
private String choosePlatform(File file) throws InterruptedIOException {
BufferedReader br = null;
List<String> p = null;
try {
br = new BufferedReader(new FileReader(file));
String line = br.readLine();
if (line == null) {
errorMessage = "no content in file";
return null;
}
while (line != null) {
if (line.startsWith("!Series_platform_id")) {
if (p == null) {
p = new ArrayList<String>();
}
String platformName = line.split("\\s")[2];
p.add(platformName);
} else if (p != null) {
// finish processing platform id
break;
}
line = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
errorMessage = e.getMessage();
return null;
} catch (IOException e) {
e.printStackTrace();
errorMessage = e.getMessage();
return null;
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (p == null) {
errorMessage = "invalid content in file";
return null;
} else if (p.size() == 1) {
return p.get(0);
} else {
// ask user to choose
PlatformChooser chooser = new PlatformChooser(
p.toArray(new String[0]));
try {
SwingUtilities.invokeAndWait(chooser);
} catch (InterruptedException e) {
e.printStackTrace();
return null;
} catch (InvocationTargetException e) {
e.printStackTrace();
return null;
}
platformChoice = chooser.choice;
if (platformChoice == null)
errorMessage = "No choice was made.";
return platformChoice;
}
}
private volatile String platformChoice;
private static boolean isComment(String line) {
if (line.startsWith(commentSign1) || line.startsWith(commentSign2)
|| line.startsWith(commentSign3))
return true;
else
return false;
}
/*
* (non-Javadoc)
*
* @see
* org.geworkbench.components.parsers.FileFormat#getMArraySet(java.io.File)
*/
public DSMicroarraySet parseSOFTSeriesFile(File file)
throws InputFileFormatException, InterruptedIOException {
String platformChosen = choosePlatform(file);
if (platformChosen == null) {
throw new InputFileFormatException(errorMessage);
}
BufferedReader in = null;
final int extSeperater = '.';
String fileName = file.getName();
int dotIndex = fileName.lastIndexOf(extSeperater);
if (dotIndex != -1) {
fileName = fileName.substring(0, dotIndex);
}
CSMicroarraySet maSet = new CSMicroarraySet();
maSet.setLabel(fileName);
Map<String, List<CSExpressionMarkerValue>> arrayToMarkers = new HashMap<String, List<CSExpressionMarkerValue>>();
List<String> markers = new ArrayList<String>();
int m = 0;
int valueIndex = -1;
int callIndex = -1;
int pValueIndex = -1;
try {
in = new BufferedReader(new FileReader(file));
int counter = 0;
String line = in.readLine();
String currentSample = null;
String currentSampleTitle = null;
String currentPlatform = null;
String currentArrayName = null;
boolean rightSample = false;
boolean insideSampleTable = false;
while (line != null) {
/*
* Adding comments to Experiment Information tab.We will ignore
* the line which start with '!platform_table_end',
* '!platform_table_begin', '!sample_table_begin'and
* '!sample_table_end'
*/
if (line.startsWith(commentSign1)
|| line.startsWith(commentSign2)) {
if (!line.equalsIgnoreCase("!platform_table_end")
&& !line.equalsIgnoreCase("!platform_table_begin")
&& !line.equalsIgnoreCase("!sample_table_begin")
&& !line.equalsIgnoreCase("!sample_table_end")) {
// to be consistent, this detailed information should be used else where instead of as "description" field
// maSet.setDescription(line.substring(1));
}
}
final String sampleTag = "^SAMPLE = ";
if (line.startsWith(sampleTag)) {
currentSample = line.substring(sampleTag.length());
rightSample = false;
line = in.readLine();
continue;
}
final String sampleTitleTag = "!Sample_title = ";
if (line.startsWith(sampleTitleTag)) {
currentSampleTitle = line
.substring(sampleTitleTag.length());
line = in.readLine();
continue;
}
final String platformTag = "!Sample_platform_id = ";
if (line.startsWith("!Sample_platform_id = ")) {
currentPlatform = line.substring(platformTag.length());
rightSample = (currentPlatform.equals(platformChosen));
if (rightSample) {
// pre-condition: sample title goes before platform id
// in the file
currentArrayName = currentSample + ": "
+ currentSampleTitle;
arrayToMarkers.put(currentArrayName,
new ArrayList<CSExpressionMarkerValue>());
}
line = in.readLine();
continue;
}
final String sampleTableBeginTag = "!sample_table_begin";
final String sampleTableEndTag = "!sample_table_end";
if (isComment(line) || !rightSample) {
if (!insideSampleTable && line.startsWith(sampleTableBeginTag)) {
insideSampleTable = true;
}
if (insideSampleTable && line.startsWith(sampleTableEndTag)) {
insideSampleTable = false;
}
line = in.readLine();
continue;
}
if(!insideSampleTable) {
line = in.readLine();
continue;
}
if (line.startsWith("ID_REF")) {
if (counter == 0) {
String[] valueLabels = line.split("\t");
for (int p = 0; p < valueLabels.length; p++) {
if (valueLabels[p].equals("VALUE")) {
valueIndex = p;
}
if (valueLabels[p].equals("DETECTION_CALL")
|| valueLabels[p].equals("ABS_CALL")) {
callIndex = p;
}
if (valueLabels[p].equals("DETECTION P-VALUE")
|| valueLabels[p].equals("DETECTION_P")) {
pValueIndex = p;
}
}
}
counter++;
}
if (!line.startsWith("ID_REF")) {
String[] markerToken = line.split("\t");
if (counter == 1) {
markers.add(markerToken[0]);
String markerName = new String(markerToken[0].trim());
CSExpressionMarker marker = new CSExpressionMarker(m);
marker.setLabel(markerName);
maSet.getMarkers().add(m, marker);
m++;
}
float value = Float.NaN;
try {
if (valueIndex < markerToken.length) {
value = Float.parseFloat(markerToken[valueIndex]
.trim());
}
} catch (NumberFormatException nfe) {
}
// create marker values
CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue(
value);
if (Float.isNaN(value)) {
markerValue.setMissing(true);
} else {
markerValue.setPresent();
}
boolean pValueFound = false;
if (pValueIndex >= 0) {
Double value1 = Double.valueOf(markerToken[pValueIndex]
.trim());
markerValue.setConfidence(value1);
pValueFound = true;
}
if (callIndex >= 0) {
String ca = markerToken[callIndex].trim();
char Call = Character.toUpperCase(ca.charAt(0));
if (!pValueFound) {
switch (Call) {
case PRESENT:
markerValue.setPresent();
break;
case ABSENT:
markerValue.setAbsent();
break;
case MARGINAL:
markerValue.setMarginal();
break;
}
}
}
List<CSExpressionMarkerValue> list = arrayToMarkers
.get(currentArrayName);
list.add(markerValue);
}
line = in.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
in.close();
} catch (IOException e) {
}
}
final int markerCount = markers.size();
int arrayIndex = 0;
for (String arrayName : arrayToMarkers.keySet()) {
CSMicroarray array = new CSMicroarray(arrayIndex, markerCount,
arrayName, DSMicroarraySet.affyTxtType);
List<CSExpressionMarkerValue> markerList = arrayToMarkers
- .get(arrayName);
- for (int markerIndex = 0; markerIndex < markerList.size(); markerIndex++) {
- array.setMarkerValue(markerIndex, markerList.get(markerIndex));
+ .get(arrayName);
+ if (markerList.size()>array.getMarkerValues().length){
+ errorMessage = "Number of markers differs from samples!";
+ throw new InputFileFormatException(errorMessage);
+ }
+ for (int markerIndex = 0; markerIndex < markerList.size(); markerIndex++) {
+ array.setMarkerValue(markerIndex, markerList.get(markerIndex));
}
maSet.add(array);
}
// both the second and the third arguments of matchChipType are in
// fact ignored
String annotationFilename = AffyAnnotationUtil.matchAffyAnnotationFile(maSet);
maSet.setCompatibilityLabel(annotationFilename);
for (DSGeneMarker marker : maSet.getMarkers()) {
String token = marker.getLabel();
String[] locusResult = AnnotationParser.getInfo(token,
AnnotationParser.LOCUSLINK);
String locus = "";
if ((locusResult != null)
&& (!locusResult[0].trim().equals(""))) {
locus = locusResult[0].trim();
}
if (locus.compareTo("") != 0) {
try {
marker.setGeneId(Integer.parseInt(locus));
} catch (NumberFormatException e) {
log.info("Couldn't parse locus id: " + locus);
}
}
String[] geneNames = AnnotationParser.getInfo(token,
AnnotationParser.ABREV);
if (geneNames != null) {
marker.setGeneName(geneNames[0]);
}
marker.getUnigene().set(token);
}
return maSet;
}
}
| true | true |
public DSMicroarraySet parseSOFTSeriesFile(File file)
throws InputFileFormatException, InterruptedIOException {
String platformChosen = choosePlatform(file);
if (platformChosen == null) {
throw new InputFileFormatException(errorMessage);
}
BufferedReader in = null;
final int extSeperater = '.';
String fileName = file.getName();
int dotIndex = fileName.lastIndexOf(extSeperater);
if (dotIndex != -1) {
fileName = fileName.substring(0, dotIndex);
}
CSMicroarraySet maSet = new CSMicroarraySet();
maSet.setLabel(fileName);
Map<String, List<CSExpressionMarkerValue>> arrayToMarkers = new HashMap<String, List<CSExpressionMarkerValue>>();
List<String> markers = new ArrayList<String>();
int m = 0;
int valueIndex = -1;
int callIndex = -1;
int pValueIndex = -1;
try {
in = new BufferedReader(new FileReader(file));
int counter = 0;
String line = in.readLine();
String currentSample = null;
String currentSampleTitle = null;
String currentPlatform = null;
String currentArrayName = null;
boolean rightSample = false;
boolean insideSampleTable = false;
while (line != null) {
/*
* Adding comments to Experiment Information tab.We will ignore
* the line which start with '!platform_table_end',
* '!platform_table_begin', '!sample_table_begin'and
* '!sample_table_end'
*/
if (line.startsWith(commentSign1)
|| line.startsWith(commentSign2)) {
if (!line.equalsIgnoreCase("!platform_table_end")
&& !line.equalsIgnoreCase("!platform_table_begin")
&& !line.equalsIgnoreCase("!sample_table_begin")
&& !line.equalsIgnoreCase("!sample_table_end")) {
// to be consistent, this detailed information should be used else where instead of as "description" field
// maSet.setDescription(line.substring(1));
}
}
final String sampleTag = "^SAMPLE = ";
if (line.startsWith(sampleTag)) {
currentSample = line.substring(sampleTag.length());
rightSample = false;
line = in.readLine();
continue;
}
final String sampleTitleTag = "!Sample_title = ";
if (line.startsWith(sampleTitleTag)) {
currentSampleTitle = line
.substring(sampleTitleTag.length());
line = in.readLine();
continue;
}
final String platformTag = "!Sample_platform_id = ";
if (line.startsWith("!Sample_platform_id = ")) {
currentPlatform = line.substring(platformTag.length());
rightSample = (currentPlatform.equals(platformChosen));
if (rightSample) {
// pre-condition: sample title goes before platform id
// in the file
currentArrayName = currentSample + ": "
+ currentSampleTitle;
arrayToMarkers.put(currentArrayName,
new ArrayList<CSExpressionMarkerValue>());
}
line = in.readLine();
continue;
}
final String sampleTableBeginTag = "!sample_table_begin";
final String sampleTableEndTag = "!sample_table_end";
if (isComment(line) || !rightSample) {
if (!insideSampleTable && line.startsWith(sampleTableBeginTag)) {
insideSampleTable = true;
}
if (insideSampleTable && line.startsWith(sampleTableEndTag)) {
insideSampleTable = false;
}
line = in.readLine();
continue;
}
if(!insideSampleTable) {
line = in.readLine();
continue;
}
if (line.startsWith("ID_REF")) {
if (counter == 0) {
String[] valueLabels = line.split("\t");
for (int p = 0; p < valueLabels.length; p++) {
if (valueLabels[p].equals("VALUE")) {
valueIndex = p;
}
if (valueLabels[p].equals("DETECTION_CALL")
|| valueLabels[p].equals("ABS_CALL")) {
callIndex = p;
}
if (valueLabels[p].equals("DETECTION P-VALUE")
|| valueLabels[p].equals("DETECTION_P")) {
pValueIndex = p;
}
}
}
counter++;
}
if (!line.startsWith("ID_REF")) {
String[] markerToken = line.split("\t");
if (counter == 1) {
markers.add(markerToken[0]);
String markerName = new String(markerToken[0].trim());
CSExpressionMarker marker = new CSExpressionMarker(m);
marker.setLabel(markerName);
maSet.getMarkers().add(m, marker);
m++;
}
float value = Float.NaN;
try {
if (valueIndex < markerToken.length) {
value = Float.parseFloat(markerToken[valueIndex]
.trim());
}
} catch (NumberFormatException nfe) {
}
// create marker values
CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue(
value);
if (Float.isNaN(value)) {
markerValue.setMissing(true);
} else {
markerValue.setPresent();
}
boolean pValueFound = false;
if (pValueIndex >= 0) {
Double value1 = Double.valueOf(markerToken[pValueIndex]
.trim());
markerValue.setConfidence(value1);
pValueFound = true;
}
if (callIndex >= 0) {
String ca = markerToken[callIndex].trim();
char Call = Character.toUpperCase(ca.charAt(0));
if (!pValueFound) {
switch (Call) {
case PRESENT:
markerValue.setPresent();
break;
case ABSENT:
markerValue.setAbsent();
break;
case MARGINAL:
markerValue.setMarginal();
break;
}
}
}
List<CSExpressionMarkerValue> list = arrayToMarkers
.get(currentArrayName);
list.add(markerValue);
}
line = in.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
in.close();
} catch (IOException e) {
}
}
final int markerCount = markers.size();
int arrayIndex = 0;
for (String arrayName : arrayToMarkers.keySet()) {
CSMicroarray array = new CSMicroarray(arrayIndex, markerCount,
arrayName, DSMicroarraySet.affyTxtType);
List<CSExpressionMarkerValue> markerList = arrayToMarkers
.get(arrayName);
for (int markerIndex = 0; markerIndex < markerList.size(); markerIndex++) {
array.setMarkerValue(markerIndex, markerList.get(markerIndex));
}
maSet.add(array);
}
// both the second and the third arguments of matchChipType are in
// fact ignored
String annotationFilename = AffyAnnotationUtil.matchAffyAnnotationFile(maSet);
maSet.setCompatibilityLabel(annotationFilename);
for (DSGeneMarker marker : maSet.getMarkers()) {
String token = marker.getLabel();
String[] locusResult = AnnotationParser.getInfo(token,
AnnotationParser.LOCUSLINK);
String locus = "";
if ((locusResult != null)
&& (!locusResult[0].trim().equals(""))) {
locus = locusResult[0].trim();
}
if (locus.compareTo("") != 0) {
try {
marker.setGeneId(Integer.parseInt(locus));
} catch (NumberFormatException e) {
log.info("Couldn't parse locus id: " + locus);
}
}
String[] geneNames = AnnotationParser.getInfo(token,
AnnotationParser.ABREV);
if (geneNames != null) {
marker.setGeneName(geneNames[0]);
}
marker.getUnigene().set(token);
}
return maSet;
}
|
public DSMicroarraySet parseSOFTSeriesFile(File file)
throws InputFileFormatException, InterruptedIOException {
String platformChosen = choosePlatform(file);
if (platformChosen == null) {
throw new InputFileFormatException(errorMessage);
}
BufferedReader in = null;
final int extSeperater = '.';
String fileName = file.getName();
int dotIndex = fileName.lastIndexOf(extSeperater);
if (dotIndex != -1) {
fileName = fileName.substring(0, dotIndex);
}
CSMicroarraySet maSet = new CSMicroarraySet();
maSet.setLabel(fileName);
Map<String, List<CSExpressionMarkerValue>> arrayToMarkers = new HashMap<String, List<CSExpressionMarkerValue>>();
List<String> markers = new ArrayList<String>();
int m = 0;
int valueIndex = -1;
int callIndex = -1;
int pValueIndex = -1;
try {
in = new BufferedReader(new FileReader(file));
int counter = 0;
String line = in.readLine();
String currentSample = null;
String currentSampleTitle = null;
String currentPlatform = null;
String currentArrayName = null;
boolean rightSample = false;
boolean insideSampleTable = false;
while (line != null) {
/*
* Adding comments to Experiment Information tab.We will ignore
* the line which start with '!platform_table_end',
* '!platform_table_begin', '!sample_table_begin'and
* '!sample_table_end'
*/
if (line.startsWith(commentSign1)
|| line.startsWith(commentSign2)) {
if (!line.equalsIgnoreCase("!platform_table_end")
&& !line.equalsIgnoreCase("!platform_table_begin")
&& !line.equalsIgnoreCase("!sample_table_begin")
&& !line.equalsIgnoreCase("!sample_table_end")) {
// to be consistent, this detailed information should be used else where instead of as "description" field
// maSet.setDescription(line.substring(1));
}
}
final String sampleTag = "^SAMPLE = ";
if (line.startsWith(sampleTag)) {
currentSample = line.substring(sampleTag.length());
rightSample = false;
line = in.readLine();
continue;
}
final String sampleTitleTag = "!Sample_title = ";
if (line.startsWith(sampleTitleTag)) {
currentSampleTitle = line
.substring(sampleTitleTag.length());
line = in.readLine();
continue;
}
final String platformTag = "!Sample_platform_id = ";
if (line.startsWith("!Sample_platform_id = ")) {
currentPlatform = line.substring(platformTag.length());
rightSample = (currentPlatform.equals(platformChosen));
if (rightSample) {
// pre-condition: sample title goes before platform id
// in the file
currentArrayName = currentSample + ": "
+ currentSampleTitle;
arrayToMarkers.put(currentArrayName,
new ArrayList<CSExpressionMarkerValue>());
}
line = in.readLine();
continue;
}
final String sampleTableBeginTag = "!sample_table_begin";
final String sampleTableEndTag = "!sample_table_end";
if (isComment(line) || !rightSample) {
if (!insideSampleTable && line.startsWith(sampleTableBeginTag)) {
insideSampleTable = true;
}
if (insideSampleTable && line.startsWith(sampleTableEndTag)) {
insideSampleTable = false;
}
line = in.readLine();
continue;
}
if(!insideSampleTable) {
line = in.readLine();
continue;
}
if (line.startsWith("ID_REF")) {
if (counter == 0) {
String[] valueLabels = line.split("\t");
for (int p = 0; p < valueLabels.length; p++) {
if (valueLabels[p].equals("VALUE")) {
valueIndex = p;
}
if (valueLabels[p].equals("DETECTION_CALL")
|| valueLabels[p].equals("ABS_CALL")) {
callIndex = p;
}
if (valueLabels[p].equals("DETECTION P-VALUE")
|| valueLabels[p].equals("DETECTION_P")) {
pValueIndex = p;
}
}
}
counter++;
}
if (!line.startsWith("ID_REF")) {
String[] markerToken = line.split("\t");
if (counter == 1) {
markers.add(markerToken[0]);
String markerName = new String(markerToken[0].trim());
CSExpressionMarker marker = new CSExpressionMarker(m);
marker.setLabel(markerName);
maSet.getMarkers().add(m, marker);
m++;
}
float value = Float.NaN;
try {
if (valueIndex < markerToken.length) {
value = Float.parseFloat(markerToken[valueIndex]
.trim());
}
} catch (NumberFormatException nfe) {
}
// create marker values
CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue(
value);
if (Float.isNaN(value)) {
markerValue.setMissing(true);
} else {
markerValue.setPresent();
}
boolean pValueFound = false;
if (pValueIndex >= 0) {
Double value1 = Double.valueOf(markerToken[pValueIndex]
.trim());
markerValue.setConfidence(value1);
pValueFound = true;
}
if (callIndex >= 0) {
String ca = markerToken[callIndex].trim();
char Call = Character.toUpperCase(ca.charAt(0));
if (!pValueFound) {
switch (Call) {
case PRESENT:
markerValue.setPresent();
break;
case ABSENT:
markerValue.setAbsent();
break;
case MARGINAL:
markerValue.setMarginal();
break;
}
}
}
List<CSExpressionMarkerValue> list = arrayToMarkers
.get(currentArrayName);
list.add(markerValue);
}
line = in.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
in.close();
} catch (IOException e) {
}
}
final int markerCount = markers.size();
int arrayIndex = 0;
for (String arrayName : arrayToMarkers.keySet()) {
CSMicroarray array = new CSMicroarray(arrayIndex, markerCount,
arrayName, DSMicroarraySet.affyTxtType);
List<CSExpressionMarkerValue> markerList = arrayToMarkers
.get(arrayName);
if (markerList.size()>array.getMarkerValues().length){
errorMessage = "Number of markers differs from samples!";
throw new InputFileFormatException(errorMessage);
}
for (int markerIndex = 0; markerIndex < markerList.size(); markerIndex++) {
array.setMarkerValue(markerIndex, markerList.get(markerIndex));
}
maSet.add(array);
}
// both the second and the third arguments of matchChipType are in
// fact ignored
String annotationFilename = AffyAnnotationUtil.matchAffyAnnotationFile(maSet);
maSet.setCompatibilityLabel(annotationFilename);
for (DSGeneMarker marker : maSet.getMarkers()) {
String token = marker.getLabel();
String[] locusResult = AnnotationParser.getInfo(token,
AnnotationParser.LOCUSLINK);
String locus = "";
if ((locusResult != null)
&& (!locusResult[0].trim().equals(""))) {
locus = locusResult[0].trim();
}
if (locus.compareTo("") != 0) {
try {
marker.setGeneId(Integer.parseInt(locus));
} catch (NumberFormatException e) {
log.info("Couldn't parse locus id: " + locus);
}
}
String[] geneNames = AnnotationParser.getInfo(token,
AnnotationParser.ABREV);
if (geneNames != null) {
marker.setGeneName(geneNames[0]);
}
marker.getUnigene().set(token);
}
return maSet;
}
|
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/ntriples/RdfNTriplesWritingContentHandler.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/ntriples/RdfNTriplesWritingContentHandler.java
index 26e35cda0..a84308327 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/ntriples/RdfNTriplesWritingContentHandler.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/ntriples/RdfNTriplesWritingContentHandler.java
@@ -1,194 +1,194 @@
/**
* Copyright 2005-2009 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.ext.rdf.internal.ntriples;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import org.restlet.data.Reference;
import org.restlet.ext.rdf.Graph;
import org.restlet.ext.rdf.GraphHandler;
import org.restlet.ext.rdf.Link;
import org.restlet.ext.rdf.LinkReference;
import org.restlet.ext.rdf.Literal;
/**
* Handler of RDF content according to the N-Triples notation.
*
* @author Thierry Boileau
*/
public class RdfNTriplesWritingContentHandler extends GraphHandler {
/** Buffered writer. */
private BufferedWriter bw;
/** The graph of links to write. */
private Graph linkSet;
/**
* Constructor.
*
* @param linkSet
* The set of links to write to the output stream.
* @param outputStream
* The output stream to write to.
* @throws IOException
* @throws IOException
*/
public RdfNTriplesWritingContentHandler(Graph linkSet,
OutputStream outputStream) throws IOException {
super();
this.linkSet = linkSet;
this.bw = new BufferedWriter(new OutputStreamWriter(outputStream));
}
@Override
public void link(Graph source, Reference typeRef, Literal target) {
org.restlet.Context.getCurrentLogger().warning(
"Subjects as Graph are not supported in N-Triples.");
}
@Override
public void link(Graph source, Reference typeRef, Reference target) {
org.restlet.Context.getCurrentLogger().warning(
"Subjects as Graph are not supported in N-Triples.");
}
@Override
public void link(Reference source, Reference typeRef, Literal target) {
try {
write(source);
this.bw.write(" ");
write(typeRef);
this.bw.write(" ");
write(target);
} catch (IOException e) {
org.restlet.Context.getCurrentLogger().warning(
"Cannot write the representation of a statement due to: "
+ e.getMessage());
}
}
@Override
public void link(Reference source, Reference typeRef, Reference target) {
try {
write(source);
this.bw.write(" ");
write(typeRef);
this.bw.write(" ");
write(target);
} catch (IOException e) {
org.restlet.Context.getCurrentLogger().warning(
"Cannot write the representation of a statement due to: "
+ e.getMessage());
}
}
/**
* Writes the current graph of links.
*
* @throws IOException
*/
public void write() throws IOException {
if (this.linkSet != null) {
write(this.linkSet);
this.bw.flush();
}
}
/**
* Write the representation of the given graph of links.
*
* @param linkset
* the given graph of links.
* @throws IOException
* @throws IOException
*/
private void write(Graph linkset) throws IOException {
for (Link link : linkset) {
if (link.hasReferenceSource()) {
if (link.hasReferenceTarget()) {
link(link.getSourceAsReference(), link.getTypeRef(), link
.getTargetAsReference());
} else if (link.hasLiteralTarget()) {
link(link.getSourceAsReference(), link.getTypeRef(), link
.getTargetAsLiteral());
} else {
org.restlet.Context
.getCurrentLogger()
.warning(
"Cannot write the representation of a statement due to the fact that the object is neither a Reference nor a literal.");
}
} else if (link.hasGraphSource()) {
org.restlet.Context
.getCurrentLogger()
.warning(
"Cannot write the representation of a statement due to the fact that the subject is not a Reference.");
}
+ this.bw.write(".\n");
}
- this.bw.write(".\n");
}
/**
* Writes the representation of a literal.
*
* @param literal
* The literal to write.
* @throws IOException
*/
private void write(Literal literal) throws IOException {
// Write it as a string
this.bw.write("\"");
this.bw.write(literal.getValue());
this.bw.write("\"");
}
/**
* Writes the representation of a given reference.
*
* @param reference
* The reference to write.
* @throws IOException
*/
private void write(Reference reference) throws IOException {
String uri = reference.toString();
if (LinkReference.isBlank(reference)) {
this.bw.write(uri);
} else {
this.bw.append("<");
this.bw.append(uri);
this.bw.append(">");
}
}
}
| false | true |
private void write(Graph linkset) throws IOException {
for (Link link : linkset) {
if (link.hasReferenceSource()) {
if (link.hasReferenceTarget()) {
link(link.getSourceAsReference(), link.getTypeRef(), link
.getTargetAsReference());
} else if (link.hasLiteralTarget()) {
link(link.getSourceAsReference(), link.getTypeRef(), link
.getTargetAsLiteral());
} else {
org.restlet.Context
.getCurrentLogger()
.warning(
"Cannot write the representation of a statement due to the fact that the object is neither a Reference nor a literal.");
}
} else if (link.hasGraphSource()) {
org.restlet.Context
.getCurrentLogger()
.warning(
"Cannot write the representation of a statement due to the fact that the subject is not a Reference.");
}
}
this.bw.write(".\n");
}
|
private void write(Graph linkset) throws IOException {
for (Link link : linkset) {
if (link.hasReferenceSource()) {
if (link.hasReferenceTarget()) {
link(link.getSourceAsReference(), link.getTypeRef(), link
.getTargetAsReference());
} else if (link.hasLiteralTarget()) {
link(link.getSourceAsReference(), link.getTypeRef(), link
.getTargetAsLiteral());
} else {
org.restlet.Context
.getCurrentLogger()
.warning(
"Cannot write the representation of a statement due to the fact that the object is neither a Reference nor a literal.");
}
} else if (link.hasGraphSource()) {
org.restlet.Context
.getCurrentLogger()
.warning(
"Cannot write the representation of a statement due to the fact that the subject is not a Reference.");
}
this.bw.write(".\n");
}
}
|
diff --git a/src/main/java/org/dynmap/bukkit/BukkitVersionHelperCB.java b/src/main/java/org/dynmap/bukkit/BukkitVersionHelperCB.java
index 83f83f72..007a20d4 100644
--- a/src/main/java/org/dynmap/bukkit/BukkitVersionHelperCB.java
+++ b/src/main/java/org/dynmap/bukkit/BukkitVersionHelperCB.java
@@ -1,222 +1,222 @@
package org.dynmap.bukkit;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Server;
import org.bukkit.World;
import org.dynmap.Log;
import org.dynmap.common.BiomeMap;
/**
* Helper for isolation of bukkit version specific issues
*/
public class BukkitVersionHelperCB extends BukkitVersionHelperGeneric {
private Class<?> nmsblock;
private Class<?> nmsblockarray;
private Class<?> nmsmaterial;
private Field blockbyid;
private Field blockname;
private Field material;
private Method blockbyidfunc; // 1.7+ method for getting block by id
BukkitVersionHelperCB() {
}
@Override
protected String getNMSPackage() {
Server srv = Bukkit.getServer();
/* Get getHandle() method */
try {
Method m = srv.getClass().getMethod("getHandle");
Object scm = m.invoke(srv); /* And use it to get SCM (nms object) */
return scm.getClass().getPackage().getName();
} catch (Exception x) {
Log.severe("Error finding net.minecraft.server packages");
return null;
}
}
@Override
protected void loadNMS() {
// Get block fields
nmsblock = getNMSClass("net.minecraft.server.Block");
nmsblockarray = getNMSClass("[Lnet.minecraft.server.Block;");
nmsmaterial = getNMSClass("net.minecraft.server.Material");
blockbyid = getFieldNoFail(nmsblock, new String[] { "byId" }, nmsblockarray);
if (blockbyid == null) {
blockbyidfunc = getMethod(nmsblock, new String[] { "e" }, new Class[] { int.class });
}
blockname = getPrivateField(nmsblock, new String[] { "name", "b" }, String.class);
material = getPrivateField(nmsblock, new String[] { "material" }, nmsmaterial);
/* Set up biomebase fields */
biomebase = getNMSClass("net.minecraft.server.BiomeBase");
biomebasearray = getNMSClass("[Lnet.minecraft.server.BiomeBase;");
biomebaselist = getPrivateField(biomebase, new String[] { "biomes" }, biomebasearray);
biomebasetemp = getField(biomebase, new String[] { "temperature", "F" }, float.class);
biomebasehumi = getField(biomebase, new String[] { "humidity", "G" }, float.class);
biomebaseidstring = getField(biomebase, new String[] { "y", "af" }, String.class);
biomebaseid = getField(biomebase, new String[] { "id" }, int.class);
/* n.m.s.World */
nmsworld = getNMSClass("net.minecraft.server.WorldServer");
chunkprovserver = getNMSClass("net.minecraft.server.ChunkProviderServer");
nmsw_chunkproviderserver = getField(nmsworld, new String[] { "chunkProviderServer" }, chunkprovserver);
longhashset = getOBCClassNoFail("org.bukkit.craftbukkit.util.LongHashSet");
if(longhashset != null) {
lhs_containskey = getMethod(longhashset, new String[] { "contains" }, new Class[] { int.class, int.class });
}
else {
longhashset = getOBCClass("org.bukkit.craftbukkit.util.LongHashset");
lhs_containskey = getMethod(longhashset, new String[] { "containsKey" }, new Class[] { int.class, int.class });
}
cps_unloadqueue = getFieldNoFail(chunkprovserver, new String[] { "unloadQueue" }, longhashset);
if(cps_unloadqueue == null) {
Log.info("Unload queue not found - default to unload all chunks");
}
/** n.m.s.Chunk */
nmschunk = getNMSClass("net.minecraft.server.Chunk");
nmsc_removeentities = getMethod(nmschunk, new String[] { "removeEntities" }, new Class[0]);
nmsc_tileentities = getField(nmschunk, new String[] { "tileEntities" }, Map.class);
- nmsc_inhabitedticks = getFieldNoFail(nmschunk, new String[] { "s", "q" }, Long.class);
+ nmsc_inhabitedticks = getFieldNoFail(nmschunk, new String[] { "s", "q" }, long.class);
if (nmsc_inhabitedticks == null) {
Log.info("inhabitedTicks field not found - inhabited shader not functional");
}
/** nbt classes */
nbttagcompound = getNMSClass("net.minecraft.server.NBTTagCompound");
nbttagbyte = getNMSClass("net.minecraft.server.NBTTagByte");
nbttagshort = getNMSClass("net.minecraft.server.NBTTagShort");
nbttagint = getNMSClass("net.minecraft.server.NBTTagInt");
nbttaglong = getNMSClass("net.minecraft.server.NBTTagLong");
nbttagfloat = getNMSClass("net.minecraft.server.NBTTagFloat");
nbttagdouble = getNMSClass("net.minecraft.server.NBTTagDouble");
nbttagbytearray = getNMSClass("net.minecraft.server.NBTTagByteArray");
nbttagstring = getNMSClass("net.minecraft.server.NBTTagString");
nbttagintarray = getNMSClass("net.minecraft.server.NBTTagIntArray");
compound_get = getMethod(nbttagcompound, new String[] { "get" }, new Class[] { String.class });
nbttagbyte_val = getPrivateField(nbttagbyte, new String[] { "data" }, byte.class);
nbttagshort_val = getPrivateField(nbttagshort, new String[] { "data" }, short.class);
nbttagint_val = getPrivateField(nbttagint, new String[] { "data" }, int.class);
nbttaglong_val = getPrivateField(nbttaglong, new String[] { "data" }, long.class);
nbttagfloat_val = getPrivateField(nbttagfloat, new String[] { "data" }, float.class);
nbttagdouble_val = getPrivateField(nbttagdouble, new String[] { "data" }, double.class);
nbttagbytearray_val = getPrivateField(nbttagbytearray, new String[] { "data" }, byte[].class);
nbttagstring_val = getPrivateField(nbttagstring, new String[] { "data" }, String.class);
nbttagintarray_val = getPrivateField(nbttagintarray, new String[] { "data" }, int[].class);
/** Tile entity */
nms_tileentity = getNMSClass("net.minecraft.server.TileEntity");
nmst_readnbt = getMethod(nms_tileentity, new String[] { "b" }, new Class[] { nbttagcompound });
nmst_x = getField(nms_tileentity, new String[] { "x" }, int.class);
nmst_y = getField(nms_tileentity, new String[] { "y" }, int.class);
nmst_z = getField(nms_tileentity, new String[] { "z" }, int.class);
}
@Override
public void unloadChunkNoSave(World w, Chunk c, int cx, int cz) {
this.removeEntitiesFromChunk(c);
w.unloadChunk(cx, cz, false, false);
}
/**
* Get block short name list
*/
@Override
public String[] getBlockShortNames() {
try {
String[] names = new String[4096];
if (blockbyid != null) {
Object[] byid = (Object[])blockbyid.get(nmsblock);
for (int i = 0; i < names.length; i++) {
if (byid[i] != null) {
names[i] = (String)blockname.get(byid[i]);
}
}
}
else {
for (int i = 0; i < names.length; i++) {
Object blk = blockbyidfunc.invoke(nmsblock, i);
if (blk != null) {
names[i] = (String)blockname.get(blk);
}
}
}
return names;
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
return new String[0];
}
/**
* Get biome name list
*/
@Override
public String[] getBiomeNames() {
String[] names;
/* Find array of biomes in biomebase */
Object[] biomelist = getBiomeBaseList();
names = new String[biomelist.length];
/* Loop through list, starting afer well known biomes */
for(int i = 0; i < biomelist.length; i++) {
Object bb = biomelist[i];
if(bb != null) {
names[i] = getBiomeBaseIDString(bb);
}
}
return names;
}
/**
* Get block material index list
*/
public int[] getBlockMaterialMap() {
try {
int[] map = new int[4096];
if (blockbyid != null) {
Object[] byid = (Object[])blockbyid.get(nmsblock);
ArrayList<Object> mats = new ArrayList<Object>();
for (int i = 0; i < map.length; i++) {
if (byid[i] != null) {
Object mat = (Object)material.get(byid[i]);
if (mat != null) {
map[i] = mats.indexOf(mat);
if (map[i] < 0) {
map[i] = mats.size();
mats.add(mat);
}
}
else {
map[i] = -1;
}
}
}
}
else {
ArrayList<Object> mats = new ArrayList<Object>();
for (int i = 0; i < map.length; i++) {
Object blk = blockbyidfunc.invoke(nmsblock, i);
if (blk != null) {
Object mat = (Object)material.get(blk);
if (mat != null) {
map[i] = mats.indexOf(mat);
if (map[i] < 0) {
map[i] = mats.size();
mats.add(mat);
}
}
else {
map[i] = -1;
}
}
}
}
return map;
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
return new int[0];
}
}
| true | true |
protected void loadNMS() {
// Get block fields
nmsblock = getNMSClass("net.minecraft.server.Block");
nmsblockarray = getNMSClass("[Lnet.minecraft.server.Block;");
nmsmaterial = getNMSClass("net.minecraft.server.Material");
blockbyid = getFieldNoFail(nmsblock, new String[] { "byId" }, nmsblockarray);
if (blockbyid == null) {
blockbyidfunc = getMethod(nmsblock, new String[] { "e" }, new Class[] { int.class });
}
blockname = getPrivateField(nmsblock, new String[] { "name", "b" }, String.class);
material = getPrivateField(nmsblock, new String[] { "material" }, nmsmaterial);
/* Set up biomebase fields */
biomebase = getNMSClass("net.minecraft.server.BiomeBase");
biomebasearray = getNMSClass("[Lnet.minecraft.server.BiomeBase;");
biomebaselist = getPrivateField(biomebase, new String[] { "biomes" }, biomebasearray);
biomebasetemp = getField(biomebase, new String[] { "temperature", "F" }, float.class);
biomebasehumi = getField(biomebase, new String[] { "humidity", "G" }, float.class);
biomebaseidstring = getField(biomebase, new String[] { "y", "af" }, String.class);
biomebaseid = getField(biomebase, new String[] { "id" }, int.class);
/* n.m.s.World */
nmsworld = getNMSClass("net.minecraft.server.WorldServer");
chunkprovserver = getNMSClass("net.minecraft.server.ChunkProviderServer");
nmsw_chunkproviderserver = getField(nmsworld, new String[] { "chunkProviderServer" }, chunkprovserver);
longhashset = getOBCClassNoFail("org.bukkit.craftbukkit.util.LongHashSet");
if(longhashset != null) {
lhs_containskey = getMethod(longhashset, new String[] { "contains" }, new Class[] { int.class, int.class });
}
else {
longhashset = getOBCClass("org.bukkit.craftbukkit.util.LongHashset");
lhs_containskey = getMethod(longhashset, new String[] { "containsKey" }, new Class[] { int.class, int.class });
}
cps_unloadqueue = getFieldNoFail(chunkprovserver, new String[] { "unloadQueue" }, longhashset);
if(cps_unloadqueue == null) {
Log.info("Unload queue not found - default to unload all chunks");
}
/** n.m.s.Chunk */
nmschunk = getNMSClass("net.minecraft.server.Chunk");
nmsc_removeentities = getMethod(nmschunk, new String[] { "removeEntities" }, new Class[0]);
nmsc_tileentities = getField(nmschunk, new String[] { "tileEntities" }, Map.class);
nmsc_inhabitedticks = getFieldNoFail(nmschunk, new String[] { "s", "q" }, Long.class);
if (nmsc_inhabitedticks == null) {
Log.info("inhabitedTicks field not found - inhabited shader not functional");
}
/** nbt classes */
nbttagcompound = getNMSClass("net.minecraft.server.NBTTagCompound");
nbttagbyte = getNMSClass("net.minecraft.server.NBTTagByte");
nbttagshort = getNMSClass("net.minecraft.server.NBTTagShort");
nbttagint = getNMSClass("net.minecraft.server.NBTTagInt");
nbttaglong = getNMSClass("net.minecraft.server.NBTTagLong");
nbttagfloat = getNMSClass("net.minecraft.server.NBTTagFloat");
nbttagdouble = getNMSClass("net.minecraft.server.NBTTagDouble");
nbttagbytearray = getNMSClass("net.minecraft.server.NBTTagByteArray");
nbttagstring = getNMSClass("net.minecraft.server.NBTTagString");
nbttagintarray = getNMSClass("net.minecraft.server.NBTTagIntArray");
compound_get = getMethod(nbttagcompound, new String[] { "get" }, new Class[] { String.class });
nbttagbyte_val = getPrivateField(nbttagbyte, new String[] { "data" }, byte.class);
nbttagshort_val = getPrivateField(nbttagshort, new String[] { "data" }, short.class);
nbttagint_val = getPrivateField(nbttagint, new String[] { "data" }, int.class);
nbttaglong_val = getPrivateField(nbttaglong, new String[] { "data" }, long.class);
nbttagfloat_val = getPrivateField(nbttagfloat, new String[] { "data" }, float.class);
nbttagdouble_val = getPrivateField(nbttagdouble, new String[] { "data" }, double.class);
nbttagbytearray_val = getPrivateField(nbttagbytearray, new String[] { "data" }, byte[].class);
nbttagstring_val = getPrivateField(nbttagstring, new String[] { "data" }, String.class);
nbttagintarray_val = getPrivateField(nbttagintarray, new String[] { "data" }, int[].class);
/** Tile entity */
nms_tileentity = getNMSClass("net.minecraft.server.TileEntity");
nmst_readnbt = getMethod(nms_tileentity, new String[] { "b" }, new Class[] { nbttagcompound });
nmst_x = getField(nms_tileentity, new String[] { "x" }, int.class);
nmst_y = getField(nms_tileentity, new String[] { "y" }, int.class);
nmst_z = getField(nms_tileentity, new String[] { "z" }, int.class);
}
|
protected void loadNMS() {
// Get block fields
nmsblock = getNMSClass("net.minecraft.server.Block");
nmsblockarray = getNMSClass("[Lnet.minecraft.server.Block;");
nmsmaterial = getNMSClass("net.minecraft.server.Material");
blockbyid = getFieldNoFail(nmsblock, new String[] { "byId" }, nmsblockarray);
if (blockbyid == null) {
blockbyidfunc = getMethod(nmsblock, new String[] { "e" }, new Class[] { int.class });
}
blockname = getPrivateField(nmsblock, new String[] { "name", "b" }, String.class);
material = getPrivateField(nmsblock, new String[] { "material" }, nmsmaterial);
/* Set up biomebase fields */
biomebase = getNMSClass("net.minecraft.server.BiomeBase");
biomebasearray = getNMSClass("[Lnet.minecraft.server.BiomeBase;");
biomebaselist = getPrivateField(biomebase, new String[] { "biomes" }, biomebasearray);
biomebasetemp = getField(biomebase, new String[] { "temperature", "F" }, float.class);
biomebasehumi = getField(biomebase, new String[] { "humidity", "G" }, float.class);
biomebaseidstring = getField(biomebase, new String[] { "y", "af" }, String.class);
biomebaseid = getField(biomebase, new String[] { "id" }, int.class);
/* n.m.s.World */
nmsworld = getNMSClass("net.minecraft.server.WorldServer");
chunkprovserver = getNMSClass("net.minecraft.server.ChunkProviderServer");
nmsw_chunkproviderserver = getField(nmsworld, new String[] { "chunkProviderServer" }, chunkprovserver);
longhashset = getOBCClassNoFail("org.bukkit.craftbukkit.util.LongHashSet");
if(longhashset != null) {
lhs_containskey = getMethod(longhashset, new String[] { "contains" }, new Class[] { int.class, int.class });
}
else {
longhashset = getOBCClass("org.bukkit.craftbukkit.util.LongHashset");
lhs_containskey = getMethod(longhashset, new String[] { "containsKey" }, new Class[] { int.class, int.class });
}
cps_unloadqueue = getFieldNoFail(chunkprovserver, new String[] { "unloadQueue" }, longhashset);
if(cps_unloadqueue == null) {
Log.info("Unload queue not found - default to unload all chunks");
}
/** n.m.s.Chunk */
nmschunk = getNMSClass("net.minecraft.server.Chunk");
nmsc_removeentities = getMethod(nmschunk, new String[] { "removeEntities" }, new Class[0]);
nmsc_tileentities = getField(nmschunk, new String[] { "tileEntities" }, Map.class);
nmsc_inhabitedticks = getFieldNoFail(nmschunk, new String[] { "s", "q" }, long.class);
if (nmsc_inhabitedticks == null) {
Log.info("inhabitedTicks field not found - inhabited shader not functional");
}
/** nbt classes */
nbttagcompound = getNMSClass("net.minecraft.server.NBTTagCompound");
nbttagbyte = getNMSClass("net.minecraft.server.NBTTagByte");
nbttagshort = getNMSClass("net.minecraft.server.NBTTagShort");
nbttagint = getNMSClass("net.minecraft.server.NBTTagInt");
nbttaglong = getNMSClass("net.minecraft.server.NBTTagLong");
nbttagfloat = getNMSClass("net.minecraft.server.NBTTagFloat");
nbttagdouble = getNMSClass("net.minecraft.server.NBTTagDouble");
nbttagbytearray = getNMSClass("net.minecraft.server.NBTTagByteArray");
nbttagstring = getNMSClass("net.minecraft.server.NBTTagString");
nbttagintarray = getNMSClass("net.minecraft.server.NBTTagIntArray");
compound_get = getMethod(nbttagcompound, new String[] { "get" }, new Class[] { String.class });
nbttagbyte_val = getPrivateField(nbttagbyte, new String[] { "data" }, byte.class);
nbttagshort_val = getPrivateField(nbttagshort, new String[] { "data" }, short.class);
nbttagint_val = getPrivateField(nbttagint, new String[] { "data" }, int.class);
nbttaglong_val = getPrivateField(nbttaglong, new String[] { "data" }, long.class);
nbttagfloat_val = getPrivateField(nbttagfloat, new String[] { "data" }, float.class);
nbttagdouble_val = getPrivateField(nbttagdouble, new String[] { "data" }, double.class);
nbttagbytearray_val = getPrivateField(nbttagbytearray, new String[] { "data" }, byte[].class);
nbttagstring_val = getPrivateField(nbttagstring, new String[] { "data" }, String.class);
nbttagintarray_val = getPrivateField(nbttagintarray, new String[] { "data" }, int[].class);
/** Tile entity */
nms_tileentity = getNMSClass("net.minecraft.server.TileEntity");
nmst_readnbt = getMethod(nms_tileentity, new String[] { "b" }, new Class[] { nbttagcompound });
nmst_x = getField(nms_tileentity, new String[] { "x" }, int.class);
nmst_y = getField(nms_tileentity, new String[] { "y" }, int.class);
nmst_z = getField(nms_tileentity, new String[] { "z" }, int.class);
}
|
diff --git a/src/main/java/org/apache/commons/exec/environment/DefaultProcessingEnvironment.java b/src/main/java/org/apache/commons/exec/environment/DefaultProcessingEnvironment.java
index b1e097d..f118a72 100644
--- a/src/main/java/org/apache/commons/exec/environment/DefaultProcessingEnvironment.java
+++ b/src/main/java/org/apache/commons/exec/environment/DefaultProcessingEnvironment.java
@@ -1,218 +1,218 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.exec.environment;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.OS;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.exec.util.MapUtils;
/**
* Helper class to determine the environment variable
* for the OS. Depending on the JDK the environment
* variables can be either retrieved directly from the
* JVM or requires starting a process to get them running
* an OS command line.
*/
public class DefaultProcessingEnvironment {
/** the line seperator of the system */
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
/** the environment variables of the process */
protected Map procEnvironment;
/**
* Find the list of environment variables for this process.
*
* @return a map containing the environment variables
* @throws IOException obtaining the environment variables failed
*/
public synchronized Map getProcEnvironment() throws IOException {
if(procEnvironment == null) {
procEnvironment = this.createProcEnvironment();
}
// create a copy of the map just in case that
// anyone is going to modifiy it, e.g. removing
// or setting an evironment variable
return MapUtils.copy(procEnvironment);
}
/**
* Find the list of environment variables for this process.
*
* @return a amp containing the environment variables
* @throws IOException the operation failed
*/
protected Map createProcEnvironment() throws IOException {
if (procEnvironment == null) {
try {
- Method getenvs = System.class.getMethod( "getenv", null );
- Map env = (Map) getenvs.invoke( null, null );
+ Method getenvs = System.class.getMethod( "getenv", (java.lang.Class[]) null );
+ Map env = (Map) getenvs.invoke( null, (java.lang.Object[]) null );
procEnvironment = new HashMap( env );
} catch ( NoSuchMethodException e ) {
// ok, just not on JDK 1.5
} catch ( IllegalAccessException e ) {
// Unexpected error obtaining environment - using JDK 1.4 method
} catch ( InvocationTargetException e ) {
// Unexpected error obtaining environment - using JDK 1.4 method
}
}
if(procEnvironment == null) {
procEnvironment = new HashMap();
BufferedReader in = runProcEnvCommand();
String var = null;
String line;
while ((line = in.readLine()) != null) {
if (line.indexOf('=') == -1) {
// Chunk part of previous env var (UNIX env vars can
// contain embedded new lines).
if (var == null) {
var = LINE_SEPARATOR + line;
} else {
var += LINE_SEPARATOR + line;
}
} else {
// New env var...append the previous one if we have it.
if (var != null) {
EnvironmentUtil.addVariableToEnvironment(procEnvironment, var);
}
var = line;
}
}
// Since we "look ahead" before adding, there's one last env var.
if (var != null) {
EnvironmentUtil.addVariableToEnvironment(procEnvironment, var);
}
}
return procEnvironment;
}
/**
* Start a process to list the environment variables.
*
* @return a reader containing the output of the process
* @throws IOException starting the process failed
*/
protected BufferedReader runProcEnvCommand() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Executor exe = new DefaultExecutor();
exe.setStreamHandler(new PumpStreamHandler(out));
int retval = exe.execute(getProcEnvCommand(), new HashMap());
if (retval != 0) {
// Just try to use what we got
}
return new BufferedReader(new StringReader(toString(out)));
}
/**
* Determine the OS specific command line to get a list of environment
* variables.
*
* @return the command line
*/
protected CommandLine getProcEnvCommand() {
String executable;
String[] arguments = null;
if (OS.isFamilyOS2()) {
// OS/2 - use same mechanism as Windows 2000
executable = "cmd";
arguments = new String[] {"/c", "set"};
} else if (OS.isFamilyWindows()) {
// Determine if we're running under XP/2000/NT or 98/95
if (OS.isFamilyWin9x()) {
executable = "command.com";
// Windows 98/95
} else {
executable = "cmd";
// Windows XP/2000/NT/2003
}
arguments = new String[] {"/c", "set"};
} else if (OS.isFamilyZOS() || OS.isFamilyUnix()) {
// On most systems one could use: /bin/sh -c env
// Some systems have /bin/env, others /usr/bin/env, just try
if (new File("/bin/env").canRead()) {
executable = "/bin/env";
} else if (new File("/usr/bin/env").canRead()) {
executable = "/usr/bin/env";
} else {
// rely on PATH
executable = "env";
}
} else if (OS.isFamilyNetware() || OS.isFamilyOS400()) {
// rely on PATH
executable = "env";
} else {
// MAC OS 9 and previous
// TODO: I have no idea how to get it, someone must fix it
executable = null;
}
CommandLine commandLine = null;
if(executable != null) {
commandLine = new CommandLine(executable);
commandLine.addArguments(arguments);
}
return commandLine;
}
/**
* ByteArrayOutputStream#toString doesn't seem to work reliably on OS/390,
* at least not the way we use it in the execution context.
*
* @param bos
* the output stream that one wants to read
* @return the output stream as a string, read with special encodings in the
* case of z/os and os/400
*/
private String toString(final ByteArrayOutputStream bos) {
if (OS.isFamilyZOS()) {
try {
return bos.toString("Cp1047");
} catch (java.io.UnsupportedEncodingException e) {
// noop default encoding used
}
} else if (OS.isFamilyOS400()) {
try {
return bos.toString("Cp500");
} catch (java.io.UnsupportedEncodingException e) {
// noop default encoding used
}
}
return bos.toString();
}
}
| true | true |
protected Map createProcEnvironment() throws IOException {
if (procEnvironment == null) {
try {
Method getenvs = System.class.getMethod( "getenv", null );
Map env = (Map) getenvs.invoke( null, null );
procEnvironment = new HashMap( env );
} catch ( NoSuchMethodException e ) {
// ok, just not on JDK 1.5
} catch ( IllegalAccessException e ) {
// Unexpected error obtaining environment - using JDK 1.4 method
} catch ( InvocationTargetException e ) {
// Unexpected error obtaining environment - using JDK 1.4 method
}
}
if(procEnvironment == null) {
procEnvironment = new HashMap();
BufferedReader in = runProcEnvCommand();
String var = null;
String line;
while ((line = in.readLine()) != null) {
if (line.indexOf('=') == -1) {
// Chunk part of previous env var (UNIX env vars can
// contain embedded new lines).
if (var == null) {
var = LINE_SEPARATOR + line;
} else {
var += LINE_SEPARATOR + line;
}
} else {
// New env var...append the previous one if we have it.
if (var != null) {
EnvironmentUtil.addVariableToEnvironment(procEnvironment, var);
}
var = line;
}
}
// Since we "look ahead" before adding, there's one last env var.
if (var != null) {
EnvironmentUtil.addVariableToEnvironment(procEnvironment, var);
}
}
return procEnvironment;
}
|
protected Map createProcEnvironment() throws IOException {
if (procEnvironment == null) {
try {
Method getenvs = System.class.getMethod( "getenv", (java.lang.Class[]) null );
Map env = (Map) getenvs.invoke( null, (java.lang.Object[]) null );
procEnvironment = new HashMap( env );
} catch ( NoSuchMethodException e ) {
// ok, just not on JDK 1.5
} catch ( IllegalAccessException e ) {
// Unexpected error obtaining environment - using JDK 1.4 method
} catch ( InvocationTargetException e ) {
// Unexpected error obtaining environment - using JDK 1.4 method
}
}
if(procEnvironment == null) {
procEnvironment = new HashMap();
BufferedReader in = runProcEnvCommand();
String var = null;
String line;
while ((line = in.readLine()) != null) {
if (line.indexOf('=') == -1) {
// Chunk part of previous env var (UNIX env vars can
// contain embedded new lines).
if (var == null) {
var = LINE_SEPARATOR + line;
} else {
var += LINE_SEPARATOR + line;
}
} else {
// New env var...append the previous one if we have it.
if (var != null) {
EnvironmentUtil.addVariableToEnvironment(procEnvironment, var);
}
var = line;
}
}
// Since we "look ahead" before adding, there's one last env var.
if (var != null) {
EnvironmentUtil.addVariableToEnvironment(procEnvironment, var);
}
}
return procEnvironment;
}
|
diff --git a/FinancialRecorderServer/src/main/java/com/financial/tools/recorderserver/util/CustomJsonDateDeserializer.java b/FinancialRecorderServer/src/main/java/com/financial/tools/recorderserver/util/CustomJsonDateDeserializer.java
index 7de126a..6f5d8bd 100644
--- a/FinancialRecorderServer/src/main/java/com/financial/tools/recorderserver/util/CustomJsonDateDeserializer.java
+++ b/FinancialRecorderServer/src/main/java/com/financial/tools/recorderserver/util/CustomJsonDateDeserializer.java
@@ -1,32 +1,32 @@
package com.financial.tools.recorderserver.util;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
public class CustomJsonDateDeserializer extends JsonDeserializer<Date> {
private static Logger logger = LoggerFactory.getLogger(CustomJsonDateDeserializer.class);
@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
- SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
+ SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
String date = jp.getText();
try {
return format.parse(date);
} catch (ParseException e) {
- logger.error("Failed to parse date json string value with format: dd/MM/yyyy.");
+ logger.error("Failed to parse date json string value with format: MM/dd/yyyy.");
throw new RuntimeException(e);
}
}
}
| false | true |
public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
String date = jp.getText();
try {
return format.parse(date);
} catch (ParseException e) {
logger.error("Failed to parse date json string value with format: dd/MM/yyyy.");
throw new RuntimeException(e);
}
}
|
public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
String date = jp.getText();
try {
return format.parse(date);
} catch (ParseException e) {
logger.error("Failed to parse date json string value with format: MM/dd/yyyy.");
throw new RuntimeException(e);
}
}
|
diff --git a/src/org/sqlite/NestedDB.java b/src/org/sqlite/NestedDB.java
index b630239..35a38f3 100644
--- a/src/org/sqlite/NestedDB.java
+++ b/src/org/sqlite/NestedDB.java
@@ -1,411 +1,411 @@
/* Copyright 2006 David Crawshaw, see LICENSE file for licensing [BSD]. */
package org.sqlite;
import org.ibex.nestedvm.Runtime;
import java.io.File;
import java.io.PrintWriter;
import java.sql.*;
// FEATURE: strdup is wasteful, SQLite interface will take unterminated char*
/** Communicates with the Java version of SQLite provided by NestedVM. */
final class NestedDB extends DB
{
/** database pointer */
int handle = 0;
/** sqlite binary embedded in nestedvm */
private Runtime rt = null;
/** user defined functions referenced by position (stored in used data) */
private Function[] functions = null;
private String[] funcNames = null;
// WRAPPER FUNCTIONS ////////////////////////////////////////////
synchronized void open(String filename) throws SQLException {
if (handle != 0) throw new SQLException("DB already open");
if (rt != null) throw new SQLException("DB closed but runtime exists");
// start the nestedvm runtime
try {
rt = (Runtime)Class.forName("org.sqlite.SQLite").newInstance();
rt.start();
} catch (Exception e) {
throw new CausedSQLException(e);
}
// callback for user defined functions
rt.setCallJavaCB(new Runtime.CallJavaCB() {
public int call(int xType, int context, int args, int value) {
xUDF(xType, context, args, value);
return 0;
}
});
// open the db and retrieve sqlite3_db* pointer
int passback = rt.xmalloc(4);
int str = rt.strdup(filename);
if (call("sqlite3_open", str, passback) != SQLITE_OK)
throwex();
handle = deref(passback);
rt.free(str);
rt.free(passback);
}
synchronized void close() throws SQLException {
if (handle == 0) return;
int rc = call("sqlite3_close", handle);
handle = 0;
rt.stop();
rt = null;
if (rc != SQLITE_OK) throwex();
}
synchronized void interrupt() throws SQLException {
call("sqlite3_interrupt", handle);
}
synchronized void busy_timeout(int ms) throws SQLException {
call("sqlite3_busy_timeout", handle, ms);
}
synchronized void exec(String sql) throws SQLException {
int pointer = (int)prepare(sql);
try { execute(pointer, null); } finally { finalize(pointer); }
}
// TODO: store sqlite3_stmt against PhantomReference for org.sqlite.RS
synchronized long prepare(String sql) throws SQLException {
int passback = rt.xmalloc(4);
int str = rt.strdup(sql);
int ret = call("sqlite3_prepare", handle, str, -1, passback, 0);
rt.free(str);
if (ret != SQLITE_OK) {
rt.free(passback);
throwex();
}
int pointer = deref(passback);
rt.free(passback);
return pointer;
}
synchronized String errmsg() throws SQLException {
return cstring(call("sqlite3_errmsg", handle)); }
synchronized String libversion() throws SQLException {
return cstring(call("sqlite3_libversion", handle)); }
synchronized int changes() throws SQLException {
return call("sqlite3_changes", handle); }
// TODO: clear sqlite3_stmt from PhantomReference
synchronized int finalize(long stmt) throws SQLException {
return call("sqlite3_finalize", (int)stmt); }
synchronized int step(long stmt) throws SQLException {
int rc = call("sqlite3_step", (int)stmt);
if (rc == SQLITE_ERROR)
rc = reset(stmt);
return rc;
}
synchronized int reset(long stmt) throws SQLException {
return call("sqlite3_reset", (int)stmt); }
synchronized int clear_bindings(long stmt) throws SQLException {
return call("sqlite3_clear_bindings", (int)stmt); }
synchronized int bind_parameter_count(long stmt) throws SQLException {
return call("sqlite3_bind_parameter_count", (int)stmt); }
synchronized int column_count(long stmt) throws SQLException {
return call("sqlite3_column_count", (int)stmt); }
synchronized int column_type(long stmt, int col) throws SQLException {
return call("sqlite3_column_type", (int)stmt, col); }
synchronized String column_name(long stmt, int col) throws SQLException {
return utfstring(call("sqlite3_column_name", (int)stmt, col)); }
synchronized String column_text(long stmt, int col) throws SQLException {
return utfstring(call("sqlite3_column_text", (int)stmt, col)); }
synchronized byte[] column_blob(long stmt, int col) throws SQLException {
byte[] blob = new byte[call("sqlite3_column_bytes", (int)stmt, col)];
int addr = call("sqlite3_column_blob", (int)stmt, col);
copyin(addr, blob, blob.length);
return blob;
}
synchronized double column_double(long stmt, int col) throws SQLException {
try { return Double.parseDouble(column_text(stmt, col)); }
catch (NumberFormatException e) { return Double.NaN; } // TODO
}
synchronized long column_long(long stmt, int col) throws SQLException {
try { return Long.parseLong(column_text(stmt, col)); }
catch (NumberFormatException e) { return 0; } // TODO
}
synchronized int column_int(long stmt, int col) throws SQLException {
return call("sqlite3_column_int", (int)stmt, col); }
synchronized String column_decltype(long stmt, int col)
throws SQLException {
return utfstring(call("sqlite3_column_decltype", (int)stmt, col)); }
synchronized String column_table_name(long stmt, int col)
throws SQLException {
return utfstring(call("sqlite3_column_table_name", (int)stmt, col));
}
synchronized int bind_null(long stmt, int pos) throws SQLException {
return call("sqlite3_bind_null", (int)stmt, pos);
}
synchronized int bind_int(long stmt, int pos, int v) throws SQLException {
return call("sqlite3_bind_int", (int)stmt, pos, v);
}
synchronized int bind_long(long stmt, int pos, long v) throws SQLException {
return bind_text(stmt, pos, Long.toString(v)); // TODO
}
synchronized int bind_double(long stmt, int pos, double v)
throws SQLException {
return bind_text(stmt, pos, Double.toString(v)); // TODO
}
synchronized int bind_text(long stmt, int pos, String v)
throws SQLException {
if (v == null) return bind_null(stmt, pos);
return call("sqlite3_bind_text", (int)stmt, pos, rt.strdup(v),
-1, rt.lookupSymbol("free"));
}
synchronized int bind_blob(long stmt, int pos, byte[] buf)
throws SQLException {
if (buf == null || buf.length < 1) return bind_null(stmt, pos);
int len = buf.length;
int blob = rt.xmalloc(len); // free()ed by sqlite3_bind_blob
copyout(buf, blob, len);
return call("sqlite3_bind_blob", (int)stmt, pos, blob, len,
rt.lookupSymbol("free"));
}
synchronized void result_null (long cxt) throws SQLException {
call("sqlite3_result_null", (int)cxt); }
synchronized void result_text (long cxt, String val) throws SQLException {
call("sqlite3_result_text", (int)cxt, rt.strdup(val), -1,
rt.lookupSymbol("free"));
}
synchronized void result_blob (long cxt, byte[] val) throws SQLException {
if (val == null || val.length == 0) { result_null(cxt); return; }
int blob = rt.xmalloc(val.length);
copyout(val, blob, val.length);
call("sqlite3_result_blob", (int)cxt, blob,
val.length, rt.lookupSymbol("free"));
}
synchronized void result_double(long cxt, double val) throws SQLException {
result_text(cxt, Double.toString(val)); } // TODO
synchronized void result_long(long cxt, long val) throws SQLException {
result_text(cxt, Long.toString(val)); } // TODO
synchronized void result_int(long cxt, int val) throws SQLException {
call("sqlite3_result_int", (int)cxt, val); }
synchronized void result_error(long cxt, String err) throws SQLException {
int str = rt.strdup(err);
call("sqlite3_result_error", (int)cxt, str, -1);
rt.free(str);
}
synchronized int value_bytes(Function f, int arg) throws SQLException {
return call("sqlite3_value_bytes", value(f, arg));
}
synchronized String value_text(Function f, int arg) throws SQLException {
return utfstring(call("sqlite3_value_text", value(f, arg)));
}
synchronized byte[] value_blob(Function f, int arg) throws SQLException {
byte[] blob = new byte[value_bytes(f, arg)];
int addr = call("sqlite3_value_blob", value(f, arg));
copyin(addr, blob, blob.length);
return blob;
}
synchronized double value_double(Function f, int arg) throws SQLException {
return Double.parseDouble(value_text(f, arg)); // TODO
}
synchronized long value_long(Function f, int arg) throws SQLException {
return Long.parseLong(value_text(f, arg)); // TODO
}
synchronized int value_int(Function f, int arg) throws SQLException {
return call("sqlite3_value_int", value(f, arg));
}
synchronized int value_type(Function f, int arg) throws SQLException {
return call("sqlite3_value_type", value(f, arg));
}
private int value(Function f, int arg) throws SQLException {
return deref((int)f.value + (arg*4));
}
synchronized int create_function(String name, Function func)
throws SQLException {
if (functions == null) {
functions = new Function[10];
funcNames = new String[10];
}
// find a position
int pos;
for (pos=0; pos < functions.length; pos++)
if (functions[pos] == null) break;
if (pos == functions.length) { // expand function arrays
Function[] fnew = new Function[functions.length * 2];
String[] nnew = new String[funcNames.length * 2];
System.arraycopy(functions, 0, fnew, 0, functions.length);
System.arraycopy(funcNames, 0, nnew, 0, funcNames.length);
functions = fnew;
funcNames = nnew;
}
// register function
functions[pos] = func;
funcNames[pos] = name;
int str = rt.strdup(name);
int rc = call("create_function_helper", handle, str, pos,
func instanceof Function.Aggregate ? 1 : 0);
rt.free(str);
return rc;
}
synchronized int destroy_function(String name) throws SQLException {
if (name == null) return 0;
// find function position number
int pos;
for (pos = 0; pos < funcNames.length; pos++)
if (name.equals(funcNames[pos])) break;
if (pos == funcNames.length) return 0;
functions[pos] = null;
funcNames[pos] = null;
// deregister function
int str = rt.strdup(name);
int rc = call("create_function_helper", handle, str, -1, 0);
rt.free(str);
return rc;
}
/* unused as we use the user_data pointer to store a single word */
synchronized void free_functions() {}
/** Callback used by xFunc (1), xStep (2) and xFinal (3). */
synchronized void xUDF(int xType, int context, int args, int value) {
Function func = null;
try {
int pos = call("sqlite3_user_data", context);
func = functions[pos];
if (func == null)
throw new SQLException("function state inconsistent");
func.context = context;
func.value = value;
func.args = args;
switch (xType) {
case 1: func.xFunc(); break;
case 2: ((Function.Aggregate)func).xStep(); break;
case 3: ((Function.Aggregate)func).xFinal(); break;
}
} catch (SQLException e) {
try {
String err = e.toString();
if (err == null) err = "unknown error";
- int str = rt.strdup(e.toString());
- call("sqlite3_result_error", str, -1);
+ int str = rt.strdup(err);
+ call("sqlite3_result_error", context, str, -1);
rt.free(str);
} catch (SQLException exp) {
exp.printStackTrace();//TODO
}
} finally {
if (func != null) {
func.context = 0;
func.value = 0;
func.args = 0;
}
}
}
/** Calls support function found in upstream/sqlite-metadata.patch */
synchronized boolean[][] column_metadata(long stmt) throws SQLException {
int colCount = call("sqlite3_column_count", (int)stmt);
boolean[][] meta = new boolean[colCount][3];
int pass = rt.xmalloc(12); // struct metadata
for (int i=0; i < colCount; i++) {
call("column_metadata_helper", handle, (int)stmt, i, pass);
meta[i][0] = deref(pass) == 1;
meta[i][1] = deref(pass + 4) == 1;
meta[i][2] = deref(pass + 8) == 1;
}
rt.free(pass);
return meta;
}
// HELPER FUNCTIONS /////////////////////////////////////////////
/** safe to reuse parameter arrays as all functions are syncrhonized */
private final int[]
p0 = new int[] {},
p1 = new int[] { 0 },
p2 = new int[] { 0, 0 },
p3 = new int[] { 0, 0, 0 },
p4 = new int[] { 0, 0, 0, 0 },
p5 = new int[] { 0, 0, 0, 0, 0 };
private int call(String addr, int a0) throws SQLException {
p1[0] = a0; return call(addr, p1); }
private int call(String addr, int a0, int a1) throws SQLException {
p2[0] = a0; p2[1] = a1; return call(addr, p2); }
private int call(String addr, int a0, int a1, int a2) throws SQLException {
p3[0] = a0; p3[1] = a1; p3[2] = a2; return call(addr, p3); }
private int call(String addr, int a0, int a1, int a2, int a3)
throws SQLException {
p4[0] = a0; p4[1] = a1; p4[2] = a2; p4[3] = a3;
return call(addr, p4);
}
private int call(String addr, int a0, int a1, int a2, int a3, int a4)
throws SQLException {
p5[0] = a0; p5[1] = a1; p5[2] = a2; p5[3] = a3; p5[4] = a4;
return call(addr, p5);
}
private int call(String func, int[] args) throws SQLException {
try {
return rt.call(func, args);
} catch (Runtime.CallException e) { throw new CausedSQLException(e); }
}
/** Dereferences a pointer, returning the word it points to. */
private int deref(int pointer) throws SQLException {
try { return rt.memRead(pointer); }
catch (Runtime.ReadFaultException e) { throw new CausedSQLException(e);}
}
private String utfstring(int str) throws SQLException {
try { return rt.utfstring(str); }
catch (Runtime.ReadFaultException e) { throw new CausedSQLException(e);}
}
private String cstring(int str) throws SQLException {
try { return rt.cstring(str); }
catch (Runtime.ReadFaultException e) { throw new CausedSQLException(e);}
}
private void copyin(int addr, byte[] buf, int count) throws SQLException {
try { rt.copyin(addr, buf, count); }
catch (Runtime.ReadFaultException e) { throw new CausedSQLException(e);}
}
private void copyout(byte[] buf, int addr, int count) throws SQLException {
try { rt.copyout(buf, addr, count); }
catch (Runtime.FaultException e) { throw new CausedSQLException(e);}
}
/** Maps any exception onto an SQLException. */
private static final class CausedSQLException extends SQLException {
private final Exception cause;
CausedSQLException(Exception e) {
if (e == null) throw new RuntimeException("null exception cause");
cause = e;
}
public Throwable getCause() { return cause; }
public void printStackTrace() { cause.printStackTrace(); }
public void printStackTrace(PrintWriter s) { cause.printStackTrace(s); }
public Throwable fillInStackTrace() { return cause.fillInStackTrace(); }
public StackTraceElement[] getStackTrace() {
return cause.getStackTrace(); }
public String getMessage() { return cause.getMessage(); }
}
}
| true | true |
synchronized void xUDF(int xType, int context, int args, int value) {
Function func = null;
try {
int pos = call("sqlite3_user_data", context);
func = functions[pos];
if (func == null)
throw new SQLException("function state inconsistent");
func.context = context;
func.value = value;
func.args = args;
switch (xType) {
case 1: func.xFunc(); break;
case 2: ((Function.Aggregate)func).xStep(); break;
case 3: ((Function.Aggregate)func).xFinal(); break;
}
} catch (SQLException e) {
try {
String err = e.toString();
if (err == null) err = "unknown error";
int str = rt.strdup(e.toString());
call("sqlite3_result_error", str, -1);
rt.free(str);
} catch (SQLException exp) {
exp.printStackTrace();//TODO
}
} finally {
if (func != null) {
func.context = 0;
func.value = 0;
func.args = 0;
}
}
}
|
synchronized void xUDF(int xType, int context, int args, int value) {
Function func = null;
try {
int pos = call("sqlite3_user_data", context);
func = functions[pos];
if (func == null)
throw new SQLException("function state inconsistent");
func.context = context;
func.value = value;
func.args = args;
switch (xType) {
case 1: func.xFunc(); break;
case 2: ((Function.Aggregate)func).xStep(); break;
case 3: ((Function.Aggregate)func).xFinal(); break;
}
} catch (SQLException e) {
try {
String err = e.toString();
if (err == null) err = "unknown error";
int str = rt.strdup(err);
call("sqlite3_result_error", context, str, -1);
rt.free(str);
} catch (SQLException exp) {
exp.printStackTrace();//TODO
}
} finally {
if (func != null) {
func.context = 0;
func.value = 0;
func.args = 0;
}
}
}
|
diff --git a/src/com/android/settings/MultiSimSettings.java b/src/com/android/settings/MultiSimSettings.java
index aa2e0898..f99935d7 100644
--- a/src/com/android/settings/MultiSimSettings.java
+++ b/src/com/android/settings/MultiSimSettings.java
@@ -1,310 +1,310 @@
/*
* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.Log;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Message;
import android.os.Handler;
import android.os.AsyncResult;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.preference.PreferenceScreen;
import com.android.internal.telephony.SubscriptionManager;
import com.android.internal.telephony.MSimPhoneFactory;
import com.android.settings.R;
public class MultiSimSettings extends PreferenceActivity implements DialogInterface.OnDismissListener,
DialogInterface.OnClickListener, Preference.OnPreferenceChangeListener {
private static final String TAG = "MultiSimSettings";
private static final String KEY_VOICE = "voice";
private static final String KEY_DATA = "data";
private static final String KEY_SMS = "sms";
private static final String KEY_CONFIG_SUB = "config_sub";
private static final String CONFIG_SUB = "CONFIG_SUB";
private static final int DIALOG_SET_DATA_SUBSCRIPTION_IN_PROGRESS = 100;
static final int EVENT_SET_DATA_SUBSCRIPTION_DONE = 1;
protected boolean mIsForeground = false;
static final int SUBSCRIPTION_ID_0 = 0;
static final int SUBSCRIPTION_ID_1 = 1;
static final int SUBSCRIPTION_ID_INVALID = -1;
static final int PROMPT_OPTION = 2;
private ListPreference mVoice;
private ListPreference mData;
private ListPreference mSms;
private PreferenceScreen mConfigSub;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.multi_sim_settings);
mVoice = (ListPreference) findPreference(KEY_VOICE);
mVoice.setOnPreferenceChangeListener(this);
mData = (ListPreference) findPreference(KEY_DATA);
mData.setOnPreferenceChangeListener(this);
mSms = (ListPreference) findPreference(KEY_SMS);
mSms.setOnPreferenceChangeListener(this);
mConfigSub = (PreferenceScreen) findPreference(KEY_CONFIG_SUB);
mConfigSub.getIntent().putExtra(CONFIG_SUB, true);
if (isAirplaneModeOn()) {
Log.d(TAG, "Airplane mode is ON, grayout the config subscription menu!!!");
mConfigSub.setEnabled(false);
}
}
@Override
protected void onResume() {
super.onResume();
mIsForeground = true;
updateState();
}
@Override
protected void onPause() {
super.onPause();
mIsForeground = false;
}
private boolean isAirplaneModeOn() {
return Settings.System.getInt(getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
private void updateState() {
updateVoiceSummary();
updateDataSummary();
updateSmsSummary();
}
private void updateVoiceSummary() {
int voiceSub = SUBSCRIPTION_ID_INVALID;
CharSequence[] summaries = getResources().getTextArray(R.array.multi_sim_summaries_voice);
try {
voiceSub = Settings.System.getInt(getContentResolver(),Settings.System.MULTI_SIM_VOICE_CALL_SUBSCRIPTION);
} catch (SettingNotFoundException snfe) {
Log.e(TAG, "Settings Exception Reading Multi sim Voice Call Values", snfe);
}
boolean promptEnabled = MSimPhoneFactory.isPromptEnabled();
Log.d(TAG, "updateVoiceSummary: voiceSub = " + voiceSub + "promptEnabled = " + promptEnabled);
if (voiceSub == SUBSCRIPTION_ID_0 && (!promptEnabled)) {
mVoice.setValue("0");
mVoice.setSummary(summaries[0]);
} else if (voiceSub == SUBSCRIPTION_ID_1 && (!promptEnabled)) {
mVoice.setValue("1");
mVoice.setSummary(summaries[1]);
} else if (promptEnabled) {
Log.d(TAG, "prompt is enabled");
mVoice.setValue("2");
mVoice.setSummary(summaries[2]);
} else {
mVoice.setValue("0");
mVoice.setSummary(summaries[0]);
}
}
private void updateDataSummary() {
int Data_val = SUBSCRIPTION_ID_INVALID;
CharSequence[] summaries = getResources().getTextArray(R.array.multi_sim_summaries);
try {
Data_val = Settings.System.getInt(getContentResolver(),Settings.System.MULTI_SIM_DATA_CALL_SUBSCRIPTION);
} catch (SettingNotFoundException snfe) {
Log.e(TAG, "Settings Exception Reading Multi Sim Data Subscription Value.", snfe);
}
Log.d(TAG, "updateDataSummary: Data_val = " + Data_val);
if (Data_val == SUBSCRIPTION_ID_0) {
mData.setValue("0");
mData.setSummary(summaries[0]);
} else if (Data_val == SUBSCRIPTION_ID_1) {
mData.setValue("1");
mData.setSummary(summaries[1]);
} else {
mData.setValue("0");
mData.setSummary(summaries[0]);
}
}
private void updateSmsSummary() {
int Sms_val = SUBSCRIPTION_ID_INVALID;
CharSequence[] summaries = getResources().getTextArray(R.array.multi_sim_summaries);
try {
Sms_val = Settings.System.getInt(getContentResolver(),Settings.System.MULTI_SIM_SMS_SUBSCRIPTION);
} catch (SettingNotFoundException snfe) {
Log.e(TAG, "Settings Exception Reading Multi Sim SMS Call Values.", snfe);
}
Log.d(TAG, "updateSmsSummary: Sms_val = " + Sms_val);
if (Sms_val == SUBSCRIPTION_ID_0) {
mSms.setValue("0");
mSms.setSummary(summaries[0]);
} else if (Sms_val == SUBSCRIPTION_ID_1) {
mSms.setValue("1");
mSms.setSummary(summaries[1]);
} else {
mSms.setValue("0");
mSms.setSummary(summaries[0]);
}
}
public boolean onPreferenceChange(Preference preference, Object objValue) {
final String key = preference.getKey();
CharSequence[] summaries = getResources().getTextArray(R.array.multi_sim_summaries);
if (KEY_VOICE.equals(key)) {
summaries = getResources().getTextArray(R.array.multi_sim_summaries_voice);
int V_value = Integer.parseInt((String) objValue);
if (V_value == PROMPT_OPTION) {
MSimPhoneFactory.setPromptEnabled(true);
Log.d(TAG, "prompt is enabled " + V_value);
} else {
Log.d(TAG, "setVoiceSubscription " + V_value);
MSimPhoneFactory.setPromptEnabled(false);
MSimPhoneFactory.setVoiceSubscription(V_value);
}
mVoice.setSummary(summaries[V_value]);
}
if (KEY_DATA.equals(key)) {
int D_value = Integer.parseInt((String) objValue);
Log.d(TAG, "setDataSubscription " + D_value);
if (mIsForeground) {
showDialog(DIALOG_SET_DATA_SUBSCRIPTION_IN_PROGRESS);
}
SubscriptionManager mSubscriptionManager = SubscriptionManager.getInstance();
Message setDdsMsg = Message.obtain(mHandler, EVENT_SET_DATA_SUBSCRIPTION_DONE, null);
mSubscriptionManager.setDataSubscription(D_value, setDdsMsg);
}
if (KEY_SMS.equals(key)) {
int S_value = Integer.parseInt((String) objValue);
Log.d(TAG, "setSMSSubscription " + S_value);
MSimPhoneFactory.setSMSSubscription(S_value);
mSms.setSummary(summaries[S_value]);
}
return true;
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
AsyncResult ar;
switch(msg.what) {
case EVENT_SET_DATA_SUBSCRIPTION_DONE:
Log.d(TAG, "EVENT_SET_DATA_SUBSCRIPTION_DONE");
if (mIsForeground) {
dismissDialog(DIALOG_SET_DATA_SUBSCRIPTION_IN_PROGRESS);
}
getPreferenceScreen().setEnabled(true);
updateDataSummary();
ar = (AsyncResult) msg.obj;
String status;
if (ar.exception != null) {
- // This should never happens. But display an alert message in case.
- status = getResources().getString(R.string.set_dds_failed);
+ status = getResources().getString(R.string.set_dds_error)
+ + " " + ar.exception.getMessage();
displayAlertDialog(status);
break;
}
boolean result = (Boolean)ar.result;
Log.d(TAG, "SET_DATA_SUBSCRIPTION_DONE: result = " + result);
if (result == true) {
status = getResources().getString(R.string.set_dds_success);
Toast toast = Toast.makeText(getApplicationContext(), status, Toast.LENGTH_LONG);
toast.show();
} else {
status = getResources().getString(R.string.set_dds_failed);
displayAlertDialog(status);
}
break;
}
}
};
@Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_SET_DATA_SUBSCRIPTION_IN_PROGRESS) {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage(getResources().getString(R.string.set_data_subscription_progress));
dialog.setCancelable(false);
dialog.setIndeterminate(true);
return dialog;
}
return null;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
if (id == DIALOG_SET_DATA_SUBSCRIPTION_IN_PROGRESS) {
// when the dialogs come up, we'll need to indicate that
// we're in a busy state to disallow further input.
getPreferenceScreen().setEnabled(false);
}
}
// This is a method implemented for DialogInterface.OnDismissListener
public void onDismiss(DialogInterface dialog) {
Log.d(TAG, "onDismiss!");
}
// This is a method implemented for DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "onClick!");
}
void displayAlertDialog(String msg) {
Log.d(TAG, "displayErrorDialog!" + msg);
new AlertDialog.Builder(this).setMessage(msg)
.setTitle(android.R.string.dialog_alert_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, this)
.show()
.setOnDismissListener(this);
}
}
| true | true |
public void handleMessage(Message msg) {
AsyncResult ar;
switch(msg.what) {
case EVENT_SET_DATA_SUBSCRIPTION_DONE:
Log.d(TAG, "EVENT_SET_DATA_SUBSCRIPTION_DONE");
if (mIsForeground) {
dismissDialog(DIALOG_SET_DATA_SUBSCRIPTION_IN_PROGRESS);
}
getPreferenceScreen().setEnabled(true);
updateDataSummary();
ar = (AsyncResult) msg.obj;
String status;
if (ar.exception != null) {
// This should never happens. But display an alert message in case.
status = getResources().getString(R.string.set_dds_failed);
displayAlertDialog(status);
break;
}
boolean result = (Boolean)ar.result;
Log.d(TAG, "SET_DATA_SUBSCRIPTION_DONE: result = " + result);
if (result == true) {
status = getResources().getString(R.string.set_dds_success);
Toast toast = Toast.makeText(getApplicationContext(), status, Toast.LENGTH_LONG);
toast.show();
} else {
status = getResources().getString(R.string.set_dds_failed);
displayAlertDialog(status);
}
break;
}
}
|
public void handleMessage(Message msg) {
AsyncResult ar;
switch(msg.what) {
case EVENT_SET_DATA_SUBSCRIPTION_DONE:
Log.d(TAG, "EVENT_SET_DATA_SUBSCRIPTION_DONE");
if (mIsForeground) {
dismissDialog(DIALOG_SET_DATA_SUBSCRIPTION_IN_PROGRESS);
}
getPreferenceScreen().setEnabled(true);
updateDataSummary();
ar = (AsyncResult) msg.obj;
String status;
if (ar.exception != null) {
status = getResources().getString(R.string.set_dds_error)
+ " " + ar.exception.getMessage();
displayAlertDialog(status);
break;
}
boolean result = (Boolean)ar.result;
Log.d(TAG, "SET_DATA_SUBSCRIPTION_DONE: result = " + result);
if (result == true) {
status = getResources().getString(R.string.set_dds_success);
Toast toast = Toast.makeText(getApplicationContext(), status, Toast.LENGTH_LONG);
toast.show();
} else {
status = getResources().getString(R.string.set_dds_failed);
displayAlertDialog(status);
}
break;
}
}
|
diff --git a/src/ch/unibe/scg/cc/javaFrontend/JavaType1ReplacerFactory.java b/src/ch/unibe/scg/cc/javaFrontend/JavaType1ReplacerFactory.java
index f9ae9c6..518f430 100644
--- a/src/ch/unibe/scg/cc/javaFrontend/JavaType1ReplacerFactory.java
+++ b/src/ch/unibe/scg/cc/javaFrontend/JavaType1ReplacerFactory.java
@@ -1,102 +1,102 @@
package ch.unibe.scg.cc.javaFrontend;
import javax.inject.Singleton;
import jregex.Pattern;
import ch.unibe.scg.cc.ReplacerProvider;
import ch.unibe.scg.cc.regex.Replace;
import com.google.inject.Provider;
@Singleton
public class JavaType1ReplacerFactory extends ReplacerProvider implements Provider<Replace[]> {
/**
* Hides deep function definitions
*/
// Replace makeHideDeepDefinitions() {
// Pattern ifPattern = new
// Pattern("(\\t{2,}|\\ {8,})([a-zA-Z \\t<>,]*\\([a-zA-Z \\t<>,]*\\)[a-zA-Z \\t<>,]*\\{|(\\n|[^\n]*[^.])class)");
// return new Replace(ifPattern, "; $1");
// }
/**
* 0
*/
public Replace make00WhitespaceA() {
Pattern whiteSpace = new Pattern("\\s*\\n\\s*");
return new Replace(whiteSpace, "\n");
}
/**
* 1
*/
public Replace make01WhitespaceB() {
Pattern whiteSpace = new Pattern("[ \f\r\t]+");
return new Replace(whiteSpace, " ");
}
/**
* 2. removes package prefixes. <br>
* <code>example 1:<br>"import java.util.Math;" gets "import Math;"</code><br>
* <code>example 2:<br>
* "int a = java.util.Math.sqrt(1);" gets "int a = Math.sqrt(1);"</code>
*/
public Replace make02Rj1() {
- Pattern packagesGo = new Pattern("\\b[a-z]+\\.[a-z.]*([A-Z])");
- String replaceWith = "$1";
+ final Pattern packagesGo = new Pattern("\\b[a-z]+[a-z.]*\\.([A-Z])");
+ final String replaceWith = "$1";
return new Replace(packagesGo, replaceWith);
}
/**
* 3
*/
public Replace make03Rj3a() {
Pattern initializationList = new Pattern("=\\s?\\{.*?\\}");
return new Replace(initializationList, "= { }");
}
/**
* 4
*/
public Replace make04Rj3b() {
Pattern initializationList = new Pattern("\\]\\s?\\{.*?\\}");
return new Replace(initializationList, "] { }");
}
/**
* 5
*/
public Replace make05Rj5() {
Pattern visibility = new Pattern("(\\s)(?:private\\s|public\\s|protected\\s)");
return new Replace(visibility, "$1");
}
/**
* 6
*/
public Replace make06Rj6() {
Pattern ifPattern = new Pattern("\\sif\\s*\\((?:.*)\\)\\s*(\\n[^\\n\\{\\}]*)$");
return new Replace(ifPattern, " {\\n$1\\n}\\n");
}
/**
* 7. This is necessary for tokenization. while statements look a lot like
* function definitions.
*
* @return
*/
public Replace make07RenameWhile() {
Pattern ifPattern = new Pattern("while");
return new Replace(ifPattern, ";while");
}
/**
* 8. removes leading whitespace at the beginning of the string. example:
* " public void a() {" gets "public void a() {"
*/
public Replace make08RemoveLeadingWhitespace() {
Pattern leadingWhiteSpace = new Pattern("^[ \f\r\t]*");
return new Replace(leadingWhiteSpace, "");
}
}
| true | true |
public Replace make02Rj1() {
Pattern packagesGo = new Pattern("\\b[a-z]+\\.[a-z.]*([A-Z])");
String replaceWith = "$1";
return new Replace(packagesGo, replaceWith);
}
|
public Replace make02Rj1() {
final Pattern packagesGo = new Pattern("\\b[a-z]+[a-z.]*\\.([A-Z])");
final String replaceWith = "$1";
return new Replace(packagesGo, replaceWith);
}
|
diff --git a/src/main/java/com/topsy/jmxproxy/jmx/ConnectionManager.java b/src/main/java/com/topsy/jmxproxy/jmx/ConnectionManager.java
index 9c7984e..00392c8 100644
--- a/src/main/java/com/topsy/jmxproxy/jmx/ConnectionManager.java
+++ b/src/main/java/com/topsy/jmxproxy/jmx/ConnectionManager.java
@@ -1,76 +1,76 @@
package com.topsy.jmxproxy.jmx;
import com.topsy.jmxproxy.core.Host;
import com.yammer.dropwizard.lifecycle.Managed;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConnectionManager implements Managed {
private static final Logger LOG = LoggerFactory.getLogger(ConnectionManager.class);
private final JMXProxyServiceConfiguration config;
private Map<String, ConnectionWorker> hosts;
private ScheduledExecutorService purge;
private boolean started = false;
public ConnectionManager(JMXProxyServiceConfiguration config) {
this.config = config;
hosts = new HashMap<String, ConnectionWorker>();
purge = Executors.newSingleThreadScheduledExecutor();
}
public Host getHost(String host) throws Exception {
synchronized (hosts) {
if (!hosts.containsKey(host)) {
LOG.info("creating new worker for " + host);
hosts.put(host, new ConnectionWorker(host));
}
}
return hosts.get(host).getHost();
}
public boolean isStarted() {
return started;
}
public void start() {
LOG.info("starting jmx connection manager");
purge.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
LOG.debug("begin expiring stale hosts");
synchronized (hosts) {
for (Map.Entry<String, ConnectionWorker>hostEntry : hosts.entrySet()) {
if (hostEntry.getValue().isExpired()) {
LOG.debug("purging " + hostEntry.getKey());
hosts.remove(hostEntry.getKey());
}
}
}
LOG.debug("end expiring stale hosts");
}
- }, 1, 1, TimeUnit.MINUTES);
+ }, config.getCleanInterval(), config.getCleanInterval(), TimeUnit.MINUTES);
started = true;
}
public void stop() {
LOG.info("stopping jmx connection manager");
purge.shutdown();
hosts.clear();
started = false;
}
}
| true | true |
public void start() {
LOG.info("starting jmx connection manager");
purge.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
LOG.debug("begin expiring stale hosts");
synchronized (hosts) {
for (Map.Entry<String, ConnectionWorker>hostEntry : hosts.entrySet()) {
if (hostEntry.getValue().isExpired()) {
LOG.debug("purging " + hostEntry.getKey());
hosts.remove(hostEntry.getKey());
}
}
}
LOG.debug("end expiring stale hosts");
}
}, 1, 1, TimeUnit.MINUTES);
started = true;
}
|
public void start() {
LOG.info("starting jmx connection manager");
purge.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
LOG.debug("begin expiring stale hosts");
synchronized (hosts) {
for (Map.Entry<String, ConnectionWorker>hostEntry : hosts.entrySet()) {
if (hostEntry.getValue().isExpired()) {
LOG.debug("purging " + hostEntry.getKey());
hosts.remove(hostEntry.getKey());
}
}
}
LOG.debug("end expiring stale hosts");
}
}, config.getCleanInterval(), config.getCleanInterval(), TimeUnit.MINUTES);
started = true;
}
|
diff --git a/org.emftext.sdk.concretesyntax.resource.cs.post_processing/src/org/emftext/sdk/syntax_analysis/OperatorAnnotationsValidator.java b/org.emftext.sdk.concretesyntax.resource.cs.post_processing/src/org/emftext/sdk/syntax_analysis/OperatorAnnotationsValidator.java
index 3219575f3..db80c5e72 100644
--- a/org.emftext.sdk.concretesyntax.resource.cs.post_processing/src/org/emftext/sdk/syntax_analysis/OperatorAnnotationsValidator.java
+++ b/org.emftext.sdk.concretesyntax.resource.cs.post_processing/src/org/emftext/sdk/syntax_analysis/OperatorAnnotationsValidator.java
@@ -1,390 +1,395 @@
/*******************************************************************************
* Copyright (c) 2006-2010
* Software Technology Group, Dresden University of Technology
*
* 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:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.sdk.syntax_analysis;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.eclipse.emf.codegen.ecore.genmodel.GenClass;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.emftext.sdk.AbstractPostProcessor;
import org.emftext.sdk.concretesyntax.Annotation;
import org.emftext.sdk.concretesyntax.ConcreteSyntax;
import org.emftext.sdk.concretesyntax.ConcretesyntaxPackage;
import org.emftext.sdk.concretesyntax.Containment;
import org.emftext.sdk.concretesyntax.Definition;
import org.emftext.sdk.concretesyntax.EClassUtil;
import org.emftext.sdk.concretesyntax.OperatorAnnotationProperty;
import org.emftext.sdk.concretesyntax.OperatorAnnotationType;
import org.emftext.sdk.concretesyntax.Rule;
import org.emftext.sdk.concretesyntax.Sequence;
import org.emftext.sdk.concretesyntax.resource.cs.mopp.CsResource;
import org.emftext.sdk.concretesyntax.resource.cs.util.CsEObjectUtil;
import org.emftext.sdk.finders.GenClassFinder;
import org.emftext.sdk.util.ConcreteSyntaxUtil;
/**
* The OperatorAnnotationsValidator inspects all rules that are annotated with
* the 'operator' annotation. It checks whether the arguments of the annotation
* have the correct type and whether the right sides of the annotated rule match
* the annotation.
*/
public class OperatorAnnotationsValidator extends AbstractPostProcessor {
private static final String OPERATOR_CLASSES_CANNOT_BE_USED_DIRECTLY = "Operator classes cannot be used directly. Use the abstract expression superclass instead.";
private ConcreteSyntaxUtil csUtil = new ConcreteSyntaxUtil();
@Override
public void analyse(CsResource resource, ConcreteSyntax syntax) {
EList<Rule> operatorRules = syntax.getOperatorRules();
if (operatorRules != null && !operatorRules.isEmpty()) {
checkRulesWithOperatorAnnotation(resource, syntax);
checkOperatorTypes(resource, syntax);
Set<GenClass> operatorGenClasses = getOperatorClasses(syntax);
checkStartSymbols(resource, syntax, operatorGenClasses);
checkContainmentsInOperatorRules(resource, syntax, operatorGenClasses);
checkContainmentsInNormalRules(resource, syntax, operatorGenClasses);
}
}
/**
* Checks if all grammar rules with operator annotations are conform to the
* syntactic operator constraints.
*/
private void checkRulesWithOperatorAnnotation(CsResource resource,
ConcreteSyntax syntax) {
for (Rule operatorRule : syntax.getOperatorRules()) {
Annotation annotation = operatorRule.getOperatorAnnotation();
String weight = annotation.getValue(OperatorAnnotationProperty.WEIGHT.toString());
String identifier = annotation.getValue(OperatorAnnotationProperty.IDENTIFIER.toString());
String typeString = annotation.getValue(OperatorAnnotationProperty.TYPE.toString());
if (weight == null || identifier == null || typeString == null) {
resource
.addError(
"Operator annotations require values for weigth, type and identifier.",
annotation);
continue;
}
checkWeightParameter(resource, annotation, weight);
GenClass expressionMetaClass = mapIdentifierToGenClass(syntax, identifier);
if (expressionMetaClass==null ||
(!expressionMetaClass.isAbstract() && !expressionMetaClass.isInterface())){
resource.addError("Expression idenfitier must map to a common abstract metaclass or interface.",annotation);
}
else{
EClassUtil eUtil = syntax.getEClassUtil();
if(!eUtil.isSubClass(operatorRule.getMetaclass().getEcoreClass(), expressionMetaClass.getEcoreClass())){
resource.addError("Operator rule must be associated with a subclass of "+identifier,operatorRule);
}
}
OperatorAnnotationType type = csUtil.getOperatorAnnotationType(annotation);
if(type==null){
- // TODO skarol: improve error message by giving the valid types
- resource.addError("Could not determine operator type.",annotation);
+ String possibleValues = "Should be one of: ";
+ OperatorAnnotationType[] values = OperatorAnnotationType.values();
+ for (OperatorAnnotationType operatorAnnotationType : values) {
+ possibleValues += operatorAnnotationType.getLiteral() + ", " ;
+ }
+ possibleValues = possibleValues.substring(0, possibleValues.length()-2);
+ resource.addError("Invalid operator type. " + possibleValues, annotation);
continue;
}
if (type != OperatorAnnotationType.PRIMITIVE) {
List<Sequence> options = operatorRule.getDefinition()
.getOptions();
if (options.size() == 1) {
List<Definition> definitions = options.get(0).getParts();
if (type == OperatorAnnotationType.BINARY_LEFT_ASSOCIATIVE ||
type == OperatorAnnotationType.BINARY_RIGHT_ASSOCIATIVE) {
checkBinaryOperatorRule(resource, syntax, annotation,
definitions,expressionMetaClass);
} else {
checkUnaryOperatorRule(resource, syntax, annotation,
definitions,expressionMetaClass);
}
} else {
resource
.addError(
"Non primitive operator annotations require exactly one Choice in rule.",
operatorRule);
}
}
}
}
/**
* Checks whether all operator rules with the same weight do have the same
* type.
*
* @param resource
* @param syntax
*/
private void checkOperatorTypes(CsResource resource, ConcreteSyntax syntax) {
for (String subsetIdent : syntax.getOperatorRuleSubsets()) {
List<Rule> subset = syntax.getOperatorRuleSubset(subsetIdent);
for (int i = 0; i < subset.size(); i++) {
Rule firstRule = subset.get(i);
Annotation firstAnnotation = firstRule.getOperatorAnnotation();
String firstWeight = firstAnnotation
.getValue(OperatorAnnotationProperty.WEIGHT.toString());
firstWeight = firstWeight == null ? "" : firstWeight;
for (int j = i + 1; j < subset.size(); j++) {
Rule rule = subset.get(j);
Annotation annotation = rule.getOperatorAnnotation();
String weight = annotation
.getValue(OperatorAnnotationProperty.WEIGHT
.toString());
if (!firstWeight.equals(weight)) {
i = j - 1;
break;
} else if (firstAnnotation.getType() != annotation
.getType()) {
resource
.addError(
"All equal weight operators must be of the same operator type.",
annotation);
}
}
}
}
}
private void checkStartSymbols(CsResource resource, ConcreteSyntax syntax,
Set<GenClass> operatorGenClasses) {
for (GenClass startSymbol : syntax.getActiveStartSymbols()) {
if (operatorGenClasses.contains(startSymbol))
resource
.addError(
"Operator metaclasses cannot be used as startsymbol directly, use common expression metaclass instead.",
startSymbol);
}
}
private Set<GenClass> getOperatorClasses(ConcreteSyntax syntax) {
Set<GenClass> operatorClasses = new LinkedHashSet<GenClass>(syntax.getOperatorRules().size());
for (Rule operatorRule : syntax.getOperatorRules()) {
operatorClasses.add(operatorRule.getMetaclass());
}
return operatorClasses;
}
/**
* Checks that all containments do not have subclass restrictions.
*
* @param resource
* @param syntax
*/
private void checkContainmentsInOperatorRules(CsResource resource,
ConcreteSyntax syntax, Set<GenClass> operatorGenClasses) {
List<Rule> operatorRules = syntax.getOperatorRules();
for (Rule operatorRule : operatorRules) {
Collection<Containment> containments = CsEObjectUtil.getObjectsByType(operatorRule.eAllContents(), ConcretesyntaxPackage.eINSTANCE.getContainment());
for (Containment containment : containments) {
List<GenClass> allowedTypes = containment.getTypes();
if (allowedTypes.size() > 0) {
resource.addError("Subclass restrictions are not allowed in operator rules.", containment);
}
}
}
}
/**
* Checks that all containments do not to refer to operator classes directly.
* Only references to the common expression superclass (currently specified
* by the parameter 'identifier') are allowed.
*
* @param resource
* @param syntax
*/
private void checkContainmentsInNormalRules(CsResource resource,
ConcreteSyntax syntax, Set<GenClass> operatorGenClasses) {
Collection<Rule> nonOperatorRules = new LinkedList<Rule>(syntax
.getAllRules());
nonOperatorRules.removeAll(syntax.getOperatorRules());
for (Rule rule : nonOperatorRules) {
Iterator<EObject> it = rule.eAllContents();
while (it.hasNext()) {
EObject eo = it.next();
if (eo instanceof Containment) {
Containment containment = (Containment) eo;
if (containment.getTypes() != null
&& containment.getTypes().isEmpty()) {
// no explicit types given
GenClass genClass = containment.getFeature()
.getTypeGenClass();
if (genClass.isAbstract() || genClass.isInterface()) {
//check if genclass is common operator metaclass, if so skip since EMFText
//will generate an appropriate production (in the case ANTLR is used)
List<Rule> opSubset = syntax.getOperatorRuleSubset(genClass.getName());
if(opSubset!=null&&!opSubset.isEmpty())
continue;
// if abstract and no common operator metaclass, check subclasses with syntax for
// operator annotations
Collection<GenClass> subClasses = syntax
.getSubClassesWithSyntax(genClass, false);
for (GenClass subClass : subClasses) {
if (operatorGenClasses.contains(subClass)) {
resource
.addError(
"Implicit choice derived by EMFText refers to annotated operator rules. Please declare explicit allowed subclasses explicitly.",
containment);
}
}
} else if (operatorGenClasses.contains(genClass)) {
resource
.addError(
OPERATOR_CLASSES_CANNOT_BE_USED_DIRECTLY,
containment);
}
} else {
for (GenClass genClass : containment.getTypes()) {
if (operatorGenClasses.contains(genClass)) {
resource
.addError(
OPERATOR_CLASSES_CANNOT_BE_USED_DIRECTLY,
containment);
}
}
}
}
}
}
}
/**
* Checks whether the parameter 'weight' is an integer.
*
* @param resource
* @param annotation
* @param weight
*/
private void checkWeightParameter(CsResource resource,
Annotation annotation, String weight) {
try {
Integer.parseInt(weight);
} catch (NumberFormatException nfe) {
resource.addError("Weight parameter must be Integer.", annotation);
}
}
/**
* Looking up GenClass for identifier
*
* @param syntax
* @param identifier
*/
private GenClass mapIdentifierToGenClass(ConcreteSyntax syntax, String identifier) {
// TODO use MetaclassReferenceResolver here, look for other code
// that resolves meta class identifiers in operation rules and
// replace it with a call to this method
GenClassFinder finder = new GenClassFinder();
Set<GenClass> genClasses = finder.findAllGenClasses(syntax,true,true);
for (GenClass genClass : genClasses) {
if (genClass.getName().equals(identifier)) {
return genClass;
}
}
return null;
}
/**
* Checks the right side of a binary operator rule for correctness.
*
* @param resource
* @param annotation
* @param definitions
*/
private void checkBinaryOperatorRule(CsResource resource, ConcreteSyntax syntax,
Annotation annotation, List<Definition> definitions, GenClass commonMetaClass) {
if (definitions.size() < 2
|| !(definitions.get(0) instanceof Containment)
|| !(definitions.get(definitions.size()-1) instanceof Containment)) {
resource
.addError(
"Rules for binary operators must be structured as follows : containment [arbitrary sequence] containment.",
annotation);
return;
}
if(commonMetaClass!=null){
checkContainment(resource, syntax, commonMetaClass,(Containment)definitions.get(0));
checkContainment(resource, syntax, commonMetaClass,(Containment)definitions.get(2));
}
}
/**
* Checks the right side of a unary operator rule for syntactical correctness.
*
* @param resource
* @param annotation
* @param definitions
*/
private void checkUnaryOperatorRule(CsResource resource, ConcreteSyntax syntax,
Annotation annotation, List<Definition> definitions, GenClass commonMetaClass) {
OperatorAnnotationType annotationType = csUtil.getOperatorAnnotationType(annotation);
int containmentIndex = -1;
if(annotationType == OperatorAnnotationType.UNARY_PREFIX){
containmentIndex = definitions.size()-1;
}
else{
assert annotationType == OperatorAnnotationType.UNARY_POSTFIX;
containmentIndex = 0;
}
if (definitions.size() < 2
|| !(definitions.get(containmentIndex) instanceof Containment)) {
resource
.addError(
"Rules for unary operators require no less than two arguments: " +
"[arbitrary sequence] containment for prefix " +
"or containment [arbitrary sequence] " +
"for postfix (left recursive) operators.",
annotation);
return;
}
if(commonMetaClass!=null){
checkContainment(resource, syntax, commonMetaClass,(Containment)definitions.get(containmentIndex));
}
}
/**
* Checks if the containment does not have explicit metaclass choices since these are ignored and
* checks if the containments GenFeature typeGenClass is equal to the common expression meta class
* or if it is a super type.
*
* @param resource
* @param commonMetaClass
* @param containment
*/
private void checkContainment(CsResource resource, ConcreteSyntax syntax, GenClass commonMetaClass, Containment containment){
if (containment.getTypes() != null && !containment.getTypes().isEmpty()) {
resource.addError("Subclass restrictions are not allowed in operator rules.",containment);
}
GenClass containmentClass = containment.getFeature().getTypeGenClass();
if (!containmentClass.equals(commonMetaClass)){
EClassUtil eUtil = syntax.getEClassUtil();
if(!eUtil.isSubClass(commonMetaClass.getEcoreClass(),containmentClass.getEcoreClass())){
resource.addError("Argument types must be equal or a super type of the common metaclass.",containment);
}
}
}
}
| true | true |
private void checkRulesWithOperatorAnnotation(CsResource resource,
ConcreteSyntax syntax) {
for (Rule operatorRule : syntax.getOperatorRules()) {
Annotation annotation = operatorRule.getOperatorAnnotation();
String weight = annotation.getValue(OperatorAnnotationProperty.WEIGHT.toString());
String identifier = annotation.getValue(OperatorAnnotationProperty.IDENTIFIER.toString());
String typeString = annotation.getValue(OperatorAnnotationProperty.TYPE.toString());
if (weight == null || identifier == null || typeString == null) {
resource
.addError(
"Operator annotations require values for weigth, type and identifier.",
annotation);
continue;
}
checkWeightParameter(resource, annotation, weight);
GenClass expressionMetaClass = mapIdentifierToGenClass(syntax, identifier);
if (expressionMetaClass==null ||
(!expressionMetaClass.isAbstract() && !expressionMetaClass.isInterface())){
resource.addError("Expression idenfitier must map to a common abstract metaclass or interface.",annotation);
}
else{
EClassUtil eUtil = syntax.getEClassUtil();
if(!eUtil.isSubClass(operatorRule.getMetaclass().getEcoreClass(), expressionMetaClass.getEcoreClass())){
resource.addError("Operator rule must be associated with a subclass of "+identifier,operatorRule);
}
}
OperatorAnnotationType type = csUtil.getOperatorAnnotationType(annotation);
if(type==null){
// TODO skarol: improve error message by giving the valid types
resource.addError("Could not determine operator type.",annotation);
continue;
}
if (type != OperatorAnnotationType.PRIMITIVE) {
List<Sequence> options = operatorRule.getDefinition()
.getOptions();
if (options.size() == 1) {
List<Definition> definitions = options.get(0).getParts();
if (type == OperatorAnnotationType.BINARY_LEFT_ASSOCIATIVE ||
type == OperatorAnnotationType.BINARY_RIGHT_ASSOCIATIVE) {
checkBinaryOperatorRule(resource, syntax, annotation,
definitions,expressionMetaClass);
} else {
checkUnaryOperatorRule(resource, syntax, annotation,
definitions,expressionMetaClass);
}
} else {
resource
.addError(
"Non primitive operator annotations require exactly one Choice in rule.",
operatorRule);
}
}
}
}
|
private void checkRulesWithOperatorAnnotation(CsResource resource,
ConcreteSyntax syntax) {
for (Rule operatorRule : syntax.getOperatorRules()) {
Annotation annotation = operatorRule.getOperatorAnnotation();
String weight = annotation.getValue(OperatorAnnotationProperty.WEIGHT.toString());
String identifier = annotation.getValue(OperatorAnnotationProperty.IDENTIFIER.toString());
String typeString = annotation.getValue(OperatorAnnotationProperty.TYPE.toString());
if (weight == null || identifier == null || typeString == null) {
resource
.addError(
"Operator annotations require values for weigth, type and identifier.",
annotation);
continue;
}
checkWeightParameter(resource, annotation, weight);
GenClass expressionMetaClass = mapIdentifierToGenClass(syntax, identifier);
if (expressionMetaClass==null ||
(!expressionMetaClass.isAbstract() && !expressionMetaClass.isInterface())){
resource.addError("Expression idenfitier must map to a common abstract metaclass or interface.",annotation);
}
else{
EClassUtil eUtil = syntax.getEClassUtil();
if(!eUtil.isSubClass(operatorRule.getMetaclass().getEcoreClass(), expressionMetaClass.getEcoreClass())){
resource.addError("Operator rule must be associated with a subclass of "+identifier,operatorRule);
}
}
OperatorAnnotationType type = csUtil.getOperatorAnnotationType(annotation);
if(type==null){
String possibleValues = "Should be one of: ";
OperatorAnnotationType[] values = OperatorAnnotationType.values();
for (OperatorAnnotationType operatorAnnotationType : values) {
possibleValues += operatorAnnotationType.getLiteral() + ", " ;
}
possibleValues = possibleValues.substring(0, possibleValues.length()-2);
resource.addError("Invalid operator type. " + possibleValues, annotation);
continue;
}
if (type != OperatorAnnotationType.PRIMITIVE) {
List<Sequence> options = operatorRule.getDefinition()
.getOptions();
if (options.size() == 1) {
List<Definition> definitions = options.get(0).getParts();
if (type == OperatorAnnotationType.BINARY_LEFT_ASSOCIATIVE ||
type == OperatorAnnotationType.BINARY_RIGHT_ASSOCIATIVE) {
checkBinaryOperatorRule(resource, syntax, annotation,
definitions,expressionMetaClass);
} else {
checkUnaryOperatorRule(resource, syntax, annotation,
definitions,expressionMetaClass);
}
} else {
resource
.addError(
"Non primitive operator annotations require exactly one Choice in rule.",
operatorRule);
}
}
}
}
|
diff --git a/whois-api/src/test/java/net/ripe/db/whois/api/log/UpdateLogTestIntegration.java b/whois-api/src/test/java/net/ripe/db/whois/api/log/UpdateLogTestIntegration.java
index 4e2c83e11..b8a84f43b 100644
--- a/whois-api/src/test/java/net/ripe/db/whois/api/log/UpdateLogTestIntegration.java
+++ b/whois-api/src/test/java/net/ripe/db/whois/api/log/UpdateLogTestIntegration.java
@@ -1,177 +1,177 @@
package net.ripe.db.whois.api.log;
import com.google.common.net.HttpHeaders;
import net.ripe.db.whois.api.AbstractIntegrationTest;
import net.ripe.db.whois.api.RestTest;
import net.ripe.db.whois.api.rest.RestClient;
import net.ripe.db.whois.api.rest.RestClientUtils;
import net.ripe.db.whois.common.rpsl.RpslObject;
import net.ripe.db.whois.common.support.FileHelper;
import net.ripe.db.whois.update.support.TestUpdateLog;
import org.joda.time.LocalDateTime;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import java.io.File;
import static net.ripe.db.whois.common.rpsl.RpslObjectFilter.buildGenericObject;
import static net.ripe.db.whois.common.support.StringMatchesRegexp.stringMatchesRegexp;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
public class UpdateLogTestIntegration extends AbstractIntegrationTest {
private static final RpslObject OWNER_MNT = RpslObject.parse("" +
"mntner: OWNER-MNT\n" +
"descr: Owner Maintainer\n" +
"admin-c: TP1-TEST\n" +
"upd-to: [email protected]\n" +
"auth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test\n" +
"mnt-by: OWNER-MNT\n" +
"referral-by: OWNER-MNT\n" +
"changed: [email protected] 20120101\n" +
"source: TEST");
private static final RpslObject TEST_PERSON = RpslObject.parse("" +
"person: Test Person\n" +
"address: Singel 258\n" +
"phone: +31 6 12345678\n" +
"nic-hdl: TP1-TEST\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20120101\n" +
"source: TEST");
@Value("${dir.update.audit.log}") // TODO: use system temporary directory
private String auditLog;
@Autowired
private TestUpdateLog updateLog;
private RestClient restClient;
@Before
public void setup() throws Exception {
testDateTimeProvider.setTime(LocalDateTime.parse("2001-02-04T17:00:00"));
databaseHelper.addObjects(OWNER_MNT, TEST_PERSON);
restClient = new RestClient(String.format("http://localhost:%d/whois", getPort()), "TEST");
}
@Test
public void create_gets_logged() {
final RpslObject secondPerson = buildGenericObject(TEST_PERSON, "nic-hdl: TP2-TEST");
restClient.request()
.addHeader(HttpHeaders.X_FORWARDED_FOR, "10.20.30.40")
.addParam("password", "test")
.create(secondPerson);
final String audit = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.rest_10.20.30.40_0/000.audit.xml.gz"));
assertThat(audit, containsString("<query"));
assertThat(audit, containsString("<sql"));
assertThat(audit, containsString("<message><![CDATA[Header: X-Forwarded-For=10.20.30.40]]></message>"));
assertThat(audit, containsString("<message><![CDATA[/whois/TEST/person?password=test]]></message>"));
final String msgIn = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.rest_10.20.30.40_0/001.msg-in.txt.gz"));
assertThat(msgIn, containsString("person: Test Person"));
final String ack = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.rest_10.20.30.40_0/002.ack.txt.gz"));
assertThat(ack, containsString("Create SUCCEEDED: [person] TP2-TEST Test Person"));
assertThat(updateLog.getMessages(), hasSize(1));
assertThat(updateLog.getMessage(0), stringMatchesRegexp(".*UPD CREATE person\\s+TP2-TEST\\s+\\(1\\) SUCCESS\\s+:.*"));
assertThat(updateLog.getMessage(0), containsString("<E0,W0,I0> AUTH PWD - WhoisRestApi(10.20.30.40)"));
}
@Test
public void update_gets_logged() {
final RpslObject updatedPerson = buildGenericObject(TEST_PERSON, "remarks: i will be back");
restClient.request()
.addHeader(HttpHeaders.X_FORWARDED_FOR, "10.20.30.40")
.addParam("password", "test")
.update(updatedPerson);
final String audit = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.rest_10.20.30.40_0/000.audit.xml.gz"));
assertThat(audit, containsString("<query"));
assertThat(audit, containsString("<sql"));
assertThat(audit, containsString("<message><![CDATA[Header: X-Forwarded-For=10.20.30.40]]></message>"));
assertThat(audit, containsString("<message><![CDATA[/whois/TEST/person/TP1-TEST?password=test]]></message>"));
final String msgIn = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.rest_10.20.30.40_0/001.msg-in.txt.gz"));
assertThat(msgIn, containsString("person: Test Person"));
final String ack = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.rest_10.20.30.40_0/002.ack.txt.gz"));
assertThat(ack, containsString("Modify SUCCEEDED: [person] TP1-TEST Test Person"));
assertThat(updateLog.getMessages(), hasSize(1));
assertThat(updateLog.getMessage(0), stringMatchesRegexp(".*UPD MODIFY person\\s+TP1-TEST\\s+\\(1\\) SUCCESS\\s+:.*"));
assertThat(updateLog.getMessage(0), containsString("<E0,W0,I0> AUTH PWD - WhoisRestApi(10.20.30.40)"));
}
@Test
public void delete_gets_logged() {
final RpslObject secondPerson = buildGenericObject(TEST_PERSON, "nic-hdl: TP2-TEST");
databaseHelper.addObject(secondPerson);
restClient.request()
.addHeader(HttpHeaders.X_FORWARDED_FOR, "10.20.30.40")
.addParam("password", "test")
.delete(secondPerson);
final String audit = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.rest_10.20.30.40_0/000.audit.xml.gz"));
assertThat(audit, containsString("<query"));
assertThat(audit, containsString("<sql"));
assertThat(audit, containsString("<message><![CDATA[Header: X-Forwarded-For=10.20.30.40]]></message>"));
assertThat(audit, containsString("<message><![CDATA[/whois/TEST/person/TP2-TEST?password=test]]></message>"));
final String msgIn = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.rest_10.20.30.40_0/001.msg-in.txt.gz"));
assertThat(msgIn, containsString("person: Test Person"));
final String ack = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.rest_10.20.30.40_0/002.ack.txt.gz"));
assertThat(ack, containsString("Delete SUCCEEDED: [person] TP2-TEST Test Person"));
assertThat(updateLog.getMessages(), hasSize(1));
assertThat(updateLog.getMessage(0), stringMatchesRegexp(".*UPD DELETE person\\s+TP2-TEST\\s+\\(1\\) SUCCESS\\s+:.*"));
assertThat(updateLog.getMessage(0), containsString("<E0,W0,I0> AUTH PWD - WhoisRestApi(10.20.30.40)"));
}
@Test
public void syncupdate_gets_logged() throws Exception {
final RpslObject secondPerson = buildGenericObject(TEST_PERSON, "nic-hdl: TP2-TEST");
RestTest.target(getPort(), "whois/syncupdates/test?" + "DATA=" + RestClientUtils.encode(secondPerson + "\npassword: test") + "&NEW=yes")
.request()
.header(HttpHeaders.X_FORWARDED_FOR, "10.20.30.40")
.get(String.class);
final String audit = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.syncupdate_10.20.30.40_0/000.audit.xml.gz"));
assertThat(audit, containsString("<query"));
assertThat(audit, containsString("<sql"));
assertThat(audit, containsString("<message><![CDATA[Header: X-Forwarded-For=10.20.30.40]]></message>"));
assertThat(audit, containsString("<message><![CDATA[/whois/syncupdates/test?DATA"));
final String msgIn = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.syncupdate_10.20.30.40_0/001.msg-in.txt.gz"));
assertThat(msgIn, containsString("REQUEST FROM:10.20.30.40"));
assertThat(msgIn, containsString("NEW=yes"));
assertThat(msgIn, containsString("DATA="));
assertThat(msgIn, containsString("Test Person"));
assertThat(msgIn, containsString("password: test"));
final String ack = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.syncupdate_10.20.30.40_0/002.ack.txt.gz"));
assertThat(ack, containsString("Create SUCCEEDED: [person] TP2-TEST Test Person"));
final String msgOut = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.syncupdate_10.20.30.40_0/003.msg-out.txt.gz"));
assertThat(msgOut, containsString("SUMMARY OF UPDATE:"));
assertThat(msgOut, containsString("DETAILED EXPLANATION:"));
assertThat(msgOut, containsString("Create SUCCEEDED: [person] TP2-TEST Test Person"));
assertThat(updateLog.getMessages(), hasSize(1));
assertThat(updateLog.getMessage(0), stringMatchesRegexp(".*UPD CREATE person\\s+TP2-TEST\\s+\\(1\\) SUCCESS\\s+:.*"));
- assertThat(updateLog.getMessage(0), containsString("<E0,W0,I0> AUTH PWD - WhoisRestApi(10.20.30.40)"));
+ assertThat(updateLog.getMessage(0), containsString("<E0,W0,I0> AUTH PWD - SyncUpdate(10.20.30.40)"));
}
@Test
public void mailupdate_gets_logged() throws Exception {
// TODO: test mailupdate gets logged
}
}
| true | true |
public void syncupdate_gets_logged() throws Exception {
final RpslObject secondPerson = buildGenericObject(TEST_PERSON, "nic-hdl: TP2-TEST");
RestTest.target(getPort(), "whois/syncupdates/test?" + "DATA=" + RestClientUtils.encode(secondPerson + "\npassword: test") + "&NEW=yes")
.request()
.header(HttpHeaders.X_FORWARDED_FOR, "10.20.30.40")
.get(String.class);
final String audit = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.syncupdate_10.20.30.40_0/000.audit.xml.gz"));
assertThat(audit, containsString("<query"));
assertThat(audit, containsString("<sql"));
assertThat(audit, containsString("<message><![CDATA[Header: X-Forwarded-For=10.20.30.40]]></message>"));
assertThat(audit, containsString("<message><![CDATA[/whois/syncupdates/test?DATA"));
final String msgIn = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.syncupdate_10.20.30.40_0/001.msg-in.txt.gz"));
assertThat(msgIn, containsString("REQUEST FROM:10.20.30.40"));
assertThat(msgIn, containsString("NEW=yes"));
assertThat(msgIn, containsString("DATA="));
assertThat(msgIn, containsString("Test Person"));
assertThat(msgIn, containsString("password: test"));
final String ack = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.syncupdate_10.20.30.40_0/002.ack.txt.gz"));
assertThat(ack, containsString("Create SUCCEEDED: [person] TP2-TEST Test Person"));
final String msgOut = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.syncupdate_10.20.30.40_0/003.msg-out.txt.gz"));
assertThat(msgOut, containsString("SUMMARY OF UPDATE:"));
assertThat(msgOut, containsString("DETAILED EXPLANATION:"));
assertThat(msgOut, containsString("Create SUCCEEDED: [person] TP2-TEST Test Person"));
assertThat(updateLog.getMessages(), hasSize(1));
assertThat(updateLog.getMessage(0), stringMatchesRegexp(".*UPD CREATE person\\s+TP2-TEST\\s+\\(1\\) SUCCESS\\s+:.*"));
assertThat(updateLog.getMessage(0), containsString("<E0,W0,I0> AUTH PWD - WhoisRestApi(10.20.30.40)"));
}
|
public void syncupdate_gets_logged() throws Exception {
final RpslObject secondPerson = buildGenericObject(TEST_PERSON, "nic-hdl: TP2-TEST");
RestTest.target(getPort(), "whois/syncupdates/test?" + "DATA=" + RestClientUtils.encode(secondPerson + "\npassword: test") + "&NEW=yes")
.request()
.header(HttpHeaders.X_FORWARDED_FOR, "10.20.30.40")
.get(String.class);
final String audit = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.syncupdate_10.20.30.40_0/000.audit.xml.gz"));
assertThat(audit, containsString("<query"));
assertThat(audit, containsString("<sql"));
assertThat(audit, containsString("<message><![CDATA[Header: X-Forwarded-For=10.20.30.40]]></message>"));
assertThat(audit, containsString("<message><![CDATA[/whois/syncupdates/test?DATA"));
final String msgIn = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.syncupdate_10.20.30.40_0/001.msg-in.txt.gz"));
assertThat(msgIn, containsString("REQUEST FROM:10.20.30.40"));
assertThat(msgIn, containsString("NEW=yes"));
assertThat(msgIn, containsString("DATA="));
assertThat(msgIn, containsString("Test Person"));
assertThat(msgIn, containsString("password: test"));
final String ack = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.syncupdate_10.20.30.40_0/002.ack.txt.gz"));
assertThat(ack, containsString("Create SUCCEEDED: [person] TP2-TEST Test Person"));
final String msgOut = FileHelper.fetchGzip(new File(auditLog + "/20010204/170000.syncupdate_10.20.30.40_0/003.msg-out.txt.gz"));
assertThat(msgOut, containsString("SUMMARY OF UPDATE:"));
assertThat(msgOut, containsString("DETAILED EXPLANATION:"));
assertThat(msgOut, containsString("Create SUCCEEDED: [person] TP2-TEST Test Person"));
assertThat(updateLog.getMessages(), hasSize(1));
assertThat(updateLog.getMessage(0), stringMatchesRegexp(".*UPD CREATE person\\s+TP2-TEST\\s+\\(1\\) SUCCESS\\s+:.*"));
assertThat(updateLog.getMessage(0), containsString("<E0,W0,I0> AUTH PWD - SyncUpdate(10.20.30.40)"));
}
|
diff --git a/plugins/org.eclipse.dltk.ruby.ui/src/org/eclipse/dltk/ruby/internal/ui/RubyPerspective.java b/plugins/org.eclipse.dltk.ruby.ui/src/org/eclipse/dltk/ruby/internal/ui/RubyPerspective.java
index 8d17ae6b..3ac28c9a 100644
--- a/plugins/org.eclipse.dltk.ruby.ui/src/org/eclipse/dltk/ruby/internal/ui/RubyPerspective.java
+++ b/plugins/org.eclipse.dltk.ruby.ui/src/org/eclipse/dltk/ruby/internal/ui/RubyPerspective.java
@@ -1,46 +1,46 @@
package org.eclipse.dltk.ruby.internal.ui;
import org.eclipse.ui.IFolderLayout;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipse.ui.progress.IProgressConstants;
public class RubyPerspective implements IPerspectiveFactory {
public void createInitialLayout(IPageLayout layout) {
String editorArea = layout.getEditorArea();
IFolderLayout folder= layout.createFolder("left", IPageLayout.LEFT, (float)0.2, editorArea); //$NON-NLS-1$
String navigator = "org.eclipse.dltk.ui.ScriptExplorer";
folder.addView(navigator);
folder.addPlaceholder(IPageLayout.ID_BOOKMARKS);
IFolderLayout outputfolder= layout.createFolder("bottom", IPageLayout.BOTTOM, (float)0.75, editorArea); //$NON-NLS-1$
outputfolder.addView(IPageLayout.ID_PROBLEM_VIEW);
outputfolder.addView(IPageLayout.ID_TASK_LIST);
outputfolder.addView("org.eclipse.dltk.ruby.ui.RubyDocumentationView");
outputfolder.addPlaceholder(IPageLayout.ID_BOOKMARKS);
outputfolder.addPlaceholder(IProgressConstants.PROGRESS_VIEW_ID);
layout.addView(IPageLayout.ID_OUTLINE, IPageLayout.RIGHT, (float)0.75, editorArea);
layout.addActionSet(IPageLayout.ID_NAVIGATE_ACTION_SET);
- //layout.addActionSet(RubyUI.ID_ACTION_SET);
+ layout.addActionSet("org.eclipse.dltk.ruby.ui.RubyActionSet"); // TODO: externalize constant
// views - standard workbench
layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
layout.addShowViewShortcut(IPageLayout.ID_PROBLEM_VIEW);
layout.addShowViewShortcut(navigator);
layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST);
layout.addShowViewShortcut(IProgressConstants.PROGRESS_VIEW_ID);
- // new actions - Python project creation wizard
+ // new actions - Ruby project creation wizard
layout.addNewWizardShortcut("org.eclipse.dltk.ruby.internal.ui.wizards.RubyProjectWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.dltk.ruby.internal.ui.wizards.RubyFileCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");//$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");//$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.editors.wizards.UntitledTextFileWizard");//$NON-NLS-1$
}
}
| false | true |
public void createInitialLayout(IPageLayout layout) {
String editorArea = layout.getEditorArea();
IFolderLayout folder= layout.createFolder("left", IPageLayout.LEFT, (float)0.2, editorArea); //$NON-NLS-1$
String navigator = "org.eclipse.dltk.ui.ScriptExplorer";
folder.addView(navigator);
folder.addPlaceholder(IPageLayout.ID_BOOKMARKS);
IFolderLayout outputfolder= layout.createFolder("bottom", IPageLayout.BOTTOM, (float)0.75, editorArea); //$NON-NLS-1$
outputfolder.addView(IPageLayout.ID_PROBLEM_VIEW);
outputfolder.addView(IPageLayout.ID_TASK_LIST);
outputfolder.addView("org.eclipse.dltk.ruby.ui.RubyDocumentationView");
outputfolder.addPlaceholder(IPageLayout.ID_BOOKMARKS);
outputfolder.addPlaceholder(IProgressConstants.PROGRESS_VIEW_ID);
layout.addView(IPageLayout.ID_OUTLINE, IPageLayout.RIGHT, (float)0.75, editorArea);
layout.addActionSet(IPageLayout.ID_NAVIGATE_ACTION_SET);
//layout.addActionSet(RubyUI.ID_ACTION_SET);
// views - standard workbench
layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
layout.addShowViewShortcut(IPageLayout.ID_PROBLEM_VIEW);
layout.addShowViewShortcut(navigator);
layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST);
layout.addShowViewShortcut(IProgressConstants.PROGRESS_VIEW_ID);
// new actions - Python project creation wizard
layout.addNewWizardShortcut("org.eclipse.dltk.ruby.internal.ui.wizards.RubyProjectWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.dltk.ruby.internal.ui.wizards.RubyFileCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");//$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");//$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.editors.wizards.UntitledTextFileWizard");//$NON-NLS-1$
}
|
public void createInitialLayout(IPageLayout layout) {
String editorArea = layout.getEditorArea();
IFolderLayout folder= layout.createFolder("left", IPageLayout.LEFT, (float)0.2, editorArea); //$NON-NLS-1$
String navigator = "org.eclipse.dltk.ui.ScriptExplorer";
folder.addView(navigator);
folder.addPlaceholder(IPageLayout.ID_BOOKMARKS);
IFolderLayout outputfolder= layout.createFolder("bottom", IPageLayout.BOTTOM, (float)0.75, editorArea); //$NON-NLS-1$
outputfolder.addView(IPageLayout.ID_PROBLEM_VIEW);
outputfolder.addView(IPageLayout.ID_TASK_LIST);
outputfolder.addView("org.eclipse.dltk.ruby.ui.RubyDocumentationView");
outputfolder.addPlaceholder(IPageLayout.ID_BOOKMARKS);
outputfolder.addPlaceholder(IProgressConstants.PROGRESS_VIEW_ID);
layout.addView(IPageLayout.ID_OUTLINE, IPageLayout.RIGHT, (float)0.75, editorArea);
layout.addActionSet(IPageLayout.ID_NAVIGATE_ACTION_SET);
layout.addActionSet("org.eclipse.dltk.ruby.ui.RubyActionSet"); // TODO: externalize constant
// views - standard workbench
layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
layout.addShowViewShortcut(IPageLayout.ID_PROBLEM_VIEW);
layout.addShowViewShortcut(navigator);
layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST);
layout.addShowViewShortcut(IProgressConstants.PROGRESS_VIEW_ID);
// new actions - Ruby project creation wizard
layout.addNewWizardShortcut("org.eclipse.dltk.ruby.internal.ui.wizards.RubyProjectWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.dltk.ruby.internal.ui.wizards.RubyFileCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");//$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");//$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.editors.wizards.UntitledTextFileWizard");//$NON-NLS-1$
}
|
diff --git a/src/hexadoku/HtmlGenerator.java b/src/hexadoku/HtmlGenerator.java
index a31ae19..54be598 100644
--- a/src/hexadoku/HtmlGenerator.java
+++ b/src/hexadoku/HtmlGenerator.java
@@ -1,62 +1,62 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hexadoku;
import java.io.PrintStream;
/**
* Generates HTML for a board.
*
* @author Sam Fredrickson <[email protected]>
*/
public class HtmlGenerator {
private static String[] header = {
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">",
"<html xmlns=\"http://www.w3.org/1999/xhtml\">",
"<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>",
"<title>Hexadoku</title><style type=\"text/css\">",
"*{margin:0;padding:0;}",
"body{margin-left:auto;margin-right:auto;text-align:center;width:50em;}",
"table#board{border:2px solid black;border-collapse:collapse;font-family:\"Courier New\";font-size:16pt;margin-left:auto;margin-right:auto;}",
"table#board tbody tr td{border:1px solid black;height:32px;min-width:32px;}",
"table#board tbody tr.sb{border-bottom:2px solid black;}table#board tbody tr td.sr {border-right:2px solid black;}",
"</style></head><body>",
"<h1>Hexadoku</h1><h2>By Sam Fredrickson</h2><table id=\"board\"><tbody>",
};
private static String footer = "</tbody></table></body></html>";
private static void writeRow(Board board, PrintStream stream, int row)
{
char cell;
stream.print("<tr");
if(row == 3 || row == 7 || row == 11)
stream.print(" class=\"sb\"");
stream.print('>');
for(int i = 0; i < Board.NUM_DIGITS; ++i)
{
stream.print("<td");
if(i == 3 || i == 7 || i == 11)
- stream.print(" class=\"sr\");");
+ stream.print(" class=\"sr\"");
stream.print('>');
cell = board.getCellValue(row * Board.NUM_DIGITS + i);
stream.print(cell == '\0' ? ' ' : cell);
stream.print("</td>");
}
stream.print("</tr>");
}
public static void generate(Board board, PrintStream stream)
{
for(String line : header)
stream.print(line);
for(int row = 0; row < Board.NUM_DIGITS; ++row)
writeRow(board, stream, row);
stream.print(footer);
}
}
| true | true |
private static void writeRow(Board board, PrintStream stream, int row)
{
char cell;
stream.print("<tr");
if(row == 3 || row == 7 || row == 11)
stream.print(" class=\"sb\"");
stream.print('>');
for(int i = 0; i < Board.NUM_DIGITS; ++i)
{
stream.print("<td");
if(i == 3 || i == 7 || i == 11)
stream.print(" class=\"sr\");");
stream.print('>');
cell = board.getCellValue(row * Board.NUM_DIGITS + i);
stream.print(cell == '\0' ? ' ' : cell);
stream.print("</td>");
}
stream.print("</tr>");
}
|
private static void writeRow(Board board, PrintStream stream, int row)
{
char cell;
stream.print("<tr");
if(row == 3 || row == 7 || row == 11)
stream.print(" class=\"sb\"");
stream.print('>');
for(int i = 0; i < Board.NUM_DIGITS; ++i)
{
stream.print("<td");
if(i == 3 || i == 7 || i == 11)
stream.print(" class=\"sr\"");
stream.print('>');
cell = board.getCellValue(row * Board.NUM_DIGITS + i);
stream.print(cell == '\0' ? ' ' : cell);
stream.print("</td>");
}
stream.print("</tr>");
}
|
diff --git a/xjc/src/com/sun/tools/xjc/generator/bean/ObjectFactoryGeneratorImpl.java b/xjc/src/com/sun/tools/xjc/generator/bean/ObjectFactoryGeneratorImpl.java
index 2231f7e2..de1bbaf9 100644
--- a/xjc/src/com/sun/tools/xjc/generator/bean/ObjectFactoryGeneratorImpl.java
+++ b/xjc/src/com/sun/tools/xjc/generator/bean/ObjectFactoryGeneratorImpl.java
@@ -1,391 +1,391 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.tools.xjc.generator.bean;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JExpression;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JInvocation;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.JType;
import com.sun.codemodel.JVar;
import com.sun.tools.xjc.generator.annotation.spec.XmlElementDeclWriter;
import com.sun.tools.xjc.generator.annotation.spec.XmlRegistryWriter;
import com.sun.tools.xjc.model.CElementInfo;
import com.sun.tools.xjc.model.CPropertyInfo;
import com.sun.tools.xjc.model.Constructor;
import com.sun.tools.xjc.model.Model;
import com.sun.tools.xjc.outline.Aspect;
import com.sun.tools.xjc.outline.FieldAccessor;
import com.sun.tools.xjc.outline.FieldOutline;
import com.sun.xml.bind.v2.TODO;
/**
* Generates <code>ObjectFactory</code> then wraps it and provides
* access to it.
*
* <p>
* The ObjectFactory contains
* factory methods for each schema derived content class
*
* @author
* Ryan Shoemaker
*/
abstract class ObjectFactoryGeneratorImpl extends ObjectFactoryGenerator {
private final BeanGenerator outline;
private final Model model;
private final JCodeModel codeModel;
/**
* Ref to {@link Class}.
*/
private final JClass classRef;
/**
* Reference to the generated ObjectFactory class.
*/
private final JDefinedClass objectFactory;
/** map of qname to the QName constant field. */
private final HashMap<QName,JFieldVar> qnameMap = new HashMap<QName,JFieldVar>();
/**
* Names of the element factory methods that are created.
* Used to detect collisions.
*
* The value is used for reporting error locations.
*/
private final Map<String,CElementInfo> elementFactoryNames = new HashMap<String,CElementInfo>();
/**
* Names of the value factory methods that are created.
* Used to detect collisions.
*
* The value is used for reporting error locations.
*/
private final Map<String,ClassOutlineImpl> valueFactoryNames = new HashMap<String,ClassOutlineImpl>();
/**
* Returns a reference to the generated (public) ObjectFactory
*/
public JDefinedClass getObjectFactory() {
return objectFactory;
}
public ObjectFactoryGeneratorImpl( BeanGenerator outline, Model model, JPackage targetPackage ) {
this.outline = outline;
this.model = model;
this.codeModel = this.model.codeModel;
this.classRef = codeModel.ref(Class.class);
// create the ObjectFactory class skeleton
objectFactory = this.outline.getClassFactory().createClass(
targetPackage, "ObjectFactory", null );
objectFactory.annotate2(XmlRegistryWriter.class);
// generate the default constructor
//
// m1 result:
// public ObjectFactory() {}
JMethod m1 = objectFactory.constructor(JMod.PUBLIC);
m1.javadoc().append("Create a new ObjectFactory that can be used to " +
"create new instances of schema derived classes " +
"for package: " + targetPackage.name());
// add some class javadoc
objectFactory.javadoc().append(
"This object contains factory methods for each \n" +
"Java content interface and Java element interface \n" +
"generated in the " + targetPackage.name() + " package. \n" +
"<p>An ObjectFactory allows you to programatically \n" +
"construct new instances of the Java representation \n" +
"for XML content. The Java representation of XML \n" +
"content can consist of schema derived interfaces \n" +
"and classes representing the binding of schema \n" +
"type definitions, element declarations and model \n" +
"groups. Factory methods for each of these are \n" +
"provided in this class." );
}
/**
* Adds code for the given {@link CElementInfo} to ObjectFactory.
*/
protected final void populate( CElementInfo ei, Aspect impl, Aspect exposed ) {
JType exposedElementType = ei.toType(outline,exposed);
JType exposedType = ei.getContentInMemoryType().toType(outline,exposed);
JType implType = ei.getContentInMemoryType().toType(outline,impl);
String namespaceURI = ei.getElementName().getNamespaceURI();
String localPart = ei.getElementName().getLocalPart();
JClass scope=null;
if(ei.getScope()!=null)
- scope = outline.getClazz(ei.getScope()).implRef;
+ scope = outline.getClazz(ei.getScope()).implClass;
JMethod m;
if(ei.isAbstract()) {
// TODO: see the "Abstract elements and mighty IXmlElement" e-mail
// that I sent to jaxb-tech
TODO.checkSpec();
}
{// collision check
CElementInfo existing = elementFactoryNames.put(ei.getSqueezedName(),ei);
if( existing!=null ) {
outline.getErrorReceiver().error(existing.getLocator(),
Messages.OBJECT_FACTORY_CONFLICT.format(ei.getSqueezedName()));
outline.getErrorReceiver().error(ei.getLocator(),
Messages.OBJECT_FACTORY_CONFLICT_RELATED.format());
return;
}
}
// no arg constructor
// [RESULT] if the element doesn't have its own class, something like:
//
// @XmlElementMapping(uri = "", name = "foo")
// public JAXBElement<Foo> createFoo( Foo value ) {
// return new JAXBElement<Foo>(
// new QName("","foo"),(Class)FooImpl.class,scope,(FooImpl)value);
// }
// NOTE: when we generate value classes Foo==FooImpl
//
// [RESULT] otherwise
//
// @XmlElementMapping(uri = "", name = "foo")
// public Foo createFoo( FooType value ) {
// return new Foo((FooTypeImpl)value);
// }
// NOTE: when we generate value classes FooType==FooTypeImpl
//
// to deal with
// new JAXBElement<List<String>>( ..., List.class, ... );
// we sometimes have to produce (Class)List.class instead of just List.class
m = objectFactory.method( JMod.PUBLIC, exposedElementType, "create" + ei.getSqueezedName() );
JVar $value = m.param(exposedType,"value");
JExpression declaredType;
if(implType.boxify().isParameterized() || !exposedType.equals(implType))
declaredType = JExpr.cast(classRef,implType.boxify().dotclass());
else
declaredType = implType.boxify().dotclass();
JExpression scopeClass = scope==null?JExpr._null():scope.dotclass();
// build up the return extpression
JInvocation exp = JExpr._new(exposedElementType);
if(!ei.hasClass()) {
exp.arg(getQNameInvocation(ei));
exp.arg(declaredType);
exp.arg(scopeClass);
}
if(implType==exposedType)
exp.arg($value);
else
exp.arg(JExpr.cast(implType,$value));
m.body()._return( exp );
m.javadoc()
.append("Create an instance of ")
.append(exposedElementType)
.append("}");
XmlElementDeclWriter xemw = m.annotate2(XmlElementDeclWriter.class);
xemw.namespace(namespaceURI).name(localPart);
if(scope!=null)
xemw.scope(scope);
if(ei.getSubstitutionHead()!=null) {
QName n = ei.getSubstitutionHead().getElementName();
xemw.substitutionHeadNamespace(n.getNamespaceURI());
xemw.substitutionHeadName(n.getLocalPart());
}
if(ei.getDefaultValue()!=null)
xemw.defaultValue(ei.getDefaultValue());
// if the element is adapter, put that annotation on the factory method
outline.generateAdapterIfNecessary(ei.getProperty(),m);
}
/**
* return a JFieldVar that represents the QName field for the given information.
*
* if it doesn't exist, create a static field in the class and store a new JFieldVar.
*/
private JExpression getQNameInvocation(CElementInfo ei) {
QName name = ei.getElementName();
if(qnameMap.containsKey(name)) {
return qnameMap.get(name);
}
if(qnameMap.size()>1024)
// stop gap measure to avoid 'code too large' error in javac.
return createQName(name);
// [RESULT]
// private static final QName _XYZ_NAME = new QName("uri", "local");
JFieldVar qnameField = objectFactory.field(
JMod.PRIVATE | JMod.STATIC | JMod.FINAL,
QName.class,
'_' + ei.getSqueezedName() + "_QNAME", createQName(name));
qnameMap.put(name, qnameField);
return qnameField;
}
/**
* Generates an expression that evaluates to "new QName(...)"
*/
private JInvocation createQName(QName name) {
return JExpr._new(codeModel.ref(QName.class)).arg(name.getNamespaceURI()).arg(name.getLocalPart());
}
protected final void populate( ClassOutlineImpl cc, JClass sigType ) {
// add static factory method for this class to JAXBContext.
//
// generate methods like:
// public static final SIGTYPE createFoo() {
// return new FooImpl();
// }
if(!cc.target.isAbstract()) {
JMethod m = objectFactory.method(
JMod.PUBLIC, sigType, "create" + cc.target.getSqueezedName() );
m.body()._return( JExpr._new(cc.implRef) );
// add some jdoc to avoid javadoc warnings in jdk1.4
m.javadoc()
.append("Create an instance of ")
.append(cc.ref);
}
// add static factory methods for all the other constructors.
Collection<? extends Constructor> consl = cc.target.getConstructors();
if(consl.size()!=0) {
// if we are going to add constructors with parameters,
// first we need to have a default constructor.
cc.implClass.constructor(JMod.PUBLIC);
}
{// collision check
String name = cc.target.getSqueezedName();
ClassOutlineImpl existing = valueFactoryNames.put(name,cc);
if( existing!=null ) {
outline.getErrorReceiver().error(existing.target.getLocator(),
Messages.OBJECT_FACTORY_CONFLICT.format(name));
outline.getErrorReceiver().error(cc.target.getLocator(),
Messages.OBJECT_FACTORY_CONFLICT_RELATED.format());
return;
}
}
for( Constructor cons : consl ) {
// method on ObjectFactory
// [RESULT]
// Foo createFoo( T1 a, T2 b, T3 c, ... ) throws JAXBException {
// return new FooImpl(a,b,c,...);
// }
JMethod m = objectFactory.method( JMod.PUBLIC,
cc.ref, "create" + cc.target.getSqueezedName() );
JInvocation inv = JExpr._new(cc.implRef);
m.body()._return(inv);
// let's not throw this exception.
// m._throws(codeModel.ref(JAXBException.class));
// add some jdoc to avoid javadoc warnings in jdk1.4
m.javadoc()
.append( "Create an instance of " )
.append( cc.ref )
.addThrows(JAXBException.class).append("if an error occurs");
// constructor
// [RESULT]
// FooImpl( T1 a, T2 b, T3 c, ... ) {
// }
JMethod c = cc.implClass.constructor(JMod.PUBLIC);
for( String fieldName : cons.fields ) {
CPropertyInfo field = cc.target.getProperty(fieldName);
if(field==null) {
outline.getErrorReceiver().error(cc.target.getLocator(),
Messages.ILLEGAL_CONSTRUCTOR_PARAM.format(fieldName));
continue;
}
fieldName = camelize(fieldName);
FieldOutline fo = outline.getField(field);
FieldAccessor accessor = fo.create(JExpr._this());
// declare a parameter on this factory method and set
// it to the field
inv.arg(m.param( fo.getRawType(), fieldName ));
JVar $var = c.param( fo.getRawType(), fieldName );
accessor.fromRawValue(c.body(),'_'+fieldName,$var);
}
}
}
/** Change the first character to the lower case. */
private static String camelize( String s ) {
return Character.toLowerCase(s.charAt(0)) + s.substring(1);
}
}
| true | true |
protected final void populate( CElementInfo ei, Aspect impl, Aspect exposed ) {
JType exposedElementType = ei.toType(outline,exposed);
JType exposedType = ei.getContentInMemoryType().toType(outline,exposed);
JType implType = ei.getContentInMemoryType().toType(outline,impl);
String namespaceURI = ei.getElementName().getNamespaceURI();
String localPart = ei.getElementName().getLocalPart();
JClass scope=null;
if(ei.getScope()!=null)
scope = outline.getClazz(ei.getScope()).implRef;
JMethod m;
if(ei.isAbstract()) {
// TODO: see the "Abstract elements and mighty IXmlElement" e-mail
// that I sent to jaxb-tech
TODO.checkSpec();
}
{// collision check
CElementInfo existing = elementFactoryNames.put(ei.getSqueezedName(),ei);
if( existing!=null ) {
outline.getErrorReceiver().error(existing.getLocator(),
Messages.OBJECT_FACTORY_CONFLICT.format(ei.getSqueezedName()));
outline.getErrorReceiver().error(ei.getLocator(),
Messages.OBJECT_FACTORY_CONFLICT_RELATED.format());
return;
}
}
// no arg constructor
// [RESULT] if the element doesn't have its own class, something like:
//
// @XmlElementMapping(uri = "", name = "foo")
// public JAXBElement<Foo> createFoo( Foo value ) {
// return new JAXBElement<Foo>(
// new QName("","foo"),(Class)FooImpl.class,scope,(FooImpl)value);
// }
// NOTE: when we generate value classes Foo==FooImpl
//
// [RESULT] otherwise
//
// @XmlElementMapping(uri = "", name = "foo")
// public Foo createFoo( FooType value ) {
// return new Foo((FooTypeImpl)value);
// }
// NOTE: when we generate value classes FooType==FooTypeImpl
//
// to deal with
// new JAXBElement<List<String>>( ..., List.class, ... );
// we sometimes have to produce (Class)List.class instead of just List.class
m = objectFactory.method( JMod.PUBLIC, exposedElementType, "create" + ei.getSqueezedName() );
JVar $value = m.param(exposedType,"value");
JExpression declaredType;
if(implType.boxify().isParameterized() || !exposedType.equals(implType))
declaredType = JExpr.cast(classRef,implType.boxify().dotclass());
else
declaredType = implType.boxify().dotclass();
JExpression scopeClass = scope==null?JExpr._null():scope.dotclass();
// build up the return extpression
JInvocation exp = JExpr._new(exposedElementType);
if(!ei.hasClass()) {
exp.arg(getQNameInvocation(ei));
exp.arg(declaredType);
exp.arg(scopeClass);
}
if(implType==exposedType)
exp.arg($value);
else
exp.arg(JExpr.cast(implType,$value));
m.body()._return( exp );
m.javadoc()
.append("Create an instance of ")
.append(exposedElementType)
.append("}");
XmlElementDeclWriter xemw = m.annotate2(XmlElementDeclWriter.class);
xemw.namespace(namespaceURI).name(localPart);
if(scope!=null)
xemw.scope(scope);
if(ei.getSubstitutionHead()!=null) {
QName n = ei.getSubstitutionHead().getElementName();
xemw.substitutionHeadNamespace(n.getNamespaceURI());
xemw.substitutionHeadName(n.getLocalPart());
}
if(ei.getDefaultValue()!=null)
xemw.defaultValue(ei.getDefaultValue());
// if the element is adapter, put that annotation on the factory method
outline.generateAdapterIfNecessary(ei.getProperty(),m);
}
|
protected final void populate( CElementInfo ei, Aspect impl, Aspect exposed ) {
JType exposedElementType = ei.toType(outline,exposed);
JType exposedType = ei.getContentInMemoryType().toType(outline,exposed);
JType implType = ei.getContentInMemoryType().toType(outline,impl);
String namespaceURI = ei.getElementName().getNamespaceURI();
String localPart = ei.getElementName().getLocalPart();
JClass scope=null;
if(ei.getScope()!=null)
scope = outline.getClazz(ei.getScope()).implClass;
JMethod m;
if(ei.isAbstract()) {
// TODO: see the "Abstract elements and mighty IXmlElement" e-mail
// that I sent to jaxb-tech
TODO.checkSpec();
}
{// collision check
CElementInfo existing = elementFactoryNames.put(ei.getSqueezedName(),ei);
if( existing!=null ) {
outline.getErrorReceiver().error(existing.getLocator(),
Messages.OBJECT_FACTORY_CONFLICT.format(ei.getSqueezedName()));
outline.getErrorReceiver().error(ei.getLocator(),
Messages.OBJECT_FACTORY_CONFLICT_RELATED.format());
return;
}
}
// no arg constructor
// [RESULT] if the element doesn't have its own class, something like:
//
// @XmlElementMapping(uri = "", name = "foo")
// public JAXBElement<Foo> createFoo( Foo value ) {
// return new JAXBElement<Foo>(
// new QName("","foo"),(Class)FooImpl.class,scope,(FooImpl)value);
// }
// NOTE: when we generate value classes Foo==FooImpl
//
// [RESULT] otherwise
//
// @XmlElementMapping(uri = "", name = "foo")
// public Foo createFoo( FooType value ) {
// return new Foo((FooTypeImpl)value);
// }
// NOTE: when we generate value classes FooType==FooTypeImpl
//
// to deal with
// new JAXBElement<List<String>>( ..., List.class, ... );
// we sometimes have to produce (Class)List.class instead of just List.class
m = objectFactory.method( JMod.PUBLIC, exposedElementType, "create" + ei.getSqueezedName() );
JVar $value = m.param(exposedType,"value");
JExpression declaredType;
if(implType.boxify().isParameterized() || !exposedType.equals(implType))
declaredType = JExpr.cast(classRef,implType.boxify().dotclass());
else
declaredType = implType.boxify().dotclass();
JExpression scopeClass = scope==null?JExpr._null():scope.dotclass();
// build up the return extpression
JInvocation exp = JExpr._new(exposedElementType);
if(!ei.hasClass()) {
exp.arg(getQNameInvocation(ei));
exp.arg(declaredType);
exp.arg(scopeClass);
}
if(implType==exposedType)
exp.arg($value);
else
exp.arg(JExpr.cast(implType,$value));
m.body()._return( exp );
m.javadoc()
.append("Create an instance of ")
.append(exposedElementType)
.append("}");
XmlElementDeclWriter xemw = m.annotate2(XmlElementDeclWriter.class);
xemw.namespace(namespaceURI).name(localPart);
if(scope!=null)
xemw.scope(scope);
if(ei.getSubstitutionHead()!=null) {
QName n = ei.getSubstitutionHead().getElementName();
xemw.substitutionHeadNamespace(n.getNamespaceURI());
xemw.substitutionHeadName(n.getLocalPart());
}
if(ei.getDefaultValue()!=null)
xemw.defaultValue(ei.getDefaultValue());
// if the element is adapter, put that annotation on the factory method
outline.generateAdapterIfNecessary(ei.getProperty(),m);
}
|
diff --git a/api/src/main/java/org/openmrs/module/reporting/report/util/SqlUtils.java b/api/src/main/java/org/openmrs/module/reporting/report/util/SqlUtils.java
index e63f4b24..5964a49f 100644
--- a/api/src/main/java/org/openmrs/module/reporting/report/util/SqlUtils.java
+++ b/api/src/main/java/org/openmrs/module/reporting/report/util/SqlUtils.java
@@ -1,244 +1,249 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.reporting.report.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.openmrs.Cohort;
import org.openmrs.OpenmrsObject;
import org.openmrs.module.reporting.common.ObjectUtil;
import org.openmrs.module.reporting.evaluation.parameter.ParameterException;
import org.openmrs.module.reporting.IllegalDatabaseAccessException;
/**
* Provides access to a variety of common SQL functionality
*/
public class SqlUtils {
/**
* Binds the given paramMap to the query by replacing all named parameters (e.g. :paramName)
* with their corresponding values in the parameter map. TODO copied from
* HibernateCohortQueryDAO
*
* @param connection
* @param query
* @param paramMap
* @throws SQLException
*/
@SuppressWarnings("unchecked")
public static PreparedStatement prepareStatement(Connection connection, String query, Map<String, Object> paramMap) throws SQLException {
PreparedStatement statement;
if (!isSelectQuery(query)) {
throw new IllegalDatabaseAccessException();
}
boolean containParams = query.indexOf(":") > 0;
if (containParams) {
// the first process is replacing the :paramName with ?
// implementation taken from: http://www.javaworld.com/javaworld/jw-04-2007/jw-04-jdbc.html?page=2
Map<String, List<Integer>> params = new HashMap<String, List<Integer>>();
StringBuffer parsedQuery = new StringBuffer();
int index = 1;
for (int i = 0; i < query.length(); i++) {
// we can use charAt here, but we might need to append "(?, ?, ?)" when the where parameter is a list
// http://stackoverflow.com/questions/178479/alternatives-for-java-sql-preparedstatement-in-clause-issue
// http://www.javaranch.com/journal/200510/Journal200510.jsp#a2
String s = query.substring(i, i + 1);
if (StringUtils.equals(s, ":") && i + 1 < query.length()
&& Character.isJavaIdentifierStart(query.charAt(i + 1))) {
// we already make sure that (i + 1) is a valid character, now check the next one after (i + 1)
int j = i + 2;
while (j < query.length() && Character.isJavaIdentifierPart(query.charAt(j)))
j++;
String name = query.substring(i + 1, j);
Object paramValue = paramMap.get(name);
// are we dealing with collection or not
int size = 1;
if (paramValue != null)
if (Cohort.class.isAssignableFrom(paramValue.getClass()))
size = ((Cohort) paramValue).getSize();
else if (Collection.class.isAssignableFrom(paramValue.getClass()))
size = ((Collection<?>) paramValue).size();
// skip until the end of the param name
i += name.length();
String[] sqlParams = new String[size];
for (int k = 0; k < sqlParams.length; k++) {
sqlParams[k] = "?";
// record the location of the parameter in the sql statemet
List<Integer> indexList = params.get(name);
if (indexList == null) {
indexList = new LinkedList<Integer>();
params.put(name, indexList);
}
indexList.add(new Integer(index));
index++;
}
s = StringUtils.join(sqlParams, ",");
// for the "IN" query, we need to add bracket
if (size > 1)
s = "(" + s + ")";
}
parsedQuery.append(s);
}
// the query string contains parameters, re-create the prepared statement with the new parsed query string
statement = connection.prepareStatement(parsedQuery.toString());
// Iterate over parameters and bind them to the Query object
for (String paramName : paramMap.keySet()) {
Object paramValue = paramMap.get(paramName);
// Indicates whether we should bind this parameter in the query
// Make sure parameter value is not null
if (paramValue == null) {
// TODO Should try to convert 'columnName = null' to 'columnName IS NULL'
throw new ParameterException(
"Cannot bind an empty value to parameter "
+ paramName
+ ". "
+ "Please provide a real value or use the 'IS NULL' constraint in your query (e.g. 'table.columnName IS NULL').");
}
int i = 0;
List<Integer> positions = params.get(paramName);
if (positions != null) {
// Cohort (needs to be first, otherwise it will resolve as OpenmrsObject)
if (Cohort.class.isAssignableFrom(paramValue.getClass())) {
Cohort cohort = (Cohort) paramValue;
for (Integer patientId : cohort.getMemberIds()) {
statement.setInt(positions.get(i++), patientId);
}
}
// OpenmrsObject (e.g. Location)
else if (OpenmrsObject.class.isAssignableFrom(paramValue.getClass())) {
for (Integer position : positions) {
statement.setInt(position, ((OpenmrsObject) paramValue).getId());
}
}
// List<OpenmrsObject> (e.g. List<Location>)
else if (List.class.isAssignableFrom(paramValue.getClass())) {
// If first element in the list is an OpenmrsObject
if (OpenmrsObject.class.isAssignableFrom(((List<?>) paramValue).get(0).getClass())) {
List<Integer> openmrsObjectIds = SqlUtils.openmrsObjectIdListHelper((List<OpenmrsObject>) paramValue);
for (Integer openmrsObjectId : openmrsObjectIds) {
statement.setInt(positions.get(i++), openmrsObjectId);
}
}
// a List of Strings, Integers?
else {
List<String> strings = SqlUtils.objectListHelper((List<Object>) paramValue);
for (String string : strings) {
statement.setString(positions.get(i++), string);
}
}
}
// java.util.Date and subclasses
else if (paramValue instanceof Date) {
for (Integer position : positions) {
statement.setDate(position, new java.sql.Date(((Date) paramValue).getTime()));
}
}
- // String, Integer, et al (this might break since this is a catch all for all other classes)
+ else if (paramValue instanceof Integer || paramValue instanceof Long) {
+ for (Integer position : positions) {
+ statement.setLong(position, (Integer)paramValue);
+ }
+ }
+ // String, et al (this might break since this is a catch all for all other classes)
else {
for (Integer position : positions) {
statement.setString(position, new String(paramValue.toString()));
}
}
}
}
} else
statement = connection.prepareStatement(query);
return statement;
}
/**
* TODO Move this to a reporting utility class or to core.
*
* @param list a list of OpenmrsObjects
* @return null if passed null or an empty list, otherwise returns a list of the ids of the
* OpenmrsObjects in list
*/
public static List<Integer> openmrsObjectIdListHelper(List<? extends OpenmrsObject> list) {
if (list == null || list.size() == 0)
return null;
List<Integer> ret = new ArrayList<Integer>();
for (OpenmrsObject o : list)
ret.add(o.getId());
return ret;
}
/**
* TODO Move this to a reporting utility class or to core.
*
* @param list a list of Objects
* @return null if passed null or an empty list, otherwise returns a list of Object.toString()
*/
public static List<String> objectListHelper(List<? extends Object> list) {
if (list == null || list.size() == 0)
return null;
List<String> results = new ArrayList<String>();
for (Object object : list)
results.add(object.toString());
return results;
}
/**
* Used to check if a query is a select query or if it is a update/insert/delete/drop or select into query.
* This is used to prevent queries that tries to perform database modifications
*/
public static boolean isSelectQuery(String query) {
List<String> updateWords = Arrays.asList("insert", "update", "delete", "alter", "drop", "create", "rename", "into");
for (String statement : query.trim().split(";")) {
String s = statement.toLowerCase().trim();
if (ObjectUtil.notNull(s)) {
if (!s.startsWith("select")) {
return false;
}
for (String word : s.split("\\s")) {
if (updateWords.contains(word)) {
return false;
}
}
}
}
return true;
}
}
| true | true |
public static PreparedStatement prepareStatement(Connection connection, String query, Map<String, Object> paramMap) throws SQLException {
PreparedStatement statement;
if (!isSelectQuery(query)) {
throw new IllegalDatabaseAccessException();
}
boolean containParams = query.indexOf(":") > 0;
if (containParams) {
// the first process is replacing the :paramName with ?
// implementation taken from: http://www.javaworld.com/javaworld/jw-04-2007/jw-04-jdbc.html?page=2
Map<String, List<Integer>> params = new HashMap<String, List<Integer>>();
StringBuffer parsedQuery = new StringBuffer();
int index = 1;
for (int i = 0; i < query.length(); i++) {
// we can use charAt here, but we might need to append "(?, ?, ?)" when the where parameter is a list
// http://stackoverflow.com/questions/178479/alternatives-for-java-sql-preparedstatement-in-clause-issue
// http://www.javaranch.com/journal/200510/Journal200510.jsp#a2
String s = query.substring(i, i + 1);
if (StringUtils.equals(s, ":") && i + 1 < query.length()
&& Character.isJavaIdentifierStart(query.charAt(i + 1))) {
// we already make sure that (i + 1) is a valid character, now check the next one after (i + 1)
int j = i + 2;
while (j < query.length() && Character.isJavaIdentifierPart(query.charAt(j)))
j++;
String name = query.substring(i + 1, j);
Object paramValue = paramMap.get(name);
// are we dealing with collection or not
int size = 1;
if (paramValue != null)
if (Cohort.class.isAssignableFrom(paramValue.getClass()))
size = ((Cohort) paramValue).getSize();
else if (Collection.class.isAssignableFrom(paramValue.getClass()))
size = ((Collection<?>) paramValue).size();
// skip until the end of the param name
i += name.length();
String[] sqlParams = new String[size];
for (int k = 0; k < sqlParams.length; k++) {
sqlParams[k] = "?";
// record the location of the parameter in the sql statemet
List<Integer> indexList = params.get(name);
if (indexList == null) {
indexList = new LinkedList<Integer>();
params.put(name, indexList);
}
indexList.add(new Integer(index));
index++;
}
s = StringUtils.join(sqlParams, ",");
// for the "IN" query, we need to add bracket
if (size > 1)
s = "(" + s + ")";
}
parsedQuery.append(s);
}
// the query string contains parameters, re-create the prepared statement with the new parsed query string
statement = connection.prepareStatement(parsedQuery.toString());
// Iterate over parameters and bind them to the Query object
for (String paramName : paramMap.keySet()) {
Object paramValue = paramMap.get(paramName);
// Indicates whether we should bind this parameter in the query
// Make sure parameter value is not null
if (paramValue == null) {
// TODO Should try to convert 'columnName = null' to 'columnName IS NULL'
throw new ParameterException(
"Cannot bind an empty value to parameter "
+ paramName
+ ". "
+ "Please provide a real value or use the 'IS NULL' constraint in your query (e.g. 'table.columnName IS NULL').");
}
int i = 0;
List<Integer> positions = params.get(paramName);
if (positions != null) {
// Cohort (needs to be first, otherwise it will resolve as OpenmrsObject)
if (Cohort.class.isAssignableFrom(paramValue.getClass())) {
Cohort cohort = (Cohort) paramValue;
for (Integer patientId : cohort.getMemberIds()) {
statement.setInt(positions.get(i++), patientId);
}
}
// OpenmrsObject (e.g. Location)
else if (OpenmrsObject.class.isAssignableFrom(paramValue.getClass())) {
for (Integer position : positions) {
statement.setInt(position, ((OpenmrsObject) paramValue).getId());
}
}
// List<OpenmrsObject> (e.g. List<Location>)
else if (List.class.isAssignableFrom(paramValue.getClass())) {
// If first element in the list is an OpenmrsObject
if (OpenmrsObject.class.isAssignableFrom(((List<?>) paramValue).get(0).getClass())) {
List<Integer> openmrsObjectIds = SqlUtils.openmrsObjectIdListHelper((List<OpenmrsObject>) paramValue);
for (Integer openmrsObjectId : openmrsObjectIds) {
statement.setInt(positions.get(i++), openmrsObjectId);
}
}
// a List of Strings, Integers?
else {
List<String> strings = SqlUtils.objectListHelper((List<Object>) paramValue);
for (String string : strings) {
statement.setString(positions.get(i++), string);
}
}
}
// java.util.Date and subclasses
else if (paramValue instanceof Date) {
for (Integer position : positions) {
statement.setDate(position, new java.sql.Date(((Date) paramValue).getTime()));
}
}
// String, Integer, et al (this might break since this is a catch all for all other classes)
else {
for (Integer position : positions) {
statement.setString(position, new String(paramValue.toString()));
}
}
}
}
} else
statement = connection.prepareStatement(query);
return statement;
}
|
public static PreparedStatement prepareStatement(Connection connection, String query, Map<String, Object> paramMap) throws SQLException {
PreparedStatement statement;
if (!isSelectQuery(query)) {
throw new IllegalDatabaseAccessException();
}
boolean containParams = query.indexOf(":") > 0;
if (containParams) {
// the first process is replacing the :paramName with ?
// implementation taken from: http://www.javaworld.com/javaworld/jw-04-2007/jw-04-jdbc.html?page=2
Map<String, List<Integer>> params = new HashMap<String, List<Integer>>();
StringBuffer parsedQuery = new StringBuffer();
int index = 1;
for (int i = 0; i < query.length(); i++) {
// we can use charAt here, but we might need to append "(?, ?, ?)" when the where parameter is a list
// http://stackoverflow.com/questions/178479/alternatives-for-java-sql-preparedstatement-in-clause-issue
// http://www.javaranch.com/journal/200510/Journal200510.jsp#a2
String s = query.substring(i, i + 1);
if (StringUtils.equals(s, ":") && i + 1 < query.length()
&& Character.isJavaIdentifierStart(query.charAt(i + 1))) {
// we already make sure that (i + 1) is a valid character, now check the next one after (i + 1)
int j = i + 2;
while (j < query.length() && Character.isJavaIdentifierPart(query.charAt(j)))
j++;
String name = query.substring(i + 1, j);
Object paramValue = paramMap.get(name);
// are we dealing with collection or not
int size = 1;
if (paramValue != null)
if (Cohort.class.isAssignableFrom(paramValue.getClass()))
size = ((Cohort) paramValue).getSize();
else if (Collection.class.isAssignableFrom(paramValue.getClass()))
size = ((Collection<?>) paramValue).size();
// skip until the end of the param name
i += name.length();
String[] sqlParams = new String[size];
for (int k = 0; k < sqlParams.length; k++) {
sqlParams[k] = "?";
// record the location of the parameter in the sql statemet
List<Integer> indexList = params.get(name);
if (indexList == null) {
indexList = new LinkedList<Integer>();
params.put(name, indexList);
}
indexList.add(new Integer(index));
index++;
}
s = StringUtils.join(sqlParams, ",");
// for the "IN" query, we need to add bracket
if (size > 1)
s = "(" + s + ")";
}
parsedQuery.append(s);
}
// the query string contains parameters, re-create the prepared statement with the new parsed query string
statement = connection.prepareStatement(parsedQuery.toString());
// Iterate over parameters and bind them to the Query object
for (String paramName : paramMap.keySet()) {
Object paramValue = paramMap.get(paramName);
// Indicates whether we should bind this parameter in the query
// Make sure parameter value is not null
if (paramValue == null) {
// TODO Should try to convert 'columnName = null' to 'columnName IS NULL'
throw new ParameterException(
"Cannot bind an empty value to parameter "
+ paramName
+ ". "
+ "Please provide a real value or use the 'IS NULL' constraint in your query (e.g. 'table.columnName IS NULL').");
}
int i = 0;
List<Integer> positions = params.get(paramName);
if (positions != null) {
// Cohort (needs to be first, otherwise it will resolve as OpenmrsObject)
if (Cohort.class.isAssignableFrom(paramValue.getClass())) {
Cohort cohort = (Cohort) paramValue;
for (Integer patientId : cohort.getMemberIds()) {
statement.setInt(positions.get(i++), patientId);
}
}
// OpenmrsObject (e.g. Location)
else if (OpenmrsObject.class.isAssignableFrom(paramValue.getClass())) {
for (Integer position : positions) {
statement.setInt(position, ((OpenmrsObject) paramValue).getId());
}
}
// List<OpenmrsObject> (e.g. List<Location>)
else if (List.class.isAssignableFrom(paramValue.getClass())) {
// If first element in the list is an OpenmrsObject
if (OpenmrsObject.class.isAssignableFrom(((List<?>) paramValue).get(0).getClass())) {
List<Integer> openmrsObjectIds = SqlUtils.openmrsObjectIdListHelper((List<OpenmrsObject>) paramValue);
for (Integer openmrsObjectId : openmrsObjectIds) {
statement.setInt(positions.get(i++), openmrsObjectId);
}
}
// a List of Strings, Integers?
else {
List<String> strings = SqlUtils.objectListHelper((List<Object>) paramValue);
for (String string : strings) {
statement.setString(positions.get(i++), string);
}
}
}
// java.util.Date and subclasses
else if (paramValue instanceof Date) {
for (Integer position : positions) {
statement.setDate(position, new java.sql.Date(((Date) paramValue).getTime()));
}
}
else if (paramValue instanceof Integer || paramValue instanceof Long) {
for (Integer position : positions) {
statement.setLong(position, (Integer)paramValue);
}
}
// String, et al (this might break since this is a catch all for all other classes)
else {
for (Integer position : positions) {
statement.setString(position, new String(paramValue.toString()));
}
}
}
}
} else
statement = connection.prepareStatement(query);
return statement;
}
|
diff --git a/src/com/dmdirc/actions/CoreActionComponent.java b/src/com/dmdirc/actions/CoreActionComponent.java
index 26e8ed698..09abcd390 100644
--- a/src/com/dmdirc/actions/CoreActionComponent.java
+++ b/src/com/dmdirc/actions/CoreActionComponent.java
@@ -1,504 +1,502 @@
/*
* 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.actions;
import com.dmdirc.actions.interfaces.ActionComponent;
import com.dmdirc.Channel;
import com.dmdirc.FrameContainer;
import com.dmdirc.Query;
import com.dmdirc.Server;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.parser.irc.ChannelClientInfo;
import com.dmdirc.parser.irc.ClientInfo;
import com.dmdirc.ui.messages.Styliser;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.KeyStroke;
/**
* A CoreActionComponent represents a component of some object that the user can
* use as the subject of a condition within an action.
* @author chris
*/
public enum CoreActionComponent implements ActionComponent {
/** Returns the name of the server. */
SERVER_NAME {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((Server) argument).getName(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return Server.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "name"; }
},
/** Returns the network of the server. */
SERVER_NETWORK {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((Server) argument).getNetwork(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return Server.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "network"; }
},
/** Returns the away reason for the server. */
SERVER_MYAWAYREASON {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((Server) argument).getAwayMessage(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return Server.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "away reason"; }
},
/** Returns the channel umodes for the server. */
SERVER_CHANNELUMODES {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((Server) argument).getParser().getPrefixModes(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return Server.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "list of channel usermodes"; }
},
/** Returns the nickname for the server. */
SERVER_MYNICKNAME {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) {
final Server server = (Server) argument;
- if (server == null || server.getParser() == null || server.getParser().getMyself().isFake()) {
+ if (server == null || server.getParser() == null) {
Logger.appError(ErrorLevel.LOW, "SERVER_MYNICKNAME.get() called with null element",
new UnsupportedOperationException(
server == null ? "Server was null" :
- server.getParser() == null ? "Parser was null" :
- server.getParser().getMyself().isFake() ? "Myself was fake" :
- "Unknown"
+ server.getParser() == null ? "Parser was null" : "Unknown"
));
return "null";
} else {
return server.getParser().getMyself().getNickname();
}
}
/** {@inheritDoc} */
@Override
public Class appliesTo() { return Server.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "nickname"; }
},
/** Returns the name of the channel. */
CHANNEL_NAME {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((Channel) argument).getChannelInfo().getName(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return Channel.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "name"; }
},
/** Returns the notification colour of the channel. */
CHANNEL_COLOUR {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((Channel) argument).getNotification(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return Channel.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return Color.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "notification colour"; }
},
/** Returns the name of a client. */
CLIENT_NAME {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((ClientInfo) argument).getNickname(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return ClientInfo.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "nickname"; }
},
/** Returns the host of a client. */
CLIENT_HOST {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((ClientInfo) argument).getHost(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return ClientInfo.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "host"; }
},
/** Returns the name of a client. */
USER_NAME {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((ChannelClientInfo) argument).getNickname(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return ChannelClientInfo.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "nickname"; }
},
/** Returns the modes of a client. */
USER_MODES {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((ChannelClientInfo) argument).getChanModeStr(false); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return ChannelClientInfo.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "modes"; }
},
/** Returns the host of a client. */
USER_HOST {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((ChannelClientInfo) argument).getClient().getHost(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return ChannelClientInfo.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "host"; }
},
/** Returns the number of common channels the client is on. */
USER_COMCHANS {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return Integer.valueOf(((ChannelClientInfo) argument).getClient().channelCount()); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return ChannelClientInfo.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return Integer.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "number of common channels"; }
},
/** Returns the content of a string. */
STRING_STRING {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return argument; }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return String.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "content"; }
},
/** Returns the content of a string, stripped of formatting. */
STRING_STRIPPED {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return Styliser.stipControlCodes((String) argument); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return String.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "content (without formatting)"; }
},
/** Returns the length of a string. */
STRING_LENGTH {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((String) argument).length(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return String.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return Integer.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "length"; }
},
/** Returns the size of a string array. */
STRINGARRAY_LENGTH {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return Integer.valueOf(((String[]) argument).length); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return String[].class; }
/** {@inheritDoc} */
@Override
public Class getType() { return Integer.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "size"; }
},
/** Returns the readable representation of a date. */
CALENDAR_FULLSTRING {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((GregorianCalendar) argument).getTime().toString(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return Calendar.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "full date"; }
},
/** Returns the name of the key that was pressed. */
KEYEVENT_KEYNAME {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return KeyEvent.getKeyText(((KeyStroke) argument).getKeyCode()); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return KeyStroke.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "key name"; }
},
/** Returns the state of the control key for a key press event. */
KEYEVENT_CTRLSTATE {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) {
return Boolean.valueOf((((KeyStroke) argument).getModifiers() & KeyEvent.CTRL_DOWN_MASK) != 0);
}
/** {@inheritDoc} */
@Override
public Class appliesTo() { return KeyStroke.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return Boolean.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "control key state"; }
},
/** Returns the state of the shift key for a key press event. */
KEYEVENT_SHIFTSTATE {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) {
return Boolean.valueOf((((KeyStroke) argument).getModifiers() & KeyEvent.SHIFT_DOWN_MASK) != 0);
}
/** {@inheritDoc} */
@Override
public Class appliesTo() { return KeyStroke.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return Boolean.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "shift key state"; }
},
/** Returns the state of the shift key for a key press event. */
KEYEVENT_ALTSTATE {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) {
return Boolean.valueOf((((KeyStroke) argument).getModifiers() & KeyEvent.ALT_DOWN_MASK) != 0);
}
/** {@inheritDoc} */
@Override
public Class appliesTo() { return KeyStroke.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return Boolean.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "alt key state"; }
},
/** Returns the host of the query. */
QUERY_HOST {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((Query) argument).getHost(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return Query.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "host"; }
},
/** Returns the host of the query. */
QUERY_NICK {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((Query) argument).toString(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return Query.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "nick"; }
},
/** Returns the notification colour of the query. */
QUERY_COLOUR {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((Query) argument).getNotification(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return Query.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return Color.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "notification colour"; }
},
/** The name of a window. */
WINDOW_NAME {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((FrameContainer) argument).toString(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return FrameContainer.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return String.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "name"; }
},
/** Returns the notification colour of the window. */
WINDOW_COLOUR {
/** {@inheritDoc} */
@Override
public Object get(final Object argument) { return ((FrameContainer) argument).getNotification(); }
/** {@inheritDoc} */
@Override
public Class appliesTo() { return FrameContainer.class; }
/** {@inheritDoc} */
@Override
public Class getType() { return Color.class; }
/** {@inheritDoc} */
@Override
public String getName() { return "notification colour"; }
};
}
| false | true |
public Object get(final Object argument) {
final Server server = (Server) argument;
if (server == null || server.getParser() == null || server.getParser().getMyself().isFake()) {
Logger.appError(ErrorLevel.LOW, "SERVER_MYNICKNAME.get() called with null element",
new UnsupportedOperationException(
server == null ? "Server was null" :
server.getParser() == null ? "Parser was null" :
server.getParser().getMyself().isFake() ? "Myself was fake" :
"Unknown"
));
return "null";
} else {
return server.getParser().getMyself().getNickname();
}
}
|
public Object get(final Object argument) {
final Server server = (Server) argument;
if (server == null || server.getParser() == null) {
Logger.appError(ErrorLevel.LOW, "SERVER_MYNICKNAME.get() called with null element",
new UnsupportedOperationException(
server == null ? "Server was null" :
server.getParser() == null ? "Parser was null" : "Unknown"
));
return "null";
} else {
return server.getParser().getMyself().getNickname();
}
}
|
diff --git a/src/org/geometerplus/android/fbreader/preferences/PreferenceActivity.java b/src/org/geometerplus/android/fbreader/preferences/PreferenceActivity.java
index cb9d4e593..c7e8206dc 100644
--- a/src/org/geometerplus/android/fbreader/preferences/PreferenceActivity.java
+++ b/src/org/geometerplus/android/fbreader/preferences/PreferenceActivity.java
@@ -1,510 +1,514 @@
/*
* Copyright (C) 2009-2013 Geometer Plus <[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 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.android.fbreader.preferences;
import android.content.Intent;
import android.net.Uri;
import android.view.KeyEvent;
import org.geometerplus.zlibrary.core.application.ZLKeyBindings;
import org.geometerplus.zlibrary.core.options.ZLIntegerOption;
import org.geometerplus.zlibrary.core.options.ZLIntegerRangeOption;
import org.geometerplus.zlibrary.core.resources.ZLResource;
import org.geometerplus.zlibrary.text.view.style.*;
import org.geometerplus.zlibrary.ui.android.library.ZLAndroidLibrary;
import org.geometerplus.zlibrary.ui.android.view.AndroidFontUtil;
import org.geometerplus.zlibrary.ui.android.view.ZLAndroidPaintContext;
import org.geometerplus.fbreader.Paths;
import org.geometerplus.fbreader.bookmodel.FBTextKind;
import org.geometerplus.fbreader.fbreader.*;
import org.geometerplus.fbreader.tips.TipsManager;
import org.geometerplus.android.fbreader.FBReader;
import org.geometerplus.android.fbreader.DictionaryUtil;
import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
public class PreferenceActivity extends ZLPreferenceActivity {
private BookCollectionShadow myCollection = new BookCollectionShadow();
public PreferenceActivity() {
super("Preferences");
}
@Override
protected void onStart() {
super.onStart();
myCollection.bindToService(this, null);
}
@Override
protected void onStop() {
myCollection.unbind();
super.onStop();
}
@Override
protected void init(Intent intent) {
setResult(FBReader.RESULT_REPAINT);
final FBReaderApp fbReader = (FBReaderApp)FBReaderApp.Instance();
final ZLAndroidLibrary androidLibrary = (ZLAndroidLibrary)ZLAndroidLibrary.Instance();
final ColorProfile profile = fbReader.getColorProfile();
final Screen directoriesScreen = createPreferenceScreen("directories");
directoriesScreen.addPreference(new ZLStringOptionPreference(
this, Paths.BooksDirectoryOption(), directoriesScreen.Resource, "books"
) {
protected void setValue(String value) {
super.setValue(value);
myCollection.reset(false);
}
});
directoriesScreen.addOption(Paths.FontsDirectoryOption(), "fonts");
directoriesScreen.addOption(Paths.WallpapersDirectoryOption(), "wallpapers");
final Screen appearanceScreen = createPreferenceScreen("appearance");
appearanceScreen.addPreference(new LanguagePreference(
this, appearanceScreen.Resource, "language", ZLResource.languages()
) {
@Override
protected void init() {
setInitialValue(ZLResource.LanguageOption.getValue());
}
@Override
protected void setLanguage(String code) {
if (!code.equals(ZLResource.LanguageOption.getValue())) {
ZLResource.LanguageOption.setValue(code);
startActivity(new Intent(
Intent.ACTION_VIEW, Uri.parse("fbreader-action:preferences#appearance")
));
}
}
});
appearanceScreen.addPreference(new ZLStringChoicePreference(
this, appearanceScreen.Resource, "screenOrientation",
androidLibrary.OrientationOption, androidLibrary.allOrientations()
));
appearanceScreen.addPreference(new ZLBooleanPreference(
this,
fbReader.AllowScreenBrightnessAdjustmentOption,
appearanceScreen.Resource,
"allowScreenBrightnessAdjustment"
) {
private final int myLevel = androidLibrary.ScreenBrightnessLevelOption.getValue();
@Override
protected void onClick() {
super.onClick();
androidLibrary.ScreenBrightnessLevelOption.setValue(isChecked() ? myLevel : 0);
}
});
appearanceScreen.addPreference(new BatteryLevelToTurnScreenOffPreference(
this,
androidLibrary.BatteryLevelToTurnScreenOffOption,
appearanceScreen.Resource,
"dontTurnScreenOff"
));
/*
appearanceScreen.addPreference(new ZLBooleanPreference(
this,
androidLibrary.DontTurnScreenOffDuringChargingOption,
appearanceScreen.Resource,
"dontTurnScreenOffDuringCharging"
));
*/
appearanceScreen.addOption(androidLibrary.ShowStatusBarOption, "showStatusBar");
appearanceScreen.addOption(androidLibrary.DisableButtonLightsOption, "disableButtonLights");
final Screen textScreen = createPreferenceScreen("text");
final Screen fontPropertiesScreen = textScreen.createPreferenceScreen("fontProperties");
fontPropertiesScreen.addOption(ZLAndroidPaintContext.AntiAliasOption, "antiAlias");
fontPropertiesScreen.addOption(ZLAndroidPaintContext.DeviceKerningOption, "deviceKerning");
fontPropertiesScreen.addOption(ZLAndroidPaintContext.DitheringOption, "dithering");
fontPropertiesScreen.addOption(ZLAndroidPaintContext.SubpixelOption, "subpixel");
final ZLTextStyleCollection collection = ZLTextStyleCollection.Instance();
final ZLTextBaseStyle baseStyle = collection.getBaseStyle();
textScreen.addPreference(new FontOption(
this, textScreen.Resource, "font",
baseStyle.FontFamilyOption, false
));
textScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("fontSize"),
baseStyle.FontSizeOption
));
textScreen.addPreference(new FontStylePreference(
this, textScreen.Resource, "fontStyle",
baseStyle.BoldOption, baseStyle.ItalicOption
));
final ZLIntegerRangeOption spaceOption = baseStyle.LineSpaceOption;
final String[] spacings = new String[spaceOption.MaxValue - spaceOption.MinValue + 1];
for (int i = 0; i < spacings.length; ++i) {
final int val = spaceOption.MinValue + i;
spacings[i] = (char)(val / 10 + '0') + "." + (char)(val % 10 + '0');
}
textScreen.addPreference(new ZLChoicePreference(
this, textScreen.Resource, "lineSpacing",
spaceOption, spacings
));
final String[] alignments = { "left", "right", "center", "justify" };
textScreen.addPreference(new ZLChoicePreference(
this, textScreen.Resource, "alignment",
baseStyle.AlignmentOption, alignments
));
textScreen.addOption(baseStyle.AutoHyphenationOption, "autoHyphenations");
final Screen moreStylesScreen = textScreen.createPreferenceScreen("more");
byte styles[] = {
FBTextKind.REGULAR,
FBTextKind.TITLE,
FBTextKind.SECTION_TITLE,
FBTextKind.SUBTITLE,
FBTextKind.H1,
FBTextKind.H2,
FBTextKind.H3,
FBTextKind.H4,
FBTextKind.H5,
FBTextKind.H6,
FBTextKind.ANNOTATION,
FBTextKind.EPIGRAPH,
FBTextKind.AUTHOR,
FBTextKind.POEM_TITLE,
FBTextKind.STANZA,
FBTextKind.VERSE,
FBTextKind.CITE,
FBTextKind.INTERNAL_HYPERLINK,
FBTextKind.EXTERNAL_HYPERLINK,
FBTextKind.FOOTNOTE,
FBTextKind.ITALIC,
FBTextKind.EMPHASIS,
FBTextKind.BOLD,
FBTextKind.STRONG,
FBTextKind.DEFINITION,
FBTextKind.DEFINITION_DESCRIPTION,
FBTextKind.PREFORMATTED,
FBTextKind.CODE
};
for (int i = 0; i < styles.length; ++i) {
final ZLTextStyleDecoration decoration = collection.getDecoration(styles[i]);
if (decoration == null) {
continue;
}
ZLTextFullStyleDecoration fullDecoration =
decoration instanceof ZLTextFullStyleDecoration ?
(ZLTextFullStyleDecoration)decoration : null;
final Screen formatScreen = moreStylesScreen.createPreferenceScreen(decoration.getName());
formatScreen.addPreference(new FontOption(
this, textScreen.Resource, "font",
decoration.FontFamilyOption, true
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("fontSizeDifference"),
decoration.FontSizeDeltaOption
));
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "bold",
decoration.BoldOption
));
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "italic",
decoration.ItalicOption
));
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "underlined",
decoration.UnderlineOption
));
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "strikedThrough",
decoration.StrikeThroughOption
));
if (fullDecoration != null) {
final String[] allAlignments = { "unchanged", "left", "right", "center", "justify" };
formatScreen.addPreference(new ZLChoicePreference(
this, textScreen.Resource, "alignment",
fullDecoration.AlignmentOption, allAlignments
));
}
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "allowHyphenations",
decoration.AllowHyphenationsOption
));
if (fullDecoration != null) {
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("spaceBefore"),
fullDecoration.SpaceBeforeOption
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("spaceAfter"),
fullDecoration.SpaceAfterOption
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("leftIndent"),
fullDecoration.LeftIndentOption
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("rightIndent"),
fullDecoration.RightIndentOption
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("firstLineIndent"),
fullDecoration.FirstLineIndentDeltaOption
));
final ZLIntegerOption spacePercentOption = fullDecoration.LineSpacePercentOption;
final int[] spacingValues = new int[17];
final String[] spacingKeys = new String[17];
spacingValues[0] = -1;
spacingKeys[0] = "unchanged";
for (int j = 1; j < spacingValues.length; ++j) {
final int val = 4 + j;
spacingValues[j] = 10 * val;
spacingKeys[j] = (char)(val / 10 + '0') + "." + (char)(val % 10 + '0');
}
formatScreen.addPreference(new ZLIntegerChoicePreference(
this, textScreen.Resource, "lineSpacing",
spacePercentOption, spacingValues, spacingKeys
));
}
}
final ZLPreferenceSet footerPreferences = new ZLPreferenceSet();
final ZLPreferenceSet bgPreferences = new ZLPreferenceSet();
final Screen cssScreen = createPreferenceScreen("css");
cssScreen.addOption(collection.UseCSSFontSizeOption, "fontSize");
cssScreen.addOption(collection.UseCSSTextAlignmentOption, "textAlignment");
final Screen colorsScreen = createPreferenceScreen("colors");
colorsScreen.addPreference(new WallpaperPreference(
this, profile, colorsScreen.Resource, "background"
) {
@Override
protected void onDialogClosed(boolean result) {
super.onDialogClosed(result);
bgPreferences.setEnabled("".equals(getValue()));
}
});
bgPreferences.add(
colorsScreen.addOption(profile.BackgroundOption, "backgroundColor")
);
bgPreferences.setEnabled("".equals(profile.WallpaperOption.getValue()));
/*
colorsScreen.addOption(profile.SelectionBackgroundOption, "selectionBackground");
*/
colorsScreen.addOption(profile.HighlightingOption, "highlighting");
colorsScreen.addOption(profile.RegularTextOption, "text");
colorsScreen.addOption(profile.HyperlinkTextOption, "hyperlink");
colorsScreen.addOption(profile.VisitedHyperlinkTextOption, "hyperlinkVisited");
colorsScreen.addOption(profile.FooterFillOption, "footer");
colorsScreen.addOption(profile.SelectionBackgroundOption, "selectionBackground");
colorsScreen.addOption(profile.SelectionForegroundOption, "selectionForeground");
final Screen marginsScreen = createPreferenceScreen("margins");
marginsScreen.addPreference(new ZLIntegerRangePreference(
this, marginsScreen.Resource.getResource("left"),
fbReader.LeftMarginOption
));
marginsScreen.addPreference(new ZLIntegerRangePreference(
this, marginsScreen.Resource.getResource("right"),
fbReader.RightMarginOption
));
marginsScreen.addPreference(new ZLIntegerRangePreference(
this, marginsScreen.Resource.getResource("top"),
fbReader.TopMarginOption
));
marginsScreen.addPreference(new ZLIntegerRangePreference(
this, marginsScreen.Resource.getResource("bottom"),
fbReader.BottomMarginOption
));
final Screen statusLineScreen = createPreferenceScreen("scrollBar");
final String[] scrollBarTypes = {"hide", "show", "showAsProgress", "showAsFooter"};
statusLineScreen.addPreference(new ZLChoicePreference(
this, statusLineScreen.Resource, "scrollbarType",
fbReader.ScrollbarTypeOption, scrollBarTypes
) {
@Override
protected void onDialogClosed(boolean result) {
super.onDialogClosed(result);
footerPreferences.setEnabled(
findIndexOfValue(getValue()) == FBView.SCROLLBAR_SHOW_AS_FOOTER
);
}
});
footerPreferences.add(statusLineScreen.addPreference(new ZLIntegerRangePreference(
this, statusLineScreen.Resource.getResource("footerHeight"),
fbReader.FooterHeightOption
)));
footerPreferences.add(statusLineScreen.addOption(profile.FooterFillOption, "footerColor"));
footerPreferences.add(statusLineScreen.addOption(fbReader.FooterShowTOCMarksOption, "tocMarks"));
footerPreferences.add(statusLineScreen.addOption(fbReader.FooterShowClockOption, "showClock"));
footerPreferences.add(statusLineScreen.addOption(fbReader.FooterShowBatteryOption, "showBattery"));
footerPreferences.add(statusLineScreen.addOption(fbReader.FooterShowProgressOption, "showProgress"));
footerPreferences.add(statusLineScreen.addPreference(new FontOption(
this, statusLineScreen.Resource, "font",
fbReader.FooterFontOption, false
)));
footerPreferences.setEnabled(
fbReader.ScrollbarTypeOption.getValue() == FBView.SCROLLBAR_SHOW_AS_FOOTER
);
/*
final Screen colorProfileScreen = createPreferenceScreen("colorProfile");
final ZLResource resource = colorProfileScreen.Resource;
colorProfileScreen.setSummary(ColorProfilePreference.createTitle(resource, fbreader.getColorProfileName()));
for (String key : ColorProfile.names()) {
colorProfileScreen.addPreference(new ColorProfilePreference(
this, fbreader, colorProfileScreen, key, ColorProfilePreference.createTitle(resource, key)
));
}
*/
final ScrollingPreferences scrollingPreferences = ScrollingPreferences.Instance();
final ZLKeyBindings keyBindings = fbReader.keyBindings();
final Screen scrollingScreen = createPreferenceScreen("scrolling");
scrollingScreen.addOption(scrollingPreferences.FingerScrollingOption, "fingerScrolling");
scrollingScreen.addOption(fbReader.EnableDoubleTapOption, "enableDoubleTapDetection");
final ZLPreferenceSet volumeKeysPreferences = new ZLPreferenceSet();
scrollingScreen.addPreference(new ZLCheckBoxPreference(
this, scrollingScreen.Resource, "volumeKeys"
) {
{
setChecked(fbReader.hasActionForKey(KeyEvent.KEYCODE_VOLUME_UP, false));
}
@Override
protected void onClick() {
super.onClick();
if (isChecked()) {
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_DOWN, false, ActionCode.VOLUME_KEY_SCROLL_FORWARD);
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_UP, false, ActionCode.VOLUME_KEY_SCROLL_BACK);
} else {
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_DOWN, false, FBReaderApp.NoAction);
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_UP, false, FBReaderApp.NoAction);
}
volumeKeysPreferences.setEnabled(isChecked());
}
});
volumeKeysPreferences.add(scrollingScreen.addPreference(new ZLCheckBoxPreference(
this, scrollingScreen.Resource, "invertVolumeKeys"
) {
{
setChecked(ActionCode.VOLUME_KEY_SCROLL_FORWARD.equals(
keyBindings.getBinding(KeyEvent.KEYCODE_VOLUME_UP, false)
));
}
@Override
protected void onClick() {
super.onClick();
if (isChecked()) {
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_DOWN, false, ActionCode.VOLUME_KEY_SCROLL_BACK);
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_UP, false, ActionCode.VOLUME_KEY_SCROLL_FORWARD);
} else {
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_DOWN, false, ActionCode.VOLUME_KEY_SCROLL_FORWARD);
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_UP, false, ActionCode.VOLUME_KEY_SCROLL_BACK);
}
}
}));
volumeKeysPreferences.setEnabled(fbReader.hasActionForKey(KeyEvent.KEYCODE_VOLUME_UP, false));
scrollingScreen.addOption(scrollingPreferences.AnimationOption, "animation");
scrollingScreen.addPreference(new AnimationSpeedPreference(
this,
scrollingScreen.Resource,
"animationSpeed",
scrollingPreferences.AnimationSpeedOption
));
scrollingScreen.addOption(scrollingPreferences.HorizontalOption, "horizontal");
final Screen dictionaryScreen = createPreferenceScreen("dictionary");
- dictionaryScreen.addPreference(new DictionaryPreference(
- this,
- dictionaryScreen.Resource,
- "dictionary",
- DictionaryUtil.singleWordTranslatorOption(),
- DictionaryUtil.dictionaryInfos(this, true)
- ));
- dictionaryScreen.addPreference(new DictionaryPreference(
- this,
- dictionaryScreen.Resource,
- "translator",
- DictionaryUtil.multiWordTranslatorOption(),
- DictionaryUtil.dictionaryInfos(this, false)
- ));
+ try {
+ dictionaryScreen.addPreference(new DictionaryPreference(
+ this,
+ dictionaryScreen.Resource,
+ "dictionary",
+ DictionaryUtil.singleWordTranslatorOption(),
+ DictionaryUtil.dictionaryInfos(this, true)
+ ));
+ dictionaryScreen.addPreference(new DictionaryPreference(
+ this,
+ dictionaryScreen.Resource,
+ "translator",
+ DictionaryUtil.multiWordTranslatorOption(),
+ DictionaryUtil.dictionaryInfos(this, false)
+ ));
+ } catch (Exception e) {
+ // ignore: dictionary lists are not initialized yet
+ }
dictionaryScreen.addPreference(new ZLBooleanPreference(
this,
fbReader.NavigateAllWordsOption,
dictionaryScreen.Resource,
"navigateOverAllWords"
));
dictionaryScreen.addOption(fbReader.WordTappingActionOption, "tappingAction");
final Screen imagesScreen = createPreferenceScreen("images");
imagesScreen.addOption(fbReader.ImageTappingActionOption, "tappingAction");
imagesScreen.addOption(fbReader.FitImagesToScreenOption, "fitImagesToScreen");
imagesScreen.addOption(fbReader.ImageViewBackgroundOption, "backgroundColor");
final Screen cancelMenuScreen = createPreferenceScreen("cancelMenu");
cancelMenuScreen.addOption(fbReader.ShowLibraryInCancelMenuOption, "library");
cancelMenuScreen.addOption(fbReader.ShowNetworkLibraryInCancelMenuOption, "networkLibrary");
cancelMenuScreen.addOption(fbReader.ShowPreviousBookInCancelMenuOption, "previousBook");
cancelMenuScreen.addOption(fbReader.ShowPositionsInCancelMenuOption, "positions");
final String[] backKeyActions =
{ ActionCode.EXIT, ActionCode.SHOW_CANCEL_MENU };
cancelMenuScreen.addPreference(new ZLStringChoicePreference(
this, cancelMenuScreen.Resource, "backKeyAction",
keyBindings.getOption(KeyEvent.KEYCODE_BACK, false), backKeyActions
));
final String[] backKeyLongPressActions =
{ ActionCode.EXIT, ActionCode.SHOW_CANCEL_MENU, FBReaderApp.NoAction };
cancelMenuScreen.addPreference(new ZLStringChoicePreference(
this, cancelMenuScreen.Resource, "backKeyLongPressAction",
keyBindings.getOption(KeyEvent.KEYCODE_BACK, true), backKeyLongPressActions
));
final Screen tipsScreen = createPreferenceScreen("tips");
tipsScreen.addOption(TipsManager.Instance().ShowTipsOption, "showTips");
final Screen aboutScreen = createPreferenceScreen("about");
aboutScreen.addPreference(new InfoPreference(
this,
aboutScreen.Resource.getResource("version").getValue(),
androidLibrary.getFullVersionName()
));
aboutScreen.addPreference(new UrlPreference(this, aboutScreen.Resource, "site"));
aboutScreen.addPreference(new UrlPreference(this, aboutScreen.Resource, "email"));
aboutScreen.addPreference(new UrlPreference(this, aboutScreen.Resource, "twitter"));
}
}
| true | true |
protected void init(Intent intent) {
setResult(FBReader.RESULT_REPAINT);
final FBReaderApp fbReader = (FBReaderApp)FBReaderApp.Instance();
final ZLAndroidLibrary androidLibrary = (ZLAndroidLibrary)ZLAndroidLibrary.Instance();
final ColorProfile profile = fbReader.getColorProfile();
final Screen directoriesScreen = createPreferenceScreen("directories");
directoriesScreen.addPreference(new ZLStringOptionPreference(
this, Paths.BooksDirectoryOption(), directoriesScreen.Resource, "books"
) {
protected void setValue(String value) {
super.setValue(value);
myCollection.reset(false);
}
});
directoriesScreen.addOption(Paths.FontsDirectoryOption(), "fonts");
directoriesScreen.addOption(Paths.WallpapersDirectoryOption(), "wallpapers");
final Screen appearanceScreen = createPreferenceScreen("appearance");
appearanceScreen.addPreference(new LanguagePreference(
this, appearanceScreen.Resource, "language", ZLResource.languages()
) {
@Override
protected void init() {
setInitialValue(ZLResource.LanguageOption.getValue());
}
@Override
protected void setLanguage(String code) {
if (!code.equals(ZLResource.LanguageOption.getValue())) {
ZLResource.LanguageOption.setValue(code);
startActivity(new Intent(
Intent.ACTION_VIEW, Uri.parse("fbreader-action:preferences#appearance")
));
}
}
});
appearanceScreen.addPreference(new ZLStringChoicePreference(
this, appearanceScreen.Resource, "screenOrientation",
androidLibrary.OrientationOption, androidLibrary.allOrientations()
));
appearanceScreen.addPreference(new ZLBooleanPreference(
this,
fbReader.AllowScreenBrightnessAdjustmentOption,
appearanceScreen.Resource,
"allowScreenBrightnessAdjustment"
) {
private final int myLevel = androidLibrary.ScreenBrightnessLevelOption.getValue();
@Override
protected void onClick() {
super.onClick();
androidLibrary.ScreenBrightnessLevelOption.setValue(isChecked() ? myLevel : 0);
}
});
appearanceScreen.addPreference(new BatteryLevelToTurnScreenOffPreference(
this,
androidLibrary.BatteryLevelToTurnScreenOffOption,
appearanceScreen.Resource,
"dontTurnScreenOff"
));
/*
appearanceScreen.addPreference(new ZLBooleanPreference(
this,
androidLibrary.DontTurnScreenOffDuringChargingOption,
appearanceScreen.Resource,
"dontTurnScreenOffDuringCharging"
));
*/
appearanceScreen.addOption(androidLibrary.ShowStatusBarOption, "showStatusBar");
appearanceScreen.addOption(androidLibrary.DisableButtonLightsOption, "disableButtonLights");
final Screen textScreen = createPreferenceScreen("text");
final Screen fontPropertiesScreen = textScreen.createPreferenceScreen("fontProperties");
fontPropertiesScreen.addOption(ZLAndroidPaintContext.AntiAliasOption, "antiAlias");
fontPropertiesScreen.addOption(ZLAndroidPaintContext.DeviceKerningOption, "deviceKerning");
fontPropertiesScreen.addOption(ZLAndroidPaintContext.DitheringOption, "dithering");
fontPropertiesScreen.addOption(ZLAndroidPaintContext.SubpixelOption, "subpixel");
final ZLTextStyleCollection collection = ZLTextStyleCollection.Instance();
final ZLTextBaseStyle baseStyle = collection.getBaseStyle();
textScreen.addPreference(new FontOption(
this, textScreen.Resource, "font",
baseStyle.FontFamilyOption, false
));
textScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("fontSize"),
baseStyle.FontSizeOption
));
textScreen.addPreference(new FontStylePreference(
this, textScreen.Resource, "fontStyle",
baseStyle.BoldOption, baseStyle.ItalicOption
));
final ZLIntegerRangeOption spaceOption = baseStyle.LineSpaceOption;
final String[] spacings = new String[spaceOption.MaxValue - spaceOption.MinValue + 1];
for (int i = 0; i < spacings.length; ++i) {
final int val = spaceOption.MinValue + i;
spacings[i] = (char)(val / 10 + '0') + "." + (char)(val % 10 + '0');
}
textScreen.addPreference(new ZLChoicePreference(
this, textScreen.Resource, "lineSpacing",
spaceOption, spacings
));
final String[] alignments = { "left", "right", "center", "justify" };
textScreen.addPreference(new ZLChoicePreference(
this, textScreen.Resource, "alignment",
baseStyle.AlignmentOption, alignments
));
textScreen.addOption(baseStyle.AutoHyphenationOption, "autoHyphenations");
final Screen moreStylesScreen = textScreen.createPreferenceScreen("more");
byte styles[] = {
FBTextKind.REGULAR,
FBTextKind.TITLE,
FBTextKind.SECTION_TITLE,
FBTextKind.SUBTITLE,
FBTextKind.H1,
FBTextKind.H2,
FBTextKind.H3,
FBTextKind.H4,
FBTextKind.H5,
FBTextKind.H6,
FBTextKind.ANNOTATION,
FBTextKind.EPIGRAPH,
FBTextKind.AUTHOR,
FBTextKind.POEM_TITLE,
FBTextKind.STANZA,
FBTextKind.VERSE,
FBTextKind.CITE,
FBTextKind.INTERNAL_HYPERLINK,
FBTextKind.EXTERNAL_HYPERLINK,
FBTextKind.FOOTNOTE,
FBTextKind.ITALIC,
FBTextKind.EMPHASIS,
FBTextKind.BOLD,
FBTextKind.STRONG,
FBTextKind.DEFINITION,
FBTextKind.DEFINITION_DESCRIPTION,
FBTextKind.PREFORMATTED,
FBTextKind.CODE
};
for (int i = 0; i < styles.length; ++i) {
final ZLTextStyleDecoration decoration = collection.getDecoration(styles[i]);
if (decoration == null) {
continue;
}
ZLTextFullStyleDecoration fullDecoration =
decoration instanceof ZLTextFullStyleDecoration ?
(ZLTextFullStyleDecoration)decoration : null;
final Screen formatScreen = moreStylesScreen.createPreferenceScreen(decoration.getName());
formatScreen.addPreference(new FontOption(
this, textScreen.Resource, "font",
decoration.FontFamilyOption, true
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("fontSizeDifference"),
decoration.FontSizeDeltaOption
));
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "bold",
decoration.BoldOption
));
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "italic",
decoration.ItalicOption
));
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "underlined",
decoration.UnderlineOption
));
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "strikedThrough",
decoration.StrikeThroughOption
));
if (fullDecoration != null) {
final String[] allAlignments = { "unchanged", "left", "right", "center", "justify" };
formatScreen.addPreference(new ZLChoicePreference(
this, textScreen.Resource, "alignment",
fullDecoration.AlignmentOption, allAlignments
));
}
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "allowHyphenations",
decoration.AllowHyphenationsOption
));
if (fullDecoration != null) {
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("spaceBefore"),
fullDecoration.SpaceBeforeOption
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("spaceAfter"),
fullDecoration.SpaceAfterOption
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("leftIndent"),
fullDecoration.LeftIndentOption
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("rightIndent"),
fullDecoration.RightIndentOption
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("firstLineIndent"),
fullDecoration.FirstLineIndentDeltaOption
));
final ZLIntegerOption spacePercentOption = fullDecoration.LineSpacePercentOption;
final int[] spacingValues = new int[17];
final String[] spacingKeys = new String[17];
spacingValues[0] = -1;
spacingKeys[0] = "unchanged";
for (int j = 1; j < spacingValues.length; ++j) {
final int val = 4 + j;
spacingValues[j] = 10 * val;
spacingKeys[j] = (char)(val / 10 + '0') + "." + (char)(val % 10 + '0');
}
formatScreen.addPreference(new ZLIntegerChoicePreference(
this, textScreen.Resource, "lineSpacing",
spacePercentOption, spacingValues, spacingKeys
));
}
}
final ZLPreferenceSet footerPreferences = new ZLPreferenceSet();
final ZLPreferenceSet bgPreferences = new ZLPreferenceSet();
final Screen cssScreen = createPreferenceScreen("css");
cssScreen.addOption(collection.UseCSSFontSizeOption, "fontSize");
cssScreen.addOption(collection.UseCSSTextAlignmentOption, "textAlignment");
final Screen colorsScreen = createPreferenceScreen("colors");
colorsScreen.addPreference(new WallpaperPreference(
this, profile, colorsScreen.Resource, "background"
) {
@Override
protected void onDialogClosed(boolean result) {
super.onDialogClosed(result);
bgPreferences.setEnabled("".equals(getValue()));
}
});
bgPreferences.add(
colorsScreen.addOption(profile.BackgroundOption, "backgroundColor")
);
bgPreferences.setEnabled("".equals(profile.WallpaperOption.getValue()));
/*
colorsScreen.addOption(profile.SelectionBackgroundOption, "selectionBackground");
*/
colorsScreen.addOption(profile.HighlightingOption, "highlighting");
colorsScreen.addOption(profile.RegularTextOption, "text");
colorsScreen.addOption(profile.HyperlinkTextOption, "hyperlink");
colorsScreen.addOption(profile.VisitedHyperlinkTextOption, "hyperlinkVisited");
colorsScreen.addOption(profile.FooterFillOption, "footer");
colorsScreen.addOption(profile.SelectionBackgroundOption, "selectionBackground");
colorsScreen.addOption(profile.SelectionForegroundOption, "selectionForeground");
final Screen marginsScreen = createPreferenceScreen("margins");
marginsScreen.addPreference(new ZLIntegerRangePreference(
this, marginsScreen.Resource.getResource("left"),
fbReader.LeftMarginOption
));
marginsScreen.addPreference(new ZLIntegerRangePreference(
this, marginsScreen.Resource.getResource("right"),
fbReader.RightMarginOption
));
marginsScreen.addPreference(new ZLIntegerRangePreference(
this, marginsScreen.Resource.getResource("top"),
fbReader.TopMarginOption
));
marginsScreen.addPreference(new ZLIntegerRangePreference(
this, marginsScreen.Resource.getResource("bottom"),
fbReader.BottomMarginOption
));
final Screen statusLineScreen = createPreferenceScreen("scrollBar");
final String[] scrollBarTypes = {"hide", "show", "showAsProgress", "showAsFooter"};
statusLineScreen.addPreference(new ZLChoicePreference(
this, statusLineScreen.Resource, "scrollbarType",
fbReader.ScrollbarTypeOption, scrollBarTypes
) {
@Override
protected void onDialogClosed(boolean result) {
super.onDialogClosed(result);
footerPreferences.setEnabled(
findIndexOfValue(getValue()) == FBView.SCROLLBAR_SHOW_AS_FOOTER
);
}
});
footerPreferences.add(statusLineScreen.addPreference(new ZLIntegerRangePreference(
this, statusLineScreen.Resource.getResource("footerHeight"),
fbReader.FooterHeightOption
)));
footerPreferences.add(statusLineScreen.addOption(profile.FooterFillOption, "footerColor"));
footerPreferences.add(statusLineScreen.addOption(fbReader.FooterShowTOCMarksOption, "tocMarks"));
footerPreferences.add(statusLineScreen.addOption(fbReader.FooterShowClockOption, "showClock"));
footerPreferences.add(statusLineScreen.addOption(fbReader.FooterShowBatteryOption, "showBattery"));
footerPreferences.add(statusLineScreen.addOption(fbReader.FooterShowProgressOption, "showProgress"));
footerPreferences.add(statusLineScreen.addPreference(new FontOption(
this, statusLineScreen.Resource, "font",
fbReader.FooterFontOption, false
)));
footerPreferences.setEnabled(
fbReader.ScrollbarTypeOption.getValue() == FBView.SCROLLBAR_SHOW_AS_FOOTER
);
/*
final Screen colorProfileScreen = createPreferenceScreen("colorProfile");
final ZLResource resource = colorProfileScreen.Resource;
colorProfileScreen.setSummary(ColorProfilePreference.createTitle(resource, fbreader.getColorProfileName()));
for (String key : ColorProfile.names()) {
colorProfileScreen.addPreference(new ColorProfilePreference(
this, fbreader, colorProfileScreen, key, ColorProfilePreference.createTitle(resource, key)
));
}
*/
final ScrollingPreferences scrollingPreferences = ScrollingPreferences.Instance();
final ZLKeyBindings keyBindings = fbReader.keyBindings();
final Screen scrollingScreen = createPreferenceScreen("scrolling");
scrollingScreen.addOption(scrollingPreferences.FingerScrollingOption, "fingerScrolling");
scrollingScreen.addOption(fbReader.EnableDoubleTapOption, "enableDoubleTapDetection");
final ZLPreferenceSet volumeKeysPreferences = new ZLPreferenceSet();
scrollingScreen.addPreference(new ZLCheckBoxPreference(
this, scrollingScreen.Resource, "volumeKeys"
) {
{
setChecked(fbReader.hasActionForKey(KeyEvent.KEYCODE_VOLUME_UP, false));
}
@Override
protected void onClick() {
super.onClick();
if (isChecked()) {
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_DOWN, false, ActionCode.VOLUME_KEY_SCROLL_FORWARD);
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_UP, false, ActionCode.VOLUME_KEY_SCROLL_BACK);
} else {
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_DOWN, false, FBReaderApp.NoAction);
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_UP, false, FBReaderApp.NoAction);
}
volumeKeysPreferences.setEnabled(isChecked());
}
});
volumeKeysPreferences.add(scrollingScreen.addPreference(new ZLCheckBoxPreference(
this, scrollingScreen.Resource, "invertVolumeKeys"
) {
{
setChecked(ActionCode.VOLUME_KEY_SCROLL_FORWARD.equals(
keyBindings.getBinding(KeyEvent.KEYCODE_VOLUME_UP, false)
));
}
@Override
protected void onClick() {
super.onClick();
if (isChecked()) {
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_DOWN, false, ActionCode.VOLUME_KEY_SCROLL_BACK);
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_UP, false, ActionCode.VOLUME_KEY_SCROLL_FORWARD);
} else {
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_DOWN, false, ActionCode.VOLUME_KEY_SCROLL_FORWARD);
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_UP, false, ActionCode.VOLUME_KEY_SCROLL_BACK);
}
}
}));
volumeKeysPreferences.setEnabled(fbReader.hasActionForKey(KeyEvent.KEYCODE_VOLUME_UP, false));
scrollingScreen.addOption(scrollingPreferences.AnimationOption, "animation");
scrollingScreen.addPreference(new AnimationSpeedPreference(
this,
scrollingScreen.Resource,
"animationSpeed",
scrollingPreferences.AnimationSpeedOption
));
scrollingScreen.addOption(scrollingPreferences.HorizontalOption, "horizontal");
final Screen dictionaryScreen = createPreferenceScreen("dictionary");
dictionaryScreen.addPreference(new DictionaryPreference(
this,
dictionaryScreen.Resource,
"dictionary",
DictionaryUtil.singleWordTranslatorOption(),
DictionaryUtil.dictionaryInfos(this, true)
));
dictionaryScreen.addPreference(new DictionaryPreference(
this,
dictionaryScreen.Resource,
"translator",
DictionaryUtil.multiWordTranslatorOption(),
DictionaryUtil.dictionaryInfos(this, false)
));
dictionaryScreen.addPreference(new ZLBooleanPreference(
this,
fbReader.NavigateAllWordsOption,
dictionaryScreen.Resource,
"navigateOverAllWords"
));
dictionaryScreen.addOption(fbReader.WordTappingActionOption, "tappingAction");
final Screen imagesScreen = createPreferenceScreen("images");
imagesScreen.addOption(fbReader.ImageTappingActionOption, "tappingAction");
imagesScreen.addOption(fbReader.FitImagesToScreenOption, "fitImagesToScreen");
imagesScreen.addOption(fbReader.ImageViewBackgroundOption, "backgroundColor");
final Screen cancelMenuScreen = createPreferenceScreen("cancelMenu");
cancelMenuScreen.addOption(fbReader.ShowLibraryInCancelMenuOption, "library");
cancelMenuScreen.addOption(fbReader.ShowNetworkLibraryInCancelMenuOption, "networkLibrary");
cancelMenuScreen.addOption(fbReader.ShowPreviousBookInCancelMenuOption, "previousBook");
cancelMenuScreen.addOption(fbReader.ShowPositionsInCancelMenuOption, "positions");
final String[] backKeyActions =
{ ActionCode.EXIT, ActionCode.SHOW_CANCEL_MENU };
cancelMenuScreen.addPreference(new ZLStringChoicePreference(
this, cancelMenuScreen.Resource, "backKeyAction",
keyBindings.getOption(KeyEvent.KEYCODE_BACK, false), backKeyActions
));
final String[] backKeyLongPressActions =
{ ActionCode.EXIT, ActionCode.SHOW_CANCEL_MENU, FBReaderApp.NoAction };
cancelMenuScreen.addPreference(new ZLStringChoicePreference(
this, cancelMenuScreen.Resource, "backKeyLongPressAction",
keyBindings.getOption(KeyEvent.KEYCODE_BACK, true), backKeyLongPressActions
));
final Screen tipsScreen = createPreferenceScreen("tips");
tipsScreen.addOption(TipsManager.Instance().ShowTipsOption, "showTips");
final Screen aboutScreen = createPreferenceScreen("about");
aboutScreen.addPreference(new InfoPreference(
this,
aboutScreen.Resource.getResource("version").getValue(),
androidLibrary.getFullVersionName()
));
aboutScreen.addPreference(new UrlPreference(this, aboutScreen.Resource, "site"));
aboutScreen.addPreference(new UrlPreference(this, aboutScreen.Resource, "email"));
aboutScreen.addPreference(new UrlPreference(this, aboutScreen.Resource, "twitter"));
}
|
protected void init(Intent intent) {
setResult(FBReader.RESULT_REPAINT);
final FBReaderApp fbReader = (FBReaderApp)FBReaderApp.Instance();
final ZLAndroidLibrary androidLibrary = (ZLAndroidLibrary)ZLAndroidLibrary.Instance();
final ColorProfile profile = fbReader.getColorProfile();
final Screen directoriesScreen = createPreferenceScreen("directories");
directoriesScreen.addPreference(new ZLStringOptionPreference(
this, Paths.BooksDirectoryOption(), directoriesScreen.Resource, "books"
) {
protected void setValue(String value) {
super.setValue(value);
myCollection.reset(false);
}
});
directoriesScreen.addOption(Paths.FontsDirectoryOption(), "fonts");
directoriesScreen.addOption(Paths.WallpapersDirectoryOption(), "wallpapers");
final Screen appearanceScreen = createPreferenceScreen("appearance");
appearanceScreen.addPreference(new LanguagePreference(
this, appearanceScreen.Resource, "language", ZLResource.languages()
) {
@Override
protected void init() {
setInitialValue(ZLResource.LanguageOption.getValue());
}
@Override
protected void setLanguage(String code) {
if (!code.equals(ZLResource.LanguageOption.getValue())) {
ZLResource.LanguageOption.setValue(code);
startActivity(new Intent(
Intent.ACTION_VIEW, Uri.parse("fbreader-action:preferences#appearance")
));
}
}
});
appearanceScreen.addPreference(new ZLStringChoicePreference(
this, appearanceScreen.Resource, "screenOrientation",
androidLibrary.OrientationOption, androidLibrary.allOrientations()
));
appearanceScreen.addPreference(new ZLBooleanPreference(
this,
fbReader.AllowScreenBrightnessAdjustmentOption,
appearanceScreen.Resource,
"allowScreenBrightnessAdjustment"
) {
private final int myLevel = androidLibrary.ScreenBrightnessLevelOption.getValue();
@Override
protected void onClick() {
super.onClick();
androidLibrary.ScreenBrightnessLevelOption.setValue(isChecked() ? myLevel : 0);
}
});
appearanceScreen.addPreference(new BatteryLevelToTurnScreenOffPreference(
this,
androidLibrary.BatteryLevelToTurnScreenOffOption,
appearanceScreen.Resource,
"dontTurnScreenOff"
));
/*
appearanceScreen.addPreference(new ZLBooleanPreference(
this,
androidLibrary.DontTurnScreenOffDuringChargingOption,
appearanceScreen.Resource,
"dontTurnScreenOffDuringCharging"
));
*/
appearanceScreen.addOption(androidLibrary.ShowStatusBarOption, "showStatusBar");
appearanceScreen.addOption(androidLibrary.DisableButtonLightsOption, "disableButtonLights");
final Screen textScreen = createPreferenceScreen("text");
final Screen fontPropertiesScreen = textScreen.createPreferenceScreen("fontProperties");
fontPropertiesScreen.addOption(ZLAndroidPaintContext.AntiAliasOption, "antiAlias");
fontPropertiesScreen.addOption(ZLAndroidPaintContext.DeviceKerningOption, "deviceKerning");
fontPropertiesScreen.addOption(ZLAndroidPaintContext.DitheringOption, "dithering");
fontPropertiesScreen.addOption(ZLAndroidPaintContext.SubpixelOption, "subpixel");
final ZLTextStyleCollection collection = ZLTextStyleCollection.Instance();
final ZLTextBaseStyle baseStyle = collection.getBaseStyle();
textScreen.addPreference(new FontOption(
this, textScreen.Resource, "font",
baseStyle.FontFamilyOption, false
));
textScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("fontSize"),
baseStyle.FontSizeOption
));
textScreen.addPreference(new FontStylePreference(
this, textScreen.Resource, "fontStyle",
baseStyle.BoldOption, baseStyle.ItalicOption
));
final ZLIntegerRangeOption spaceOption = baseStyle.LineSpaceOption;
final String[] spacings = new String[spaceOption.MaxValue - spaceOption.MinValue + 1];
for (int i = 0; i < spacings.length; ++i) {
final int val = spaceOption.MinValue + i;
spacings[i] = (char)(val / 10 + '0') + "." + (char)(val % 10 + '0');
}
textScreen.addPreference(new ZLChoicePreference(
this, textScreen.Resource, "lineSpacing",
spaceOption, spacings
));
final String[] alignments = { "left", "right", "center", "justify" };
textScreen.addPreference(new ZLChoicePreference(
this, textScreen.Resource, "alignment",
baseStyle.AlignmentOption, alignments
));
textScreen.addOption(baseStyle.AutoHyphenationOption, "autoHyphenations");
final Screen moreStylesScreen = textScreen.createPreferenceScreen("more");
byte styles[] = {
FBTextKind.REGULAR,
FBTextKind.TITLE,
FBTextKind.SECTION_TITLE,
FBTextKind.SUBTITLE,
FBTextKind.H1,
FBTextKind.H2,
FBTextKind.H3,
FBTextKind.H4,
FBTextKind.H5,
FBTextKind.H6,
FBTextKind.ANNOTATION,
FBTextKind.EPIGRAPH,
FBTextKind.AUTHOR,
FBTextKind.POEM_TITLE,
FBTextKind.STANZA,
FBTextKind.VERSE,
FBTextKind.CITE,
FBTextKind.INTERNAL_HYPERLINK,
FBTextKind.EXTERNAL_HYPERLINK,
FBTextKind.FOOTNOTE,
FBTextKind.ITALIC,
FBTextKind.EMPHASIS,
FBTextKind.BOLD,
FBTextKind.STRONG,
FBTextKind.DEFINITION,
FBTextKind.DEFINITION_DESCRIPTION,
FBTextKind.PREFORMATTED,
FBTextKind.CODE
};
for (int i = 0; i < styles.length; ++i) {
final ZLTextStyleDecoration decoration = collection.getDecoration(styles[i]);
if (decoration == null) {
continue;
}
ZLTextFullStyleDecoration fullDecoration =
decoration instanceof ZLTextFullStyleDecoration ?
(ZLTextFullStyleDecoration)decoration : null;
final Screen formatScreen = moreStylesScreen.createPreferenceScreen(decoration.getName());
formatScreen.addPreference(new FontOption(
this, textScreen.Resource, "font",
decoration.FontFamilyOption, true
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("fontSizeDifference"),
decoration.FontSizeDeltaOption
));
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "bold",
decoration.BoldOption
));
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "italic",
decoration.ItalicOption
));
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "underlined",
decoration.UnderlineOption
));
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "strikedThrough",
decoration.StrikeThroughOption
));
if (fullDecoration != null) {
final String[] allAlignments = { "unchanged", "left", "right", "center", "justify" };
formatScreen.addPreference(new ZLChoicePreference(
this, textScreen.Resource, "alignment",
fullDecoration.AlignmentOption, allAlignments
));
}
formatScreen.addPreference(new ZLBoolean3Preference(
this, textScreen.Resource, "allowHyphenations",
decoration.AllowHyphenationsOption
));
if (fullDecoration != null) {
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("spaceBefore"),
fullDecoration.SpaceBeforeOption
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("spaceAfter"),
fullDecoration.SpaceAfterOption
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("leftIndent"),
fullDecoration.LeftIndentOption
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("rightIndent"),
fullDecoration.RightIndentOption
));
formatScreen.addPreference(new ZLIntegerRangePreference(
this, textScreen.Resource.getResource("firstLineIndent"),
fullDecoration.FirstLineIndentDeltaOption
));
final ZLIntegerOption spacePercentOption = fullDecoration.LineSpacePercentOption;
final int[] spacingValues = new int[17];
final String[] spacingKeys = new String[17];
spacingValues[0] = -1;
spacingKeys[0] = "unchanged";
for (int j = 1; j < spacingValues.length; ++j) {
final int val = 4 + j;
spacingValues[j] = 10 * val;
spacingKeys[j] = (char)(val / 10 + '0') + "." + (char)(val % 10 + '0');
}
formatScreen.addPreference(new ZLIntegerChoicePreference(
this, textScreen.Resource, "lineSpacing",
spacePercentOption, spacingValues, spacingKeys
));
}
}
final ZLPreferenceSet footerPreferences = new ZLPreferenceSet();
final ZLPreferenceSet bgPreferences = new ZLPreferenceSet();
final Screen cssScreen = createPreferenceScreen("css");
cssScreen.addOption(collection.UseCSSFontSizeOption, "fontSize");
cssScreen.addOption(collection.UseCSSTextAlignmentOption, "textAlignment");
final Screen colorsScreen = createPreferenceScreen("colors");
colorsScreen.addPreference(new WallpaperPreference(
this, profile, colorsScreen.Resource, "background"
) {
@Override
protected void onDialogClosed(boolean result) {
super.onDialogClosed(result);
bgPreferences.setEnabled("".equals(getValue()));
}
});
bgPreferences.add(
colorsScreen.addOption(profile.BackgroundOption, "backgroundColor")
);
bgPreferences.setEnabled("".equals(profile.WallpaperOption.getValue()));
/*
colorsScreen.addOption(profile.SelectionBackgroundOption, "selectionBackground");
*/
colorsScreen.addOption(profile.HighlightingOption, "highlighting");
colorsScreen.addOption(profile.RegularTextOption, "text");
colorsScreen.addOption(profile.HyperlinkTextOption, "hyperlink");
colorsScreen.addOption(profile.VisitedHyperlinkTextOption, "hyperlinkVisited");
colorsScreen.addOption(profile.FooterFillOption, "footer");
colorsScreen.addOption(profile.SelectionBackgroundOption, "selectionBackground");
colorsScreen.addOption(profile.SelectionForegroundOption, "selectionForeground");
final Screen marginsScreen = createPreferenceScreen("margins");
marginsScreen.addPreference(new ZLIntegerRangePreference(
this, marginsScreen.Resource.getResource("left"),
fbReader.LeftMarginOption
));
marginsScreen.addPreference(new ZLIntegerRangePreference(
this, marginsScreen.Resource.getResource("right"),
fbReader.RightMarginOption
));
marginsScreen.addPreference(new ZLIntegerRangePreference(
this, marginsScreen.Resource.getResource("top"),
fbReader.TopMarginOption
));
marginsScreen.addPreference(new ZLIntegerRangePreference(
this, marginsScreen.Resource.getResource("bottom"),
fbReader.BottomMarginOption
));
final Screen statusLineScreen = createPreferenceScreen("scrollBar");
final String[] scrollBarTypes = {"hide", "show", "showAsProgress", "showAsFooter"};
statusLineScreen.addPreference(new ZLChoicePreference(
this, statusLineScreen.Resource, "scrollbarType",
fbReader.ScrollbarTypeOption, scrollBarTypes
) {
@Override
protected void onDialogClosed(boolean result) {
super.onDialogClosed(result);
footerPreferences.setEnabled(
findIndexOfValue(getValue()) == FBView.SCROLLBAR_SHOW_AS_FOOTER
);
}
});
footerPreferences.add(statusLineScreen.addPreference(new ZLIntegerRangePreference(
this, statusLineScreen.Resource.getResource("footerHeight"),
fbReader.FooterHeightOption
)));
footerPreferences.add(statusLineScreen.addOption(profile.FooterFillOption, "footerColor"));
footerPreferences.add(statusLineScreen.addOption(fbReader.FooterShowTOCMarksOption, "tocMarks"));
footerPreferences.add(statusLineScreen.addOption(fbReader.FooterShowClockOption, "showClock"));
footerPreferences.add(statusLineScreen.addOption(fbReader.FooterShowBatteryOption, "showBattery"));
footerPreferences.add(statusLineScreen.addOption(fbReader.FooterShowProgressOption, "showProgress"));
footerPreferences.add(statusLineScreen.addPreference(new FontOption(
this, statusLineScreen.Resource, "font",
fbReader.FooterFontOption, false
)));
footerPreferences.setEnabled(
fbReader.ScrollbarTypeOption.getValue() == FBView.SCROLLBAR_SHOW_AS_FOOTER
);
/*
final Screen colorProfileScreen = createPreferenceScreen("colorProfile");
final ZLResource resource = colorProfileScreen.Resource;
colorProfileScreen.setSummary(ColorProfilePreference.createTitle(resource, fbreader.getColorProfileName()));
for (String key : ColorProfile.names()) {
colorProfileScreen.addPreference(new ColorProfilePreference(
this, fbreader, colorProfileScreen, key, ColorProfilePreference.createTitle(resource, key)
));
}
*/
final ScrollingPreferences scrollingPreferences = ScrollingPreferences.Instance();
final ZLKeyBindings keyBindings = fbReader.keyBindings();
final Screen scrollingScreen = createPreferenceScreen("scrolling");
scrollingScreen.addOption(scrollingPreferences.FingerScrollingOption, "fingerScrolling");
scrollingScreen.addOption(fbReader.EnableDoubleTapOption, "enableDoubleTapDetection");
final ZLPreferenceSet volumeKeysPreferences = new ZLPreferenceSet();
scrollingScreen.addPreference(new ZLCheckBoxPreference(
this, scrollingScreen.Resource, "volumeKeys"
) {
{
setChecked(fbReader.hasActionForKey(KeyEvent.KEYCODE_VOLUME_UP, false));
}
@Override
protected void onClick() {
super.onClick();
if (isChecked()) {
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_DOWN, false, ActionCode.VOLUME_KEY_SCROLL_FORWARD);
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_UP, false, ActionCode.VOLUME_KEY_SCROLL_BACK);
} else {
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_DOWN, false, FBReaderApp.NoAction);
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_UP, false, FBReaderApp.NoAction);
}
volumeKeysPreferences.setEnabled(isChecked());
}
});
volumeKeysPreferences.add(scrollingScreen.addPreference(new ZLCheckBoxPreference(
this, scrollingScreen.Resource, "invertVolumeKeys"
) {
{
setChecked(ActionCode.VOLUME_KEY_SCROLL_FORWARD.equals(
keyBindings.getBinding(KeyEvent.KEYCODE_VOLUME_UP, false)
));
}
@Override
protected void onClick() {
super.onClick();
if (isChecked()) {
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_DOWN, false, ActionCode.VOLUME_KEY_SCROLL_BACK);
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_UP, false, ActionCode.VOLUME_KEY_SCROLL_FORWARD);
} else {
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_DOWN, false, ActionCode.VOLUME_KEY_SCROLL_FORWARD);
keyBindings.bindKey(KeyEvent.KEYCODE_VOLUME_UP, false, ActionCode.VOLUME_KEY_SCROLL_BACK);
}
}
}));
volumeKeysPreferences.setEnabled(fbReader.hasActionForKey(KeyEvent.KEYCODE_VOLUME_UP, false));
scrollingScreen.addOption(scrollingPreferences.AnimationOption, "animation");
scrollingScreen.addPreference(new AnimationSpeedPreference(
this,
scrollingScreen.Resource,
"animationSpeed",
scrollingPreferences.AnimationSpeedOption
));
scrollingScreen.addOption(scrollingPreferences.HorizontalOption, "horizontal");
final Screen dictionaryScreen = createPreferenceScreen("dictionary");
try {
dictionaryScreen.addPreference(new DictionaryPreference(
this,
dictionaryScreen.Resource,
"dictionary",
DictionaryUtil.singleWordTranslatorOption(),
DictionaryUtil.dictionaryInfos(this, true)
));
dictionaryScreen.addPreference(new DictionaryPreference(
this,
dictionaryScreen.Resource,
"translator",
DictionaryUtil.multiWordTranslatorOption(),
DictionaryUtil.dictionaryInfos(this, false)
));
} catch (Exception e) {
// ignore: dictionary lists are not initialized yet
}
dictionaryScreen.addPreference(new ZLBooleanPreference(
this,
fbReader.NavigateAllWordsOption,
dictionaryScreen.Resource,
"navigateOverAllWords"
));
dictionaryScreen.addOption(fbReader.WordTappingActionOption, "tappingAction");
final Screen imagesScreen = createPreferenceScreen("images");
imagesScreen.addOption(fbReader.ImageTappingActionOption, "tappingAction");
imagesScreen.addOption(fbReader.FitImagesToScreenOption, "fitImagesToScreen");
imagesScreen.addOption(fbReader.ImageViewBackgroundOption, "backgroundColor");
final Screen cancelMenuScreen = createPreferenceScreen("cancelMenu");
cancelMenuScreen.addOption(fbReader.ShowLibraryInCancelMenuOption, "library");
cancelMenuScreen.addOption(fbReader.ShowNetworkLibraryInCancelMenuOption, "networkLibrary");
cancelMenuScreen.addOption(fbReader.ShowPreviousBookInCancelMenuOption, "previousBook");
cancelMenuScreen.addOption(fbReader.ShowPositionsInCancelMenuOption, "positions");
final String[] backKeyActions =
{ ActionCode.EXIT, ActionCode.SHOW_CANCEL_MENU };
cancelMenuScreen.addPreference(new ZLStringChoicePreference(
this, cancelMenuScreen.Resource, "backKeyAction",
keyBindings.getOption(KeyEvent.KEYCODE_BACK, false), backKeyActions
));
final String[] backKeyLongPressActions =
{ ActionCode.EXIT, ActionCode.SHOW_CANCEL_MENU, FBReaderApp.NoAction };
cancelMenuScreen.addPreference(new ZLStringChoicePreference(
this, cancelMenuScreen.Resource, "backKeyLongPressAction",
keyBindings.getOption(KeyEvent.KEYCODE_BACK, true), backKeyLongPressActions
));
final Screen tipsScreen = createPreferenceScreen("tips");
tipsScreen.addOption(TipsManager.Instance().ShowTipsOption, "showTips");
final Screen aboutScreen = createPreferenceScreen("about");
aboutScreen.addPreference(new InfoPreference(
this,
aboutScreen.Resource.getResource("version").getValue(),
androidLibrary.getFullVersionName()
));
aboutScreen.addPreference(new UrlPreference(this, aboutScreen.Resource, "site"));
aboutScreen.addPreference(new UrlPreference(this, aboutScreen.Resource, "email"));
aboutScreen.addPreference(new UrlPreference(this, aboutScreen.Resource, "twitter"));
}
|
diff --git a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticator.java b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticator.java
index e640e376a..70764bd87 100644
--- a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticator.java
+++ b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticator.java
@@ -1,177 +1,180 @@
// ========================================================================
// Copyright (c) 2008-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.security.jaspi;
import java.security.Principal;
import java.util.Map;
import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.callback.CallerPrincipalCallback;
import javax.security.auth.message.callback.GroupPrincipalCallback;
import javax.security.auth.message.config.ServerAuthConfig;
import javax.security.auth.message.config.ServerAuthContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.eclipse.jetty.security.Authenticator;
import org.eclipse.jetty.security.IdentityService;
import org.eclipse.jetty.security.ServerAuthException;
import org.eclipse.jetty.security.UserAuthentication;
import org.eclipse.jetty.security.authentication.DeferredAuthentication;
import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.server.Authentication.User;
/**
* @version $Rev: 4793 $ $Date: 2009-03-19 00:00:01 +0100 (Thu, 19 Mar 2009) $
*/
public class JaspiAuthenticator implements Authenticator
{
private final ServerAuthConfig _authConfig;
private final Map _authProperties;
private final ServletCallbackHandler _callbackHandler;
private final Subject _serviceSubject;
private final boolean _allowLazyAuthentication;
private final IdentityService _identityService;
private final DeferredAuthentication _deferred;
public JaspiAuthenticator(ServerAuthConfig authConfig, Map authProperties, ServletCallbackHandler callbackHandler,
Subject serviceSubject, boolean allowLazyAuthentication, IdentityService identityService)
{
// TODO maybe pass this in via setConfiguration ?
if (callbackHandler == null)
throw new NullPointerException("No CallbackHandler");
if (authConfig == null)
throw new NullPointerException("No AuthConfig");
this._authConfig = authConfig;
this._authProperties = authProperties;
this._callbackHandler = callbackHandler;
this._serviceSubject = serviceSubject;
this._allowLazyAuthentication = allowLazyAuthentication;
this._identityService = identityService;
this._deferred=new DeferredAuthentication(this);
}
public void setConfiguration(Configuration configuration)
{
}
public String getAuthMethod()
{
return "JASPI";
}
public Authentication validateRequest(ServletRequest request, ServletResponse response, boolean mandatory) throws ServerAuthException
{
if (_allowLazyAuthentication && !mandatory)
return _deferred;
JaspiMessageInfo info = new JaspiMessageInfo(request, response, mandatory);
request.setAttribute("org.eclipse.jetty.security.jaspi.info",info);
return validateRequest(info);
}
// most likely validatedUser is not needed here.
public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException
{
JaspiMessageInfo info = (JaspiMessageInfo)req.getAttribute("org.eclipse.jetty.security.jaspi.info");
if (info==null) throw new NullPointerException("MeesageInfo from request missing: " + req);
return secureResponse(info,validatedUser);
}
public Authentication validateRequest(JaspiMessageInfo messageInfo) throws ServerAuthException
{
try
{
String authContextId = _authConfig.getAuthContextID(messageInfo);
ServerAuthContext authContext = _authConfig.getAuthContext(authContextId,_serviceSubject,_authProperties);
Subject clientSubject = new Subject();
AuthStatus authStatus = authContext.validateRequest(messageInfo,clientSubject,_serviceSubject);
// String authMethod = (String)messageInfo.getMap().get(JaspiMessageInfo.AUTH_METHOD_KEY);
if (authStatus == AuthStatus.SEND_CONTINUE)
return Authentication.SEND_CONTINUE;
if (authStatus == AuthStatus.SEND_FAILURE)
return Authentication.SEND_FAILURE;
if (authStatus == AuthStatus.SUCCESS)
{
Set<UserIdentity> ids = clientSubject.getPrivateCredentials(UserIdentity.class);
UserIdentity userIdentity;
- if (ids.size() > 0) {
+ if (ids.size() > 0)
+ {
userIdentity = ids.iterator().next();
-// return new FormAuthenticator.FormAuthentication(this,ids.iterator().next());
} else {
CallerPrincipalCallback principalCallback = _callbackHandler.getThreadCallerPrincipalCallback();
- if (principalCallback == null) throw new NullPointerException("No CallerPrincipalCallback");
+ if (principalCallback == null)
+ {
+ return Authentication.UNAUTHENTICATED;
+ }
Principal principal = principalCallback.getPrincipal();
if (principal == null) {
String principalName = principalCallback.getName();
Set<Principal> principals = principalCallback.getSubject().getPrincipals();
for (Principal p: principals)
{
if (p.getName().equals(principalName))
{
principal = p;
break;
}
}
if (principal == null)
{
return Authentication.UNAUTHENTICATED;
}
}
GroupPrincipalCallback groupPrincipalCallback = _callbackHandler.getThreadGroupPrincipalCallback();
String[] groups = groupPrincipalCallback == null ? null : groupPrincipalCallback.getGroups();
userIdentity = _identityService.newUserIdentity(clientSubject, principal, groups);
}
return new UserAuthentication(this, userIdentity);
}
if (authStatus == AuthStatus.SEND_SUCCESS)
{
//we are processing a message in a secureResponse dialog.
return Authentication.SEND_SUCCESS;
}
//should not happen
throw new NullPointerException("No AuthStatus returned");
}
catch (AuthException e)
{
throw new ServerAuthException(e);
}
}
public boolean secureResponse(JaspiMessageInfo messageInfo, Authentication validatedUser) throws ServerAuthException
{
try
{
String authContextId = _authConfig.getAuthContextID(messageInfo);
ServerAuthContext authContext = _authConfig.getAuthContext(authContextId,_serviceSubject,_authProperties);
// TODO authContext.cleanSubject(messageInfo,validatedUser.getUserIdentity().getSubject());
AuthStatus status = authContext.secureResponse(messageInfo,_serviceSubject);
return (AuthStatus.SEND_SUCCESS.equals(status));
}
catch (AuthException e)
{
throw new ServerAuthException(e);
}
}
}
| false | true |
public Authentication validateRequest(JaspiMessageInfo messageInfo) throws ServerAuthException
{
try
{
String authContextId = _authConfig.getAuthContextID(messageInfo);
ServerAuthContext authContext = _authConfig.getAuthContext(authContextId,_serviceSubject,_authProperties);
Subject clientSubject = new Subject();
AuthStatus authStatus = authContext.validateRequest(messageInfo,clientSubject,_serviceSubject);
// String authMethod = (String)messageInfo.getMap().get(JaspiMessageInfo.AUTH_METHOD_KEY);
if (authStatus == AuthStatus.SEND_CONTINUE)
return Authentication.SEND_CONTINUE;
if (authStatus == AuthStatus.SEND_FAILURE)
return Authentication.SEND_FAILURE;
if (authStatus == AuthStatus.SUCCESS)
{
Set<UserIdentity> ids = clientSubject.getPrivateCredentials(UserIdentity.class);
UserIdentity userIdentity;
if (ids.size() > 0) {
userIdentity = ids.iterator().next();
// return new FormAuthenticator.FormAuthentication(this,ids.iterator().next());
} else {
CallerPrincipalCallback principalCallback = _callbackHandler.getThreadCallerPrincipalCallback();
if (principalCallback == null) throw new NullPointerException("No CallerPrincipalCallback");
Principal principal = principalCallback.getPrincipal();
if (principal == null) {
String principalName = principalCallback.getName();
Set<Principal> principals = principalCallback.getSubject().getPrincipals();
for (Principal p: principals)
{
if (p.getName().equals(principalName))
{
principal = p;
break;
}
}
if (principal == null)
{
return Authentication.UNAUTHENTICATED;
}
}
GroupPrincipalCallback groupPrincipalCallback = _callbackHandler.getThreadGroupPrincipalCallback();
String[] groups = groupPrincipalCallback == null ? null : groupPrincipalCallback.getGroups();
userIdentity = _identityService.newUserIdentity(clientSubject, principal, groups);
}
return new UserAuthentication(this, userIdentity);
}
if (authStatus == AuthStatus.SEND_SUCCESS)
{
//we are processing a message in a secureResponse dialog.
return Authentication.SEND_SUCCESS;
}
//should not happen
throw new NullPointerException("No AuthStatus returned");
}
catch (AuthException e)
{
throw new ServerAuthException(e);
}
}
|
public Authentication validateRequest(JaspiMessageInfo messageInfo) throws ServerAuthException
{
try
{
String authContextId = _authConfig.getAuthContextID(messageInfo);
ServerAuthContext authContext = _authConfig.getAuthContext(authContextId,_serviceSubject,_authProperties);
Subject clientSubject = new Subject();
AuthStatus authStatus = authContext.validateRequest(messageInfo,clientSubject,_serviceSubject);
// String authMethod = (String)messageInfo.getMap().get(JaspiMessageInfo.AUTH_METHOD_KEY);
if (authStatus == AuthStatus.SEND_CONTINUE)
return Authentication.SEND_CONTINUE;
if (authStatus == AuthStatus.SEND_FAILURE)
return Authentication.SEND_FAILURE;
if (authStatus == AuthStatus.SUCCESS)
{
Set<UserIdentity> ids = clientSubject.getPrivateCredentials(UserIdentity.class);
UserIdentity userIdentity;
if (ids.size() > 0)
{
userIdentity = ids.iterator().next();
} else {
CallerPrincipalCallback principalCallback = _callbackHandler.getThreadCallerPrincipalCallback();
if (principalCallback == null)
{
return Authentication.UNAUTHENTICATED;
}
Principal principal = principalCallback.getPrincipal();
if (principal == null) {
String principalName = principalCallback.getName();
Set<Principal> principals = principalCallback.getSubject().getPrincipals();
for (Principal p: principals)
{
if (p.getName().equals(principalName))
{
principal = p;
break;
}
}
if (principal == null)
{
return Authentication.UNAUTHENTICATED;
}
}
GroupPrincipalCallback groupPrincipalCallback = _callbackHandler.getThreadGroupPrincipalCallback();
String[] groups = groupPrincipalCallback == null ? null : groupPrincipalCallback.getGroups();
userIdentity = _identityService.newUserIdentity(clientSubject, principal, groups);
}
return new UserAuthentication(this, userIdentity);
}
if (authStatus == AuthStatus.SEND_SUCCESS)
{
//we are processing a message in a secureResponse dialog.
return Authentication.SEND_SUCCESS;
}
//should not happen
throw new NullPointerException("No AuthStatus returned");
}
catch (AuthException e)
{
throw new ServerAuthException(e);
}
}
|
diff --git a/src/main/java/com/kfuntak/gwt/json/serialization/SerializationGenerator.java b/src/main/java/com/kfuntak/gwt/json/serialization/SerializationGenerator.java
index f3b8466..0cb1b9b 100644
--- a/src/main/java/com/kfuntak/gwt/json/serialization/SerializationGenerator.java
+++ b/src/main/java/com/kfuntak/gwt/json/serialization/SerializationGenerator.java
@@ -1,643 +1,652 @@
package com.kfuntak.gwt.json.serialization;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JField;
import com.google.gwt.core.ext.typeinfo.JParameterizedType;
import com.google.gwt.core.ext.typeinfo.JPrimitiveType;
import com.google.gwt.core.ext.typeinfo.JType;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.core.ext.typeinfo.TypeOracle;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;
import com.kfuntak.gwt.json.serialization.client.DeserializerHelper;
import com.kfuntak.gwt.json.serialization.client.IncompatibleObjectException;
import com.kfuntak.gwt.json.serialization.client.JsonSerializable;
import com.kfuntak.gwt.json.serialization.client.ObjectSerializer;
import com.kfuntak.gwt.json.serialization.client.SerializerHelper;
public class SerializationGenerator extends Generator {
private JClassType serializeInterface;
private JClassType stringClass;
private SourceWriter srcWriter;
private String className;
private TypeOracle typeOracle;
private Set<String> importsList = new HashSet<String>();
public String generate(TreeLogger logger, GeneratorContext ctx,
String requestedClass) throws UnableToCompleteException {
//get the type oracle
typeOracle = ctx.getTypeOracle();
assert (typeOracle != null);
serializeInterface = typeOracle.findType(JsonSerializable.class.getName());
assert (serializeInterface != null);
stringClass = typeOracle.findType(String.class.getName());
assert (stringClass != null);
//get class from type oracle
JClassType serializeClass = typeOracle.findType(requestedClass);
if (serializeClass == null) {
logger.log(TreeLogger.ERROR, "Unable to find metadata for type '"
+ requestedClass + "'", null);
throw new UnableToCompleteException();
}
//create source writer
String packageName = serializeClass.getPackage().getName();
className = serializeClass.getSimpleSourceName() + "_TypeSerializer";
PrintWriter printWriter = ctx.tryCreate(logger, packageName, className);
if (printWriter == null) {
return packageName + "." + className;
}
ClassSourceFileComposerFactory composerFactory =
new ClassSourceFileComposerFactory(packageName, className);
composerFactory.setSuperclass("com.kfuntak.gwt.json.serialization.client.Serializer");
// // Java imports
composerFactory.addImport(java.util.Collection.class.getName());
composerFactory.addImport(java.util.List.class.getName());
composerFactory.addImport(java.util.ArrayList.class.getName());
composerFactory.addImport(java.util.LinkedList.class.getName());
composerFactory.addImport(java.util.Stack.class.getName());
composerFactory.addImport(java.util.Vector.class.getName());
composerFactory.addImport(java.util.Set.class.getName());
composerFactory.addImport(java.util.TreeSet.class.getName());
composerFactory.addImport(java.util.HashSet.class.getName());
composerFactory.addImport(java.util.LinkedHashSet.class.getName());
composerFactory.addImport(java.util.SortedSet.class.getName());
composerFactory.addImport(java.util.Date.class.getName());
// // GWT imports
composerFactory.addImport(com.google.gwt.core.client.GWT.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONNull.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONNumber.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONString.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONValue.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONObject.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONArray.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONBoolean.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONParser.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONException.class.getName());
// // Module imports
composerFactory.addImport(ObjectSerializer.class.getName());
composerFactory.addImport(JsonSerializable.class.getName());
composerFactory.addImport(IncompatibleObjectException.class.getName());
composerFactory.addImport(SerializerHelper.class.getName());
composerFactory.addImport(DeserializerHelper.class.getName());
JClassType[] subTypes = serializeInterface.getSubtypes();
for (int i = 0; i < subTypes.length; ++i) {
composerFactory.addImport(subTypes[i].getQualifiedSourceName());
}
srcWriter = composerFactory.createSourceWriter(ctx, printWriter);
if (srcWriter == null) {
return packageName + "." + className;
}
//create a serializer for each interface that supports Serializable
for (int i = 0; i < subTypes.length; ++i) {
srcWriter.println("public class " + subTypes[i].getName() + "_SerializableImpl implements ObjectSerializer{");
// System.out.println("public class "+subTypes[i].getName()+"_SerializableImpl implements ObjectSerializer{");
srcWriter.indent();
srcWriter.println("public " + subTypes[i].getName() + "_SerializableImpl(){}");
// System.out.println("public "+subTypes[i].getName()+"_SerializableImpl(){}");
StringBuffer buffer = new StringBuffer();
try {
String defaultSerializationString = generateDefaultSerialization();
String typeSerializationString = generateTypeSerialization(subTypes[i].getQualifiedSourceName());
String defaultDeserializationString = generateDefaultDeserialization(subTypes[i].getQualifiedSourceName());
String tyepDeserializationString = generateTypeDeserialization(subTypes[i].getQualifiedSourceName());
buffer.append(defaultSerializationString);
buffer.append("\n");
buffer.append(typeSerializationString);
buffer.append("\n");
buffer.append(defaultDeserializationString);
buffer.append("\n");
buffer.append(tyepDeserializationString);
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
//System.out.println(buffer.toString());
} catch (NotFoundException e) {
e.printStackTrace();
}
srcWriter.println(buffer.toString());
// System.out.println(buffer.toString());
}
//in the class constructor, add each serializer
srcWriter.println("public " + className + "(){");
// System.out.println("public "+className+"(){");
srcWriter.indent();
for (int i = 0; i < subTypes.length; ++i) {
srcWriter.println("addObjectSerializer(\"" + subTypes[i].getQualifiedSourceName() + "\", new " + subTypes[i].getName() + "_SerializableImpl() );");
// System.out.println("addObjectSerializer(\""+subTypes[i].getQualifiedSourceName()+"\", new "+subTypes[i].getName()+"_SerializableImpl() );");
}
srcWriter.outdent();
srcWriter.println("}");
// System.out.println("}");
srcWriter.commit(logger);
return packageName + "." + className;
}
private String generateTypeDeserialization(String typeName) throws NotFoundException {
JClassType baseType = typeOracle.getType(typeName);
String packageName = baseType.getPackage().getName();
StringBuffer buffer = new StringBuffer();
buffer.append("public Object deSerialize(JSONValue jsonValue, String className) throws JSONException{");
buffer.append("\n");
// Return null if the given object is null
buffer.append("if(jsonValue instanceof JSONNull){");
buffer.append("\n");
buffer.append("return null;");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Throw Incompatible exception is JsonValue is not an instance of
// JsonObject
buffer.append("if(!(jsonValue instanceof JSONObject)){");
buffer.append("\n");
buffer.append("throw new IncompatibleObjectException();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Initialise JsonObject then
String baseTypeName = baseType.getSimpleSourceName();
buffer.append("JSONObject jsonObject=(JSONObject)jsonValue;");
buffer.append("\n");
buffer.append(baseTypeName + " mainResult=new " + baseTypeName + "();");
buffer.append("\n");
buffer.append("Serializer serializer;");
buffer.append("\n");
buffer.append("JSONArray inputJsonArray=null;");
buffer.append("\n");
buffer.append("int inpJsonArSize=0;");
buffer.append("\n");
buffer.append("JSONValue fieldJsonValue=null;");
buffer.append("\n");
// Start deSerialisation
List<JField> allFields = new ArrayList<JField>();
JField[] fields = baseType.getFields();
for (JField field : fields) {
if (!field.isStatic() && !field.isTransient()) {
allFields.add(field);
}
}
if (baseType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
boolean flag = true;
JClassType superClassType = baseType;
while (flag) {
superClassType = superClassType.getSuperclass();
if (superClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
JField[] subClassFields = superClassType.getFields();
for (JField subClassField : subClassFields) {
if (!subClassField.isStatic() && !subClassField.isTransient()) {
allFields.add(subClassField);
}
}
} else {
flag = false;
}
}
}
fields = new JField[allFields.size()];
allFields.toArray(fields);
for (JField field : fields) {
JType fieldType = field.getType();
String fieldName = field.getName();
String fieldNameForGS = getNameForGS(fieldName);
buffer.append("fieldJsonValue=jsonObject.get(\"" + fieldName + "\");");
buffer.append("\n");
if (fieldType.isPrimitive() != null) {
JPrimitiveType fieldPrimitiveType = (JPrimitiveType) fieldType;
JClassType fieldBoxedType = typeOracle.getType(fieldPrimitiveType.getQualifiedBoxedSourceName());
if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Short")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getShort(fieldJsonValue));");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Byte")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getByte(fieldJsonValue));");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Long")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getLong(fieldJsonValue));");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Integer")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getInt(fieldJsonValue));");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Float")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getFloat(fieldJsonValue));");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Double")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getDouble(fieldJsonValue));");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getBoolean(fieldJsonValue));");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getShort(fieldJsonValue));");
buffer.append("\n");
}
} else {
JClassType fieldClassType = (JClassType) fieldType;
if (fieldClassType.getQualifiedSourceName().equals("java.lang.Short")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getShort(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Byte")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getByte(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Long")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getLong(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Integer")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getInt(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Float")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getFloat(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Double")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getDouble(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getBoolean(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getShort(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getDate(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("mainResult.set" + fieldNameForGS + "((" + fieldClassType.getSimpleSourceName() + ")serializer.deSerialize(fieldJsonValue, \"" + fieldClassType.getQualifiedSourceName() + "\"));");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("java.util.Collection"))) {
deserializeCollection(buffer, fieldClassType, fieldNameForGS, fieldName);
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getString(fieldJsonValue));");
buffer.append("\n");
}
}
}
buffer.append("return mainResult;");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
return buffer.toString();
}
private void deserializeCollection(StringBuffer buffer, JClassType fieldClassType, String fieldNameForGS, String fieldName) throws NotFoundException {
// Return null if JSON object is null
buffer.append("if(fieldJsonValue==null){");
buffer.append("\n");
buffer.append("mainResult.set" + fieldNameForGS + "(null);");
buffer.append("\n");
buffer.append("return mainResult;");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Throw Incompatible exception if the JSON object is not a collection
buffer.append("if(!(fieldJsonValue instanceof JSONArray)){");
buffer.append("\n");
buffer.append("throw new IncompatibleObjectException();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Start deSerilisation
buffer.append("inputJsonArray=(JSONArray)fieldJsonValue;");
buffer.append("\n");
buffer.append("inpJsonArSize=inputJsonArray.size();");
buffer.append("\n");
String fieldTypeQualifiedName = fieldClassType.getQualifiedSourceName();
JParameterizedType parameterizedType = (JParameterizedType) fieldClassType;
fieldClassType = parameterizedType.getTypeArgs()[0];
String parameterSimpleName = fieldClassType.getSimpleSourceName();
String fieldColName = fieldName + "Col";// Field Collection Result
// Object Name
importsList.add(fieldClassType.getQualifiedSourceName());
if (fieldTypeQualifiedName.equals("java.util.List") || fieldTypeQualifiedName.equals("java.util.ArrayList")) {
buffer.append("ArrayList<" + parameterSimpleName + "> " + fieldColName + " = new ArrayList<" + parameterSimpleName + ">();");
buffer.append("\n");
} else if (fieldTypeQualifiedName.equals("java.util.Set") || fieldTypeQualifiedName.equals("java.util.HashSet")) {
buffer.append("HashSet<" + parameterSimpleName + "> " + fieldColName + " = new HashSet<" + parameterSimpleName + ">();");
buffer.append("\n");
} else if (fieldTypeQualifiedName.equals("java.util.SortedSet") || fieldTypeQualifiedName.equals("java.util.TreeSet")) {
buffer.append("TreeSet<" + parameterSimpleName + "> " + fieldColName + " = new TreeSet<" + parameterSimpleName + ">();");
buffer.append("\n");
} else if (fieldTypeQualifiedName.equals("java.util.LinkedList")) {
buffer.append("LinkedList<" + parameterSimpleName + "> " + fieldColName + " = new LinkedList<" + parameterSimpleName + ">();");
buffer.append("\n");
buffer.append("mainResult.set" + fieldNameForGS + "(" + fieldColName + ");");
buffer.append("\n");
} else if (fieldTypeQualifiedName.equals("java.util.Stack")) {
buffer.append("Stack<" + parameterSimpleName + "> " + fieldColName + " = new Stack<" + parameterSimpleName + ">();");
buffer.append("\n");
} else if (fieldTypeQualifiedName.equals("java.util.Vector")) {
buffer.append("Vector<" + parameterSimpleName + "> " + fieldColName + " = new Vector<" + parameterSimpleName + ">();");
buffer.append("\n");
} else if (fieldTypeQualifiedName.equals("java.util.LinkedHashSet")) {
buffer.append("LinkedHashSet<" + parameterSimpleName + "> " + fieldColName + "=new LinkedHashSet<" + parameterSimpleName + ">();");
buffer.append("\n");
}
buffer.append("for(int ij=0;ij<inpJsonArSize;ij++){");
// DeSerialise individual elements
buffer.append("fieldJsonValue=inputJsonArray.get(ij);");
if (fieldClassType.getQualifiedSourceName().equals("java.lang.Short")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getShort(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Byte")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getByte(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Long")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getLong(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Integer")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getInt(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Float")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getFloat(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Double")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getDouble(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getBoolean(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getShort(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getDate(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("JSONValue _class = ((JSONObject)fieldJsonValue).get(\"class\");");
buffer.append("\n");
buffer.append("if (_class != null && _class instanceof JSONString) {");
buffer.append("\n");
buffer.append(fieldColName + ".add((" + fieldClassType.getSimpleSourceName() + ")serializer.deSerialize(fieldJsonValue, ((JSONString)_class).stringValue()));");
buffer.append("\n");
buffer.append("} else {");
buffer.append(fieldColName + ".add((" + fieldClassType.getSimpleSourceName() + ")serializer.deSerialize(fieldJsonValue, \"" + fieldClassType.getQualifiedSourceName() + "\"));");
buffer.append("}");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getString(fieldJsonValue));");
buffer.append("\n");
}
buffer.append("}");
buffer.append("\n");
buffer.append("mainResult.set" + fieldNameForGS + "(" + fieldColName + ");");
buffer.append("\n");
}
private String generateDefaultDeserialization(String className) {
StringBuffer buffer = new StringBuffer();
buffer.append("public Object deSerialize(String jsonString, String className) throws JSONException{");
buffer.append("\n");
buffer.append("return deSerialize(JSONParser.parse(jsonString), \"" + className + "\");");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
return buffer.toString();
}
private String generateTypeSerialization(String typeName) throws NotFoundException {
JClassType baseType = typeOracle.getType(typeName);
String packageName = baseType.getPackage().getName();
StringBuffer buffer = new StringBuffer();
buffer.append("public JSONValue serializeToJson(Object object){");
buffer.append("\n");
// Return JSONNull instance if object is null
buffer.append("if(object==null){");
buffer.append("\n");
buffer.append("return JSONNull.getInstance();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Throw Incompatible Exception if object is not of the type it claims
// to be
buffer.append("if(!(object instanceof " + baseType.getSimpleSourceName() + ")){");
buffer.append("\n");
buffer.append("throw new IncompatibleObjectException();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Initialise result object
buffer.append("JSONObject mainResult=new JSONObject();");
buffer.append("\n");
buffer.append("JSONValue jsonValue=null;");
buffer.append("\n");
buffer.append("JSONArray jsonResultArray=null;");
buffer.append("\n");
buffer.append("int index=0;");
buffer.append("\n");
buffer.append("Serializer serializer=null;");
buffer.append("\n");
buffer.append("Object fieldValue=null;");
buffer.append("\n");
buffer.append(baseType.getSimpleSourceName() + " mainVariable=(" + baseType.getSimpleSourceName() + ")object;");
buffer.append("\n");
// Serialise fields
List<JField> allFields = new ArrayList<JField>();
JField[] fields = baseType.getFields();
- allFields.addAll(Arrays.asList(fields));
+ for (JField field : fields) {
+ if (!field.isStatic() && !field.isTransient()) {
+ allFields.add(field);
+ }
+ }
if (baseType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
boolean flag = true;
JClassType superClassType = baseType;
while (flag) {
superClassType = superClassType.getSuperclass();
if (superClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
- allFields.addAll(Arrays.asList(superClassType.getFields()));
+ JField[] subClassFields = superClassType.getFields();
+ for (JField subClassField : subClassFields) {
+ if (!subClassField.isStatic() && !subClassField.isTransient()) {
+ allFields.add(subClassField);
+ }
+ }
} else {
flag = false;
}
}
}
fields = new JField[allFields.size()];
allFields.toArray(fields);
for (JField field : fields) {
JType fieldType = field.getType();
String fieldName = field.getName();
String fieldNameForGS = getNameForGS(fieldName);
// Get field value for object
buffer.append("fieldValue=mainVariable.get" + fieldNameForGS + "();");
buffer.append("\n");
if (fieldType.isPrimitive() != null) {
JPrimitiveType fieldPrimitiveType = (JPrimitiveType) fieldType;
JClassType fieldBoxedType = typeOracle.getType(fieldPrimitiveType.getQualifiedBoxedSourceName());
if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldBoxedType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
}
} else {
JClassType fieldClassType = (JClassType) fieldType;
if (fieldClassType.isAssignableTo(typeOracle.getType("java.util.Collection"))) {
// Serialise collection
JParameterizedType parameterizedType = (JParameterizedType) fieldClassType;
fieldClassType = parameterizedType.getTypeArgs()[0];
importsList.add(fieldClassType.getQualifiedSourceName());
String fieldSimpleName = fieldClassType.getSimpleSourceName();
buffer.append("\n");
buffer.append("if(fieldValue != null){");
buffer.append("\n");
buffer.append("Collection<" + fieldSimpleName + "> " + fieldSimpleName.toLowerCase() + "ColValue=(Collection<" + fieldSimpleName + ">)fieldValue;");
buffer.append("\n");
buffer.append("jsonResultArray=new JSONArray();");
buffer.append("\n");
buffer.append("index=0;");
buffer.append("\n");
buffer.append("for(" + fieldSimpleName + " dummy : " + fieldSimpleName.toLowerCase() + "ColValue){");
buffer.append("\n");
if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append("jsonValue=SerializerHelper.getString((String)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append("jsonValue=SerializerHelper.getDate((Date)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
// TODO: Put alternalive to importsList
//importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,serializer.serializeToJson(dummy));");
buffer.append("\n");
}
buffer.append("}");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonResultArray);");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append("jsonValue=SerializerHelper.getString((String)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append("jsonValue=SerializerHelper.getDate((Date)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",serializer.serializeToJson(fieldValue));");
buffer.append("\n");
}
}
}
// Put class type for compatibility with flex JSON [de]serialisation
buffer.append("mainResult.put(\"class\",new JSONString(\"" + baseType.getQualifiedSourceName() + "\"));");
buffer.append("\n");
// Return statement
buffer.append("return mainResult;");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
return buffer.toString();
}
private String generateDefaultSerialization() {
StringBuffer buffer = new StringBuffer();
buffer.append("public String serialize(Object pojo){");
buffer.append("\n");
buffer.append("return serializeToJson(pojo).toString();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
return buffer.toString();
}
private static String getNameForGS(String name) {
StringBuffer buffer = new StringBuffer(name);
buffer.setCharAt(0, new String(new char[]{name.charAt(0)}).toUpperCase().charAt(0));
return buffer.toString();
}
}
| false | true |
private String generateTypeSerialization(String typeName) throws NotFoundException {
JClassType baseType = typeOracle.getType(typeName);
String packageName = baseType.getPackage().getName();
StringBuffer buffer = new StringBuffer();
buffer.append("public JSONValue serializeToJson(Object object){");
buffer.append("\n");
// Return JSONNull instance if object is null
buffer.append("if(object==null){");
buffer.append("\n");
buffer.append("return JSONNull.getInstance();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Throw Incompatible Exception if object is not of the type it claims
// to be
buffer.append("if(!(object instanceof " + baseType.getSimpleSourceName() + ")){");
buffer.append("\n");
buffer.append("throw new IncompatibleObjectException();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Initialise result object
buffer.append("JSONObject mainResult=new JSONObject();");
buffer.append("\n");
buffer.append("JSONValue jsonValue=null;");
buffer.append("\n");
buffer.append("JSONArray jsonResultArray=null;");
buffer.append("\n");
buffer.append("int index=0;");
buffer.append("\n");
buffer.append("Serializer serializer=null;");
buffer.append("\n");
buffer.append("Object fieldValue=null;");
buffer.append("\n");
buffer.append(baseType.getSimpleSourceName() + " mainVariable=(" + baseType.getSimpleSourceName() + ")object;");
buffer.append("\n");
// Serialise fields
List<JField> allFields = new ArrayList<JField>();
JField[] fields = baseType.getFields();
allFields.addAll(Arrays.asList(fields));
if (baseType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
boolean flag = true;
JClassType superClassType = baseType;
while (flag) {
superClassType = superClassType.getSuperclass();
if (superClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
allFields.addAll(Arrays.asList(superClassType.getFields()));
} else {
flag = false;
}
}
}
fields = new JField[allFields.size()];
allFields.toArray(fields);
for (JField field : fields) {
JType fieldType = field.getType();
String fieldName = field.getName();
String fieldNameForGS = getNameForGS(fieldName);
// Get field value for object
buffer.append("fieldValue=mainVariable.get" + fieldNameForGS + "();");
buffer.append("\n");
if (fieldType.isPrimitive() != null) {
JPrimitiveType fieldPrimitiveType = (JPrimitiveType) fieldType;
JClassType fieldBoxedType = typeOracle.getType(fieldPrimitiveType.getQualifiedBoxedSourceName());
if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldBoxedType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
}
} else {
JClassType fieldClassType = (JClassType) fieldType;
if (fieldClassType.isAssignableTo(typeOracle.getType("java.util.Collection"))) {
// Serialise collection
JParameterizedType parameterizedType = (JParameterizedType) fieldClassType;
fieldClassType = parameterizedType.getTypeArgs()[0];
importsList.add(fieldClassType.getQualifiedSourceName());
String fieldSimpleName = fieldClassType.getSimpleSourceName();
buffer.append("\n");
buffer.append("if(fieldValue != null){");
buffer.append("\n");
buffer.append("Collection<" + fieldSimpleName + "> " + fieldSimpleName.toLowerCase() + "ColValue=(Collection<" + fieldSimpleName + ">)fieldValue;");
buffer.append("\n");
buffer.append("jsonResultArray=new JSONArray();");
buffer.append("\n");
buffer.append("index=0;");
buffer.append("\n");
buffer.append("for(" + fieldSimpleName + " dummy : " + fieldSimpleName.toLowerCase() + "ColValue){");
buffer.append("\n");
if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append("jsonValue=SerializerHelper.getString((String)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append("jsonValue=SerializerHelper.getDate((Date)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
// TODO: Put alternalive to importsList
//importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,serializer.serializeToJson(dummy));");
buffer.append("\n");
}
buffer.append("}");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonResultArray);");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append("jsonValue=SerializerHelper.getString((String)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append("jsonValue=SerializerHelper.getDate((Date)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",serializer.serializeToJson(fieldValue));");
buffer.append("\n");
}
}
}
// Put class type for compatibility with flex JSON [de]serialisation
buffer.append("mainResult.put(\"class\",new JSONString(\"" + baseType.getQualifiedSourceName() + "\"));");
buffer.append("\n");
// Return statement
buffer.append("return mainResult;");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
return buffer.toString();
}
|
private String generateTypeSerialization(String typeName) throws NotFoundException {
JClassType baseType = typeOracle.getType(typeName);
String packageName = baseType.getPackage().getName();
StringBuffer buffer = new StringBuffer();
buffer.append("public JSONValue serializeToJson(Object object){");
buffer.append("\n");
// Return JSONNull instance if object is null
buffer.append("if(object==null){");
buffer.append("\n");
buffer.append("return JSONNull.getInstance();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Throw Incompatible Exception if object is not of the type it claims
// to be
buffer.append("if(!(object instanceof " + baseType.getSimpleSourceName() + ")){");
buffer.append("\n");
buffer.append("throw new IncompatibleObjectException();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Initialise result object
buffer.append("JSONObject mainResult=new JSONObject();");
buffer.append("\n");
buffer.append("JSONValue jsonValue=null;");
buffer.append("\n");
buffer.append("JSONArray jsonResultArray=null;");
buffer.append("\n");
buffer.append("int index=0;");
buffer.append("\n");
buffer.append("Serializer serializer=null;");
buffer.append("\n");
buffer.append("Object fieldValue=null;");
buffer.append("\n");
buffer.append(baseType.getSimpleSourceName() + " mainVariable=(" + baseType.getSimpleSourceName() + ")object;");
buffer.append("\n");
// Serialise fields
List<JField> allFields = new ArrayList<JField>();
JField[] fields = baseType.getFields();
for (JField field : fields) {
if (!field.isStatic() && !field.isTransient()) {
allFields.add(field);
}
}
if (baseType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
boolean flag = true;
JClassType superClassType = baseType;
while (flag) {
superClassType = superClassType.getSuperclass();
if (superClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
JField[] subClassFields = superClassType.getFields();
for (JField subClassField : subClassFields) {
if (!subClassField.isStatic() && !subClassField.isTransient()) {
allFields.add(subClassField);
}
}
} else {
flag = false;
}
}
}
fields = new JField[allFields.size()];
allFields.toArray(fields);
for (JField field : fields) {
JType fieldType = field.getType();
String fieldName = field.getName();
String fieldNameForGS = getNameForGS(fieldName);
// Get field value for object
buffer.append("fieldValue=mainVariable.get" + fieldNameForGS + "();");
buffer.append("\n");
if (fieldType.isPrimitive() != null) {
JPrimitiveType fieldPrimitiveType = (JPrimitiveType) fieldType;
JClassType fieldBoxedType = typeOracle.getType(fieldPrimitiveType.getQualifiedBoxedSourceName());
if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldBoxedType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
}
} else {
JClassType fieldClassType = (JClassType) fieldType;
if (fieldClassType.isAssignableTo(typeOracle.getType("java.util.Collection"))) {
// Serialise collection
JParameterizedType parameterizedType = (JParameterizedType) fieldClassType;
fieldClassType = parameterizedType.getTypeArgs()[0];
importsList.add(fieldClassType.getQualifiedSourceName());
String fieldSimpleName = fieldClassType.getSimpleSourceName();
buffer.append("\n");
buffer.append("if(fieldValue != null){");
buffer.append("\n");
buffer.append("Collection<" + fieldSimpleName + "> " + fieldSimpleName.toLowerCase() + "ColValue=(Collection<" + fieldSimpleName + ">)fieldValue;");
buffer.append("\n");
buffer.append("jsonResultArray=new JSONArray();");
buffer.append("\n");
buffer.append("index=0;");
buffer.append("\n");
buffer.append("for(" + fieldSimpleName + " dummy : " + fieldSimpleName.toLowerCase() + "ColValue){");
buffer.append("\n");
if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append("jsonValue=SerializerHelper.getString((String)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append("jsonValue=SerializerHelper.getDate((Date)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
// TODO: Put alternalive to importsList
//importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,serializer.serializeToJson(dummy));");
buffer.append("\n");
}
buffer.append("}");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonResultArray);");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append("jsonValue=SerializerHelper.getString((String)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append("jsonValue=SerializerHelper.getDate((Date)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",serializer.serializeToJson(fieldValue));");
buffer.append("\n");
}
}
}
// Put class type for compatibility with flex JSON [de]serialisation
buffer.append("mainResult.put(\"class\",new JSONString(\"" + baseType.getQualifiedSourceName() + "\"));");
buffer.append("\n");
// Return statement
buffer.append("return mainResult;");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
return buffer.toString();
}
|
diff --git a/src/main/java/com/redhat/ceylon/compiler/js/ComprehensionGenerator.java b/src/main/java/com/redhat/ceylon/compiler/js/ComprehensionGenerator.java
index 5e7ca76d..5b5f7761 100644
--- a/src/main/java/com/redhat/ceylon/compiler/js/ComprehensionGenerator.java
+++ b/src/main/java/com/redhat/ceylon/compiler/js/ComprehensionGenerator.java
@@ -1,312 +1,315 @@
package com.redhat.ceylon.compiler.js;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Comprehension;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ComprehensionClause;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ExpressionComprehensionClause;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ForComprehensionClause;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ForIterator;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.IfComprehensionClause;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.InitialComprehensionClause;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.KeyValueIterator;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ValueIterator;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Variable;
/** This component is used by the main JS visitor to generate code for comprehensions.
*
* @author Enrique Zamudio
* @author Ivo Kasiuk
*/
class ComprehensionGenerator {
private final GenerateJsVisitor gen;
private final JsIdentifierNames names;
private final RetainedVars retainedVars = new RetainedVars();
private final String finished;
private final Set<Declaration> directAccess;
ComprehensionGenerator(GenerateJsVisitor gen, JsIdentifierNames names, Set<Declaration> directDeclarations) {
this.gen = gen;
finished = String.format("%sgetFinished()", GenerateJsVisitor.getClAlias());
this.names = names;
directAccess = directDeclarations;
}
void generateComprehension(Comprehension that) {
gen.out(GenerateJsVisitor.getClAlias(), "Comprehension(function()");
gen.beginBlock();
if (gen.opts.isComment()) {
gen.out("//Comprehension"); gen.location(that); gen.endLine();
}
// gather information about all loops and conditions in the comprehension
List<ComprehensionLoopInfo> loops = new ArrayList<ComprehensionLoopInfo>();
Expression expression = null;
ComprehensionClause startClause = that.getInitialComprehensionClause();
String tail = null;
/**
* The number of initial "if" comprehension clauses, i. e., the number of blocks that have to be ended.
*/
int initialIfClauses = 0;
while (!(startClause instanceof ForComprehensionClause)) {
if (startClause instanceof IfComprehensionClause) {
// check the condition
IfComprehensionClause ifClause = (IfComprehensionClause)startClause;
gen.conds.specialConditions(
gen.conds.gatherVariables(ifClause.getConditionList()),
ifClause.getConditionList(),
"if");
initialIfClauses++;
gen.beginBlock();
startClause = ifClause.getComprehensionClause();
- if (startClause instanceof ForComprehensionClause) {
- // we'll put the rest of the condition inside this if block;
+ if (!(startClause instanceof IfComprehensionClause)) {
+ // we'll put the rest of the comprehension inside this if block;
// outside the if block, return nothing (if any condition isn't true)
tail = "return function(){return " + finished + ";}";
}
} else if (startClause instanceof ExpressionComprehensionClause) {
// return the expression result
gen.out("return function() {");
((ExpressionComprehensionClause)startClause).getExpression().visit(gen);
gen.out("};");
for (int i = 0; i < initialIfClauses; i++) {
gen.endBlock();
}
+ gen.endLine();
+ gen.out(tail);
gen.endBlock(); // end one more block - this one is for the function
gen.out(",");
TypeUtils.printTypeArguments(that, gen.getTypeUtils().wrapAsIterableArguments(that.getTypeModel()), gen);
gen.out(")");
return;
} else {
that.addError("No support for comprehension clause of type "
+ startClause.getClass().getName());
return;
}
}
ForComprehensionClause forClause = (ForComprehensionClause)startClause;
while (forClause != null) {
ComprehensionLoopInfo loop = new ComprehensionLoopInfo(that, forClause.getForIterator());
ComprehensionClause clause = forClause.getComprehensionClause();
while ((clause != null) && !(clause instanceof ForComprehensionClause)) {
if (clause instanceof IfComprehensionClause) {
IfComprehensionClause ifClause = ((IfComprehensionClause) clause);
loop.conditions.add(ifClause.getConditionList());
loop.conditionVars.add(gen.conds.gatherVariables(ifClause.getConditionList()));
clause = ifClause.getComprehensionClause();
} else if (clause instanceof ExpressionComprehensionClause) {
expression = ((ExpressionComprehensionClause) clause).getExpression();
clause = null;
} else {
that.addError("No support for comprehension clause of type "
+ clause.getClass().getName());
return;
}
}
loops.add(loop);
forClause = (ForComprehensionClause) clause;
}
// generate variables and "next" function for each for loop
for (int loopIndex=0; loopIndex<loops.size(); loopIndex++) {
ComprehensionLoopInfo loop = loops.get(loopIndex);
// iterator variable
gen.out("var ", loop.itVarName);
if (loopIndex == 0) {
gen.out("=");
loop.forIterator.getSpecifierExpression().visit(gen);
gen.out(".iterator()");
}
gen.endLine(true);
// value or key/value variables
if (loop.keyVarName == null) {
gen.out("var ", loop.valueVarName, "=", finished);
gen.endLine(true);
} else {
gen.out("var ", loop.keyVarName, ",", loop.valueVarName);
gen.endLine(true);
}
// variables for is/exists/nonempty conditions
for (List<ConditionGenerator.VarHolder> condVarList : loop.conditionVars) {
for (ConditionGenerator.VarHolder condVar : condVarList) {
gen.out("var ", condVar.name); gen.endLine(true);
directAccess.add(condVar.var.getDeclarationModel());
}
}
// generate the "next" function for this loop
boolean isLastLoop = (loopIndex == (loops.size()-1));
if (isLastLoop && loop.conditions.isEmpty() && (loop.keyVarName == null)) {
// simple case: innermost loop without conditions, no key/value iterator
gen.out("var next$", loop.valueVarName, "=function(){return ",
loop.valueVarName, "=", loop.itVarName, ".next();}");
gen.endLine();
}
else {
gen.out("var next$", loop.valueVarName, "=function()");
gen.beginBlock();
// extra entry variable for key/value iterators
String elemVarName = loop.valueVarName;
if (loop.keyVarName != null) {
elemVarName = names.createTempVariable("entry");
gen.out("var ", elemVarName); gen.endLine(true);
}
// if/while ((elemVar=it.next()!==$finished)
gen.out(loop.conditions.isEmpty()?"if":"while", "((", elemVarName, "=",
loop.itVarName, ".next())!==", finished, ")");
gen.beginBlock();
// get key/value if necessary
if (loop.keyVarName != null) {
gen.out(loop.keyVarName, "=", elemVarName, ".key"); gen.endLine(true);
gen.out(loop.valueVarName, "=", elemVarName, ".item"); gen.endLine(true);
}
// generate conditions as nested ifs
for (int i=0; i<loop.conditions.size(); i++) {
gen.conds.specialConditions(loop.conditionVars.get(i), loop.conditions.get(i), "if");
gen.beginBlock();
}
// initialize iterator of next loop and get its first element
if (!isLastLoop) {
ComprehensionLoopInfo nextLoop = loops.get(loopIndex+1);
gen.out(nextLoop.itVarName, "=");
nextLoop.forIterator.getSpecifierExpression().visit(gen);
gen.out(".iterator()"); gen.endLine(true);
gen.out("next$", nextLoop.valueVarName, "()"); gen.endLine(true);
}
gen.out("return ", elemVarName); gen.endLine(true);
for (int i=0; i<=loop.conditions.size(); i++) { gen.endBlockNewLine(); }
retainedVars.emitRetainedVars(gen);
// for key/value iterators, value==undefined indicates that the iterator is finished
if (loop.keyVarName != null) {
gen.out(loop.valueVarName, "=undefined"); gen.endLine(true);
}
gen.out("return ", finished, ";");
gen.endBlockNewLine();
}
}
// get the first element
gen.out("next$", loops.get(0).valueVarName, "()"); gen.endLine(true);
// generate the "next" function for the comprehension
gen.out("return function()");
gen.beginBlock();
// start a do-while block for all except the innermost loop
for (int i=1; i<loops.size(); i++) {
gen.out("do"); gen.beginBlock();
}
// Check if another element is available on the innermost loop.
// If yes, evaluate the expression, advance the iterator and return the result.
ComprehensionLoopInfo lastLoop = loops.get(loops.size()-1);
gen.out("if(", lastLoop.valueVarName, "!==", (lastLoop.keyVarName==null)
? finished : "undefined", ")");
gen.beginBlock();
declareExternalLoopVars(lastLoop);
String tempVarName = names.createTempVariable();
gen.out("var ", tempVarName, "=");
expression.visit(gen);
gen.endLine(true);
retainedVars.emitRetainedVars(gen);
gen.out("next$", lastLoop.valueVarName, "()"); gen.endLine(true);
gen.out("return ", tempVarName, ";");
gen.endBlockNewLine();
// "while" part of the do-while loops
for (int i=loops.size()-2; i>=0; i--) {
gen.endBlock();
gen.out("while(next$", loops.get(i).valueVarName, "()!==", finished, ")");
gen.endLine(true);
}
gen.out("return ", finished, ";");
gen.endBlockNewLine();
if (tail != null) {
- // tail is set for comprehensions beginning with an "if" clause, and contains the outer else
- gen.endLine(false);
- gen.out(tail);
- // also, we have to close the blocks that were opened by the "if"s
+ // tail is set for comprehensions beginning with an "if" clause
+ // we have to close the blocks that were opened by the "if"s
for (int i = 0; i < initialIfClauses; i++) {
gen.endBlock();
}
+ // tail contains the outer else
+ gen.endLine();
+ gen.out(tail);
}
gen.endBlock();
gen.out(",");
TypeUtils.printTypeArguments(that, gen.getTypeUtils().wrapAsIterableArguments(that.getTypeModel()), gen);
gen.out(")");
}
private void declareExternalLoopVars(ComprehensionLoopInfo loop) {
if (loop.keyVarName != null) {
String tk = names.createTempVariable(loop.keyVarName);
gen.out("var ", tk, "=", loop.keyVarName); gen.endLine(true);
names.forceName(loop.keyDecl, tk);
}
String tv = names.createTempVariable(loop.valueVarName);
gen.out("var ", tv, "=", loop.valueVarName); gen.endLine(true);
names.forceName(loop.valDecl, tv);
}
/** Represents one of the for loops of a comprehension including the associated conditions */
private class ComprehensionLoopInfo {
public final ForIterator forIterator;
public final List<Tree.ConditionList> conditions = new ArrayList<Tree.ConditionList>();
public final List<List<ConditionGenerator.VarHolder>> conditionVars = new ArrayList<List<ConditionGenerator.VarHolder>>();
public final String itVarName;
public final String valueVarName;
public final String keyVarName;
public final Declaration keyDecl;
public final Declaration valDecl;
public ComprehensionLoopInfo(Comprehension that, ForIterator forIterator) {
this.forIterator = forIterator;
itVarName = names.createTempVariable("it");
Variable valueVar = null;
Variable keyVar = null;
if (forIterator instanceof ValueIterator) {
valueVar = ((ValueIterator) forIterator).getVariable();
} else if (forIterator instanceof KeyValueIterator) {
KeyValueIterator kvit = (KeyValueIterator) forIterator;
valueVar = kvit.getValueVariable();
keyVar = kvit.getKeyVariable();
} else {
that.addError("No support yet for iterators of type "
+ forIterator.getClass().getName());
valueVarName = null;
keyVarName = null;
keyDecl = null;
valDecl = null;
return;
}
if (keyVar == null) {
keyVarName = null;
keyDecl = null;
} else {
keyDecl = keyVar.getDeclarationModel();
keyVarName = names.name(keyDecl);
directAccess.add(keyDecl);
}
valDecl = valueVar.getDeclarationModel();
this.valueVarName = names.name(valDecl);
directAccess.add(valDecl);
}
}
}
| false | true |
void generateComprehension(Comprehension that) {
gen.out(GenerateJsVisitor.getClAlias(), "Comprehension(function()");
gen.beginBlock();
if (gen.opts.isComment()) {
gen.out("//Comprehension"); gen.location(that); gen.endLine();
}
// gather information about all loops and conditions in the comprehension
List<ComprehensionLoopInfo> loops = new ArrayList<ComprehensionLoopInfo>();
Expression expression = null;
ComprehensionClause startClause = that.getInitialComprehensionClause();
String tail = null;
/**
* The number of initial "if" comprehension clauses, i. e., the number of blocks that have to be ended.
*/
int initialIfClauses = 0;
while (!(startClause instanceof ForComprehensionClause)) {
if (startClause instanceof IfComprehensionClause) {
// check the condition
IfComprehensionClause ifClause = (IfComprehensionClause)startClause;
gen.conds.specialConditions(
gen.conds.gatherVariables(ifClause.getConditionList()),
ifClause.getConditionList(),
"if");
initialIfClauses++;
gen.beginBlock();
startClause = ifClause.getComprehensionClause();
if (startClause instanceof ForComprehensionClause) {
// we'll put the rest of the condition inside this if block;
// outside the if block, return nothing (if any condition isn't true)
tail = "return function(){return " + finished + ";}";
}
} else if (startClause instanceof ExpressionComprehensionClause) {
// return the expression result
gen.out("return function() {");
((ExpressionComprehensionClause)startClause).getExpression().visit(gen);
gen.out("};");
for (int i = 0; i < initialIfClauses; i++) {
gen.endBlock();
}
gen.endBlock(); // end one more block - this one is for the function
gen.out(",");
TypeUtils.printTypeArguments(that, gen.getTypeUtils().wrapAsIterableArguments(that.getTypeModel()), gen);
gen.out(")");
return;
} else {
that.addError("No support for comprehension clause of type "
+ startClause.getClass().getName());
return;
}
}
ForComprehensionClause forClause = (ForComprehensionClause)startClause;
while (forClause != null) {
ComprehensionLoopInfo loop = new ComprehensionLoopInfo(that, forClause.getForIterator());
ComprehensionClause clause = forClause.getComprehensionClause();
while ((clause != null) && !(clause instanceof ForComprehensionClause)) {
if (clause instanceof IfComprehensionClause) {
IfComprehensionClause ifClause = ((IfComprehensionClause) clause);
loop.conditions.add(ifClause.getConditionList());
loop.conditionVars.add(gen.conds.gatherVariables(ifClause.getConditionList()));
clause = ifClause.getComprehensionClause();
} else if (clause instanceof ExpressionComprehensionClause) {
expression = ((ExpressionComprehensionClause) clause).getExpression();
clause = null;
} else {
that.addError("No support for comprehension clause of type "
+ clause.getClass().getName());
return;
}
}
loops.add(loop);
forClause = (ForComprehensionClause) clause;
}
// generate variables and "next" function for each for loop
for (int loopIndex=0; loopIndex<loops.size(); loopIndex++) {
ComprehensionLoopInfo loop = loops.get(loopIndex);
// iterator variable
gen.out("var ", loop.itVarName);
if (loopIndex == 0) {
gen.out("=");
loop.forIterator.getSpecifierExpression().visit(gen);
gen.out(".iterator()");
}
gen.endLine(true);
// value or key/value variables
if (loop.keyVarName == null) {
gen.out("var ", loop.valueVarName, "=", finished);
gen.endLine(true);
} else {
gen.out("var ", loop.keyVarName, ",", loop.valueVarName);
gen.endLine(true);
}
// variables for is/exists/nonempty conditions
for (List<ConditionGenerator.VarHolder> condVarList : loop.conditionVars) {
for (ConditionGenerator.VarHolder condVar : condVarList) {
gen.out("var ", condVar.name); gen.endLine(true);
directAccess.add(condVar.var.getDeclarationModel());
}
}
// generate the "next" function for this loop
boolean isLastLoop = (loopIndex == (loops.size()-1));
if (isLastLoop && loop.conditions.isEmpty() && (loop.keyVarName == null)) {
// simple case: innermost loop without conditions, no key/value iterator
gen.out("var next$", loop.valueVarName, "=function(){return ",
loop.valueVarName, "=", loop.itVarName, ".next();}");
gen.endLine();
}
else {
gen.out("var next$", loop.valueVarName, "=function()");
gen.beginBlock();
// extra entry variable for key/value iterators
String elemVarName = loop.valueVarName;
if (loop.keyVarName != null) {
elemVarName = names.createTempVariable("entry");
gen.out("var ", elemVarName); gen.endLine(true);
}
// if/while ((elemVar=it.next()!==$finished)
gen.out(loop.conditions.isEmpty()?"if":"while", "((", elemVarName, "=",
loop.itVarName, ".next())!==", finished, ")");
gen.beginBlock();
// get key/value if necessary
if (loop.keyVarName != null) {
gen.out(loop.keyVarName, "=", elemVarName, ".key"); gen.endLine(true);
gen.out(loop.valueVarName, "=", elemVarName, ".item"); gen.endLine(true);
}
// generate conditions as nested ifs
for (int i=0; i<loop.conditions.size(); i++) {
gen.conds.specialConditions(loop.conditionVars.get(i), loop.conditions.get(i), "if");
gen.beginBlock();
}
// initialize iterator of next loop and get its first element
if (!isLastLoop) {
ComprehensionLoopInfo nextLoop = loops.get(loopIndex+1);
gen.out(nextLoop.itVarName, "=");
nextLoop.forIterator.getSpecifierExpression().visit(gen);
gen.out(".iterator()"); gen.endLine(true);
gen.out("next$", nextLoop.valueVarName, "()"); gen.endLine(true);
}
gen.out("return ", elemVarName); gen.endLine(true);
for (int i=0; i<=loop.conditions.size(); i++) { gen.endBlockNewLine(); }
retainedVars.emitRetainedVars(gen);
// for key/value iterators, value==undefined indicates that the iterator is finished
if (loop.keyVarName != null) {
gen.out(loop.valueVarName, "=undefined"); gen.endLine(true);
}
gen.out("return ", finished, ";");
gen.endBlockNewLine();
}
}
// get the first element
gen.out("next$", loops.get(0).valueVarName, "()"); gen.endLine(true);
// generate the "next" function for the comprehension
gen.out("return function()");
gen.beginBlock();
// start a do-while block for all except the innermost loop
for (int i=1; i<loops.size(); i++) {
gen.out("do"); gen.beginBlock();
}
// Check if another element is available on the innermost loop.
// If yes, evaluate the expression, advance the iterator and return the result.
ComprehensionLoopInfo lastLoop = loops.get(loops.size()-1);
gen.out("if(", lastLoop.valueVarName, "!==", (lastLoop.keyVarName==null)
? finished : "undefined", ")");
gen.beginBlock();
declareExternalLoopVars(lastLoop);
String tempVarName = names.createTempVariable();
gen.out("var ", tempVarName, "=");
expression.visit(gen);
gen.endLine(true);
retainedVars.emitRetainedVars(gen);
gen.out("next$", lastLoop.valueVarName, "()"); gen.endLine(true);
gen.out("return ", tempVarName, ";");
gen.endBlockNewLine();
// "while" part of the do-while loops
for (int i=loops.size()-2; i>=0; i--) {
gen.endBlock();
gen.out("while(next$", loops.get(i).valueVarName, "()!==", finished, ")");
gen.endLine(true);
}
gen.out("return ", finished, ";");
gen.endBlockNewLine();
if (tail != null) {
// tail is set for comprehensions beginning with an "if" clause, and contains the outer else
gen.endLine(false);
gen.out(tail);
// also, we have to close the blocks that were opened by the "if"s
for (int i = 0; i < initialIfClauses; i++) {
gen.endBlock();
}
}
gen.endBlock();
gen.out(",");
TypeUtils.printTypeArguments(that, gen.getTypeUtils().wrapAsIterableArguments(that.getTypeModel()), gen);
gen.out(")");
}
|
void generateComprehension(Comprehension that) {
gen.out(GenerateJsVisitor.getClAlias(), "Comprehension(function()");
gen.beginBlock();
if (gen.opts.isComment()) {
gen.out("//Comprehension"); gen.location(that); gen.endLine();
}
// gather information about all loops and conditions in the comprehension
List<ComprehensionLoopInfo> loops = new ArrayList<ComprehensionLoopInfo>();
Expression expression = null;
ComprehensionClause startClause = that.getInitialComprehensionClause();
String tail = null;
/**
* The number of initial "if" comprehension clauses, i. e., the number of blocks that have to be ended.
*/
int initialIfClauses = 0;
while (!(startClause instanceof ForComprehensionClause)) {
if (startClause instanceof IfComprehensionClause) {
// check the condition
IfComprehensionClause ifClause = (IfComprehensionClause)startClause;
gen.conds.specialConditions(
gen.conds.gatherVariables(ifClause.getConditionList()),
ifClause.getConditionList(),
"if");
initialIfClauses++;
gen.beginBlock();
startClause = ifClause.getComprehensionClause();
if (!(startClause instanceof IfComprehensionClause)) {
// we'll put the rest of the comprehension inside this if block;
// outside the if block, return nothing (if any condition isn't true)
tail = "return function(){return " + finished + ";}";
}
} else if (startClause instanceof ExpressionComprehensionClause) {
// return the expression result
gen.out("return function() {");
((ExpressionComprehensionClause)startClause).getExpression().visit(gen);
gen.out("};");
for (int i = 0; i < initialIfClauses; i++) {
gen.endBlock();
}
gen.endLine();
gen.out(tail);
gen.endBlock(); // end one more block - this one is for the function
gen.out(",");
TypeUtils.printTypeArguments(that, gen.getTypeUtils().wrapAsIterableArguments(that.getTypeModel()), gen);
gen.out(")");
return;
} else {
that.addError("No support for comprehension clause of type "
+ startClause.getClass().getName());
return;
}
}
ForComprehensionClause forClause = (ForComprehensionClause)startClause;
while (forClause != null) {
ComprehensionLoopInfo loop = new ComprehensionLoopInfo(that, forClause.getForIterator());
ComprehensionClause clause = forClause.getComprehensionClause();
while ((clause != null) && !(clause instanceof ForComprehensionClause)) {
if (clause instanceof IfComprehensionClause) {
IfComprehensionClause ifClause = ((IfComprehensionClause) clause);
loop.conditions.add(ifClause.getConditionList());
loop.conditionVars.add(gen.conds.gatherVariables(ifClause.getConditionList()));
clause = ifClause.getComprehensionClause();
} else if (clause instanceof ExpressionComprehensionClause) {
expression = ((ExpressionComprehensionClause) clause).getExpression();
clause = null;
} else {
that.addError("No support for comprehension clause of type "
+ clause.getClass().getName());
return;
}
}
loops.add(loop);
forClause = (ForComprehensionClause) clause;
}
// generate variables and "next" function for each for loop
for (int loopIndex=0; loopIndex<loops.size(); loopIndex++) {
ComprehensionLoopInfo loop = loops.get(loopIndex);
// iterator variable
gen.out("var ", loop.itVarName);
if (loopIndex == 0) {
gen.out("=");
loop.forIterator.getSpecifierExpression().visit(gen);
gen.out(".iterator()");
}
gen.endLine(true);
// value or key/value variables
if (loop.keyVarName == null) {
gen.out("var ", loop.valueVarName, "=", finished);
gen.endLine(true);
} else {
gen.out("var ", loop.keyVarName, ",", loop.valueVarName);
gen.endLine(true);
}
// variables for is/exists/nonempty conditions
for (List<ConditionGenerator.VarHolder> condVarList : loop.conditionVars) {
for (ConditionGenerator.VarHolder condVar : condVarList) {
gen.out("var ", condVar.name); gen.endLine(true);
directAccess.add(condVar.var.getDeclarationModel());
}
}
// generate the "next" function for this loop
boolean isLastLoop = (loopIndex == (loops.size()-1));
if (isLastLoop && loop.conditions.isEmpty() && (loop.keyVarName == null)) {
// simple case: innermost loop without conditions, no key/value iterator
gen.out("var next$", loop.valueVarName, "=function(){return ",
loop.valueVarName, "=", loop.itVarName, ".next();}");
gen.endLine();
}
else {
gen.out("var next$", loop.valueVarName, "=function()");
gen.beginBlock();
// extra entry variable for key/value iterators
String elemVarName = loop.valueVarName;
if (loop.keyVarName != null) {
elemVarName = names.createTempVariable("entry");
gen.out("var ", elemVarName); gen.endLine(true);
}
// if/while ((elemVar=it.next()!==$finished)
gen.out(loop.conditions.isEmpty()?"if":"while", "((", elemVarName, "=",
loop.itVarName, ".next())!==", finished, ")");
gen.beginBlock();
// get key/value if necessary
if (loop.keyVarName != null) {
gen.out(loop.keyVarName, "=", elemVarName, ".key"); gen.endLine(true);
gen.out(loop.valueVarName, "=", elemVarName, ".item"); gen.endLine(true);
}
// generate conditions as nested ifs
for (int i=0; i<loop.conditions.size(); i++) {
gen.conds.specialConditions(loop.conditionVars.get(i), loop.conditions.get(i), "if");
gen.beginBlock();
}
// initialize iterator of next loop and get its first element
if (!isLastLoop) {
ComprehensionLoopInfo nextLoop = loops.get(loopIndex+1);
gen.out(nextLoop.itVarName, "=");
nextLoop.forIterator.getSpecifierExpression().visit(gen);
gen.out(".iterator()"); gen.endLine(true);
gen.out("next$", nextLoop.valueVarName, "()"); gen.endLine(true);
}
gen.out("return ", elemVarName); gen.endLine(true);
for (int i=0; i<=loop.conditions.size(); i++) { gen.endBlockNewLine(); }
retainedVars.emitRetainedVars(gen);
// for key/value iterators, value==undefined indicates that the iterator is finished
if (loop.keyVarName != null) {
gen.out(loop.valueVarName, "=undefined"); gen.endLine(true);
}
gen.out("return ", finished, ";");
gen.endBlockNewLine();
}
}
// get the first element
gen.out("next$", loops.get(0).valueVarName, "()"); gen.endLine(true);
// generate the "next" function for the comprehension
gen.out("return function()");
gen.beginBlock();
// start a do-while block for all except the innermost loop
for (int i=1; i<loops.size(); i++) {
gen.out("do"); gen.beginBlock();
}
// Check if another element is available on the innermost loop.
// If yes, evaluate the expression, advance the iterator and return the result.
ComprehensionLoopInfo lastLoop = loops.get(loops.size()-1);
gen.out("if(", lastLoop.valueVarName, "!==", (lastLoop.keyVarName==null)
? finished : "undefined", ")");
gen.beginBlock();
declareExternalLoopVars(lastLoop);
String tempVarName = names.createTempVariable();
gen.out("var ", tempVarName, "=");
expression.visit(gen);
gen.endLine(true);
retainedVars.emitRetainedVars(gen);
gen.out("next$", lastLoop.valueVarName, "()"); gen.endLine(true);
gen.out("return ", tempVarName, ";");
gen.endBlockNewLine();
// "while" part of the do-while loops
for (int i=loops.size()-2; i>=0; i--) {
gen.endBlock();
gen.out("while(next$", loops.get(i).valueVarName, "()!==", finished, ")");
gen.endLine(true);
}
gen.out("return ", finished, ";");
gen.endBlockNewLine();
if (tail != null) {
// tail is set for comprehensions beginning with an "if" clause
// we have to close the blocks that were opened by the "if"s
for (int i = 0; i < initialIfClauses; i++) {
gen.endBlock();
}
// tail contains the outer else
gen.endLine();
gen.out(tail);
}
gen.endBlock();
gen.out(",");
TypeUtils.printTypeArguments(that, gen.getTypeUtils().wrapAsIterableArguments(that.getTypeModel()), gen);
gen.out(")");
}
|
diff --git a/net.sf.jmoney.jdbcdatastore/src/net/sf/jmoney/jdbcdatastore/handlers/OpenSessionHandler.java b/net.sf.jmoney.jdbcdatastore/src/net/sf/jmoney/jdbcdatastore/handlers/OpenSessionHandler.java
index 5e66e283..83b72e5f 100644
--- a/net.sf.jmoney.jdbcdatastore/src/net/sf/jmoney/jdbcdatastore/handlers/OpenSessionHandler.java
+++ b/net.sf.jmoney.jdbcdatastore/src/net/sf/jmoney/jdbcdatastore/handlers/OpenSessionHandler.java
@@ -1,63 +1,63 @@
package net.sf.jmoney.jdbcdatastore.handlers;
import net.sf.jmoney.JMoneyPlugin;
import net.sf.jmoney.jdbcdatastore.JDBCDatastorePlugin;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.WorkbenchException;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.services.IEvaluationService;
/**
* Shows the given perspective. If no perspective is specified in the
* parameters, then this opens the perspective selection dialog.
*
* @since 3.1
*/
public final class OpenSessionHandler extends AbstractHandler {
public final Object execute(final ExecutionEvent event)
throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
if (JMoneyPlugin.getDefault().saveOldSession(window)) {
IWorkbenchPage activePage = window.getActivePage();
activePage.close();
net.sf.jmoney.jdbcdatastore.SessionManager sessionManager = JDBCDatastorePlugin.getDefault().readSession(window);
if (sessionManager != null) {
// This call needs to be cleaned up, but is still needed
// to ensure a default currency is set.
- JMoneyPlugin.getDefault().setSessionManager(sessionManager);
+ JMoneyPlugin.getDefault().initializeNewSession(sessionManager);
}
try {
window.openPage(sessionManager);
} catch (WorkbenchException e) {
ErrorDialog.openError(window.getShell(),
"Open Session failed", e
.getMessage(), e.getStatus());
throw new ExecutionException("Session could not be opened.", e); //$NON-NLS-1$
}
/*
* The state of the 'isSessionOpen' property may have changed, so we
* force a re-evaluation which will update any UI items whose
* state depends on this property.
*/
IEvaluationService service = (IEvaluationService)PlatformUI.getWorkbench().getService(IEvaluationService.class);
service.requestEvaluation("net.sf.jmoney.core.isSessionOpen");
}
return null;
}
}
| true | true |
public final Object execute(final ExecutionEvent event)
throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
if (JMoneyPlugin.getDefault().saveOldSession(window)) {
IWorkbenchPage activePage = window.getActivePage();
activePage.close();
net.sf.jmoney.jdbcdatastore.SessionManager sessionManager = JDBCDatastorePlugin.getDefault().readSession(window);
if (sessionManager != null) {
// This call needs to be cleaned up, but is still needed
// to ensure a default currency is set.
JMoneyPlugin.getDefault().setSessionManager(sessionManager);
}
try {
window.openPage(sessionManager);
} catch (WorkbenchException e) {
ErrorDialog.openError(window.getShell(),
"Open Session failed", e
.getMessage(), e.getStatus());
throw new ExecutionException("Session could not be opened.", e); //$NON-NLS-1$
}
/*
* The state of the 'isSessionOpen' property may have changed, so we
* force a re-evaluation which will update any UI items whose
* state depends on this property.
*/
IEvaluationService service = (IEvaluationService)PlatformUI.getWorkbench().getService(IEvaluationService.class);
service.requestEvaluation("net.sf.jmoney.core.isSessionOpen");
}
return null;
}
|
public final Object execute(final ExecutionEvent event)
throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
if (JMoneyPlugin.getDefault().saveOldSession(window)) {
IWorkbenchPage activePage = window.getActivePage();
activePage.close();
net.sf.jmoney.jdbcdatastore.SessionManager sessionManager = JDBCDatastorePlugin.getDefault().readSession(window);
if (sessionManager != null) {
// This call needs to be cleaned up, but is still needed
// to ensure a default currency is set.
JMoneyPlugin.getDefault().initializeNewSession(sessionManager);
}
try {
window.openPage(sessionManager);
} catch (WorkbenchException e) {
ErrorDialog.openError(window.getShell(),
"Open Session failed", e
.getMessage(), e.getStatus());
throw new ExecutionException("Session could not be opened.", e); //$NON-NLS-1$
}
/*
* The state of the 'isSessionOpen' property may have changed, so we
* force a re-evaluation which will update any UI items whose
* state depends on this property.
*/
IEvaluationService service = (IEvaluationService)PlatformUI.getWorkbench().getService(IEvaluationService.class);
service.requestEvaluation("net.sf.jmoney.core.isSessionOpen");
}
return null;
}
|
diff --git a/frost-wot/source/frost/fileTransfer/FileListManager.java b/frost-wot/source/frost/fileTransfer/FileListManager.java
index 90a5c920..c66c507a 100644
--- a/frost-wot/source/frost/fileTransfer/FileListManager.java
+++ b/frost-wot/source/frost/fileTransfer/FileListManager.java
@@ -1,279 +1,286 @@
/*
FileListManager.java / Frost
Copyright (C) 2006 Frost Project <jtcfrost.sourceforge.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 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package frost.fileTransfer;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import frost.*;
import frost.fileTransfer.download.*;
import frost.fileTransfer.sharing.*;
import frost.identities.*;
import frost.storage.database.applayer.*;
public class FileListManager {
private static final Logger logger = Logger.getLogger(FileListManager.class.getName());
public static final int MAX_FILES_PER_FILE = 250; // TODO: count utf-8 size of sharedxmlfiles, not more than 512kb!
/**
* Used to sort FrostSharedFileItems by refLastSent ascending.
*/
private static final Comparator<FrostSharedFileItem> refLastSentComparator = new Comparator<FrostSharedFileItem>() {
public int compare(FrostSharedFileItem value1, FrostSharedFileItem value2) {
if (value1.getRefLastSent() > value2.getRefLastSent()) {
return 1;
} else if (value1.getRefLastSent() < value2.getRefLastSent()) {
return -1;
} else {
return 0;
}
}
};
/**
* @return an info class that is guaranteed to contain an owner and files
*/
public static FileListManagerFileInfo getFilesToSend() {
// get files to share from UPLOADFILES
// - max. 250 keys per fileindex
// - get keys of only 1 owner/anonymous, next time get keys from different owner
// this wrap-arounding ensures that each file will be send over the time
// compute minDate, items last shared before this date must be reshared
int maxAge = Core.frostSettings.getIntValue(SettingsClass.MIN_DAYS_BEFORE_FILE_RESHARE);
long maxDiff = (long)maxAge * 24L * 60L * 60L * 1000L;
long now = System.currentTimeMillis();
long minDate = now - maxDiff;
List localIdentities = Core.getIdentities().getLocalIdentities();
int identityCount = localIdentities.size();
while(identityCount > 0) {
LocalIdentity idToUpdate = null;
long minUpdateMillis = Long.MAX_VALUE;
// find next identity to update
for(Iterator i=localIdentities.iterator(); i.hasNext(); ) {
LocalIdentity id = (LocalIdentity)i.next();
long lastShared = id.getLastFilesSharedMillis();
if( lastShared < minUpdateMillis ) {
minUpdateMillis = lastShared;
idToUpdate = id;
}
}
// mark that we tried this owner
idToUpdate.updateLastFilesSharedMillis();
LinkedList<SharedFileXmlFile> filesToShare = getUploadItemsToShare(idToUpdate.getUniqueName(), MAX_FILES_PER_FILE, minDate);
if( filesToShare != null && filesToShare.size() > 0 ) {
FileListManagerFileInfo fif = new FileListManagerFileInfo(filesToShare, idToUpdate);
return fif;
}
// else try next owner
identityCount--;
}
// nothing to share now
return null;
}
private static LinkedList<SharedFileXmlFile> getUploadItemsToShare(String owner, int maxItems, long minDate) {
LinkedList<SharedFileXmlFile> result = new LinkedList<SharedFileXmlFile>();
ArrayList<FrostSharedFileItem> sorted = new ArrayList<FrostSharedFileItem>();
{
List sharedFileItems = FileTransferManager.inst().getSharedFilesManager().getModel().getItems();
// first collect all items for this owner and sort them
for( Iterator i = sharedFileItems.iterator(); i.hasNext(); ) {
FrostSharedFileItem sfo = (FrostSharedFileItem) i.next();
if( !sfo.isValid() ) {
continue;
}
if( !sfo.getOwner().equals(owner) ) {
continue;
}
sorted.add(sfo);
}
}
if( sorted.isEmpty() ) {
// no shared files for this owner
return result;
}
// sort ascending, oldest items at the beginning
Collections.sort(sorted, refLastSentComparator);
{
// check if oldest item must be shared (maybe its new or updated)
FrostSharedFileItem sfo = sorted.get(0);
if( sfo.getRefLastSent() > minDate ) {
// oldest item is'nt too old, don't share
return result;
}
}
// finally add up to MAX_FILES items from the sorted list
for( Iterator i = sorted.iterator(); i.hasNext(); ) {
FrostSharedFileItem sfo = (FrostSharedFileItem) i.next();
result.add( sfo.getSharedFileXmlFileInstance() );
if( result.size() >= maxItems ) {
return result;
}
}
return result;
}
/**
* Update sent files.
* @param files List of SharedFileXmlFile objects that were successfully sent inside a CHK file
*/
public static boolean updateFileListWasSuccessfullySent(List files) {
long now = System.currentTimeMillis();
List sharedFileItems = FileTransferManager.inst().getSharedFilesManager().getModel().getItems();
for( Iterator i = files.iterator(); i.hasNext(); ) {
SharedFileXmlFile sfx = (SharedFileXmlFile) i.next();
// update FrostSharedUploadFileObject
for( Iterator j = sharedFileItems.iterator(); j.hasNext(); ) {
FrostSharedFileItem sfo = (FrostSharedFileItem) j.next();
if( sfo.getSha().equals(sfx.getSha()) ) {
sfo.setRefLastSent(now);
}
}
}
return true;
}
/**
* Add or update received files from owner
*/
public static boolean processReceivedFileList(FileListFileContent content) {
if( content == null
|| content.getReceivedOwner() == null
|| content.getFileList() == null
|| content.getFileList().size() == 0 )
{
return false;
}
Identity localOwner = Core.getIdentities().getIdentity(content.getReceivedOwner().getUniqueName());
if( localOwner == null ) {
// new identity, maybe add
if( !Core.getIdentities().isNewIdentityValid(content.getReceivedOwner()) ) {
// hash of public key does not match the unique name
return false;
}
Core.getIdentities().addIdentity(content.getReceivedOwner());
localOwner = content.getReceivedOwner();
}
localOwner.updateLastSeenTimestamp(content.getTimestamp());
if (localOwner.isBAD() && Core.frostSettings.getBoolValue(SettingsClass.SEARCH_HIDE_BAD)) {
logger.info("Skipped index file from BAD user " + localOwner.getUniqueName());
return true;
}
// first, update all filelist files
// get a connection for updates
// works well if no duplicate SHA is in the received list, otherwise we have false updates
Connection conn = AppLayerDatabase.getInstance().getPooledConnection();
boolean errorOccured = false;
try {
conn.setAutoCommit(false);
for( Iterator i = content.getFileList().iterator(); i.hasNext(); ) {
SharedFileXmlFile sfx = (SharedFileXmlFile) i.next();
FrostFileListFileObject sfo = new FrostFileListFileObject(sfx, localOwner, content.getTimestamp());
// update filelist database table
boolean wasOk = AppLayerDatabase.getFileListDatabaseTable().insertOrUpdateFrostFileListFileObject(sfo, conn);
if( wasOk == false ) {
- // if there is one error we skip the whole processing
- conn.rollback();
errorOccured = true;
break;
}
}
if( errorOccured == false ) {
conn.commit();
+ } else {
+ // if there is one error we skip the whole processing
+ conn.rollback();
}
conn.setAutoCommit(true);
} catch(Throwable t) {
- logger.log(Level.SEVERE, "Exception during insertOrUpdateFrostSharedFileObject", t);
- try { conn.rollback(); } catch(Throwable t1) { logger.log(Level.SEVERE, "Exception during rollback", t1); }
+ if( t.getMessage() != null && t.getMessage().indexOf("Select from table that has committed changes") > 0 ) {
+ // only a warning!
+ logger.log(Level.WARNING, "INFO: Select from table that has committed changes");
+ try { conn.commit(); } catch(Throwable t1) { logger.log(Level.SEVERE, "Exception during commit", t1); }
+ } else {
+ logger.log(Level.SEVERE, "Exception during insertOrUpdateFrostSharedFileObject", t);
+ try { conn.rollback(); } catch(Throwable t1) { logger.log(Level.SEVERE, "Exception during rollback", t1); }
+ }
try { conn.setAutoCommit(true); } catch(Throwable t1) { }
} finally {
AppLayerDatabase.getInstance().givePooledConnection(conn);
}
if( errorOccured ) {
return false;
}
// after updating the db, check if we have to update download items with the new informations
List downloadItems = FileTransferManager.inst().getDownloadManager().getModel().getItems();
for( Iterator i = content.getFileList().iterator(); i.hasNext(); ) {
SharedFileXmlFile sfx = (SharedFileXmlFile) i.next();
// if a FrostDownloadItem references this file (by sha), retrieve the updated file from db and set it
for( Iterator j = downloadItems.iterator(); j.hasNext(); ) {
FrostDownloadItem dlItem = (FrostDownloadItem) j.next();
if( !dlItem.isSharedFile() ) {
continue;
}
FrostFileListFileObject dlSfo = dlItem.getFileListFileObject();
if( dlSfo.getSha().equals( sfx.getSha() ) ) {
// this download item references the updated file
// update the shared file object from database (owner, sources, ... may have changed)
FrostFileListFileObject updatedSfo = null;
try {
updatedSfo = AppLayerDatabase.getFileListDatabaseTable().retrieveFileBySha(sfx.getSha());
} catch (Throwable t) {
logger.log(Level.SEVERE, "Exception in retrieveFileBySha", t);
}
if( updatedSfo != null ) {
dlItem.setFileListFileObject(updatedSfo);
}
break; // there is only one file in download table with same SHA
}
}
}
return true;
}
}
| false | true |
public static boolean processReceivedFileList(FileListFileContent content) {
if( content == null
|| content.getReceivedOwner() == null
|| content.getFileList() == null
|| content.getFileList().size() == 0 )
{
return false;
}
Identity localOwner = Core.getIdentities().getIdentity(content.getReceivedOwner().getUniqueName());
if( localOwner == null ) {
// new identity, maybe add
if( !Core.getIdentities().isNewIdentityValid(content.getReceivedOwner()) ) {
// hash of public key does not match the unique name
return false;
}
Core.getIdentities().addIdentity(content.getReceivedOwner());
localOwner = content.getReceivedOwner();
}
localOwner.updateLastSeenTimestamp(content.getTimestamp());
if (localOwner.isBAD() && Core.frostSettings.getBoolValue(SettingsClass.SEARCH_HIDE_BAD)) {
logger.info("Skipped index file from BAD user " + localOwner.getUniqueName());
return true;
}
// first, update all filelist files
// get a connection for updates
// works well if no duplicate SHA is in the received list, otherwise we have false updates
Connection conn = AppLayerDatabase.getInstance().getPooledConnection();
boolean errorOccured = false;
try {
conn.setAutoCommit(false);
for( Iterator i = content.getFileList().iterator(); i.hasNext(); ) {
SharedFileXmlFile sfx = (SharedFileXmlFile) i.next();
FrostFileListFileObject sfo = new FrostFileListFileObject(sfx, localOwner, content.getTimestamp());
// update filelist database table
boolean wasOk = AppLayerDatabase.getFileListDatabaseTable().insertOrUpdateFrostFileListFileObject(sfo, conn);
if( wasOk == false ) {
// if there is one error we skip the whole processing
conn.rollback();
errorOccured = true;
break;
}
}
if( errorOccured == false ) {
conn.commit();
}
conn.setAutoCommit(true);
} catch(Throwable t) {
logger.log(Level.SEVERE, "Exception during insertOrUpdateFrostSharedFileObject", t);
try { conn.rollback(); } catch(Throwable t1) { logger.log(Level.SEVERE, "Exception during rollback", t1); }
try { conn.setAutoCommit(true); } catch(Throwable t1) { }
} finally {
AppLayerDatabase.getInstance().givePooledConnection(conn);
}
if( errorOccured ) {
return false;
}
// after updating the db, check if we have to update download items with the new informations
List downloadItems = FileTransferManager.inst().getDownloadManager().getModel().getItems();
for( Iterator i = content.getFileList().iterator(); i.hasNext(); ) {
SharedFileXmlFile sfx = (SharedFileXmlFile) i.next();
// if a FrostDownloadItem references this file (by sha), retrieve the updated file from db and set it
for( Iterator j = downloadItems.iterator(); j.hasNext(); ) {
FrostDownloadItem dlItem = (FrostDownloadItem) j.next();
if( !dlItem.isSharedFile() ) {
continue;
}
FrostFileListFileObject dlSfo = dlItem.getFileListFileObject();
if( dlSfo.getSha().equals( sfx.getSha() ) ) {
// this download item references the updated file
// update the shared file object from database (owner, sources, ... may have changed)
FrostFileListFileObject updatedSfo = null;
try {
updatedSfo = AppLayerDatabase.getFileListDatabaseTable().retrieveFileBySha(sfx.getSha());
} catch (Throwable t) {
logger.log(Level.SEVERE, "Exception in retrieveFileBySha", t);
}
if( updatedSfo != null ) {
dlItem.setFileListFileObject(updatedSfo);
}
break; // there is only one file in download table with same SHA
}
}
}
return true;
}
|
public static boolean processReceivedFileList(FileListFileContent content) {
if( content == null
|| content.getReceivedOwner() == null
|| content.getFileList() == null
|| content.getFileList().size() == 0 )
{
return false;
}
Identity localOwner = Core.getIdentities().getIdentity(content.getReceivedOwner().getUniqueName());
if( localOwner == null ) {
// new identity, maybe add
if( !Core.getIdentities().isNewIdentityValid(content.getReceivedOwner()) ) {
// hash of public key does not match the unique name
return false;
}
Core.getIdentities().addIdentity(content.getReceivedOwner());
localOwner = content.getReceivedOwner();
}
localOwner.updateLastSeenTimestamp(content.getTimestamp());
if (localOwner.isBAD() && Core.frostSettings.getBoolValue(SettingsClass.SEARCH_HIDE_BAD)) {
logger.info("Skipped index file from BAD user " + localOwner.getUniqueName());
return true;
}
// first, update all filelist files
// get a connection for updates
// works well if no duplicate SHA is in the received list, otherwise we have false updates
Connection conn = AppLayerDatabase.getInstance().getPooledConnection();
boolean errorOccured = false;
try {
conn.setAutoCommit(false);
for( Iterator i = content.getFileList().iterator(); i.hasNext(); ) {
SharedFileXmlFile sfx = (SharedFileXmlFile) i.next();
FrostFileListFileObject sfo = new FrostFileListFileObject(sfx, localOwner, content.getTimestamp());
// update filelist database table
boolean wasOk = AppLayerDatabase.getFileListDatabaseTable().insertOrUpdateFrostFileListFileObject(sfo, conn);
if( wasOk == false ) {
errorOccured = true;
break;
}
}
if( errorOccured == false ) {
conn.commit();
} else {
// if there is one error we skip the whole processing
conn.rollback();
}
conn.setAutoCommit(true);
} catch(Throwable t) {
if( t.getMessage() != null && t.getMessage().indexOf("Select from table that has committed changes") > 0 ) {
// only a warning!
logger.log(Level.WARNING, "INFO: Select from table that has committed changes");
try { conn.commit(); } catch(Throwable t1) { logger.log(Level.SEVERE, "Exception during commit", t1); }
} else {
logger.log(Level.SEVERE, "Exception during insertOrUpdateFrostSharedFileObject", t);
try { conn.rollback(); } catch(Throwable t1) { logger.log(Level.SEVERE, "Exception during rollback", t1); }
}
try { conn.setAutoCommit(true); } catch(Throwable t1) { }
} finally {
AppLayerDatabase.getInstance().givePooledConnection(conn);
}
if( errorOccured ) {
return false;
}
// after updating the db, check if we have to update download items with the new informations
List downloadItems = FileTransferManager.inst().getDownloadManager().getModel().getItems();
for( Iterator i = content.getFileList().iterator(); i.hasNext(); ) {
SharedFileXmlFile sfx = (SharedFileXmlFile) i.next();
// if a FrostDownloadItem references this file (by sha), retrieve the updated file from db and set it
for( Iterator j = downloadItems.iterator(); j.hasNext(); ) {
FrostDownloadItem dlItem = (FrostDownloadItem) j.next();
if( !dlItem.isSharedFile() ) {
continue;
}
FrostFileListFileObject dlSfo = dlItem.getFileListFileObject();
if( dlSfo.getSha().equals( sfx.getSha() ) ) {
// this download item references the updated file
// update the shared file object from database (owner, sources, ... may have changed)
FrostFileListFileObject updatedSfo = null;
try {
updatedSfo = AppLayerDatabase.getFileListDatabaseTable().retrieveFileBySha(sfx.getSha());
} catch (Throwable t) {
logger.log(Level.SEVERE, "Exception in retrieveFileBySha", t);
}
if( updatedSfo != null ) {
dlItem.setFileListFileObject(updatedSfo);
}
break; // there is only one file in download table with same SHA
}
}
}
return true;
}
|
diff --git a/base/src/edu/berkeley/cs/cs162/ChatServer.java b/base/src/edu/berkeley/cs/cs162/ChatServer.java
index 32acfc2..215a173 100644
--- a/base/src/edu/berkeley/cs/cs162/ChatServer.java
+++ b/base/src/edu/berkeley/cs/cs162/ChatServer.java
@@ -1,447 +1,448 @@
package edu.berkeley.cs.cs162;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* This is the core of the chat server. Put the management of groups
* and users in here. You will need to control all of the threads,
* and respond to requests from the test harness.
*
* It must implement the ChatServerInterface Interface, and you should
* not modify that interface; it is necessary for testing.
*/
public class ChatServer extends Thread implements ChatServerInterface {
private BlockingQueue<String> waiting_users;
private Map<String, User> users;
private Map<String, ChatGroup> groups;
private Set<String> allNames;
private ReentrantReadWriteLock lock;
private volatile boolean isDown;
private final static int MAX_USERS = 100;
private final static int MAX_WAITING_USERS = 10;
private ServerSocket mySocket;
private ExecutorService pool;
private Map<String, SocketParams> waiting_sockets;
public ChatServer() {
users = new HashMap<String, User>();
groups = new HashMap<String, ChatGroup>();
allNames = new HashSet<String>();
lock = new ReentrantReadWriteLock(true);
waiting_users = new ArrayBlockingQueue<String>(MAX_WAITING_USERS);
isDown = false;
}
public ChatServer(int port) throws IOException {
users = new HashMap<String, User>();
groups = new HashMap<String, ChatGroup>();
allNames = new HashSet<String>();
lock = new ReentrantReadWriteLock(true);
waiting_users = new ArrayBlockingQueue<String>(MAX_WAITING_USERS);
isDown = false;
pool = Executors.newFixedThreadPool(100);
try {
mySocket = new ServerSocket(port);
} catch (Exception e) {
throw new IOException("Server socket creation failed");
}
waiting_sockets = new ConcurrentHashMap<String, SocketParams>();
this.start();
}
@Override
public BaseUser getUser(String username) {
BaseUser u;
lock.readLock().lock();
u = users.get(username);
lock.readLock().unlock();
return u;
}
public ChatGroup getGroup(String groupname) {
ChatGroup group;
lock.readLock().lock();
group = groups.get(groupname);
lock.readLock().unlock();
return group;
}
public Set<String> getGroups() {
Set<String> groupNames;
lock.readLock().lock();
groupNames = this.groups.keySet();
lock.readLock().unlock();
return groupNames;
}
public Set<String> getUsers() {
Set<String> userNames;
lock.readLock().lock();
userNames = users.keySet();
lock.readLock().unlock();
return userNames;
}
public int getNumUsers(){
int num;
lock.readLock().lock();
num = users.size();
lock.readLock().unlock();
return num;
}
public int getNumGroups(){
int num;
lock.readLock().lock();
num = groups.size();
lock.readLock().unlock();
return num;
}
@Override
public LoginError login(String username) {
lock.writeLock().lock();
if(isDown){
TestChatServer.logUserLoginFailed(username, new Date(), LoginError.USER_REJECTED);
lock.writeLock().unlock();
return LoginError.USER_REJECTED;
}
if (allNames.contains(username)) {
lock.writeLock().unlock();
TestChatServer.logUserLoginFailed(username, new Date(), LoginError.USER_REJECTED);
return LoginError.USER_REJECTED;
}
if (users.size() >= MAX_USERS) { //exceeds capacity
lock.writeLock().unlock();
if(waiting_users.offer(username)) //attempt to add to waiting queue
return LoginError.USER_QUEUED;
else { //else drop user
TestChatServer.logUserLoginFailed(username, new Date(), LoginError.USER_DROPPED);
return LoginError.USER_DROPPED;
}
}
User newUser = new User(this, username);
users.put(username, newUser);
allNames.add(username);
newUser.connected();
lock.writeLock().unlock();
TestChatServer.logUserLogin(username, new Date());
return LoginError.USER_ACCEPTED;
}
@Override
public boolean logoff(String username) {
// TODO Auto-generated method stub
lock.writeLock().lock();
if(!users.containsKey(username)){
lock.writeLock().unlock();
return false;
}
List <String> userGroups = users.get(username).getUserGroups();
Iterator<String> it = userGroups.iterator();
while(it.hasNext()){
ChatGroup group = groups.get(it.next());
if(group.leaveGroup(username)){
if(group.getNumUsers() <= 0) {
groups.remove(group.getName());
allNames.remove(group.getName());
}
}
}
users.get(username).logoff();
allNames.remove(username);
users.remove(username);
// Check for waiting users
String uname = waiting_users.poll();
if(uname != null) { //add to ChatServer
User newUser = new User(this, uname);
SocketParams socket = waiting_sockets.get(uname);
newUser.setSocket(socket.getMySocket(), socket.getInputStream(), socket.getOutputStream());
waiting_sockets.remove(uname);
users.put(uname, newUser);
allNames.add(uname);
TransportObject reply = new TransportObject(Command.login, ServerReply.OK);
newUser.queueReply(reply);
newUser.connected();
TestChatServer.logUserLogin(uname, new Date());
}
lock.writeLock().unlock();
return true;
}
public void joinAck(User user, String gname, ServerReply reply) {
TransportObject toSend = new TransportObject(Command.join,gname,reply);
user.queueReply(toSend);
}
public void leaveAck(User user, String gname, ServerReply reply) {
TransportObject toSend = new TransportObject(Command.leave,gname,reply);
user.queueReply(toSend);
}
public void startNewTimer(Socket socket) throws IOException {
List<Handler> task = new ArrayList<Handler>();
try {
task.add(new Handler(socket));
pool.invokeAll(task, (long) 20, TimeUnit.SECONDS);
List<Future<Handler>> futures = pool.invokeAll(task, (long) 20, TimeUnit.SECONDS);
if (futures.get(0).isCancelled()) {
ObjectOutputStream sent = new ObjectOutputStream(socket.getOutputStream());
TransportObject sendObject = new TransportObject(ServerReply.timeout);
sent.writeObject(sendObject);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean joinGroup(BaseUser baseUser, String groupname) {
// TODO Auto-generated method stub
lock.writeLock().lock();
ChatGroup group;
User user = (User) baseUser;
boolean success = false;
if (!users.keySet().contains(user.getUsername())) {
lock.writeLock().unlock();
return false;
}
if(groups.containsKey(groupname)) {
group = groups.get(groupname);
success = group.joinGroup(user.getUsername(), user);
user.addToGroups(groupname);
TestChatServer.logUserJoinGroup(groupname, user.getUsername(), new Date());
if(success)
joinAck(user,groupname,ServerReply.OK_JOIN);
else
joinAck(user,groupname,ServerReply.FAIL_FULL);
lock.writeLock().unlock();
return success;
}
else {
if(allNames.contains(groupname)){
joinAck(user,groupname,ServerReply.BAD_GROUP);
lock.writeLock().unlock();
return false;
}
group = new ChatGroup(groupname);
groups.put(groupname, group);
success = group.joinGroup(user.getUsername(), user);
user.addToGroups(groupname);
TestChatServer.logUserJoinGroup(groupname, user.getUsername(), new Date());
if(success)
joinAck(user,groupname,ServerReply.OK_CREATE);
else
joinAck(user,groupname,ServerReply.FAIL_FULL);
lock.writeLock().unlock();
return success;
}
}
@Override
public boolean leaveGroup(BaseUser baseUser, String groupname) {
// TODO Auto-generated method stub
User user = (User) baseUser;
lock.writeLock().lock();
ChatGroup group = groups.get(groupname);
if (group == null){
leaveAck(user,groupname,ServerReply.BAD_GROUP);
lock.writeLock().unlock();
return false;
}
if(group.leaveGroup(user.getUsername())) {
leaveAck(user,groupname,ServerReply.OK);
if(group.getNumUsers() <= 0) {
groups.remove(group.getName());
allNames.remove(group.getName());
}
user.removeFromGroups(groupname);
TestChatServer.logUserLeaveGroup(groupname, user.getUsername(), new Date());
lock.writeLock().unlock();
return true;
}
else {
leaveAck(user,groupname,ServerReply.NOT_MEMBER);
}
lock.writeLock().unlock();
return false;
}
@Override
public void shutdown() {
lock.writeLock().lock();
Set<String> userNames = users.keySet();
for(String name: userNames){
users.get(name).logoff();
}
users.clear();
groups.clear();
isDown = true;
lock.writeLock().unlock();
}
public MsgSendError processMessage(String source, String dest, String msg, int sqn, String timestamp) {
Message message = new Message(timestamp, source, dest, msg);
message.setSQN(sqn);
lock.readLock().lock();
if (users.containsKey(source)) {
if (users.containsKey(dest)) {
User destUser = users.get(dest);
destUser.acceptMsg(message);
} else if (groups.containsKey(dest)) {
message.setIsFromGroup();
ChatGroup group = groups.get(dest);
MsgSendError sendError = group.forwardMessage(message);
if (sendError==MsgSendError.NOT_IN_GROUP) {
TestChatServer.logChatServerDropMsg(message.toString(), new Date());
lock.readLock().unlock();
return sendError;
} else if(sendError==MsgSendError.MESSAGE_FAILED)
return sendError;
} else {
TestChatServer.logChatServerDropMsg(message.toString(), new Date());
lock.readLock().unlock();
return MsgSendError.INVALID_DEST;
}
} else {
TestChatServer.logChatServerDropMsg(message.toString(), new Date());
lock.readLock().unlock();
return MsgSendError.INVALID_SOURCE;
}
lock.readLock().unlock();
return MsgSendError.MESSAGE_SENT;
}
@Override
public void run(){
while(!isDown){
List<Handler> task = new ArrayList<Handler>();
Socket newSocket;
try {
newSocket = mySocket.accept();
Handler handler = new Handler(newSocket);
task.add(handler);
System.out.println("new socket request received");
List<Future<Handler>> futures = pool.invokeAll(task, (long) 20, TimeUnit.SECONDS);
if (futures.get(0).isCancelled()) {
ObjectOutputStream sent = handler.sent;
//ObjectInputStream received = new ObjectInputStream(newSocket.getInputStream());
TransportObject sendObject = new TransportObject(ServerReply.timeout);
sent.writeObject(sendObject);
System.out.println("client timing out");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Handler implements Callable<ChatServer.Handler>, Runnable {
private final Socket socket;
Handler(Socket socket) throws IOException {
this.socket = socket;
received = new ObjectInputStream(socket.getInputStream());
sent = new ObjectOutputStream(socket.getOutputStream());
}
private ObjectInputStream received;
private ObjectOutputStream sent;
public void run() {
}
@Override
public Handler call() throws Exception {
System.out.println("starting run method of new handler");
TransportObject recObject = null;
while(recObject == null) {
System.out.println("polling for login command");
try {
recObject = (TransportObject) received.readObject();
} catch (Exception e) {
e.printStackTrace();
+ return null;
}
if (recObject != null) {
Command type = recObject.getCommand();
System.out.println("received first command " + type.toString());
if (type == Command.login) {
String username = recObject.getUsername();
LoginError loginError = login(username);
TransportObject sendObject;
if (loginError == LoginError.USER_ACCEPTED) {
sendObject = new TransportObject(Command.login, ServerReply.OK);
System.out.println("created new transport object");
User newUser = (User) getUser(username);
System.out.println("got new user");
newUser.setSocket(socket, received, sent);
System.out.println("just set socket on new user");
} else if (loginError == LoginError.USER_QUEUED) {
sendObject = new TransportObject(Command.login, ServerReply.QUEUED);
waiting_sockets.put(username, new SocketParams(socket, received, sent));
} else {
sendObject = new TransportObject(ServerReply.error);
recObject = null;
}
try {
System.out.println("sending new object woot " + sendObject);
sent.writeObject(sendObject);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return null;
}
}
public static void main(String[] args) throws Exception{
if (args.length != 1) {
throw new Exception("Invalid number of args to command");
}
int port = Integer.parseInt(args[0]);
ChatServer chatServer = new ChatServer(port);
}
}
| true | true |
public Handler call() throws Exception {
System.out.println("starting run method of new handler");
TransportObject recObject = null;
while(recObject == null) {
System.out.println("polling for login command");
try {
recObject = (TransportObject) received.readObject();
} catch (Exception e) {
e.printStackTrace();
}
if (recObject != null) {
Command type = recObject.getCommand();
System.out.println("received first command " + type.toString());
if (type == Command.login) {
String username = recObject.getUsername();
LoginError loginError = login(username);
TransportObject sendObject;
if (loginError == LoginError.USER_ACCEPTED) {
sendObject = new TransportObject(Command.login, ServerReply.OK);
System.out.println("created new transport object");
User newUser = (User) getUser(username);
System.out.println("got new user");
newUser.setSocket(socket, received, sent);
System.out.println("just set socket on new user");
} else if (loginError == LoginError.USER_QUEUED) {
sendObject = new TransportObject(Command.login, ServerReply.QUEUED);
waiting_sockets.put(username, new SocketParams(socket, received, sent));
} else {
sendObject = new TransportObject(ServerReply.error);
recObject = null;
}
try {
System.out.println("sending new object woot " + sendObject);
sent.writeObject(sendObject);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return null;
}
|
public Handler call() throws Exception {
System.out.println("starting run method of new handler");
TransportObject recObject = null;
while(recObject == null) {
System.out.println("polling for login command");
try {
recObject = (TransportObject) received.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (recObject != null) {
Command type = recObject.getCommand();
System.out.println("received first command " + type.toString());
if (type == Command.login) {
String username = recObject.getUsername();
LoginError loginError = login(username);
TransportObject sendObject;
if (loginError == LoginError.USER_ACCEPTED) {
sendObject = new TransportObject(Command.login, ServerReply.OK);
System.out.println("created new transport object");
User newUser = (User) getUser(username);
System.out.println("got new user");
newUser.setSocket(socket, received, sent);
System.out.println("just set socket on new user");
} else if (loginError == LoginError.USER_QUEUED) {
sendObject = new TransportObject(Command.login, ServerReply.QUEUED);
waiting_sockets.put(username, new SocketParams(socket, received, sent));
} else {
sendObject = new TransportObject(ServerReply.error);
recObject = null;
}
try {
System.out.println("sending new object woot " + sendObject);
sent.writeObject(sendObject);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return null;
}
|
diff --git a/src/java/org/apache/cassandra/db/SliceFromReadCommand.java b/src/java/org/apache/cassandra/db/SliceFromReadCommand.java
index a9bbaf038..889038db3 100644
--- a/src/java/org/apache/cassandra/db/SliceFromReadCommand.java
+++ b/src/java/org/apache/cassandra/db/SliceFromReadCommand.java
@@ -1,172 +1,173 @@
/*
* 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.cassandra.db;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.db.filter.IDiskAtomFilter;
import org.apache.cassandra.db.filter.QueryFilter;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.db.filter.SliceQueryFilter;
import org.apache.cassandra.io.IVersionedSerializer;
import org.apache.cassandra.service.RowDataResolver;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.utils.ByteBufferUtil;
public class SliceFromReadCommand extends ReadCommand
{
static final Logger logger = LoggerFactory.getLogger(SliceFromReadCommand.class);
public final SliceQueryFilter filter;
public SliceFromReadCommand(String table, ByteBuffer key, ColumnParent column_parent, ByteBuffer start, ByteBuffer finish, boolean reversed, int count)
{
this(table, key, new QueryPath(column_parent), start, finish, reversed, count);
}
public SliceFromReadCommand(String table, ByteBuffer key, QueryPath path, ByteBuffer start, ByteBuffer finish, boolean reversed, int count)
{
this(table, key, path, new SliceQueryFilter(start, finish, reversed, count));
}
public SliceFromReadCommand(String table, ByteBuffer key, QueryPath path, SliceQueryFilter filter)
{
super(table, key, path, CMD_TYPE_GET_SLICE);
this.filter = filter;
}
public ReadCommand copy()
{
ReadCommand readCommand = new SliceFromReadCommand(table, key, queryPath, filter);
readCommand.setDigestQuery(isDigestQuery());
return readCommand;
}
public Row getRow(Table table)
{
DecoratedKey dk = StorageService.getPartitioner().decorateKey(key);
return table.getRow(new QueryFilter(dk, queryPath, filter));
}
@Override
public ReadCommand maybeGenerateRetryCommand(RowDataResolver resolver, Row row)
{
int maxLiveColumns = resolver.getMaxLiveCount();
int count = filter.count;
// We generate a retry if at least one node reply with count live columns but after merge we have less
- // than the total number of column we are interested in (which may be < count on a retry)
- if (maxLiveColumns >= count)
+ // than the total number of column we are interested in (which may be < count on a retry).
+ // So in particular, if no host returned count live columns, we know it's not a short read.
+ if (maxLiveColumns < count)
return null;
int liveCountInRow = row == null || row.cf == null ? 0 : filter.getLiveCount(row.cf);
if (liveCountInRow < getOriginalRequestedCount())
{
// We asked t (= count) live columns and got l (=liveCountInRow) ones.
// From that, we can estimate that on this row, for x requested
// columns, only l/t end up live after reconciliation. So for next
// round we want to ask x column so that x * (l/t) == t, i.e. x = t^2/l.
int retryCount = liveCountInRow == 0 ? count + 1 : ((count * count) / liveCountInRow) + 1;
SliceQueryFilter newFilter = filter.withUpdatedCount(retryCount);
return new RetriedSliceFromReadCommand(table, key, queryPath, newFilter, getOriginalRequestedCount());
}
return null;
}
@Override
public void maybeTrim(Row row)
{
if ((row == null) || (row.cf == null))
return;
filter.trim(row.cf, getOriginalRequestedCount());
}
public IDiskAtomFilter filter()
{
return filter;
}
/**
* The original number of columns requested by the user.
* This can be different from count when the slice command is a retry (see
* RetriedSliceFromReadCommand)
*/
protected int getOriginalRequestedCount()
{
return filter.count;
}
@Override
public String toString()
{
return "SliceFromReadCommand(" +
"table='" + table + '\'' +
", key='" + ByteBufferUtil.bytesToHex(key) + '\'' +
", column_parent='" + queryPath + '\'' +
", filter='" + filter + '\'' +
')';
}
}
class SliceFromReadCommandSerializer implements IVersionedSerializer<ReadCommand>
{
public void serialize(ReadCommand rm, DataOutput dos, int version) throws IOException
{
SliceFromReadCommand realRM = (SliceFromReadCommand)rm;
dos.writeBoolean(realRM.isDigestQuery());
dos.writeUTF(realRM.table);
ByteBufferUtil.writeWithShortLength(realRM.key, dos);
realRM.queryPath.serialize(dos);
SliceQueryFilter.serializer.serialize(realRM.filter, dos, version);
}
public ReadCommand deserialize(DataInput dis, int version) throws IOException
{
boolean isDigest = dis.readBoolean();
String table = dis.readUTF();
ByteBuffer key = ByteBufferUtil.readWithShortLength(dis);
QueryPath path = QueryPath.deserialize(dis);
SliceQueryFilter filter = SliceQueryFilter.serializer.deserialize(dis, version);
SliceFromReadCommand rm = new SliceFromReadCommand(table, key, path, filter);
rm.setDigestQuery(isDigest);
return rm;
}
public long serializedSize(ReadCommand cmd, int version)
{
TypeSizes sizes = TypeSizes.NATIVE;
SliceFromReadCommand command = (SliceFromReadCommand) cmd;
int keySize = command.key.remaining();
int size = sizes.sizeof(cmd.isDigestQuery()); // boolean
size += sizes.sizeof(command.table);
size += sizes.sizeof((short) keySize) + keySize;
size += command.queryPath.serializedSize(sizes);
size += SliceQueryFilter.serializer.serializedSize(command.filter, version);
return size;
}
}
| true | true |
public ReadCommand maybeGenerateRetryCommand(RowDataResolver resolver, Row row)
{
int maxLiveColumns = resolver.getMaxLiveCount();
int count = filter.count;
// We generate a retry if at least one node reply with count live columns but after merge we have less
// than the total number of column we are interested in (which may be < count on a retry)
if (maxLiveColumns >= count)
return null;
int liveCountInRow = row == null || row.cf == null ? 0 : filter.getLiveCount(row.cf);
if (liveCountInRow < getOriginalRequestedCount())
{
// We asked t (= count) live columns and got l (=liveCountInRow) ones.
// From that, we can estimate that on this row, for x requested
// columns, only l/t end up live after reconciliation. So for next
// round we want to ask x column so that x * (l/t) == t, i.e. x = t^2/l.
int retryCount = liveCountInRow == 0 ? count + 1 : ((count * count) / liveCountInRow) + 1;
SliceQueryFilter newFilter = filter.withUpdatedCount(retryCount);
return new RetriedSliceFromReadCommand(table, key, queryPath, newFilter, getOriginalRequestedCount());
}
return null;
}
|
public ReadCommand maybeGenerateRetryCommand(RowDataResolver resolver, Row row)
{
int maxLiveColumns = resolver.getMaxLiveCount();
int count = filter.count;
// We generate a retry if at least one node reply with count live columns but after merge we have less
// than the total number of column we are interested in (which may be < count on a retry).
// So in particular, if no host returned count live columns, we know it's not a short read.
if (maxLiveColumns < count)
return null;
int liveCountInRow = row == null || row.cf == null ? 0 : filter.getLiveCount(row.cf);
if (liveCountInRow < getOriginalRequestedCount())
{
// We asked t (= count) live columns and got l (=liveCountInRow) ones.
// From that, we can estimate that on this row, for x requested
// columns, only l/t end up live after reconciliation. So for next
// round we want to ask x column so that x * (l/t) == t, i.e. x = t^2/l.
int retryCount = liveCountInRow == 0 ? count + 1 : ((count * count) / liveCountInRow) + 1;
SliceQueryFilter newFilter = filter.withUpdatedCount(retryCount);
return new RetriedSliceFromReadCommand(table, key, queryPath, newFilter, getOriginalRequestedCount());
}
return null;
}
|
diff --git a/clients/gui/org.cishell.reference.gui.menumanager/src/org/cishell/reference/gui/menumanager/menu/AlgorithmWrapper.java b/clients/gui/org.cishell.reference.gui.menumanager/src/org/cishell/reference/gui/menumanager/menu/AlgorithmWrapper.java
index 32245fca..71202809 100644
--- a/clients/gui/org.cishell.reference.gui.menumanager/src/org/cishell/reference/gui/menumanager/menu/AlgorithmWrapper.java
+++ b/clients/gui/org.cishell.reference.gui.menumanager/src/org/cishell/reference/gui/menumanager/menu/AlgorithmWrapper.java
@@ -1,464 +1,464 @@
/* ****************************************************************************
* CIShell: Cyberinfrastructure Shell, An Algorithm Integration Framework.
*
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Apache License v2.0 which accompanies
* this distribution, and is available at:
* http://www.apache.org/licenses/LICENSE-2.0.html
*
* Created on Aug 22, 2006 at Indiana University.
*
* Contributors:
* Indiana University -
* ***************************************************************************/
package org.cishell.reference.gui.menumanager.menu;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.cishell.app.service.datamanager.DataManagerService;
import org.cishell.framework.CIShellContext;
import org.cishell.framework.algorithm.Algorithm;
import org.cishell.framework.algorithm.AlgorithmExecutionException;
import org.cishell.framework.algorithm.AlgorithmFactory;
import org.cishell.framework.algorithm.AlgorithmProperty;
import org.cishell.framework.algorithm.DataValidator;
import org.cishell.framework.algorithm.ParameterMutator;
import org.cishell.framework.algorithm.ProgressMonitor;
import org.cishell.framework.algorithm.ProgressTrackable;
import org.cishell.framework.data.Data;
import org.cishell.framework.data.DataProperty;
import org.cishell.framework.userprefs.UserPrefsProperty;
import org.cishell.reference.gui.menumanager.Activator;
import org.cishell.reference.gui.menumanager.menu.metatypewrapper.ParamMetaTypeProvider;
import org.cishell.reference.service.metatype.BasicMetaTypeProvider;
import org.cishell.service.conversion.ConversionException;
import org.cishell.service.conversion.Converter;
import org.cishell.service.guibuilder.GUIBuilderService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.log.LogService;
import org.osgi.service.metatype.AttributeDefinition;
import org.osgi.service.metatype.MetaTypeProvider;
import org.osgi.service.metatype.MetaTypeService;
import org.osgi.service.metatype.ObjectClassDefinition;
public class AlgorithmWrapper implements Algorithm, AlgorithmProperty, ProgressTrackable {
protected ServiceReference ref;
protected BundleContext bContext;
protected CIShellContext ciContext;
protected Data[] originalData;
protected Data[] data;
protected Converter[][] converters;
protected ProgressMonitor progressMonitor;
protected Algorithm algorithm;
public AlgorithmWrapper(ServiceReference ref, BundleContext bContext,
CIShellContext ciContext, Data[] originalData, Data[] data,
Converter[][] converters) {
this.ref = ref;
this.bContext = bContext;
this.ciContext = ciContext;
this.originalData = originalData;
this.data = data;
this.converters = converters;
this.progressMonitor = null;
}
/**
* @see org.cishell.framework.algorithm.Algorithm#execute()
*/
public Data[] execute() {
AlgorithmFactory factory = (AlgorithmFactory) bContext.getService(ref);
String pid = (String)ref.getProperty(Constants.SERVICE_PID);
// convert input data to the correct format
boolean conversionSuccessful = tryConvertingDataToRequiredFormat(data, converters);
if (!conversionSuccessful) return null;
boolean inputIsValid = testDataValidityIfPossible(factory, data);
if (!inputIsValid) return null;
// create algorithm parameters
String metatype_pid = getMetaTypeID(ref);
MetaTypeProvider provider = getPossiblyMutatedMetaTypeProvider(metatype_pid, pid, factory);
Dictionary parameters = getUserEnteredParameters(metatype_pid, provider);
// check to see if the user cancelled the operation
if(parameters == null) return null;
printParameters(metatype_pid, provider, parameters);
// create the algorithm
algorithm = createAlgorithm(factory, data, parameters, ciContext);
if (algorithm == null) return null;
trackAlgorithmIfPossible(algorithm);
// execute the algorithm
Data[] outData = tryExecutingAlgorithm(algorithm);
if (outData == null) return null;
// process and return the algorithm's output
doParentage(outData);
outData = removeNullData(outData);
addDataToDataManager(outData);
return outData;
}
protected Algorithm createAlgorithm(AlgorithmFactory factory, Data[] data, Dictionary parameters, CIShellContext ciContext) {
try {
return factory.createAlgorithm(data, parameters, ciContext);
} catch (Exception e) {
String errorMessage = "Unexpected error occurred while creating algorithm " +
" \""+ref.getProperty(AlgorithmProperty.LABEL)+".\"";
GUIBuilderService builder = (GUIBuilderService)
ciContext.getService(GUIBuilderService.class.getName());
builder.showError("Error!", errorMessage, e);
log(LogService.LOG_ERROR, errorMessage, e);
return null;
}
}
protected Data[] removeNullData(Data[] outData) {
if (outData != null) {
List goodData = new ArrayList();
for (int i=0; i < outData.length; i++) {
if (outData[i] != null) {
goodData.add(outData[i]);
}
}
outData = (Data[]) goodData.toArray(new Data[0]);
}
return outData;
}
protected void addDataToDataManager(Data[] outData) {
if (outData != null) {
DataManagerService dataManager = (DataManagerService)
bContext.getService(bContext.getServiceReference(
DataManagerService.class.getName()));
if (outData.length != 0) {
dataManager.setSelectedData(outData);
}
}
}
protected Data[] tryExecutingAlgorithm(Algorithm algorithm) {
Data[] outData = null;
try {
outData = algorithm.execute();
} catch (AlgorithmExecutionException e) {
log(LogService.LOG_ERROR,
"The Algorithm: \""+ref.getProperty(AlgorithmProperty.LABEL)+
"\" had an error while executing: "+e.getMessage());
} catch (RuntimeException e) {
GUIBuilderService builder = (GUIBuilderService)
ciContext.getService(GUIBuilderService.class.getName());
builder.showError("Error!", "An unexpected exception occurred while "
+"executing \""+ref.getProperty(AlgorithmProperty.LABEL)+".\"", e);
}
return outData;
}
protected boolean tryConvertingDataToRequiredFormat(Data[] data, Converter[][] converters) {
for (int i=0; i < data.length; i++) {
if (converters[i] != null) {
try {
data[i] = converters[i][0].convert(data[i]);
} catch (ConversionException e) {
log(LogService.LOG_ERROR,"The conversion of data to give" +
" the algorithm failed for this reason: "+e.getMessage(), e);
return false;
}
if (data[i] == null && i < (data.length - 1)) {
log(LogService.LOG_ERROR, "The converter: " +
converters[i].getClass().getName() +
" returned a null result where data was expected when" +
" converting the data to give the algorithm.");
return false;
}
converters[i] = null;
}
}
return true;
}
protected boolean testDataValidityIfPossible(AlgorithmFactory factory, Data[] data) {
if (factory instanceof DataValidator) {
String validation = ((DataValidator) factory).validate(data);
if (validation != null && validation.length() > 0) {
String label = (String) ref.getProperty(LABEL);
if (label == null) {
label = "Algorithm";
}
log(LogService.LOG_ERROR,"INVALID DATA: The data given to \""+label+"\" is incompatible for this reason: "+validation);
return false;
}
}
return true;
}
protected String getMetaTypeID(ServiceReference ref) {
String pid = (String)ref.getProperty(Constants.SERVICE_PID);
String metatype_pid = (String) ref.getProperty(PARAMETERS_PID);
if (metatype_pid == null) {
metatype_pid = pid;
}
return metatype_pid;
}
protected MetaTypeProvider getPossiblyMutatedMetaTypeProvider(String metatypePID, String pid, AlgorithmFactory factory) {
MetaTypeProvider provider = null;
MetaTypeService metaTypeService = (MetaTypeService) Activator.getService(MetaTypeService.class.getName());
if (metaTypeService != null) {
provider = metaTypeService.getMetaTypeInformation(ref.getBundle());
}
if (factory instanceof ParameterMutator && provider != null) {
try {
ObjectClassDefinition ocd = provider.getObjectClassDefinition(metatypePID, null);
if (ocd == null) logNullOCDWarning(pid, metatypePID);
ocd = ((ParameterMutator) factory).mutateParameters(data, ocd);
if (ocd != null) {
provider = new BasicMetaTypeProvider(ocd);
}
} catch (IllegalArgumentException e) {
log(LogService.LOG_DEBUG, pid+" has an invalid metatype id: "+metatypePID);
} catch (Exception e) {
GUIBuilderService builder = (GUIBuilderService)
ciContext.getService(GUIBuilderService.class.getName());
String errorMessage = "An error occurred while preparing to run the algorithm "
+ref.getProperty(AlgorithmProperty.LABEL)+".\"";
builder.showError("Error!", errorMessage, e);
log(LogService.LOG_ERROR, errorMessage, e);
}
}
if (provider != null) {
provider = wrapProvider(ref, provider);
}
return provider;
}
protected void trackAlgorithmIfPossible(Algorithm algorithm) {
if (progressMonitor != null && algorithm instanceof ProgressTrackable) {
((ProgressTrackable)algorithm).setProgressMonitor(progressMonitor);
}
}
protected Dictionary getUserEnteredParameters(String metatype_pid, MetaTypeProvider provider) {
Dictionary parameters = new Hashtable();
if (provider != null) {
GUIBuilderService builder = (GUIBuilderService)
ciContext.getService(GUIBuilderService.class.getName());
parameters = builder.createGUIandWait(metatype_pid, provider);
}
return parameters;
}
// wrap the provider to provide special functionality, such as overriding default values of attributes through
// preferences.
protected MetaTypeProvider wrapProvider(ServiceReference algRef, MetaTypeProvider unwrappedProvider) {
ConfigurationAdmin ca = getConfigurationAdmin();
if (ca != null && hasParamDefaultPreferences(algRef)) {
String standardServicePID = (String) algRef.getProperty(Constants.SERVICE_PID);
String paramOverrideConfPID = standardServicePID + UserPrefsProperty.PARAM_PREFS_CONF_SUFFIX;
try {
Configuration defaultParamValueOverrider = ca.getConfiguration(paramOverrideConfPID, null);
Dictionary defaultParamOverriderDict = defaultParamValueOverrider.getProperties();
MetaTypeProvider wrappedProvider = new ParamMetaTypeProvider(unwrappedProvider,
defaultParamOverriderDict);
return wrappedProvider;
} catch (IOException e) {
return unwrappedProvider;
}
} else {
}
return unwrappedProvider;
}
protected boolean hasParamDefaultPreferences(ServiceReference algRef) {
String prefsToPublish = (String) algRef.getProperty(UserPrefsProperty.PREFS_PUBLISHED_KEY);
if (prefsToPublish == null) {
return true;
}
return prefsToPublish.contains(UserPrefsProperty.PUBLISH_PARAM_DEFAULT_PREFS_VALUE);
}
protected void log(int logLevel, String message) {
LogService log = (LogService) ciContext.getService(LogService.class.getName());
if (log != null) {
log.log(logLevel, message);
} else {
System.out.println(message);
}
}
protected void log(int logLevel, String message, Throwable exception) {
LogService log = (LogService) ciContext.getService(LogService.class.getName());
if (log != null) {
log.log(logLevel, message, exception);
} else {
System.out.println(message);
exception.printStackTrace();
}
}
protected void printParameters(String metatype_pid, MetaTypeProvider provider, Dictionary parameters) {
LogService logger = getLogService();
Map idToLabelMap = setupIdToLabelMap(metatype_pid, provider);
if (logger != null && !parameters.isEmpty()) {
//adjust to log all input parameters in one block
StringBuffer inputParams = new StringBuffer("\n"+"Input Parameters:");
for (Enumeration e = parameters.keys(); e
.hasMoreElements();) {
String key = (String) e.nextElement();
Object value = parameters.get(key);
key = (String) idToLabelMap.get(key);
inputParams.append("\n"+key+": "+value);
}
logger.log(LogService.LOG_INFO, inputParams.toString());
}
}
protected Map setupIdToLabelMap(String metatype_pid, MetaTypeProvider provider) {
Map idToLabelMap = new HashMap();
if (provider != null) {
ObjectClassDefinition ocd = null;
try {
ocd = provider.getObjectClassDefinition(metatype_pid, null);
if (ocd != null) {
AttributeDefinition[] attr =
ocd.getAttributeDefinitions(ObjectClassDefinition.ALL);
for (int i=0; i < attr.length; i++) {
String id = attr[i].getID();
String label = attr[i].getName();
idToLabelMap.put(id, label);
}
}
} catch (IllegalArgumentException e) {}
}
return idToLabelMap;
}
//only does anything if parentage=default so far...
protected void doParentage(Data[] outData) {
//make sure the parent set is the original Data and not the
//converted data...
if (outData != null && data != null && originalData != null
&& originalData.length == data.length) {
for (int i=0; i < outData.length; i++) {
if (outData[i] != null) {
Object parent = outData[i].getMetadata().get(DataProperty.PARENT);
if (parent != null) {
- for (int j=0; j < data.length; i++) {
+ for (int j=0; j < data.length; j++) {
if (parent == data[j]) {
outData[i].getMetadata().put(DataProperty.PARENT,
originalData[j]);
break;
}
}
}
}
}
}
//check and act on parentage settings
String parentage = (String)ref.getProperty("parentage");
if (parentage != null) {
parentage = parentage.trim();
if (parentage.equalsIgnoreCase("default")) {
if (originalData != null && originalData.length > 0 && originalData[0] != null) {
for (int i=0; i < outData.length; i++) {
//if they don't have a parent set already then we set one
if (outData[i] != null &&
outData[i].getMetadata().get(DataProperty.PARENT) == null) {
outData[i].getMetadata().put(DataProperty.PARENT, originalData[0]);
}
}
}
}
}
}
private LogService getLogService() {
ServiceReference serviceReference = bContext.getServiceReference(DataManagerService.class.getName());
LogService log = null;
if (serviceReference != null) {
log = (LogService) bContext.getService(
bContext.getServiceReference(LogService.class.getName()));
}
return log;
}
private ConfigurationAdmin getConfigurationAdmin() {
ServiceReference serviceReference = bContext.getServiceReference(ConfigurationAdmin.class.getName());
ConfigurationAdmin ca = null;
if (serviceReference != null) {
ca = (ConfigurationAdmin) bContext.getService(
bContext.getServiceReference(ConfigurationAdmin.class.getName()));
}
return ca;
}
private void logNullOCDWarning(String pid, String metatype_pid) {
this.log(LogService.LOG_WARNING,
"Warning: could not get object class definition '" + metatype_pid + "' from the algorithm '" + pid + "'");
}
public ProgressMonitor getProgressMonitor() {
if (algorithm instanceof ProgressTrackable) {
return progressMonitor;
}
else {
return null;
}
}
public void setProgressMonitor(ProgressMonitor monitor) {
progressMonitor = monitor;
}
}
| true | true |
protected void doParentage(Data[] outData) {
//make sure the parent set is the original Data and not the
//converted data...
if (outData != null && data != null && originalData != null
&& originalData.length == data.length) {
for (int i=0; i < outData.length; i++) {
if (outData[i] != null) {
Object parent = outData[i].getMetadata().get(DataProperty.PARENT);
if (parent != null) {
for (int j=0; j < data.length; i++) {
if (parent == data[j]) {
outData[i].getMetadata().put(DataProperty.PARENT,
originalData[j]);
break;
}
}
}
}
}
}
//check and act on parentage settings
String parentage = (String)ref.getProperty("parentage");
if (parentage != null) {
parentage = parentage.trim();
if (parentage.equalsIgnoreCase("default")) {
if (originalData != null && originalData.length > 0 && originalData[0] != null) {
for (int i=0; i < outData.length; i++) {
//if they don't have a parent set already then we set one
if (outData[i] != null &&
outData[i].getMetadata().get(DataProperty.PARENT) == null) {
outData[i].getMetadata().put(DataProperty.PARENT, originalData[0]);
}
}
}
}
}
}
|
protected void doParentage(Data[] outData) {
//make sure the parent set is the original Data and not the
//converted data...
if (outData != null && data != null && originalData != null
&& originalData.length == data.length) {
for (int i=0; i < outData.length; i++) {
if (outData[i] != null) {
Object parent = outData[i].getMetadata().get(DataProperty.PARENT);
if (parent != null) {
for (int j=0; j < data.length; j++) {
if (parent == data[j]) {
outData[i].getMetadata().put(DataProperty.PARENT,
originalData[j]);
break;
}
}
}
}
}
}
//check and act on parentage settings
String parentage = (String)ref.getProperty("parentage");
if (parentage != null) {
parentage = parentage.trim();
if (parentage.equalsIgnoreCase("default")) {
if (originalData != null && originalData.length > 0 && originalData[0] != null) {
for (int i=0; i < outData.length; i++) {
//if they don't have a parent set already then we set one
if (outData[i] != null &&
outData[i].getMetadata().get(DataProperty.PARENT) == null) {
outData[i].getMetadata().put(DataProperty.PARENT, originalData[0]);
}
}
}
}
}
}
|
diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/config/BaseVCloudRestClientModule.java b/vcloud/core/src/main/java/org/jclouds/vcloud/config/BaseVCloudRestClientModule.java
index d17b72fbf..f69fcbba9 100644
--- a/vcloud/core/src/main/java/org/jclouds/vcloud/config/BaseVCloudRestClientModule.java
+++ b/vcloud/core/src/main/java/org/jclouds/vcloud/config/BaseVCloudRestClientModule.java
@@ -1,321 +1,321 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <[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 org.jclouds.vcloud.config;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_DEFAULT_NETWORK;
import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_ENDPOINT;
import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_KEY;
import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_SESSIONINTERVAL;
import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_USER;
import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_VERSION;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.Map;
import java.util.SortedMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Resource;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.concurrent.ExpirableSupplier;
import org.jclouds.concurrent.RetryOnTimeOutExceptionSupplier;
import org.jclouds.encryption.EncryptionService;
import org.jclouds.http.HttpErrorHandler;
import org.jclouds.http.RequiresHttp;
import org.jclouds.http.annotation.ClientError;
import org.jclouds.http.annotation.Redirection;
import org.jclouds.http.annotation.ServerError;
import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.logging.Logger;
import org.jclouds.net.IPSocket;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen;
import org.jclouds.rest.AsyncClientFactory;
import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.config.RestClientModule;
import org.jclouds.vcloud.VCloudAsyncClient;
import org.jclouds.vcloud.VCloudClient;
import org.jclouds.vcloud.VCloudToken;
import org.jclouds.vcloud.domain.NamedResource;
import org.jclouds.vcloud.domain.Organization;
import org.jclouds.vcloud.domain.VApp;
import org.jclouds.vcloud.endpoints.Catalog;
import org.jclouds.vcloud.endpoints.Network;
import org.jclouds.vcloud.endpoints.Org;
import org.jclouds.vcloud.endpoints.TasksList;
import org.jclouds.vcloud.endpoints.VCloud;
import org.jclouds.vcloud.endpoints.VCloudApi;
import org.jclouds.vcloud.endpoints.VCloudLogin;
import org.jclouds.vcloud.endpoints.VDC;
import org.jclouds.vcloud.endpoints.internal.CatalogItemRoot;
import org.jclouds.vcloud.endpoints.internal.VAppRoot;
import org.jclouds.vcloud.endpoints.internal.VAppTemplateRoot;
import org.jclouds.vcloud.handlers.ParseVCloudErrorFromHttpResponse;
import org.jclouds.vcloud.internal.VCloudLoginAsyncClient;
import org.jclouds.vcloud.internal.VCloudVersionsAsyncClient;
import org.jclouds.vcloud.internal.VCloudLoginAsyncClient.VCloudSession;
import org.jclouds.vcloud.predicates.TaskSuccess;
import org.jclouds.vcloud.predicates.VAppNotFound;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.inject.Provides;
/**
* Configures the VCloud authentication service connection, including logging and http transport.
*
* @author Adrian Cole
*/
@RequiresHttp
@ConfiguresRestClient
public abstract class BaseVCloudRestClientModule<S extends VCloudClient, A extends VCloudAsyncClient>
extends RestClientModule<S, A> {
public BaseVCloudRestClientModule(Class<S> syncClientType, Class<A> asyncClientType) {
super(syncClientType, asyncClientType);
}
@Override
protected void configure() {
requestInjection(this);
super.configure();
}
@Resource
protected Logger logger = Logger.NULL;
@Provides
@Singleton
protected Predicate<IPSocket> socketTester(SocketOpen open) {
return new RetryablePredicate<IPSocket>(open, 130, 10, TimeUnit.SECONDS);
}
@Provides
@Singleton
protected Predicate<String> successTester(TaskSuccess success) {
return new RetryablePredicate<String>(success, 60 * 30, 10, TimeUnit.SECONDS);
}
@Provides
@Singleton
@Named("NOT_FOUND")
protected Predicate<VApp> successTester(VAppNotFound notFound) {
return new RetryablePredicate<VApp>(notFound, 5, 1, TimeUnit.SECONDS);
}
@VCloudToken
@Provides
String provideVCloudToken(Supplier<VCloudSession> cache) {
return checkNotNull(cache.get().getVCloudToken(), "No token present in session");
}
@Provides
@Org
@Singleton
protected URI provideOrg(Supplier<VCloudSession> cache, @Named(PROPERTY_VCLOUD_USER) String user) {
VCloudSession discovery = cache.get();
checkState(discovery.getOrgs().size() > 0, "No orgs present for user: " + user);
return Iterables.getLast(discovery.getOrgs().values()).getLocation();
}
@Provides
@VCloudApi
@Singleton
URI provideVCloudApi(@VCloudLogin URI vcloudUri) {
return URI.create(vcloudUri.toASCIIString().replace("/login", ""));
}
private AuthorizationException authException = null;
/**
* borrowing concurrency code to ensure that caching takes place properly
*/
@Provides
@Singleton
Supplier<VCloudSession> provideVCloudTokenCache(
@Named(PROPERTY_VCLOUD_SESSIONINTERVAL) long seconds, final VCloudLoginAsyncClient login) {
return new ExpirableSupplier<VCloudSession>(
new RetryOnTimeOutExceptionSupplier<VCloudSession>(new Supplier<VCloudSession>() {
public VCloudSession get() {
+ // http://code.google.com/p/google-guice/issues/detail?id=483
+ // guice doesn't remember when singleton providers throw exceptions.
+ // in this case, if describeRegions fails, it is called again for
+ // each provider method that depends on it. To short-circuit this,
+ // we remember the last exception trusting that guice is single-threaded
+ if (authException != null)
+ throw authException;
try {
- // http://code.google.com/p/google-guice/issues/detail?id=483
- // guice doesn't remember when singleton providers throw exceptions.
- // in this case, if describeRegions fails, it is called again for
- // each provider method that depends on it. To short-circuit this,
- // we remember the last exception trusting that guice is single-threaded
- if (authException != null)
- throw authException;
return login.login().get(10, TimeUnit.SECONDS);
} catch (AuthorizationException e) {
BaseVCloudRestClientModule.this.authException = e;
throw e;
} catch (Exception e) {
Throwables.propagate(e);
assert false : e;
return null;
}
}
}), seconds, TimeUnit.SECONDS);
}
@Provides
@Singleton
@VCloud
protected URI provideBaseURI(@Named(PROPERTY_VCLOUD_ENDPOINT) String endpoint) {
return URI.create(endpoint);
}
@Provides
@Singleton
@org.jclouds.vcloud.endpoints.VCloudLogin
protected URI provideAuthenticationURI(VCloudVersionsAsyncClient versionService,
@Named(PROPERTY_VCLOUD_VERSION) String version) throws InterruptedException,
ExecutionException, TimeoutException {
SortedMap<String, URI> versions = versionService.getSupportedVersions().get(180,
TimeUnit.SECONDS);
checkState(versions.size() > 0, "No versions present");
checkState(versions.containsKey(version), "version " + version + " not present in: "
+ versions);
return versions.get(version);
}
@Provides
@Singleton
protected VCloudLoginAsyncClient provideVCloudLogin(AsyncClientFactory factory) {
return factory.create(VCloudLoginAsyncClient.class);
}
@Provides
@Singleton
protected VCloudVersionsAsyncClient provideVCloudVersions(AsyncClientFactory factory) {
return factory.create(VCloudVersionsAsyncClient.class);
}
@Provides
@Singleton
public BasicAuthentication provideBasicAuthentication(@Named(PROPERTY_VCLOUD_USER) String user,
@Named(PROPERTY_VCLOUD_KEY) String key, EncryptionService encryptionService)
throws UnsupportedEncodingException {
return new BasicAuthentication(user, key, encryptionService);
}
@Provides
@CatalogItemRoot
@Singleton
String provideCatalogItemRoot(@VCloudLogin URI vcloudUri) {
return vcloudUri.toASCIIString().replace("/login", "/catalogItem");
}
@Provides
@VAppRoot
@Singleton
String provideVAppRoot(@VCloudLogin URI vcloudUri) {
return vcloudUri.toASCIIString().replace("/login", "/vapp");
}
@Provides
@VAppTemplateRoot
@Singleton
String provideVAppTemplateRoot(@VCloudLogin URI vcloudUri) {
return vcloudUri.toASCIIString().replace("/login", "/vAppTemplate");
}
@Provides
@Singleton
protected Organization provideOrganization(VCloudClient discovery) throws ExecutionException,
TimeoutException, InterruptedException {
if (authException != null)
throw authException;
try {
return discovery.getDefaultOrganization();
} catch (AuthorizationException e) {
BaseVCloudRestClientModule.this.authException = e;
throw e;
}
}
@Provides
@VDC
@Singleton
protected URI provideDefaultVDC(Organization org) {
checkState(org.getVDCs().size() > 0, "No vdcs present in org: " + org.getName());
return Iterables.get(org.getVDCs().values(), 0).getLocation();
}
@Provides
@Catalog
@Singleton
protected URI provideCatalog(Organization org, @Named(PROPERTY_VCLOUD_USER) String user) {
checkState(org.getCatalogs().size() > 0, "No catalogs present in org: " + org.getName());
return Iterables.get(org.getCatalogs().values(), 0).getLocation();
}
@Provides
@Network
@Singleton
protected URI provideDefaultNetwork(VCloudClient client) throws InterruptedException,
ExecutionException, TimeoutException {
if (authException != null)
throw authException;
try {
org.jclouds.vcloud.domain.VDC vDC = client.getDefaultVDC();
Map<String, NamedResource> networks = vDC.getAvailableNetworks();
checkState(networks.size() > 0, "No networks present in vDC: " + vDC.getName());
return Iterables.get(networks.values(), 0).getLocation();
} catch (AuthorizationException e) {
BaseVCloudRestClientModule.this.authException = e;
throw e;
}
}
@Provides
@Named(PROPERTY_VCLOUD_DEFAULT_NETWORK)
@Singleton
String provideDefaultNetworkString(@Network URI network) {
return network.toASCIIString();
}
@Override
protected void bindErrorHandlers() {
bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(
ParseVCloudErrorFromHttpResponse.class);
bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(
ParseVCloudErrorFromHttpResponse.class);
bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(
ParseVCloudErrorFromHttpResponse.class);
}
@Provides
@TasksList
@Singleton
protected URI provideDefaultTasksList(Organization org) {
checkState(org.getTasksLists().size() > 0, "No tasks lists present in org: " + org.getName());
return Iterables.get(org.getTasksLists().values(), 0).getLocation();
}
}
| false | true |
Supplier<VCloudSession> provideVCloudTokenCache(
@Named(PROPERTY_VCLOUD_SESSIONINTERVAL) long seconds, final VCloudLoginAsyncClient login) {
return new ExpirableSupplier<VCloudSession>(
new RetryOnTimeOutExceptionSupplier<VCloudSession>(new Supplier<VCloudSession>() {
public VCloudSession get() {
try {
// http://code.google.com/p/google-guice/issues/detail?id=483
// guice doesn't remember when singleton providers throw exceptions.
// in this case, if describeRegions fails, it is called again for
// each provider method that depends on it. To short-circuit this,
// we remember the last exception trusting that guice is single-threaded
if (authException != null)
throw authException;
return login.login().get(10, TimeUnit.SECONDS);
} catch (AuthorizationException e) {
BaseVCloudRestClientModule.this.authException = e;
throw e;
} catch (Exception e) {
Throwables.propagate(e);
assert false : e;
return null;
}
}
}), seconds, TimeUnit.SECONDS);
}
|
Supplier<VCloudSession> provideVCloudTokenCache(
@Named(PROPERTY_VCLOUD_SESSIONINTERVAL) long seconds, final VCloudLoginAsyncClient login) {
return new ExpirableSupplier<VCloudSession>(
new RetryOnTimeOutExceptionSupplier<VCloudSession>(new Supplier<VCloudSession>() {
public VCloudSession get() {
// http://code.google.com/p/google-guice/issues/detail?id=483
// guice doesn't remember when singleton providers throw exceptions.
// in this case, if describeRegions fails, it is called again for
// each provider method that depends on it. To short-circuit this,
// we remember the last exception trusting that guice is single-threaded
if (authException != null)
throw authException;
try {
return login.login().get(10, TimeUnit.SECONDS);
} catch (AuthorizationException e) {
BaseVCloudRestClientModule.this.authException = e;
throw e;
} catch (Exception e) {
Throwables.propagate(e);
assert false : e;
return null;
}
}
}), seconds, TimeUnit.SECONDS);
}
|
diff --git a/src/main/java/org/mctourney/AutoReferee/listeners/ZoneListener.java b/src/main/java/org/mctourney/AutoReferee/listeners/ZoneListener.java
index e8ea85f..c8f7286 100644
--- a/src/main/java/org/mctourney/AutoReferee/listeners/ZoneListener.java
+++ b/src/main/java/org/mctourney/AutoReferee/listeners/ZoneListener.java
@@ -1,615 +1,616 @@
package org.mctourney.AutoReferee.listeners;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.inventory.DoubleChestInventory;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Redstone;
import org.bukkit.plugin.Plugin;
import org.mctourney.AutoReferee.AutoRefMatch;
import org.mctourney.AutoReferee.AutoRefMatch.Role;
import org.mctourney.AutoReferee.AutoRefPlayer;
import org.mctourney.AutoReferee.AutoRefTeam;
import org.mctourney.AutoReferee.AutoReferee;
import org.mctourney.AutoReferee.AutoRefMatch.StartMechanism;
import org.mctourney.AutoReferee.AutoRefMatch.MatchStatus;
import org.mctourney.AutoReferee.goals.BlockGoal;
import org.mctourney.AutoReferee.regions.AutoRefRegion;
import org.mctourney.AutoReferee.util.BlockData;
import org.mctourney.AutoReferee.util.LocationUtil;
import com.google.common.collect.Maps;
public class ZoneListener implements Listener
{
AutoReferee plugin = null;
// distance a player may travel outside of their lane without penalty
private static final double SAFE_TRAVEL_DISTANCE = 1.595;
// minimum teleport distance worth reporting to streamers
private static final double LONG_TELE_DISTANCE = 6.0;
public static final double SNEAK_DISTANCE = 0.301;
public static final double FREEFALL_THRESHOLD = 0.350;
// convenience for changing defaults
enum ToolAction
{
TOOL_WINCOND,
TOOL_STARTMECH,
TOOL_PROTECT,
}
private Map<Integer, ToolAction> toolMap;
public static int parseTool(String s, Material def)
{
// if no string was passed, return default
if (s == null) return def.getId();
// check to see if this is a material name
Material mat = Material.getMaterial(s);
if (mat != null) return mat.getId();
// try to parse as an integer
try { return Integer.parseInt(s); }
catch (Exception e) { return def.getId(); }
}
public ZoneListener(Plugin p)
{
plugin = (AutoReferee) p;
toolMap = Maps.newHashMap();
// tools.win-condition: golden shovel
toolMap.put(parseTool(plugin.getConfig().getString(
"config-mode.tools.win-condition", null), Material.GOLD_SPADE),
ToolAction.TOOL_WINCOND);
// tools.start-mechanism: golden axe
toolMap.put(parseTool(plugin.getConfig().getString(
"config-mode.tools.start-mechanism", null), Material.GOLD_AXE),
ToolAction.TOOL_STARTMECH);
// tools.protect-entities: golden sword
toolMap.put(parseTool(plugin.getConfig().getString(
"config-mode.tools.protect-entities", null), Material.GOLD_SWORD),
ToolAction.TOOL_PROTECT);
}
@EventHandler(priority=EventPriority.MONITOR)
public void playerMove(PlayerMoveEvent event)
{
Player player = event.getPlayer();
AutoRefMatch match = plugin.getMatch(player.getWorld());
if (match == null) return;
- int blockUnder = match.getWorld().getBlockTypeIdAt(event.getTo().add(0.0, -0.1, 0.0));
+ Location locUnder = event.getTo().clone().add(0.0, -0.1, 0.0);
+ int blockUnder = match.getWorld().getBlockTypeIdAt(locUnder);
boolean onGround = (blockUnder != Material.AIR.getId());
AutoRefPlayer apl = match.getPlayer(player);
if (apl == null)
{
// if the player is not on a team and has left the start area, teleport back
if (!match.isSpectator(player) && !match.inStartRegion(event.getTo()) && onGround)
{
player.teleport(match.getWorldSpawn());
player.setFallDistance(0.0f);
}
return;
}
AutoRefTeam team = apl.getTeam();
if (team == null) return;
double fallspeed = event.getFrom().getY() - event.getTo().getY();
Location exit = apl.getExitLocation();
// don't bother if the player isn't in survival mode
if (player.getGameMode() != GameMode.SURVIVAL
|| match.inStartRegion(event.getTo())) return;
// if a player leaves the start region...
if (!match.inStartRegion(event.getTo()))
{
if (match.getCurrentState().inProgress())
{
// if they are leaving the start region, clear everything
if (match.inStartRegion(event.getFrom()) && !apl.isActive()) apl.reset();
// one way or another, the player is now active
apl.setActive();
}
else if (match.getCurrentState().isBeforeMatch())
{ if (onGround) apl.die(null, false); return; }
}
// if they have left their region, mark their exit location
if (!team.canEnter(event.getTo(), 0.3))
{
// player is sneaking off the edge and not in freefall
if (player.isSneaking() && team.canEnter(event.getTo()) && fallspeed < FREEFALL_THRESHOLD);
// if there is no exit position, set the exit position
else if (exit == null) apl.setExitLocation(player.getLocation());
// if there is an exit position and they aren't falling, kill them
else if (exit != null && fallspeed < FREEFALL_THRESHOLD && onGround)
apl.die(AutoRefPlayer.VOID_DEATH, true);
}
// player inside region
else
{
// if there is an exit location
if (exit != null)
{
// if the player traveled too far through the void, kill them
if (player.getLocation().distance(exit) > SAFE_TRAVEL_DISTANCE)
apl.die(AutoRefPlayer.VOID_DEATH, true);
// reset exit location since player in region
apl.setExitLocation(null);
}
}
}
public boolean validPlayer(Player player)
{
// if the match is not under our control, allowed
AutoRefMatch match = plugin.getMatch(player.getWorld());
if (match == null || match.getCurrentState() == MatchStatus.NONE) return true;
Role role = match.getRole(player);
// if the player is a referee or is creative, nothing is off-limits
if (role == Role.REFEREE || (match.getCurrentState().inProgress()
&& player.getGameMode() == GameMode.CREATIVE && role == Role.PLAYER)) return true;
// if the match isn't currently in progress, a player should
// not be allowed to place or destroy blocks anywhere
if (!match.getCurrentState().inProgress()) return false;
// if the player is not in their lane, they shouldn't be allowed to interact
AutoRefPlayer apl = match.getPlayer(player);
if (apl == null || apl.getExitLocation() != null) return false;
// seems okay!
return true;
}
@EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true)
public void blockPlace(BlockPlaceEvent event)
{
Player player = event.getPlayer();
Location loc = event.getBlock().getLocation();
locationEvent(event, player, loc);
}
@EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true)
public void blockBreak(BlockBreakEvent event)
{
Player player = event.getPlayer();
Location loc = event.getBlock().getLocation();
locationEvent(event, player, loc);
}
@EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true)
public void bucketFill(PlayerBucketFillEvent event)
{
Player player = event.getPlayer();
Location loc = event.getBlockClicked().getRelative(event.getBlockFace()).getLocation();
locationEvent(event, player, loc);
}
@EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true)
public void bucketEmpty(PlayerBucketEmptyEvent event)
{
Player player = event.getPlayer();
Location loc = event.getBlockClicked().getRelative(event.getBlockFace()).getLocation();
locationEvent(event, player, loc);
}
public void locationEvent(Cancellable event, Player player, Location loc)
{
AutoRefMatch match = plugin.getMatch(loc.getWorld());
if (match == null) return;
if (!validPlayer(player))
{ event.setCancelled(true); return; }
AutoRefPlayer apl = match.getPlayer(player);
if (apl != null && apl.getTeam().hasFlag(loc, AutoRefRegion.Flag.NO_BUILD))
{ event.setCancelled(true); return; }
}
@EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true)
public void blockInteract(PlayerInteractEvent event)
{
Player player = event.getPlayer();
Location loc = event.getClickedBlock().getLocation();
AutoRefMatch match = plugin.getMatch(loc.getWorld());
if (match == null) return;
if (match.isPlayer(player))
{
if (match.isStartMechanism(loc) && !match.getStartMechanism(loc).canFlip(match))
{ event.setCancelled(true); return; }
if (!validPlayer(player))
{ event.setCancelled(true); return; }
}
else // is spectator
{
if (!match.isReferee(player) && match.getCurrentState().inProgress())
event.setCancelled(true);
Material type = event.getClickedBlock().getType();
if ((type == Material.WOOD_PLATE || type == Material.STONE_PLATE)
&& match.getCurrentState().inProgress()) { event.setCancelled(true); return; }
if (event.getClickedBlock().getState() instanceof InventoryHolder
&& event.getAction() == Action.RIGHT_CLICK_BLOCK && match.getCurrentState().inProgress())
{
InventoryHolder invh = (InventoryHolder) event.getClickedBlock().getState();
Inventory inv = invh.getInventory();
ItemStack[] contents = inv.getContents();
for (int i = 0; i < contents.length; ++i)
if (contents[i] != null) contents[i] = contents[i].clone();
Inventory newinv;
if (inv instanceof DoubleChestInventory)
newinv = Bukkit.getServer().createInventory(null, 54, "Large Chest");
else newinv = Bukkit.getServer().createInventory(null, inv.getType());
newinv.setContents(contents);
player.openInventory(newinv);
event.setCancelled(true); return;
}
}
}
@EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true)
public void entityInteract(PlayerInteractEntityEvent event)
{
Player player = event.getPlayer();
Location loc = event.getRightClicked().getLocation();
AutoRefMatch match = plugin.getMatch(loc.getWorld());
if (match == null) return;
if (!validPlayer(player))
{ event.setCancelled(true); return; }
AutoRefPlayer apl = match.getPlayer(player);
if (apl != null && !apl.getTeam().canEnter(loc, 0.0))
{ event.setCancelled(true); return; }
}
// restrict item pickup by referees
@EventHandler(priority=EventPriority.HIGHEST)
public void refereePickup(PlayerPickupItemEvent event)
{
AutoRefMatch match = plugin.getMatch(event.getPlayer().getWorld());
if (match != null && match.getCurrentState().inProgress()
&& !match.isPlayer(event.getPlayer())) event.setCancelled(true);
}
// restrict item pickup by referees
@EventHandler(priority=EventPriority.HIGHEST)
public void refereeDrop(PlayerDropItemEvent event)
{
AutoRefMatch match = plugin.getMatch(event.getPlayer().getWorld());
if (match != null && match.getCurrentState().inProgress()
&& !match.isPlayer(event.getPlayer())) event.setCancelled(true);
if (event.getPlayer().getListeningPluginChannels().contains(
AutoReferee.REFEREE_PLUGIN_CHANNEL)) event.setCancelled(true);
}
@EventHandler
public void toolUsage(PlayerInteractEvent event)
{
AutoRefMatch match = plugin.getMatch(event.getPlayer().getWorld());
if (match == null || match.getCurrentState().inProgress()) return;
Block block;
BlockState blockState;
// this event is not an "item" event
if (!event.hasItem()) return;
// get type id of the event and check if its one of our tools
int typeID = event.getItem().getTypeId();
if (!toolMap.containsKey(typeID)) return;
// get which action to perform
switch (toolMap.get(typeID))
{
// this is the tool built for setting win conditions
case TOOL_WINCOND:
// if there is no block involved in this event, nothing
if (!event.hasBlock()) return;
block = event.getClickedBlock();
// if the player doesn't have configure permissions, nothing
if (!event.getPlayer().hasPermission("autoreferee.configure")) return;
for (AutoRefTeam team : match.getTeams())
if (!team.hasFlag(block.getLocation(), AutoRefRegion.Flag.NO_BUILD))
team.addGoal(new BlockGoal(team, block));
break;
// this is the tool built for setting start mechanisms
case TOOL_STARTMECH:
// if there is no block involved in this event, nothing
if (!event.hasBlock()) return;
// if the player doesn't have configure permissions, nothing
if (!event.getPlayer().hasPermission("autoreferee.configure")) return;
// determine who owns the region that the clicked block is in
block = event.getClickedBlock();
blockState = block.getState();
if (blockState.getData() instanceof Redstone)
{
// get the start mechanism
StartMechanism sm = match.addStartMech(block,
((Redstone) blockState.getData()).isPowered());
if (sm != null)
{
// announce it...
String m = ChatColor.RED + sm.toString() +
ChatColor.RESET + " is a start mechanism.";
event.getPlayer().sendMessage(m);
}
}
break;
// this isn't one of our tools...
default: return;
}
// cancel the event, since it was one of our tools being used properly
event.setCancelled(true);
}
@EventHandler
public void toolUsage(PlayerInteractEntityEvent event)
{
AutoRefMatch match = plugin.getMatch(event.getPlayer().getWorld());
if (match == null || match.getCurrentState().inProgress()) return;
// this event is not an "item" event
if (event.getPlayer().getItemInHand() == null) return;
// get type id of the event and check if its one of our tools
int typeID = event.getPlayer().getItemInHand().getTypeId();
if (!toolMap.containsKey(typeID)) return;
// get which action to perform
switch (toolMap.get(typeID))
{
// this is the tool built for protecting entities
case TOOL_PROTECT:
// if there is no entity involved in this event, nothing
if (event.getRightClicked() == null) return;
// if the player doesn't have configure permissions, nothing
if (!event.getPlayer().hasPermission("autoreferee.configure")) return;
// entity name
String ename = String.format("%s @ %s", event.getRightClicked().getType().getName(),
LocationUtil.toBlockCoords(event.getRightClicked().getLocation()));
// save the entity's unique id
UUID uid; match.toggleProtection(uid = event.getRightClicked().getUniqueId());
match.broadcast(ChatColor.RED + ename + ChatColor.RESET + " is " +
(match.isProtected(uid) ? "" : "not ") + "a protected entity");
break;
// this isn't one of our tools...
default: return;
}
// cancel the event, since it was one of our tools being used properly
event.setCancelled(true);
}
@EventHandler(priority=EventPriority.HIGHEST)
public void creatureSpawn(CreatureSpawnEvent event)
{
if (event.getEntity().getWorld() == plugin.getLobbyWorld())
{ event.setCancelled(true); return; }
AutoRefMatch match = plugin.getMatch(event.getEntity().getWorld());
if (match == null || match.getCurrentState() == MatchStatus.NONE) return;
if (event.getSpawnReason() == SpawnReason.SPAWNER_EGG)
{
Player spawner = null;
double distance = Double.POSITIVE_INFINITY;
// get the player who spawned this entity
Location loc = event.getEntity().getLocation();
for (Player pl : event.getEntity().getWorld().getPlayers())
{
double d = loc.distanceSquared(pl.getLocation());
if (d < distance && pl.getItemInHand() != null &&
pl.getItemInHand().getType() == Material.MONSTER_EGG)
{ spawner = pl; distance = d; }
}
// if the player who spawned this creature can configure...
if (spawner != null && spawner.hasPermission("autoreferee.configure")
&& spawner.getGameMode() == GameMode.CREATIVE) return;
}
if (event.getEntityType() == EntityType.SLIME &&
event.getSpawnReason() == SpawnReason.NATURAL)
{ event.setCancelled(true); return; }
// if the match hasn't started, cancel
if (!match.getCurrentState().inProgress())
{ event.setCancelled(true); return; }
// if this is a safe zone, cancel
if (match.hasFlag(event.getLocation(), AutoRefRegion.Flag.SAFE))
{ event.setCancelled(true); return; }
}
public void teleportEvent(Player pl, Location fm, Location to)
{
// cannot compare locations in different worlds
if (fm.getWorld() != to.getWorld()) return;
// if distance is too small to matter, forget about it
double dsq = fm.distanceSquared(to);
if (dsq <= SAFE_TRAVEL_DISTANCE * SAFE_TRAVEL_DISTANCE) return;
AutoRefMatch match = plugin.getMatch(to.getWorld());
if (match == null || match.getCurrentState() == MatchStatus.NONE) return;
// get the player that teleported
AutoRefPlayer apl = match.getPlayer(pl);
if (apl == null) return;
apl.setLastTeleportLocation(to);
// generate message regarding the teleport event
String bedrock = match.blockInRange(BlockData.BEDROCK, to, 5) != null ? " (near bedrock)" : "";
String message = apl.getDisplayName() + ChatColor.GRAY + " has teleported @ " +
LocationUtil.toBlockCoords(to) + bedrock;
boolean excludeStreamers = dsq <= LONG_TELE_DISTANCE * LONG_TELE_DISTANCE;
for (Player ref : match.getReferees(excludeStreamers)) ref.sendMessage(message);
plugin.getLogger().info(ChatColor.stripColor(message));
}
@EventHandler(priority=EventPriority.MONITOR)
public void playerTeleport(PlayerTeleportEvent event)
{
playerMove(event);
switch (event.getCause())
{
case PLUGIN: // if this teleport is caused by a plugin
case COMMAND: // or a vanilla command of some sort, do nothing
break;
default: // otherwise, fire a teleport event (to notify)
teleportEvent(event.getPlayer(), event.getFrom(), event.getTo());
return;
}
}
@EventHandler(priority=EventPriority.MONITOR)
public void playerVehicleEnter(VehicleEnterEvent event)
{ teleportEvent((Player) event.getEntered(), event.getEntered().getLocation(), event.getVehicle().getLocation()); }
@EventHandler(priority=EventPriority.MONITOR)
public void playerBedEnter(PlayerBedEnterEvent event)
{ teleportEvent(event.getPlayer(), event.getPlayer().getLocation(), event.getBed().getLocation()); }
@EventHandler
public void creatureTarget(EntityTargetEvent event)
{
AutoRefMatch match = plugin.getMatch(event.getEntity().getWorld());
if (match == null || event.getTarget() == null) return;
// if the target is a player that isn't on a team, get rid of the target
if (event.getTarget().getType() == EntityType.PLAYER &&
!match.isPlayer((Player) event.getTarget()))
{ event.setTarget(null); return; }
if (!match.getCurrentState().inProgress() ||
match.hasFlag(event.getTarget().getLocation(), AutoRefRegion.Flag.SAFE))
{ event.setTarget(null); return; }
}
@EventHandler
public void explosion(EntityExplodeEvent event)
{
AutoRefMatch match = plugin.getMatch(event.getEntity().getWorld());
if (match == null) return;
Iterator<Block> iter = event.blockList().iterator();
blockloop: while (iter.hasNext())
{
Block b = iter.next();
if (match.hasFlag(b.getLocation(), AutoRefRegion.Flag.NO_EXPLOSIONS))
{ iter.remove(); continue blockloop; }
}
}
@EventHandler
public void endermanPickup(EntityChangeBlockEvent event)
{
AutoRefMatch match = plugin.getMatch(event.getBlock().getWorld());
if (match == null) return;
// don't let endermen pick up blocks, as a rule
if (event.getEntityType() == EntityType.ENDERMAN)
event.setCancelled(true);
}
@EventHandler(priority=EventPriority.HIGHEST)
public void weatherChange(WeatherChangeEvent event)
{
AutoRefMatch match = plugin.getMatch(event.getWorld());
// cancels event if weather is changing to 'storm'
if (match != null && event.toWeatherState())
event.setCancelled(true);
}
}
| true | true |
public void playerMove(PlayerMoveEvent event)
{
Player player = event.getPlayer();
AutoRefMatch match = plugin.getMatch(player.getWorld());
if (match == null) return;
int blockUnder = match.getWorld().getBlockTypeIdAt(event.getTo().add(0.0, -0.1, 0.0));
boolean onGround = (blockUnder != Material.AIR.getId());
AutoRefPlayer apl = match.getPlayer(player);
if (apl == null)
{
// if the player is not on a team and has left the start area, teleport back
if (!match.isSpectator(player) && !match.inStartRegion(event.getTo()) && onGround)
{
player.teleport(match.getWorldSpawn());
player.setFallDistance(0.0f);
}
return;
}
AutoRefTeam team = apl.getTeam();
if (team == null) return;
double fallspeed = event.getFrom().getY() - event.getTo().getY();
Location exit = apl.getExitLocation();
// don't bother if the player isn't in survival mode
if (player.getGameMode() != GameMode.SURVIVAL
|| match.inStartRegion(event.getTo())) return;
// if a player leaves the start region...
if (!match.inStartRegion(event.getTo()))
{
if (match.getCurrentState().inProgress())
{
// if they are leaving the start region, clear everything
if (match.inStartRegion(event.getFrom()) && !apl.isActive()) apl.reset();
// one way or another, the player is now active
apl.setActive();
}
else if (match.getCurrentState().isBeforeMatch())
{ if (onGround) apl.die(null, false); return; }
}
// if they have left their region, mark their exit location
if (!team.canEnter(event.getTo(), 0.3))
{
// player is sneaking off the edge and not in freefall
if (player.isSneaking() && team.canEnter(event.getTo()) && fallspeed < FREEFALL_THRESHOLD);
// if there is no exit position, set the exit position
else if (exit == null) apl.setExitLocation(player.getLocation());
// if there is an exit position and they aren't falling, kill them
else if (exit != null && fallspeed < FREEFALL_THRESHOLD && onGround)
apl.die(AutoRefPlayer.VOID_DEATH, true);
}
// player inside region
else
{
// if there is an exit location
if (exit != null)
{
// if the player traveled too far through the void, kill them
if (player.getLocation().distance(exit) > SAFE_TRAVEL_DISTANCE)
apl.die(AutoRefPlayer.VOID_DEATH, true);
// reset exit location since player in region
apl.setExitLocation(null);
}
}
}
|
public void playerMove(PlayerMoveEvent event)
{
Player player = event.getPlayer();
AutoRefMatch match = plugin.getMatch(player.getWorld());
if (match == null) return;
Location locUnder = event.getTo().clone().add(0.0, -0.1, 0.0);
int blockUnder = match.getWorld().getBlockTypeIdAt(locUnder);
boolean onGround = (blockUnder != Material.AIR.getId());
AutoRefPlayer apl = match.getPlayer(player);
if (apl == null)
{
// if the player is not on a team and has left the start area, teleport back
if (!match.isSpectator(player) && !match.inStartRegion(event.getTo()) && onGround)
{
player.teleport(match.getWorldSpawn());
player.setFallDistance(0.0f);
}
return;
}
AutoRefTeam team = apl.getTeam();
if (team == null) return;
double fallspeed = event.getFrom().getY() - event.getTo().getY();
Location exit = apl.getExitLocation();
// don't bother if the player isn't in survival mode
if (player.getGameMode() != GameMode.SURVIVAL
|| match.inStartRegion(event.getTo())) return;
// if a player leaves the start region...
if (!match.inStartRegion(event.getTo()))
{
if (match.getCurrentState().inProgress())
{
// if they are leaving the start region, clear everything
if (match.inStartRegion(event.getFrom()) && !apl.isActive()) apl.reset();
// one way or another, the player is now active
apl.setActive();
}
else if (match.getCurrentState().isBeforeMatch())
{ if (onGround) apl.die(null, false); return; }
}
// if they have left their region, mark their exit location
if (!team.canEnter(event.getTo(), 0.3))
{
// player is sneaking off the edge and not in freefall
if (player.isSneaking() && team.canEnter(event.getTo()) && fallspeed < FREEFALL_THRESHOLD);
// if there is no exit position, set the exit position
else if (exit == null) apl.setExitLocation(player.getLocation());
// if there is an exit position and they aren't falling, kill them
else if (exit != null && fallspeed < FREEFALL_THRESHOLD && onGround)
apl.die(AutoRefPlayer.VOID_DEATH, true);
}
// player inside region
else
{
// if there is an exit location
if (exit != null)
{
// if the player traveled too far through the void, kill them
if (player.getLocation().distance(exit) > SAFE_TRAVEL_DISTANCE)
apl.die(AutoRefPlayer.VOID_DEATH, true);
// reset exit location since player in region
apl.setExitLocation(null);
}
}
}
|
diff --git a/src/main/java/ch/hszt/mdp/service/UserServiceImpl.java b/src/main/java/ch/hszt/mdp/service/UserServiceImpl.java
index 93744fc..efa054e 100644
--- a/src/main/java/ch/hszt/mdp/service/UserServiceImpl.java
+++ b/src/main/java/ch/hszt/mdp/service/UserServiceImpl.java
@@ -1,133 +1,134 @@
package ch.hszt.mdp.service;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ch.hszt.mdp.dao.UserDao;
import ch.hszt.mdp.domain.Activity;
import ch.hszt.mdp.domain.Friendship;
import ch.hszt.mdp.domain.Stream;
import ch.hszt.mdp.domain.User;
/**
* Implementation for UserService. This handles the registration on back-end side.
*
* @author Fabian Vogler
*
*/
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
/**
* This method saves a user into the database.
*
* @param password
* @param user
* @param userDao
* User Data Access object defination for hibernate
*/
public void create(User user) {
String password = user.getPassword();
try {
// convert password to SHA1
password = sha1(password);
user.setPassword(password);
user.setRepeat(password);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
userDao.save(user);
}
public String sha1(String password) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.reset();
byte[] buffer = password.getBytes();
md.update(buffer);
byte[] digest = md.digest();
String hexStr = "";
for (int i = 0; i < digest.length; i++) {
hexStr += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1);
}
return hexStr;
}
/**
* Creates a UserList with User Objects. The Userlist is collected from the User Database.
*/
public User getUserByEmail(String email) {
return userDao.getUserByEmail(email);
}
public List<Friendship> getAccepteFriendships(String email) {
User user = getUserByEmail(email);
List<Friendship> acceptedFriends = new ArrayList<Friendship>();
for (Friendship friend : user.getFriendships()) {
if (friend.getAccepted() == 1) {
acceptedFriends.add(friend);
}
}
return acceptedFriends;
}
public Stream getActivitiesFromFriends(String email) {
List<Friendship> friends = getAccepteFriendships(email);
DateTime now = new DateTime();
DateTime startOfToday = now.toDateMidnight().toInterval().getStart();
DateTime endOfToday = now.toDateMidnight().toInterval().getEnd();
- DateTime endOfYesterDay = now.minusDays(1).toDateMidnight().toInterval().getEnd();
+ DateTime startOfYesterDay = now.minusDays(1).toDateMidnight().toInterval().getStart();
+ System.out.println("foo"+startOfYesterDay);
Stream stream = new Stream();
for (Friendship friend : friends) {
for (Activity activity : friend.getSecondaryUser().getActivities()) {
if (activity.getTime().isAfter(startOfToday) && activity.getTime().isBefore(endOfToday)) {
stream.addTodaysActivity(activity);
- } else if (activity.getTime().isAfter(endOfYesterDay) && activity.getTime().isBefore(startOfToday)) {
+ } else if (activity.getTime().isBefore(startOfToday) && activity.getTime().isAfter(startOfYesterDay)) {
stream.addYesterdaysActivities(activity);
} else {
stream.addPastActivities(activity);
}
}
}
return stream;
}
@Override
public User getUser(int id) {
return userDao.getUser(id);
}
}
| false | true |
public Stream getActivitiesFromFriends(String email) {
List<Friendship> friends = getAccepteFriendships(email);
DateTime now = new DateTime();
DateTime startOfToday = now.toDateMidnight().toInterval().getStart();
DateTime endOfToday = now.toDateMidnight().toInterval().getEnd();
DateTime endOfYesterDay = now.minusDays(1).toDateMidnight().toInterval().getEnd();
Stream stream = new Stream();
for (Friendship friend : friends) {
for (Activity activity : friend.getSecondaryUser().getActivities()) {
if (activity.getTime().isAfter(startOfToday) && activity.getTime().isBefore(endOfToday)) {
stream.addTodaysActivity(activity);
} else if (activity.getTime().isAfter(endOfYesterDay) && activity.getTime().isBefore(startOfToday)) {
stream.addYesterdaysActivities(activity);
} else {
stream.addPastActivities(activity);
}
}
}
return stream;
}
|
public Stream getActivitiesFromFriends(String email) {
List<Friendship> friends = getAccepteFriendships(email);
DateTime now = new DateTime();
DateTime startOfToday = now.toDateMidnight().toInterval().getStart();
DateTime endOfToday = now.toDateMidnight().toInterval().getEnd();
DateTime startOfYesterDay = now.minusDays(1).toDateMidnight().toInterval().getStart();
System.out.println("foo"+startOfYesterDay);
Stream stream = new Stream();
for (Friendship friend : friends) {
for (Activity activity : friend.getSecondaryUser().getActivities()) {
if (activity.getTime().isAfter(startOfToday) && activity.getTime().isBefore(endOfToday)) {
stream.addTodaysActivity(activity);
} else if (activity.getTime().isBefore(startOfToday) && activity.getTime().isAfter(startOfYesterDay)) {
stream.addYesterdaysActivities(activity);
} else {
stream.addPastActivities(activity);
}
}
}
return stream;
}
|
diff --git a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/CubeQueryUtil.java b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/CubeQueryUtil.java
index 3402d1b0f..0da5c9c50 100644
--- a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/CubeQueryUtil.java
+++ b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/CubeQueryUtil.java
@@ -1,482 +1,487 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.data.adapter.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition;
import org.eclipse.birt.data.engine.olap.api.query.IDimensionDefinition;
import org.eclipse.birt.data.engine.olap.api.query.IEdgeDefinition;
import org.eclipse.birt.data.engine.olap.api.query.IHierarchyDefinition;
import org.eclipse.birt.data.engine.olap.api.query.ILevelDefinition;
import org.eclipse.birt.data.engine.olap.data.api.DimLevel;
import org.eclipse.birt.data.engine.olap.data.api.cube.IDatasetIterator;
import org.eclipse.birt.data.engine.olap.util.OlapExpressionCompiler;
import org.eclipse.birt.data.engine.olap.util.OlapExpressionUtil;
import org.eclipse.birt.data.engine.olap.util.OlapQueryUtil;
import org.eclipse.birt.data.engine.script.ScriptEvalUtil;
import org.eclipse.birt.report.data.adapter.api.AdapterException;
import org.eclipse.birt.report.data.adapter.api.ICubeQueryUtil;
import org.eclipse.birt.report.data.adapter.api.IModelAdapter;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DataSourceHandle;
import org.eclipse.birt.report.model.api.JointDataSetHandle;
import org.eclipse.birt.report.model.api.olap.TabularCubeHandle;
import org.eclipse.birt.report.model.api.olap.TabularDimensionHandle;
import org.eclipse.birt.report.model.api.olap.TabularHierarchyHandle;
/**
*
*/
public class CubeQueryUtil implements ICubeQueryUtil
{
private DataRequestSessionImpl session;
public CubeQueryUtil( DataRequestSessionImpl session )
{
this.session = session;
}
/**
* @throws DataException
*
*/
public List getReferableBindings( String targetLevel,
ICubeQueryDefinition cubeDefn, boolean isSort )
throws AdapterException
{
try
{
List bindings = cubeDefn.getBindings( );
if ( bindings == null )
return new ArrayList( );
DimLevel target = OlapExpressionUtil.getTargetDimLevel( targetLevel );
List result = new ArrayList( );
for ( int i = 0; i < bindings.size( ); i++ )
{
IBinding binding = (IBinding) bindings.get( i );
Set refDimLevel = OlapExpressionCompiler.getReferencedDimLevel( binding.getExpression( ),
bindings,
isSort );
if ( refDimLevel.size( ) > 1 )
continue;
if ( !refDimLevel.contains( target ) )
{
List aggrOns = binding.getAggregatOns( );
if( aggrOns.size( ) == 0 )
{
if( this.getReferencedMeasureName( binding.getExpression( ) )!= null )
{
result.add( binding );
continue;
}
}
for ( int j = 0; j < aggrOns.size( ); j++ )
{
DimLevel dimLevel = OlapExpressionUtil.getTargetDimLevel( aggrOns.get( j )
.toString( ) );
if ( dimLevel.equals( target ) )
{
//Only add to result list if the target dimLevel is the leaf level
//of its own edge that referenced in aggrOns list.
if( j == aggrOns.size( ) -1 )
result.add( binding );
else
{
DimLevel next = OlapExpressionUtil.getTargetDimLevel( aggrOns.get( j+1 )
.toString( ) );
+ //If target dim level is on ROW_EDGE, do not add any subtotal expression.
+ if ( getAxisQualifierEdgeType( target, cubeDefn ) == ICubeQueryDefinition.COLUMN_EDGE )
+ {
+ continue;
+ }
if ( getAxisQualifierLevel( next,
cubeDefn.getEdge( getAxisQualifierEdgeType( dimLevel,
cubeDefn ) ) ) == null )
continue;
else
result.add( binding );
}
break;
}
}
continue;
}
result.add( binding );
}
return result;
}
catch ( DataException e )
{
throw new AdapterException( e.getLocalizedMessage( ), e );
}
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.report.data.adapter.api.DataRequestSession#getReferencedLevels(java.lang.String, java.lang.String, org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition)
*/
public List getReferencedLevels( String targetLevel,
String bindingExpr, ICubeQueryDefinition queryDefn ) throws AdapterException
{
try
{
List result = new ArrayList();
DimLevel target = OlapExpressionUtil.getTargetDimLevel( targetLevel );
String bindingName = OlapExpressionCompiler.getReferencedScriptObject( bindingExpr, "data" );
if( bindingName == null )
return result;
IBinding binding = null;
List bindings = queryDefn.getBindings( );
for( int i = 0; i < bindings.size( ); i++ )
{
IBinding bd = (IBinding)bindings.get( i );
if( bd.getBindingName( ).equals( bindingName ))
{
binding = bd;
break;
}
}
if( binding == null )
{
return result;
}
List aggrOns = binding.getAggregatOns( );
boolean isMeasure = false;
if( aggrOns.size( ) == 0 )
{
isMeasure = this.getReferencedMeasureName( binding.getExpression( ) ) != null;
}
IEdgeDefinition axisQualifierEdge = queryDefn.getEdge( this.getAxisQualifierEdgeType( target,
queryDefn ) );
if ( isMeasure )
{
for ( int i = 0; i < axisQualifierEdge.getDimensions( ).size( ); i++ )
{
IHierarchyDefinition hier = (IHierarchyDefinition) ((IDimensionDefinition)axisQualifierEdge.getDimensions( ).get( i )).getHierarchy( ).get( 0 );
result.addAll( hier.getLevels( ) );
}
}
else
{
for ( int i = 0; i < aggrOns.size( ); i++ )
{
DimLevel dimLevel = OlapExpressionUtil.getTargetDimLevel( aggrOns.get( i )
.toString( ) );
ILevelDefinition lvl = getAxisQualifierLevel( dimLevel,
axisQualifierEdge );
if ( lvl != null )
result.add( lvl );
}
}
return result;
}
catch ( DataException e )
{
throw new AdapterException( e.getLocalizedMessage( ), e );
}
}
/**
*
* @param dimLevel
* @param edge
* @return
*/
private ILevelDefinition getAxisQualifierLevel( DimLevel dimLevel, IEdgeDefinition edge )
{
if( edge == null )
return null;
List dims = edge.getDimensions( );
for( int i = 0; i < dims.size( ); i++ )
{
IDimensionDefinition dim = (IDimensionDefinition)dims.get( i );
if( !dim.getName( ).equals( dimLevel.getDimensionName( ) ))
return null;
IHierarchyDefinition hier = (IHierarchyDefinition)dim.getHierarchy( ).get(0);
List levels = hier.getLevels( );
for( int j = 0; j < levels.size( ); j++ )
{
ILevelDefinition level = (ILevelDefinition)levels.get( j );
if( level.getName( ).equals( dimLevel.getLevelName( ) ))
return level;
}
}
return null;
}
/**
*
* @param dimLevel
* @param queryDefn
* @return
*/
private int getAxisQualifierEdgeType( DimLevel dimLevel, ICubeQueryDefinition queryDefn )
{
IEdgeDefinition edge = queryDefn.getEdge( ICubeQueryDefinition.COLUMN_EDGE );
if( edge == null )
return ICubeQueryDefinition.ROW_EDGE;
List dims = edge.getDimensions( );
for( int i = 0; i < dims.size( ); i++ )
{
IDimensionDefinition dim = (IDimensionDefinition)dims.get( i );
if( dim.getName( ).equals( dimLevel.getDimensionName( ) ))
{
return ICubeQueryDefinition.ROW_EDGE;
}
}
return ICubeQueryDefinition.COLUMN_EDGE;
}
/**
*
* @param expr
* @return
*/
public String getReferencedMeasureName( String expr )
{
return OlapExpressionCompiler.getReferencedScriptObject( expr, "measure" );
}
/**
*
* @param expr
* @return
*/
private String getReferencedMeasureName( IBaseExpression expr )
{
return OlapExpressionCompiler.getReferencedScriptObject( expr, "measure" );
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.report.data.adapter.api.ICubeQueryUtil#getMemberValueIterator(org.eclipse.birt.report.model.api.olap.TabularCubeHandle, java.lang.String, org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition)
*/
public Iterator getMemberValueIterator( TabularCubeHandle cubeHandle,
String dataBindingExpr, ICubeQueryDefinition queryDefn )
throws AdapterException
{
try
{
if ( cubeHandle == null
|| dataBindingExpr == null || queryDefn == null )
return null;
Set dimLevels = OlapExpressionCompiler.getReferencedDimLevel( new ScriptExpression( dataBindingExpr ),
queryDefn.getBindings( ),
true );
if ( dimLevels.size( ) == 0 || dimLevels.size( ) > 1 )
return null;
DimLevel target = (DimLevel) dimLevels.iterator( ).next( );
TabularHierarchyHandle hierHandle = (TabularHierarchyHandle) ( cubeHandle.getDimension( target.getDimensionName( ) ).getContent( TabularDimensionHandle.HIERARCHIES_PROP,
0 ) );
defineDataSourceAndDataSet( hierHandle.getDataSet( ) );
Map levelValueMap = new HashMap( );
DataSetIterator it = new DataSetIterator( this.session, hierHandle );
return new MemberValueIterator( it,
levelValueMap,
target.getLevelName( ) );
}
catch ( BirtException e )
{
throw new AdapterException( e.getLocalizedMessage( ), e );
}
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.report.data.adapter.api.ICubeQueryUtil#getMemberValueIterator(org.eclipse.birt.report.model.api.olap.TabularCubeHandle, java.lang.String, org.eclipse.birt.data.engine.olap.api.query.ILevelDefinition[], java.lang.Object[])
*/
public Iterator getMemberValueIterator( TabularCubeHandle cubeHandle,
String targetLevel, ILevelDefinition[] higherLevelDefns,
Object[] values ) throws AdapterException
{
try
{
if ( ( higherLevelDefns == null && values != null )
|| ( higherLevelDefns != null && values == null )
|| cubeHandle == null || targetLevel == null )
return null;
DimLevel target = OlapExpressionUtil.getTargetDimLevel( targetLevel );
TabularHierarchyHandle hierHandle = (TabularHierarchyHandle) ( cubeHandle.getDimension( target.getDimensionName( ) ).getContent( TabularDimensionHandle.HIERARCHIES_PROP,
0 ) );
defineDataSourceAndDataSet( hierHandle.getDataSet( ));
Map levelValueMap = new HashMap( );
if ( higherLevelDefns != null )
{
for ( int i = 0; i < higherLevelDefns.length; i++ )
{
if ( target.getDimensionName( )
.equals( higherLevelDefns[i].getHierarchy( )
.getDimension( )
.getName( ) ) )
{
levelValueMap.put( higherLevelDefns[i].getName( ),
values[i] );
}
}
}
DataSetIterator it = new DataSetIterator( this.session,
hierHandle );
return new MemberValueIterator( it, levelValueMap, target.getLevelName( ));
}
catch ( BirtException e )
{
throw new AdapterException( e.getLocalizedMessage( ), e );
}
}
/**
* @param hierHandle
* @throws BirtException
*/
private void defineDataSourceAndDataSet( DataSetHandle dataSet )
throws BirtException
{
IModelAdapter modelAdaptor = session.getModelAdaptor( );
DataSourceHandle dataSource = dataSet.getDataSource( );
if ( dataSource != null )
{
session.defineDataSource( modelAdaptor.adaptDataSource( dataSource ) );
}
if ( dataSet instanceof JointDataSetHandle )
{
JointDataSetHandle jointDataSet = (JointDataSetHandle) dataSet;
Iterator iter = ( (JointDataSetHandle) jointDataSet ).dataSetsIterator( );
while ( iter.hasNext( ) )
{
DataSetHandle childDataSet = (DataSetHandle) iter.next( );
if ( childDataSet != null )
{
DataSourceHandle childDataSource = childDataSet.getDataSource( );
if ( childDataSource != null )
{
session.defineDataSource( modelAdaptor.adaptDataSource( childDataSource ) );
}
defineDataSourceAndDataSet( childDataSet );
}
}
}
session.defineDataSet( modelAdaptor.adaptDataSet( dataSet ) );
}
/**
*
* @author Administrator
*
*/
private class MemberValueIterator implements Iterator
{
private IDatasetIterator dataSetIterator;
private boolean hasNext;
private Map levelValueMap;
private String targetLevelName;
private Object currentValue;
public MemberValueIterator( IDatasetIterator it, Map levelValueMap, String targetLevelName )
{
this.dataSetIterator = it;
this.hasNext = true;
this.levelValueMap = levelValueMap;
this.targetLevelName = targetLevelName;
this.next( );
}
public boolean hasNext( )
{
return this.hasNext;
}
public Object next( )
{
try
{
if( !this.hasNext )
return null;
Object result = this.currentValue;
boolean accept = false;
while( this.dataSetIterator.next( ) )
{
accept = true;
Iterator it = this.levelValueMap.keySet( ).iterator( );
while( it.hasNext())
{
String key = it.next( ).toString( );
Object value = this.levelValueMap.get( key );
if( ScriptEvalUtil.compare( value, this.dataSetIterator.getValue( this.dataSetIterator.getFieldIndex( key ) ) ) != 0)
{
accept = false;
break;
}
}
if( accept )
{
this.currentValue = this.dataSetIterator.getValue( this.dataSetIterator.getFieldIndex( this.targetLevelName ) );
break;
}
}
this.hasNext = accept;
return result;
}
catch ( BirtException e )
{
return null;
}
}
public void remove( )
{
throw new UnsupportedOperationException();
}
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.report.data.adapter.api.ICubeQueryUtil#getInvalidBindings(org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition)
*/
public List getInvalidBindings( ICubeQueryDefinition queryDefn )
throws AdapterException
{
try
{
return OlapQueryUtil.validateBinding( queryDefn, true );
}
catch ( DataException e )
{
throw new AdapterException( e.getLocalizedMessage( ), e );
}
}
}
| true | true |
public List getReferableBindings( String targetLevel,
ICubeQueryDefinition cubeDefn, boolean isSort )
throws AdapterException
{
try
{
List bindings = cubeDefn.getBindings( );
if ( bindings == null )
return new ArrayList( );
DimLevel target = OlapExpressionUtil.getTargetDimLevel( targetLevel );
List result = new ArrayList( );
for ( int i = 0; i < bindings.size( ); i++ )
{
IBinding binding = (IBinding) bindings.get( i );
Set refDimLevel = OlapExpressionCompiler.getReferencedDimLevel( binding.getExpression( ),
bindings,
isSort );
if ( refDimLevel.size( ) > 1 )
continue;
if ( !refDimLevel.contains( target ) )
{
List aggrOns = binding.getAggregatOns( );
if( aggrOns.size( ) == 0 )
{
if( this.getReferencedMeasureName( binding.getExpression( ) )!= null )
{
result.add( binding );
continue;
}
}
for ( int j = 0; j < aggrOns.size( ); j++ )
{
DimLevel dimLevel = OlapExpressionUtil.getTargetDimLevel( aggrOns.get( j )
.toString( ) );
if ( dimLevel.equals( target ) )
{
//Only add to result list if the target dimLevel is the leaf level
//of its own edge that referenced in aggrOns list.
if( j == aggrOns.size( ) -1 )
result.add( binding );
else
{
DimLevel next = OlapExpressionUtil.getTargetDimLevel( aggrOns.get( j+1 )
.toString( ) );
if ( getAxisQualifierLevel( next,
cubeDefn.getEdge( getAxisQualifierEdgeType( dimLevel,
cubeDefn ) ) ) == null )
continue;
else
result.add( binding );
}
break;
}
}
continue;
}
result.add( binding );
}
return result;
}
catch ( DataException e )
{
throw new AdapterException( e.getLocalizedMessage( ), e );
}
}
|
public List getReferableBindings( String targetLevel,
ICubeQueryDefinition cubeDefn, boolean isSort )
throws AdapterException
{
try
{
List bindings = cubeDefn.getBindings( );
if ( bindings == null )
return new ArrayList( );
DimLevel target = OlapExpressionUtil.getTargetDimLevel( targetLevel );
List result = new ArrayList( );
for ( int i = 0; i < bindings.size( ); i++ )
{
IBinding binding = (IBinding) bindings.get( i );
Set refDimLevel = OlapExpressionCompiler.getReferencedDimLevel( binding.getExpression( ),
bindings,
isSort );
if ( refDimLevel.size( ) > 1 )
continue;
if ( !refDimLevel.contains( target ) )
{
List aggrOns = binding.getAggregatOns( );
if( aggrOns.size( ) == 0 )
{
if( this.getReferencedMeasureName( binding.getExpression( ) )!= null )
{
result.add( binding );
continue;
}
}
for ( int j = 0; j < aggrOns.size( ); j++ )
{
DimLevel dimLevel = OlapExpressionUtil.getTargetDimLevel( aggrOns.get( j )
.toString( ) );
if ( dimLevel.equals( target ) )
{
//Only add to result list if the target dimLevel is the leaf level
//of its own edge that referenced in aggrOns list.
if( j == aggrOns.size( ) -1 )
result.add( binding );
else
{
DimLevel next = OlapExpressionUtil.getTargetDimLevel( aggrOns.get( j+1 )
.toString( ) );
//If target dim level is on ROW_EDGE, do not add any subtotal expression.
if ( getAxisQualifierEdgeType( target, cubeDefn ) == ICubeQueryDefinition.COLUMN_EDGE )
{
continue;
}
if ( getAxisQualifierLevel( next,
cubeDefn.getEdge( getAxisQualifierEdgeType( dimLevel,
cubeDefn ) ) ) == null )
continue;
else
result.add( binding );
}
break;
}
}
continue;
}
result.add( binding );
}
return result;
}
catch ( DataException e )
{
throw new AdapterException( e.getLocalizedMessage( ), e );
}
}
|
diff --git a/src/swing/org/pathvisio/gui/swing/MainPanelStandalone.java b/src/swing/org/pathvisio/gui/swing/MainPanelStandalone.java
index ebd21c87..3c7ae765 100644
--- a/src/swing/org/pathvisio/gui/swing/MainPanelStandalone.java
+++ b/src/swing/org/pathvisio/gui/swing/MainPanelStandalone.java
@@ -1,221 +1,222 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2007 BiGCaT Bioinformatics
//
// 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.pathvisio.gui.swing;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.Set;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import org.pathvisio.Engine;
import org.pathvisio.debug.Logger;
import org.pathvisio.gui.swing.CommonActions.ZoomAction;
import com.mammothsoftware.frwk.ddb.DropDownButton;
import edu.stanford.ejalbert.BrowserLauncher;
public class MainPanelStandalone extends MainPanel
{
private static final long serialVersionUID = 1L;
protected JMenuBar menuBar;
@Override
protected void addMenuActions(JMenuBar mb) {
JMenu fileMenu = new JMenu("File");
addToMenu(StandaloneActions.newAction, fileMenu);
addToMenu(StandaloneActions.openAction, fileMenu);
addToMenu(actions.saveAction, fileMenu);
addToMenu(actions.saveAsAction, fileMenu);
fileMenu.addSeparator();
addToMenu(actions.importAction, fileMenu);
addToMenu(actions.exportAction, fileMenu);
fileMenu.addSeparator();
addToMenu(actions.exitAction, fileMenu);
JMenu editMenu = new JMenu("Edit");
addToMenu(actions.undoAction, editMenu);
addToMenu(actions.copyAction, editMenu);
addToMenu(actions.pasteAction, editMenu);
addToMenu(StandaloneActions.searchAction, editMenu);
editMenu.addSeparator();
addToMenu(StandaloneActions.preferencesAction, editMenu);
JMenu selectionMenu = new JMenu("Selection");
JMenu alignMenu = new JMenu("Align");
JMenu stackMenu = new JMenu("Stack");
for(Action a : actions.alignActions) addToMenu(a, alignMenu);
for(Action a : actions.stackActions) addToMenu(a, stackMenu);
selectionMenu.add(alignMenu);
selectionMenu.add(stackMenu);
editMenu.add (selectionMenu);
JMenu dataMenu = new JMenu("Data");
addToMenu (StandaloneActions.selectGeneDbAction, dataMenu);
addToMenu (StandaloneActions.selectMetaboliteDbAction, dataMenu);
addToMenu (StandaloneActions.selectGexAction, dataMenu);
dataMenu.addSeparator();
addToMenu (StandaloneActions.importGexDataAction, dataMenu);
dataMenu.addSeparator();
addToMenu (new StandaloneActions.VisualizationAction(this), dataMenu);
JMenu viewMenu = new JMenu("View");
JMenu zoomMenu = new JMenu("Zoom");
viewMenu.add(zoomMenu);
for(Action a : actions.zoomActions) addToMenu(a, zoomMenu);
JMenu helpMenu = new JMenu("Help");
helpMenu.add(StandaloneActions.aboutAction);
helpMenu.add(StandaloneActions.helpAction);
mb.add(fileMenu);
mb.add(editMenu);
mb.add(dataMenu);
mb.add(viewMenu);
mb.add(helpMenu);
}
public MainPanelStandalone()
{
this (null);
}
public MainPanelStandalone(Set<Action> hideActions)
{
super(hideActions);
SearchPane searchPane = new SearchPane();
sidebarTabbedPane.addTab ("Search", searchPane);
backpagePane.addHyperlinkListener(
new HyperlinkListener()
{
public void hyperlinkUpdate(HyperlinkEvent e)
{
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
{
URL url = e.getURL();
try
{
BrowserLauncher b = new BrowserLauncher(null);
b.openURLinBrowser(url.toString());
}
catch (Exception ex)
{
Logger.log.error ("Couldn't open url '" + url + "'", ex);
JOptionPane.showMessageDialog(SwingEngine.getCurrent().getFrame(),
"Error opening the Browser, see error log for details.");
}
}
}
}
);
}
protected void addToolBarActions(JToolBar tb)
{
tb.setLayout(new WrapLayout(1, 1));
addToToolbar(StandaloneActions.newAction);
+ addToToolbar(StandaloneActions.openAction);
addToToolbar(actions.saveAction);
tb.addSeparator();
addToToolbar(actions.copyAction);
addToToolbar(actions.pasteAction);
tb.addSeparator();
addToToolbar(actions.undoAction);
tb.addSeparator();
addToToolbar(new JLabel("Zoom:", JLabel.LEFT));
JComboBox combo = new JComboBox(actions.zoomActions);
combo.setMaximumSize(combo.getPreferredSize());
combo.setEditable(true);
combo.setSelectedIndex(5); // 100%
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox combo = (JComboBox) e.getSource();
Object s = combo.getSelectedItem();
if (s instanceof Action) {
((Action) s).actionPerformed(e);
} else if (s instanceof String) {
String zs = (String) s;
try {
double zf = Double.parseDouble(zs);
ZoomAction za = new ZoomAction(zf);
za.setEnabled(true);
za.actionPerformed(e);
} catch (Exception ex) {
// Ignore bad input
}
}
}
});
addToToolbar(combo, TB_GROUP_SHOW_IF_VPATHWAY);
tb.addSeparator();
String submenu = "line";
for(Action[] aa : actions.newElementActions) {
if(aa.length == 1) {
addToToolbar(aa[0]);
} else { //This is the line/receptor sub-menu
String icon = "newlinemenu.gif";
String tooltip = "Select a line to draw";
if(submenu.equals("receptors")) { //Next one is receptors
icon = "newlineshapemenu.gif";
tooltip = "Select a receptor/ligand to draw";
} else {
submenu = "receptors";
}
DropDownButton lineButton = new DropDownButton(new ImageIcon(Engine.getCurrent()
.getResourceURL(icon)));
lineButton.setToolTipText(tooltip);
for(Action a : aa) {
lineButton.addComponent(new JMenuItem(a));
}
addToToolbar(lineButton, TB_GROUP_SHOW_IF_EDITMODE);
}
}
tb.addSeparator();
addToToolbar(actions.alignActions);
addToToolbar(actions.stackActions);
}
}
| true | true |
protected void addToolBarActions(JToolBar tb)
{
tb.setLayout(new WrapLayout(1, 1));
addToToolbar(StandaloneActions.newAction);
addToToolbar(actions.saveAction);
tb.addSeparator();
addToToolbar(actions.copyAction);
addToToolbar(actions.pasteAction);
tb.addSeparator();
addToToolbar(actions.undoAction);
tb.addSeparator();
addToToolbar(new JLabel("Zoom:", JLabel.LEFT));
JComboBox combo = new JComboBox(actions.zoomActions);
combo.setMaximumSize(combo.getPreferredSize());
combo.setEditable(true);
combo.setSelectedIndex(5); // 100%
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox combo = (JComboBox) e.getSource();
Object s = combo.getSelectedItem();
if (s instanceof Action) {
((Action) s).actionPerformed(e);
} else if (s instanceof String) {
String zs = (String) s;
try {
double zf = Double.parseDouble(zs);
ZoomAction za = new ZoomAction(zf);
za.setEnabled(true);
za.actionPerformed(e);
} catch (Exception ex) {
// Ignore bad input
}
}
}
});
addToToolbar(combo, TB_GROUP_SHOW_IF_VPATHWAY);
tb.addSeparator();
String submenu = "line";
for(Action[] aa : actions.newElementActions) {
if(aa.length == 1) {
addToToolbar(aa[0]);
} else { //This is the line/receptor sub-menu
String icon = "newlinemenu.gif";
String tooltip = "Select a line to draw";
if(submenu.equals("receptors")) { //Next one is receptors
icon = "newlineshapemenu.gif";
tooltip = "Select a receptor/ligand to draw";
} else {
submenu = "receptors";
}
DropDownButton lineButton = new DropDownButton(new ImageIcon(Engine.getCurrent()
.getResourceURL(icon)));
lineButton.setToolTipText(tooltip);
for(Action a : aa) {
lineButton.addComponent(new JMenuItem(a));
}
addToToolbar(lineButton, TB_GROUP_SHOW_IF_EDITMODE);
}
}
tb.addSeparator();
addToToolbar(actions.alignActions);
addToToolbar(actions.stackActions);
}
|
protected void addToolBarActions(JToolBar tb)
{
tb.setLayout(new WrapLayout(1, 1));
addToToolbar(StandaloneActions.newAction);
addToToolbar(StandaloneActions.openAction);
addToToolbar(actions.saveAction);
tb.addSeparator();
addToToolbar(actions.copyAction);
addToToolbar(actions.pasteAction);
tb.addSeparator();
addToToolbar(actions.undoAction);
tb.addSeparator();
addToToolbar(new JLabel("Zoom:", JLabel.LEFT));
JComboBox combo = new JComboBox(actions.zoomActions);
combo.setMaximumSize(combo.getPreferredSize());
combo.setEditable(true);
combo.setSelectedIndex(5); // 100%
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox combo = (JComboBox) e.getSource();
Object s = combo.getSelectedItem();
if (s instanceof Action) {
((Action) s).actionPerformed(e);
} else if (s instanceof String) {
String zs = (String) s;
try {
double zf = Double.parseDouble(zs);
ZoomAction za = new ZoomAction(zf);
za.setEnabled(true);
za.actionPerformed(e);
} catch (Exception ex) {
// Ignore bad input
}
}
}
});
addToToolbar(combo, TB_GROUP_SHOW_IF_VPATHWAY);
tb.addSeparator();
String submenu = "line";
for(Action[] aa : actions.newElementActions) {
if(aa.length == 1) {
addToToolbar(aa[0]);
} else { //This is the line/receptor sub-menu
String icon = "newlinemenu.gif";
String tooltip = "Select a line to draw";
if(submenu.equals("receptors")) { //Next one is receptors
icon = "newlineshapemenu.gif";
tooltip = "Select a receptor/ligand to draw";
} else {
submenu = "receptors";
}
DropDownButton lineButton = new DropDownButton(new ImageIcon(Engine.getCurrent()
.getResourceURL(icon)));
lineButton.setToolTipText(tooltip);
for(Action a : aa) {
lineButton.addComponent(new JMenuItem(a));
}
addToToolbar(lineButton, TB_GROUP_SHOW_IF_EDITMODE);
}
}
tb.addSeparator();
addToToolbar(actions.alignActions);
addToToolbar(actions.stackActions);
}
|
diff --git a/MobilisXMPP/src/de/tudresden/inf/rn/mobilis/xmpp/beans/runtimeprotocol/PublishNewServiceBean.java b/MobilisXMPP/src/de/tudresden/inf/rn/mobilis/xmpp/beans/runtimeprotocol/PublishNewServiceBean.java
index cfcde28..0ee6ae6 100644
--- a/MobilisXMPP/src/de/tudresden/inf/rn/mobilis/xmpp/beans/runtimeprotocol/PublishNewServiceBean.java
+++ b/MobilisXMPP/src/de/tudresden/inf/rn/mobilis/xmpp/beans/runtimeprotocol/PublishNewServiceBean.java
@@ -1,140 +1,141 @@
package de.tudresden.inf.rn.mobilis.xmpp.beans.runtimeprotocol;
import org.jivesoftware.smack.packet.XMPPError;
import org.xmlpull.v1.XmlPullParser;
import de.tudresden.inf.rn.mobilis.xmpp.beans.Mobilis;
import de.tudresden.inf.rn.mobilis.xmpp.beans.XMPPBean;
import de.tudresden.inf.rn.mobilis.xmpp.beans.coordination.MobilisServiceInfo;
public class PublishNewServiceBean extends XMPPBean {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final String NAMESPACE = Mobilis.NAMESPACE + "#XMPPBean:deployment:publishNewService";
public static final String CHILD_ELEMENT = "publishNewService";
public String newServiceJID;
public boolean successfullyAddedService;
private String _xmlTag_ServiceJID = "serviceJID";
/*
* Constructor to send a Result
*/
public PublishNewServiceBean() {
super();
this.type=XMPPBean.TYPE_RESULT;
}
/*
* Constructor for publish a new Service to another Runtimes Discovery
*/
public PublishNewServiceBean(String newServiceJID){
super();
this.newServiceJID = newServiceJID;
this.type=XMPPBean.TYPE_SET;
}
/*
* Constructor for occuring Errors while trying to publish a new Service
*/
public PublishNewServiceBean(String errorType, String errorCondition,
String errorText) {
super(errorType, errorCondition, errorText);
}
@Override
public void fromXML(XmlPullParser parser) throws Exception {
//String childElement = MobilisServiceInfo.CHILD_ELEMENT;
boolean done = false;
do {
switch (parser.getEventType()) {
case XmlPullParser.START_TAG:
String tagName = parser.getName();
if (tagName.equals(CHILD_ELEMENT)) {
parser.next();
} else if (tagName.equals(_xmlTag_ServiceJID)) {
this.newServiceJID = parser.nextText();
} else if (tagName.equals("error")) {
parser = parseErrorAttributes(parser);
} else
parser.next();
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals(CHILD_ELEMENT))
done = true;
else
parser.next();
break;
case XmlPullParser.END_DOCUMENT:
done = true;
break;
default:
parser.next();
}
} while (!done);
- parser.next();
- if(parser.getName().equals("error")){
- this.errorType = parser.getAttributeValue(1);
- parser.next();
- this.errorCondition = parser.getName();
- this.errorText = parser.getName();
- }
+// parser.next();
+// System.out.println(parser.getName());
+// if(parser.getName().equals("error")){
+// this.errorType = parser.getAttributeValue(1);
+// parser.next();
+// this.errorCondition = parser.getName();
+// this.errorText = parser.getName();
+// }
}
@Override
public String getChildElement() {
return PublishNewServiceBean.CHILD_ELEMENT;
}
@Override
public String getNamespace() {
return PublishNewServiceBean.NAMESPACE;
}
@Override
public PublishNewServiceBean clone() {
PublishNewServiceBean twin = new PublishNewServiceBean(this.newServiceJID);
twin = (PublishNewServiceBean) cloneBasicAttributes(twin);
return twin;
}
@Override
public String payloadToXML() {
StringBuilder sb = new StringBuilder();
if (getType() == XMPPBean.TYPE_SET) {
if(this.newServiceJID!=null){
sb.append("<" + _xmlTag_ServiceJID + ">")
.append(this.newServiceJID)
.append("</" + _xmlTag_ServiceJID + ">");
}
}
if(getType() == XMPPBean.TYPE_ERROR){
if(this.newServiceJID!=null){
sb.append("<" + _xmlTag_ServiceJID + ">")
.append(this.newServiceJID)
.append("</" + _xmlTag_ServiceJID + ">");
}
}
sb = appendErrorPayload(sb);
return sb.toString();
}
public String getNewServiceJID() {
return newServiceJID;
}
public void setNewServiceJID(String newServiceJID) {
this.newServiceJID = newServiceJID;
}
}
| true | true |
public void fromXML(XmlPullParser parser) throws Exception {
//String childElement = MobilisServiceInfo.CHILD_ELEMENT;
boolean done = false;
do {
switch (parser.getEventType()) {
case XmlPullParser.START_TAG:
String tagName = parser.getName();
if (tagName.equals(CHILD_ELEMENT)) {
parser.next();
} else if (tagName.equals(_xmlTag_ServiceJID)) {
this.newServiceJID = parser.nextText();
} else if (tagName.equals("error")) {
parser = parseErrorAttributes(parser);
} else
parser.next();
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals(CHILD_ELEMENT))
done = true;
else
parser.next();
break;
case XmlPullParser.END_DOCUMENT:
done = true;
break;
default:
parser.next();
}
} while (!done);
parser.next();
if(parser.getName().equals("error")){
this.errorType = parser.getAttributeValue(1);
parser.next();
this.errorCondition = parser.getName();
this.errorText = parser.getName();
}
}
|
public void fromXML(XmlPullParser parser) throws Exception {
//String childElement = MobilisServiceInfo.CHILD_ELEMENT;
boolean done = false;
do {
switch (parser.getEventType()) {
case XmlPullParser.START_TAG:
String tagName = parser.getName();
if (tagName.equals(CHILD_ELEMENT)) {
parser.next();
} else if (tagName.equals(_xmlTag_ServiceJID)) {
this.newServiceJID = parser.nextText();
} else if (tagName.equals("error")) {
parser = parseErrorAttributes(parser);
} else
parser.next();
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals(CHILD_ELEMENT))
done = true;
else
parser.next();
break;
case XmlPullParser.END_DOCUMENT:
done = true;
break;
default:
parser.next();
}
} while (!done);
// parser.next();
// System.out.println(parser.getName());
// if(parser.getName().equals("error")){
// this.errorType = parser.getAttributeValue(1);
// parser.next();
// this.errorCondition = parser.getName();
// this.errorText = parser.getName();
// }
}
|
diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java
index 8dc7a8c74..376ee260a 100644
--- a/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java
+++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java
@@ -1,322 +1,322 @@
/**
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.tags;
import java.util.ArrayList;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;
import com.timsu.astrid.R;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.sql.Criterion;
import com.todoroo.andlib.sql.QueryTemplate;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.andlib.utility.DialogUtilities;
import com.todoroo.astrid.actfm.TagViewFragment;
import com.todoroo.astrid.activity.TaskListFragment;
import com.todoroo.astrid.api.AstridApiConstants;
import com.todoroo.astrid.api.AstridFilterExposer;
import com.todoroo.astrid.api.Filter;
import com.todoroo.astrid.api.FilterCategory;
import com.todoroo.astrid.api.FilterListItem;
import com.todoroo.astrid.api.FilterWithCustomIntent;
import com.todoroo.astrid.api.FilterWithUpdate;
import com.todoroo.astrid.core.PluginServices;
import com.todoroo.astrid.dao.TaskDao.TaskCriteria;
import com.todoroo.astrid.data.Metadata;
import com.todoroo.astrid.data.TagData;
import com.todoroo.astrid.gtasks.GtasksPreferenceService;
import com.todoroo.astrid.service.AstridDependencyInjector;
import com.todoroo.astrid.service.TagDataService;
import com.todoroo.astrid.tags.TagService.Tag;
/**
* Exposes filters based on tags
*
* @author Tim Su <[email protected]>
*
*/
public class TagFilterExposer extends BroadcastReceiver implements AstridFilterExposer {
private static final String TAG = "tag"; //$NON-NLS-1$
@Autowired TagDataService tagDataService;
@Autowired GtasksPreferenceService gtasksPreferenceService;
/** Create filter from new tag object */
@SuppressWarnings("nls")
public static FilterWithCustomIntent filterFromTag(Context context, Tag tag, Criterion criterion) {
String title = tag.tag;
QueryTemplate tagTemplate = tag.queryTemplate(criterion);
ContentValues contentValues = new ContentValues();
contentValues.put(Metadata.KEY.name, TagService.KEY);
contentValues.put(TagService.TAG.name, tag.tag);
FilterWithUpdate filter = new FilterWithUpdate(tag.tag,
title, tagTemplate,
contentValues);
if(tag.remoteId > 0) {
filter.listingTitle += " (" + tag.count + ")";
if(tag.count == 0)
filter.color = Color.GRAY;
}
- TagData tagData = PluginServices.getTagDataService().getTag(tag.tag, TagData.ID, TagData.MEMBER_COUNT);
+ TagData tagData = PluginServices.getTagDataService().getTag(tag.tag, TagData.ID, TagData.USER_ID, TagData.MEMBER_COUNT);
int deleteIntentLabel;
if (tagData.getValue(TagData.MEMBER_COUNT) > 0 && tagData.getValue(TagData.USER_ID) != 0)
deleteIntentLabel = R.string.tag_cm_leave;
else
deleteIntentLabel = R.string.tag_cm_delete;
filter.contextMenuLabels = new String[] {
context.getString(R.string.tag_cm_rename),
context.getString(deleteIntentLabel)
};
filter.contextMenuIntents = new Intent[] {
newTagIntent(context, RenameTagActivity.class, tag),
newTagIntent(context, DeleteTagActivity.class, tag)
};
filter.customTaskList = new ComponentName(ContextManager.getContext(), TagViewFragment.class);
if(tag.image != null)
filter.imageUrl = tag.image;
if(tag.updateText != null)
filter.updateText = tag.updateText;
Bundle extras = new Bundle();
extras.putString(TagViewFragment.EXTRA_TAG_NAME, tag.tag);
extras.putLong(TagViewFragment.EXTRA_TAG_REMOTE_ID, tag.remoteId);
extras.putBoolean(TaskListFragment.TOKEN_OVERRIDE_ANIM, true);
filter.customExtras = extras;
return filter;
}
/** Create a filter from tag data object */
public static Filter filterFromTagData(Context context, TagData tagData) {
Tag tag = new Tag(tagData.getValue(TagData.NAME),
tagData.getValue(TagData.TASK_COUNT),
tagData.getValue(TagData.REMOTE_ID));
return filterFromTag(context, tag, TaskCriteria.activeAndVisible());
}
private static Intent newTagIntent(Context context, Class<? extends Activity> activity, Tag tag) {
Intent ret = new Intent(context, activity);
ret.putExtra(TAG, tag.tag);
return ret;
}
@Override
public void onReceive(Context context, Intent intent) {
FilterListItem[] listAsArray = prepareFilters(context);
Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_FILTERS);
broadcastIntent.putExtra(AstridApiConstants.EXTRAS_RESPONSE, listAsArray);
broadcastIntent.putExtra(AstridApiConstants.EXTRAS_ADDON, TagsPlugin.IDENTIFIER);
context.sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ);
}
private FilterListItem[] prepareFilters(Context context) {
DependencyInjectionService.getInstance().inject(this);
ContextManager.setContext(context);
ArrayList<FilterListItem> list = new ArrayList<FilterListItem>();
addTags(list);
// transmit filter list
FilterListItem[] listAsArray = list.toArray(new FilterListItem[list.size()]);
return listAsArray;
}
private void addTags(ArrayList<FilterListItem> list) {
ArrayList<Tag> tagList = TagService.getInstance().getTagList();
list.add(filterFromTags(tagList.toArray(new Tag[tagList.size()]),
R.string.tag_FEx_header));
}
private FilterCategory filterFromTags(Tag[] tags, int name) {
Filter[] filters = new Filter[tags.length + 1];
Context context = ContextManager.getContext();
Resources r = context.getResources();
// --- untagged
int untaggedLabel = gtasksPreferenceService.isLoggedIn() ?
R.string.tag_FEx_untagged_w_astrid : R.string.tag_FEx_untagged;
Filter untagged = new Filter(r.getString(untaggedLabel),
r.getString(R.string.tag_FEx_untagged),
TagService.untaggedTemplate(),
null);
untagged.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.gl_lists)).getBitmap();
filters[0] = untagged;
for(int i = 0; i < tags.length; i++)
filters[i+1] = filterFromTag(context, tags[i], TaskCriteria.activeAndVisible());
FilterCategory filter = new FilterCategory(context.getString(name), filters);
return filter;
}
// --- tag manipulation activities
public abstract static class TagActivity extends Activity {
protected String tag;
@Autowired public TagService tagService;
@Autowired public TagDataService tagDataService;
static {
AstridDependencyInjector.initialize();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tag = getIntent().getStringExtra(TAG);
if(tag == null) {
finish();
return;
}
DependencyInjectionService.getInstance().inject(this);
TagData tagData = tagDataService.getTag(tag, TagData.MEMBER_COUNT, TagData.USER_ID);
if(tagData != null && tagData.getValue(TagData.MEMBER_COUNT) > 0 && tagData.getValue(TagData.USER_ID) == 0) {
DialogUtilities.okCancelDialog(this, getString(R.string.actfm_tag_operation_owner_delete), getOkListener(), getCancelListener());
return;
}
showDialog(tagData);
}
protected DialogInterface.OnClickListener getOkListener() {
return new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
if (ok()) {
setResult(RESULT_OK);
} else {
toastNoChanges();
setResult(RESULT_CANCELED);
}
} finally {
finish();
}
}
};
}
protected DialogInterface.OnClickListener getCancelListener() {
return new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
toastNoChanges();
} finally {
setResult(RESULT_CANCELED);
finish();
}
}
};
}
private void toastNoChanges() {
Toast.makeText(this, R.string.TEA_no_tags_modified,
Toast.LENGTH_SHORT).show();
}
protected abstract void showDialog(TagData tagData);
protected abstract boolean ok();
}
public static class DeleteTagActivity extends TagActivity {
@Override
protected void showDialog(TagData tagData) {
int string;
if (tagData != null && tagData.getValue(TagData.MEMBER_COUNT) > 0)
string = R.string.DLG_leave_this_shared_tag_question;
else
string = R.string.DLG_delete_this_tag_question;
DialogUtilities.okCancelDialog(this, getString(string, tag), getOkListener(), getCancelListener());
}
@Override
protected boolean ok() {
int deleted = tagService.delete(tag);
TagData tagData = PluginServices.getTagDataService().getTag(tag, TagData.ID, TagData.DELETION_DATE, TagData.MEMBER_COUNT, TagData.USER_ID);
boolean shared = false;
if(tagData != null) {
tagData.setValue(TagData.DELETION_DATE, DateUtilities.now());
PluginServices.getTagDataService().save(tagData);
shared = tagData.getValue(TagData.MEMBER_COUNT) > 0 && tagData.getValue(TagData.USER_ID) != 0; // Was I a list member and NOT owner?
}
Toast.makeText(this, getString(shared ? R.string.TEA_tags_left : R.string.TEA_tags_deleted, tag, deleted),
Toast.LENGTH_SHORT).show();
Intent tagDeleted = new Intent(AstridApiConstants.BROADCAST_EVENT_TAG_DELETED);
tagDeleted.putExtra(TagViewFragment.EXTRA_TAG_NAME, tag);
sendBroadcast(tagDeleted);
return true;
}
}
public static class RenameTagActivity extends TagActivity {
private EditText editor;
@Override
protected void showDialog(TagData tagData) {
editor = new EditText(this);
DialogUtilities.viewDialog(this, getString(R.string.DLG_rename_this_tag_header, tag), editor, getOkListener(), getCancelListener());
}
@Override
protected boolean ok() {
if(editor == null)
return false;
String text = editor.getText().toString();
if (text == null || text.length() == 0) {
return false;
} else {
int renamed = tagService.rename(tag, text);
TagData tagData = tagDataService.getTag(tag, TagData.ID, TagData.NAME);
if (tagData != null) {
tagData.setValue(TagData.NAME, text);
tagDataService.save(tagData);
}
Toast.makeText(this, getString(R.string.TEA_tags_renamed, tag, text, renamed),
Toast.LENGTH_SHORT).show();
return true;
}
}
}
@Override
public FilterListItem[] getFilters() {
if (ContextManager.getContext() == null)
return null;
return prepareFilters(ContextManager.getContext());
}
}
| true | true |
public static FilterWithCustomIntent filterFromTag(Context context, Tag tag, Criterion criterion) {
String title = tag.tag;
QueryTemplate tagTemplate = tag.queryTemplate(criterion);
ContentValues contentValues = new ContentValues();
contentValues.put(Metadata.KEY.name, TagService.KEY);
contentValues.put(TagService.TAG.name, tag.tag);
FilterWithUpdate filter = new FilterWithUpdate(tag.tag,
title, tagTemplate,
contentValues);
if(tag.remoteId > 0) {
filter.listingTitle += " (" + tag.count + ")";
if(tag.count == 0)
filter.color = Color.GRAY;
}
TagData tagData = PluginServices.getTagDataService().getTag(tag.tag, TagData.ID, TagData.MEMBER_COUNT);
int deleteIntentLabel;
if (tagData.getValue(TagData.MEMBER_COUNT) > 0 && tagData.getValue(TagData.USER_ID) != 0)
deleteIntentLabel = R.string.tag_cm_leave;
else
deleteIntentLabel = R.string.tag_cm_delete;
filter.contextMenuLabels = new String[] {
context.getString(R.string.tag_cm_rename),
context.getString(deleteIntentLabel)
};
filter.contextMenuIntents = new Intent[] {
newTagIntent(context, RenameTagActivity.class, tag),
newTagIntent(context, DeleteTagActivity.class, tag)
};
filter.customTaskList = new ComponentName(ContextManager.getContext(), TagViewFragment.class);
if(tag.image != null)
filter.imageUrl = tag.image;
if(tag.updateText != null)
filter.updateText = tag.updateText;
Bundle extras = new Bundle();
extras.putString(TagViewFragment.EXTRA_TAG_NAME, tag.tag);
extras.putLong(TagViewFragment.EXTRA_TAG_REMOTE_ID, tag.remoteId);
extras.putBoolean(TaskListFragment.TOKEN_OVERRIDE_ANIM, true);
filter.customExtras = extras;
return filter;
}
|
public static FilterWithCustomIntent filterFromTag(Context context, Tag tag, Criterion criterion) {
String title = tag.tag;
QueryTemplate tagTemplate = tag.queryTemplate(criterion);
ContentValues contentValues = new ContentValues();
contentValues.put(Metadata.KEY.name, TagService.KEY);
contentValues.put(TagService.TAG.name, tag.tag);
FilterWithUpdate filter = new FilterWithUpdate(tag.tag,
title, tagTemplate,
contentValues);
if(tag.remoteId > 0) {
filter.listingTitle += " (" + tag.count + ")";
if(tag.count == 0)
filter.color = Color.GRAY;
}
TagData tagData = PluginServices.getTagDataService().getTag(tag.tag, TagData.ID, TagData.USER_ID, TagData.MEMBER_COUNT);
int deleteIntentLabel;
if (tagData.getValue(TagData.MEMBER_COUNT) > 0 && tagData.getValue(TagData.USER_ID) != 0)
deleteIntentLabel = R.string.tag_cm_leave;
else
deleteIntentLabel = R.string.tag_cm_delete;
filter.contextMenuLabels = new String[] {
context.getString(R.string.tag_cm_rename),
context.getString(deleteIntentLabel)
};
filter.contextMenuIntents = new Intent[] {
newTagIntent(context, RenameTagActivity.class, tag),
newTagIntent(context, DeleteTagActivity.class, tag)
};
filter.customTaskList = new ComponentName(ContextManager.getContext(), TagViewFragment.class);
if(tag.image != null)
filter.imageUrl = tag.image;
if(tag.updateText != null)
filter.updateText = tag.updateText;
Bundle extras = new Bundle();
extras.putString(TagViewFragment.EXTRA_TAG_NAME, tag.tag);
extras.putLong(TagViewFragment.EXTRA_TAG_REMOTE_ID, tag.remoteId);
extras.putBoolean(TaskListFragment.TOKEN_OVERRIDE_ANIM, true);
filter.customExtras = extras;
return filter;
}
|
diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java
index 6df3d53e5..c7e7e1991 100644
--- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java
+++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java
@@ -1,162 +1,165 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* 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.springframework.jdbc.datasource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.springframework.util.Assert;
/**
* Abstract base class for JDBC {@link javax.sql.DataSource} implementations
* that operate on a JDBC {@link java.sql.Driver}.
*
* @author Juergen Hoeller
* @since 2.5.5
* @see SimpleDriverDataSource
* @see DriverManagerDataSource
*/
public abstract class AbstractDriverBasedDataSource extends AbstractDataSource {
private String url;
private String username;
private String password;
private Properties connectionProperties;
/**
* Set the JDBC URL to use for connecting through the Driver.
* @see java.sql.Driver#connect(String, java.util.Properties)
*/
public void setUrl(String url) {
Assert.hasText(url, "Property 'url' must not be empty");
this.url = url.trim();
}
/**
* Return the JDBC URL to use for connecting through the Driver.
*/
public String getUrl() {
return this.url;
}
/**
* Set the JDBC username to use for connecting through the Driver.
* @see java.sql.Driver#connect(String, java.util.Properties)
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Return the JDBC username to use for connecting through the Driver.
*/
public String getUsername() {
return this.username;
}
/**
* Set the JDBC password to use for connecting through the Driver.
* @see java.sql.Driver#connect(String, java.util.Properties)
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Return the JDBC password to use for connecting through the Driver.
*/
public String getPassword() {
return this.password;
}
/**
* Specify arbitrary connection properties as key/value pairs,
* to be passed to the Driver.
* <p>Can also contain "user" and "password" properties. However,
* any "username" and "password" bean properties specified on this
* DataSource will override the corresponding connection properties.
* @see java.sql.Driver#connect(String, java.util.Properties)
*/
public void setConnectionProperties(Properties connectionProperties) {
this.connectionProperties = connectionProperties;
}
/**
* Return the connection properties to be passed to the Driver, if any.
*/
public Properties getConnectionProperties() {
return this.connectionProperties;
}
/**
* This implementation delegates to {@code getConnectionFromDriver},
* using the default username and password of this DataSource.
* @see #getConnectionFromDriver(String, String)
* @see #setUsername
* @see #setPassword
*/
public Connection getConnection() throws SQLException {
return getConnectionFromDriver(getUsername(), getPassword());
}
/**
* This implementation delegates to {@code getConnectionFromDriver},
* using the given username and password.
* @see #getConnectionFromDriver(String, String)
*/
public Connection getConnection(String username, String password) throws SQLException {
return getConnectionFromDriver(username, password);
}
/**
* Build properties for the Driver, including the given username and password (if any),
* and obtain a corresponding Connection.
* @param username the name of the user
* @param password the password to use
* @return the obtained Connection
* @throws SQLException in case of failure
* @see java.sql.Driver#connect(String, java.util.Properties)
*/
protected Connection getConnectionFromDriver(String username, String password) throws SQLException {
- Properties props = new Properties();
- props.putAll(getConnectionProperties());
+ Properties mergedProps = new Properties();
+ Properties connProps = getConnectionProperties();
+ if (connProps != null) {
+ mergedProps.putAll(connProps);
+ }
if (username != null) {
- props.setProperty("user", username);
+ mergedProps.setProperty("user", username);
}
if (password != null) {
- props.setProperty("password", password);
+ mergedProps.setProperty("password", password);
}
- return getConnectionFromDriver(props);
+ return getConnectionFromDriver(mergedProps);
}
/**
* Obtain a Connection using the given properties.
* <p>Template method to be implemented by subclasses.
* @param props the merged connection properties
* @return the obtained Connection
* @throws SQLException in case of failure
*/
protected abstract Connection getConnectionFromDriver(Properties props) throws SQLException;
}
| false | true |
protected Connection getConnectionFromDriver(String username, String password) throws SQLException {
Properties props = new Properties();
props.putAll(getConnectionProperties());
if (username != null) {
props.setProperty("user", username);
}
if (password != null) {
props.setProperty("password", password);
}
return getConnectionFromDriver(props);
}
|
protected Connection getConnectionFromDriver(String username, String password) throws SQLException {
Properties mergedProps = new Properties();
Properties connProps = getConnectionProperties();
if (connProps != null) {
mergedProps.putAll(connProps);
}
if (username != null) {
mergedProps.setProperty("user", username);
}
if (password != null) {
mergedProps.setProperty("password", password);
}
return getConnectionFromDriver(mergedProps);
}
|
diff --git a/core/src/main/java/com/google/feathercoin/core/DumpedPrivateKey.java b/core/src/main/java/com/google/feathercoin/core/DumpedPrivateKey.java
index 51c610d..3e2c26f 100644
--- a/core/src/main/java/com/google/feathercoin/core/DumpedPrivateKey.java
+++ b/core/src/main/java/com/google/feathercoin/core/DumpedPrivateKey.java
@@ -1,105 +1,105 @@
/**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.feathercoin.core;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import java.math.BigInteger;
import java.util.Arrays;
/**
* Parses and generates private keys in the form used by the Feathercoin "dumpprivkey" command. This is the private key
* bytes with a header byte and 4 checksum bytes at the end. If there are 33 private key bytes instead of 32, then
* the last byte is a discriminator value for the compressed pubkey.
*/
public class DumpedPrivateKey extends VersionedChecksummedBytes {
private boolean compressed;
// Used by ECKey.getPrivateKeyEncoded()
DumpedPrivateKey(NetworkParameters params, byte[] keyBytes, boolean compressed) {
//super(params.dumpedPrivateKeyHeader, encode(keyBytes, compressed));
// feathercoin-wallet Issue 3
// Fix courtesy of d4n13
super(params.dumpedPrivateKeyHeader + params.addressHeader, encode(keyBytes, compressed));
this.compressed = compressed;
}
private static byte[] encode(byte[] keyBytes, boolean compressed) {
Preconditions.checkArgument(keyBytes.length == 32, "Private keys must be 32 bytes");
if (!compressed) {
return keyBytes;
} else {
// Keys that have compressed public components have an extra 1 byte on the end in dumped form.
byte[] bytes = new byte[33];
System.arraycopy(keyBytes, 0, bytes, 0, 32);
bytes[32] = 1;
return bytes;
}
}
/**
* Parses the given private key as created by the "dumpprivkey" Feathercoin C++ RPC.
*
* @param params The expected network parameters of the key. If you don't care, provide null.
* @param encoded The base58 encoded string.
* @throws AddressFormatException If the string is invalid or the header byte doesn't match the network params.
*/
public DumpedPrivateKey(NetworkParameters params, String encoded) throws AddressFormatException {
super(encoded);
- if (params != null && version != params.dumpedPrivateKeyHeader)
+ if (params != null && version != params.dumpedPrivateKeyHeader + params.addressHeader)
throw new AddressFormatException("Mismatched version number, trying to cross networks? " + version +
- " vs " + params.dumpedPrivateKeyHeader);
+ " vs " + params.dumpedPrivateKeyHeader + params.addressHeader);
if (bytes.length == 33) {
compressed = true;
bytes = Arrays.copyOf(bytes, 32); // Chop off the additional marker byte.
} else if (bytes.length == 32) {
compressed = false;
} else {
throw new AddressFormatException("Wrong number of bytes for a private key, not 32 or 33");
}
}
/**
* Returns an ECKey created from this encoded private key.
*/
public ECKey getKey() {
return new ECKey(new BigInteger(1, bytes), null, compressed);
}
@Override
public boolean equals(Object other) {
// This odd construction is to avoid anti-symmetry of equality: where a.equals(b) != b.equals(a).
boolean result = false;
if (other instanceof VersionedChecksummedBytes) {
result = Arrays.equals(bytes, ((VersionedChecksummedBytes)other).bytes);
}
if (other instanceof DumpedPrivateKey) {
DumpedPrivateKey o = (DumpedPrivateKey) other;
result = Arrays.equals(bytes, o.bytes) &&
version == o.version &&
compressed == o.compressed;
}
return result;
}
@Override
public int hashCode() {
return Objects.hashCode(bytes, version, compressed);
}
}
| false | true |
public DumpedPrivateKey(NetworkParameters params, String encoded) throws AddressFormatException {
super(encoded);
if (params != null && version != params.dumpedPrivateKeyHeader)
throw new AddressFormatException("Mismatched version number, trying to cross networks? " + version +
" vs " + params.dumpedPrivateKeyHeader);
if (bytes.length == 33) {
compressed = true;
bytes = Arrays.copyOf(bytes, 32); // Chop off the additional marker byte.
} else if (bytes.length == 32) {
compressed = false;
} else {
throw new AddressFormatException("Wrong number of bytes for a private key, not 32 or 33");
}
}
|
public DumpedPrivateKey(NetworkParameters params, String encoded) throws AddressFormatException {
super(encoded);
if (params != null && version != params.dumpedPrivateKeyHeader + params.addressHeader)
throw new AddressFormatException("Mismatched version number, trying to cross networks? " + version +
" vs " + params.dumpedPrivateKeyHeader + params.addressHeader);
if (bytes.length == 33) {
compressed = true;
bytes = Arrays.copyOf(bytes, 32); // Chop off the additional marker byte.
} else if (bytes.length == 32) {
compressed = false;
} else {
throw new AddressFormatException("Wrong number of bytes for a private key, not 32 or 33");
}
}
|
diff --git a/servers/sip-servlets/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/security/UACvsUASSecurityTest.java b/servers/sip-servlets/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/security/UACvsUASSecurityTest.java
index 339bd6fce..ce6cef0c0 100644
--- a/servers/sip-servlets/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/security/UACvsUASSecurityTest.java
+++ b/servers/sip-servlets/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/security/UACvsUASSecurityTest.java
@@ -1,153 +1,153 @@
/*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.servlet.sip.testsuite.security;
import java.util.EventObject;
import java.util.Hashtable;
import javax.sip.DialogTerminatedEvent;
import javax.sip.IOExceptionEvent;
import javax.sip.RequestEvent;
import javax.sip.ResponseEvent;
import javax.sip.SipListener;
import javax.sip.SipProvider;
import javax.sip.TimeoutEvent;
import javax.sip.TransactionTerminatedEvent;
import org.apache.catalina.realm.MemoryRealm;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cafesip.sipunit.SipStack;
import org.mobicents.servlet.sip.SipServletTestCase;
import org.mobicents.servlet.sip.core.session.SipStandardManager;
import org.mobicents.servlet.sip.startup.SipContextConfig;
import org.mobicents.servlet.sip.startup.SipStandardContext;
public class UACvsUASSecurityTest extends SipServletTestCase implements SipListener {
private static Log logger = LogFactory.getLog(UACvsUASSecurityTest.class);
protected Hashtable providerTable = new Hashtable();
private SipStack sipStackTracker;
//private SipPhone sipPhoneTracker;
private Tracker tracker;
public UACvsUASSecurityTest(String name) {
super(name);
}
@Override
public void setUp() throws Exception {
//init();
tracker = new Tracker();
super.setUp();
}
public void testSecurity() {
tracker.init();
try {
- for(int q=0; q<10; q++)
+ for(int q=0; q<15; q++)
{
if(tracker.receivedInvite) break;
Thread.sleep(1111);
}
if(!tracker.receivedInvite)
fail("Didnt receive notification that the security scenario is complete.");
} catch (InterruptedException e) {
fail("Security test failed: " + e);
e.printStackTrace();
}
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
@Override
public void deployApplication() {
SipStandardContext context = new SipStandardContext();
context.setDocBase(projectHome
+ "/sip-servlets-test-suite/applications/secure-servlet/src/main/sipapp");
context.setName("sip-test-context");
context.setPath("sip-test");
context.addLifecycleListener(new SipContextConfig());
context.setManager(new SipStandardManager());
MemoryRealm realm = new MemoryRealm();
realm.setPathname(projectHome
+ "/sip-servlets-test-suite/testsuite/src/test/resources/"
+ "org/mobicents/servlet/sip/testsuite/security/tomcat-users.xml");
context.setRealm(realm);
assertTrue(tomcat.deployContext(context));
}
@Override
protected String getDarConfigurationFile() {
return "file:///"
+ projectHome
+ "/sip-servlets-test-suite/testsuite/src/test/resources/"
+ "org/mobicents/servlet/sip/testsuite/security/secure-servlet-dar.properties";
}
public void init() {
}
private SipListener getSipListener(EventObject sipEvent) {
SipProvider source = (SipProvider) sipEvent.getSource();
SipListener listener = (SipListener) providerTable.get(source);
if (listener == null)
throw new RuntimeException("Unexpected null listener");
return listener;
}
public void processRequest(RequestEvent requestEvent) {
getSipListener(requestEvent).processRequest(requestEvent);
}
public void processResponse(ResponseEvent responseEvent) {
getSipListener(responseEvent).processResponse(responseEvent);
}
public void processTimeout(TimeoutEvent timeoutEvent) {
getSipListener(timeoutEvent).processTimeout(timeoutEvent);
}
public void processIOException(IOExceptionEvent exceptionEvent) {
fail("unexpected exception");
}
public void processTransactionTerminated(
TransactionTerminatedEvent transactionTerminatedEvent) {
getSipListener(transactionTerminatedEvent)
.processTransactionTerminated(transactionTerminatedEvent);
}
public void processDialogTerminated(
DialogTerminatedEvent dialogTerminatedEvent) {
getSipListener(dialogTerminatedEvent).processDialogTerminated(
dialogTerminatedEvent);
}
}
| true | true |
public void testSecurity() {
tracker.init();
try {
for(int q=0; q<10; q++)
{
if(tracker.receivedInvite) break;
Thread.sleep(1111);
}
if(!tracker.receivedInvite)
fail("Didnt receive notification that the security scenario is complete.");
} catch (InterruptedException e) {
fail("Security test failed: " + e);
e.printStackTrace();
}
}
|
public void testSecurity() {
tracker.init();
try {
for(int q=0; q<15; q++)
{
if(tracker.receivedInvite) break;
Thread.sleep(1111);
}
if(!tracker.receivedInvite)
fail("Didnt receive notification that the security scenario is complete.");
} catch (InterruptedException e) {
fail("Security test failed: " + e);
e.printStackTrace();
}
}
|
diff --git a/tests/de/unistuttgart/iste/se/adohive/controller/mysql/test/MySqlInit.java b/tests/de/unistuttgart/iste/se/adohive/controller/mysql/test/MySqlInit.java
index 630d3d2f..5e527b12 100644
--- a/tests/de/unistuttgart/iste/se/adohive/controller/mysql/test/MySqlInit.java
+++ b/tests/de/unistuttgart/iste/se/adohive/controller/mysql/test/MySqlInit.java
@@ -1,18 +1,18 @@
/**
*
*/
package de.unistuttgart.iste.se.adohive.controller.mysql.test;
import de.unistuttgart.iste.se.adohive.controller.AdoHiveController;
/**
* @author rashfael
*
*/
public class MySqlInit {
public static void init() {
AdoHiveController.setDriver("com.mysql.jdbc.Driver");
- AdoHiveController.setConnectionString("jdbc:mysql://localhost:3306/aidger-test?user=root");
+ AdoHiveController.setConnectionString("jdbc:mysql://localhost:3306/aidgertest?user=root");
}
}
| true | true |
public static void init() {
AdoHiveController.setDriver("com.mysql.jdbc.Driver");
AdoHiveController.setConnectionString("jdbc:mysql://localhost:3306/aidger-test?user=root");
}
|
public static void init() {
AdoHiveController.setDriver("com.mysql.jdbc.Driver");
AdoHiveController.setConnectionString("jdbc:mysql://localhost:3306/aidgertest?user=root");
}
|
diff --git a/src/java/drbd/utilities/MyButtonCellRenderer.java b/src/java/drbd/utilities/MyButtonCellRenderer.java
index 6fc7e826..d4762bc4 100644
--- a/src/java/drbd/utilities/MyButtonCellRenderer.java
+++ b/src/java/drbd/utilities/MyButtonCellRenderer.java
@@ -1,93 +1,96 @@
/*
* This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH
* by Rasto Levrinc.
*
* Copyright (C) 2009, Rastislav Levrinc
* Copyright (C) 2009, LINBIT HA-Solutions GmbH.
*
* DRBD Management Console 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.
*
* DRBD Management Console 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 drbd; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package drbd.utilities;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import java.awt.Component;
import javax.swing.SwingConstants;
import java.awt.Color;
/**
* Cells with jlabels, widths and colors.
*/
public class MyButtonCellRenderer extends MyButton
implements TableCellRenderer {
/** Serial version uid. */
private static final long serialVersionUID = 1L;
/** Sets background color and padding in jlabels for every cell. */
@Override public final Component getTableCellRendererComponent(
final JTable table,
final Object value,
final boolean isSelected,
final boolean hasFocus,
final int row,
final int column) {
+ if (!(value instanceof MyButton)) {
+ return this;
+ }
final MyButton button = (MyButton) value;
if (button == null) {
setText("");
getModel().setPressed(false);
getModel().setArmed(false);
getModel().setRollover(false);
} else {
if (button.getModel().isPressed()) {
setOpaque(true);
} else {
setOpaque(button.isOpaque());
}
setText(button.getText());
setIcon(button.getIcon());
setMargin(button.getInsets());
setFont(button.getFont());
setIconTextGap(button.getIconTextGap());
getModel().setPressed(button.getModel().isPressed());
getModel().setArmed(button.getModel().isArmed());
getModel().setRollover(button.getModel().isRollover());
}
final int al = getColumnAlignment(column);
setHorizontalAlignment(al);
final Object v = table.getValueAt(row, 0);
if (v != null) {
final String key = ((MyButton) v).getText();
final Color bg = getRowColor(key);
setBackgroundColor(bg);
//setToolTipText(button.getText());
}
//(((MyButton) this).createToolTip()).setTipText("asdf");
//(((MyButton) button).createToolTip()).setTipText("asdff");
return this;
}
/** Alignment for the specified column. */
protected int getColumnAlignment(final int column) {
return SwingConstants.LEFT;
}
/** Retrurns color for some rows. */
protected Color getRowColor(final String key) {
return null;
}
}
| true | true |
@Override public final Component getTableCellRendererComponent(
final JTable table,
final Object value,
final boolean isSelected,
final boolean hasFocus,
final int row,
final int column) {
final MyButton button = (MyButton) value;
if (button == null) {
setText("");
getModel().setPressed(false);
getModel().setArmed(false);
getModel().setRollover(false);
} else {
if (button.getModel().isPressed()) {
setOpaque(true);
} else {
setOpaque(button.isOpaque());
}
setText(button.getText());
setIcon(button.getIcon());
setMargin(button.getInsets());
setFont(button.getFont());
setIconTextGap(button.getIconTextGap());
getModel().setPressed(button.getModel().isPressed());
getModel().setArmed(button.getModel().isArmed());
getModel().setRollover(button.getModel().isRollover());
}
final int al = getColumnAlignment(column);
setHorizontalAlignment(al);
final Object v = table.getValueAt(row, 0);
if (v != null) {
final String key = ((MyButton) v).getText();
final Color bg = getRowColor(key);
setBackgroundColor(bg);
//setToolTipText(button.getText());
}
//(((MyButton) this).createToolTip()).setTipText("asdf");
//(((MyButton) button).createToolTip()).setTipText("asdff");
return this;
}
|
@Override public final Component getTableCellRendererComponent(
final JTable table,
final Object value,
final boolean isSelected,
final boolean hasFocus,
final int row,
final int column) {
if (!(value instanceof MyButton)) {
return this;
}
final MyButton button = (MyButton) value;
if (button == null) {
setText("");
getModel().setPressed(false);
getModel().setArmed(false);
getModel().setRollover(false);
} else {
if (button.getModel().isPressed()) {
setOpaque(true);
} else {
setOpaque(button.isOpaque());
}
setText(button.getText());
setIcon(button.getIcon());
setMargin(button.getInsets());
setFont(button.getFont());
setIconTextGap(button.getIconTextGap());
getModel().setPressed(button.getModel().isPressed());
getModel().setArmed(button.getModel().isArmed());
getModel().setRollover(button.getModel().isRollover());
}
final int al = getColumnAlignment(column);
setHorizontalAlignment(al);
final Object v = table.getValueAt(row, 0);
if (v != null) {
final String key = ((MyButton) v).getText();
final Color bg = getRowColor(key);
setBackgroundColor(bg);
//setToolTipText(button.getText());
}
//(((MyButton) this).createToolTip()).setTipText("asdf");
//(((MyButton) button).createToolTip()).setTipText("asdff");
return this;
}
|
diff --git a/api/restfulReminiscens/app/controllers/Application.java b/api/restfulReminiscens/app/controllers/Application.java
index 10cad0f..338aebd 100644
--- a/api/restfulReminiscens/app/controllers/Application.java
+++ b/api/restfulReminiscens/app/controllers/Application.java
@@ -1,201 +1,201 @@
package controllers;
import static play.libs.Json.toJson;
import java.io.File;
import java.util.List;
import models.User;
import play.api.Play;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Http.Session;
import play.mvc.Result;
import pojos.CityBean;
import pojos.FileBean;
import pojos.ResponseStatusBean;
import providers.MyUsernamePasswordAuthProvider;
import providers.MyUsernamePasswordAuthProvider.MyLogin;
import providers.MyUsernamePasswordAuthProvider.MySignup;
import scala.Option;
import utils.FileUtilities;
import views.html.index;
import views.html.upload;
import akka.event.slf4j.Logger;
import com.feth.play.module.pa.PlayAuthenticate;
import delegates.ApplicationDelegate;
import enums.ResponseStatus;
import enums.Roles;
public class Application extends Controller {
public static final String FLASH_MESSAGE_KEY = "message";
public static final String FLASH_ERROR_KEY = "error";
public static Form<FileBean> fileForm;
public static Result index() {
return ok(index.render());
}
public static Result oAuthDenied(final String providerKey) {
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
flash(FLASH_ERROR_KEY,
"You need to accept the OAuth connection in order to use this website!");
return redirect(routes.Application.index());
}
public static User getLocalUser(final Session session) {
final User localUser = User.findByAuthUserIdentity(PlayAuthenticate
.getUser(session));
return localUser;
}
public static Result doSignup() {
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
final Form<MySignup> filledForm = MyUsernamePasswordAuthProvider.SIGNUP_FORM
.bindFromRequest();
if (filledForm.hasErrors()) {
// User did not fill everything properly try to put the errors in
// the response
// return badRequest(signup.render(filledForm));
ResponseStatusBean response = new ResponseStatusBean();
response.setResponseStatus(ResponseStatus.BADREQUEST);
response.setStatusMessage("play.authenticate.filledFromHasErrors:"
+ filledForm.errorsAsJson());
return badRequest(toJson(response));
} else {
// Everything was filled
// do something with your part of the form before handling the user
// signup
return MyUsernamePasswordAuthProvider.handleSignup(ctx());
}
}
public static Result doLogin() {
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
final Form<MyLogin> filledForm = MyUsernamePasswordAuthProvider.LOGIN_FORM
.bindFromRequest();
if (filledForm.hasErrors()) {
// User did not fill everything properly
// return badRequest(login.render(filledForm));
return badRequest();
} else {
// Everything was filled
return MyUsernamePasswordAuthProvider.handleLogin(ctx());
}
}
public static Result onLoginUserNotFound() {
ResponseStatusBean response = new ResponseStatusBean();
response.setResponseStatus(ResponseStatus.NODATA);
response.setStatusMessage("playauthenticate.password.login.unknown_user_or_pw");
return notFound(toJson(response));
// return notFound(Messages
// .get("playauthenticate.password.login.unknown_user_or_pw"));
}
// Util calls
public static Result getCities() {
List<CityBean> bean = ApplicationDelegate.getInstance().getCities();
return bean != null ? ok(toJson(bean)) : notFound();
}
public static Result getCitiesByCountryId(Long countryId) {
List<CityBean> bean = ApplicationDelegate.getInstance()
.getCitiesByCountryId(countryId);
return bean != null ? ok(toJson(bean)) : notFound();
}
public static Result getCitiesByCountryName(String countryName) {
List<CityBean> bean = ApplicationDelegate.getInstance()
.getCitiesByCountryName(countryName);
return bean != null ? ok(toJson(bean)) : notFound();
}
public static Result getNewCities(Long lastCityId) {
List<CityBean> bean = ApplicationDelegate.getInstance().getNewCities(
lastCityId);
return bean != null ? ok(toJson(bean)) : notFound();
}
public static Result getCityByName(String cityName) {
List<CityBean> bean = ApplicationDelegate.getInstance().getCityByName(
cityName);
return bean != null ? ok(toJson(bean)) : notFound();
}
public static Result testUpload() {
return ok(views.html.upload.render());
}
public static Result upload() {
play.mvc.Http.MultipartFormData body = request().body()
.asMultipartFormData();
play.mvc.Http.MultipartFormData.FilePart file = body.getFile("files[]");
//final Form<FileBean> filledForm = fileForm.bindFromRequest();
if (file != null) {
// 1. Get file metadata
//
// Option<String> dir = Play.current().configuration()
// .getString("files.home", null);
// Option<String> filesBaseURL = Play.current().configuration()
// .getString("files.baseurl", null);
String fileName = file.getFilename();
String fullPath = "/opt/reminiscens/files"+ FileUtilities.slash + fileName;
String contentType = file.getContentType();
File uploadFile = file.getFile();
String filesBaseURL = "http://test.reminiscens.me/files";
-// File localFile = new File(fullPath);
-// uploadFile.renameTo(localFile);
+ File localFile = new File(fullPath);
+ uploadFile.renameTo(localFile);
//
Logger.root().debug("Uploading File....");
Logger.root().debug("--> fileName=" + fileName);
Logger.root().debug("--> contentType=" + contentType);
Logger.root().debug("--> uploadFile=" + uploadFile);
// TODO 2. Prepare to save the file
// File localFile = new File(fullPath);
// localFile.createNewFile();
// uploadFile.renameTo(localFile);
//
//
// FileUtilities.saveFile(localFile);
// TODO 3. Generate Hashcode to use as new name
// BCrypt.hashpw(fileName, arg1)
// TODO 4. Save File in server
-// Logger.root().debug("Saving File....");
-// Logger.root().debug("--> fileName=" + fileName);
-// Logger.root().debug("--> contentType=" + contentType);
-// Logger.root().debug("--> localFile=" + localFile);
+ Logger.root().debug("Saving File....");
+ Logger.root().debug("--> fileName=" + fileName);
+ Logger.root().debug("--> contentType=" + contentType);
+ Logger.root().debug("--> localFile=" + localFile);
// TODO 5. Save File metadata in Database
// 6. Prepare response
FileBean fileBean = new FileBean();
fileBean.setFilename(fileName);
fileBean.setURI(filesBaseURL + "/" + fileName);
fileBean.setContentType(contentType);
fileBean.setFilename(fileName);
return ok(toJson(fileBean));
} else {
flash("error", "Missing file");
ResponseStatusBean response = new ResponseStatusBean();
response.setResponseStatus(ResponseStatus.BADREQUEST);
response.setStatusMessage("File is null");
return badRequest(toJson(response));
}
}
}
| false | true |
public static Result upload() {
play.mvc.Http.MultipartFormData body = request().body()
.asMultipartFormData();
play.mvc.Http.MultipartFormData.FilePart file = body.getFile("files[]");
//final Form<FileBean> filledForm = fileForm.bindFromRequest();
if (file != null) {
// 1. Get file metadata
//
// Option<String> dir = Play.current().configuration()
// .getString("files.home", null);
// Option<String> filesBaseURL = Play.current().configuration()
// .getString("files.baseurl", null);
String fileName = file.getFilename();
String fullPath = "/opt/reminiscens/files"+ FileUtilities.slash + fileName;
String contentType = file.getContentType();
File uploadFile = file.getFile();
String filesBaseURL = "http://test.reminiscens.me/files";
// File localFile = new File(fullPath);
// uploadFile.renameTo(localFile);
//
Logger.root().debug("Uploading File....");
Logger.root().debug("--> fileName=" + fileName);
Logger.root().debug("--> contentType=" + contentType);
Logger.root().debug("--> uploadFile=" + uploadFile);
// TODO 2. Prepare to save the file
// File localFile = new File(fullPath);
// localFile.createNewFile();
// uploadFile.renameTo(localFile);
//
//
// FileUtilities.saveFile(localFile);
// TODO 3. Generate Hashcode to use as new name
// BCrypt.hashpw(fileName, arg1)
// TODO 4. Save File in server
// Logger.root().debug("Saving File....");
// Logger.root().debug("--> fileName=" + fileName);
// Logger.root().debug("--> contentType=" + contentType);
// Logger.root().debug("--> localFile=" + localFile);
// TODO 5. Save File metadata in Database
// 6. Prepare response
FileBean fileBean = new FileBean();
fileBean.setFilename(fileName);
fileBean.setURI(filesBaseURL + "/" + fileName);
fileBean.setContentType(contentType);
fileBean.setFilename(fileName);
return ok(toJson(fileBean));
} else {
flash("error", "Missing file");
ResponseStatusBean response = new ResponseStatusBean();
response.setResponseStatus(ResponseStatus.BADREQUEST);
response.setStatusMessage("File is null");
return badRequest(toJson(response));
}
}
|
public static Result upload() {
play.mvc.Http.MultipartFormData body = request().body()
.asMultipartFormData();
play.mvc.Http.MultipartFormData.FilePart file = body.getFile("files[]");
//final Form<FileBean> filledForm = fileForm.bindFromRequest();
if (file != null) {
// 1. Get file metadata
//
// Option<String> dir = Play.current().configuration()
// .getString("files.home", null);
// Option<String> filesBaseURL = Play.current().configuration()
// .getString("files.baseurl", null);
String fileName = file.getFilename();
String fullPath = "/opt/reminiscens/files"+ FileUtilities.slash + fileName;
String contentType = file.getContentType();
File uploadFile = file.getFile();
String filesBaseURL = "http://test.reminiscens.me/files";
File localFile = new File(fullPath);
uploadFile.renameTo(localFile);
//
Logger.root().debug("Uploading File....");
Logger.root().debug("--> fileName=" + fileName);
Logger.root().debug("--> contentType=" + contentType);
Logger.root().debug("--> uploadFile=" + uploadFile);
// TODO 2. Prepare to save the file
// File localFile = new File(fullPath);
// localFile.createNewFile();
// uploadFile.renameTo(localFile);
//
//
// FileUtilities.saveFile(localFile);
// TODO 3. Generate Hashcode to use as new name
// BCrypt.hashpw(fileName, arg1)
// TODO 4. Save File in server
Logger.root().debug("Saving File....");
Logger.root().debug("--> fileName=" + fileName);
Logger.root().debug("--> contentType=" + contentType);
Logger.root().debug("--> localFile=" + localFile);
// TODO 5. Save File metadata in Database
// 6. Prepare response
FileBean fileBean = new FileBean();
fileBean.setFilename(fileName);
fileBean.setURI(filesBaseURL + "/" + fileName);
fileBean.setContentType(contentType);
fileBean.setFilename(fileName);
return ok(toJson(fileBean));
} else {
flash("error", "Missing file");
ResponseStatusBean response = new ResponseStatusBean();
response.setResponseStatus(ResponseStatus.BADREQUEST);
response.setStatusMessage("File is null");
return badRequest(toJson(response));
}
}
|
diff --git a/core/src/qa/qcri/nadeef/core/datamodel/CleanPlan.java b/core/src/qa/qcri/nadeef/core/datamodel/CleanPlan.java
index 9a49ca5..4e61267 100644
--- a/core/src/qa/qcri/nadeef/core/datamodel/CleanPlan.java
+++ b/core/src/qa/qcri/nadeef/core/datamodel/CleanPlan.java
@@ -1,284 +1,284 @@
/*
* Copyright (C) Qatar Computing Research Institute, 2013.
* All rights reserved.
*/
package qa.qcri.nadeef.core.datamodel;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import qa.qcri.nadeef.core.exception.InvalidCleanPlanException;
import qa.qcri.nadeef.core.exception.InvalidRuleException;
import qa.qcri.nadeef.core.util.DBConnectionFactory;
import qa.qcri.nadeef.core.util.DBMetaDataTool;
import qa.qcri.nadeef.core.util.RuleBuilder;
import qa.qcri.nadeef.tools.*;
import java.io.File;
import java.io.Reader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
/**
* Nadeef cleaning plan.
*/
public class CleanPlan {
private DBConfig source;
private Rule rule;
private static Tracer tracer = Tracer.getTracer(CleanPlan.class);
// <editor-fold desc="Constructor">
/**
* Constructor.
*/
public CleanPlan(DBConfig sourceConfig, Rule rule) {
this.source = sourceConfig;
this.rule = rule;
}
// </editor-fold>
/**
* Creates a <code>CleanPlan</code> from JSON string.
*
* @param reader JSON string reader.
* @return <code>CleanPlan</code> object.
*/
@SuppressWarnings("unchecked")
public static List<CleanPlan> createCleanPlanFromJSON(Reader reader)
throws InvalidRuleException, InvalidCleanPlanException {
Preconditions.checkNotNull(reader);
JSONObject jsonObject = (JSONObject) JSONValue.parse(reader);
// a set which prevents generating new tables whenever encounters among
// multiple rules.
List<CleanPlan> result = Lists.newArrayList();
boolean isCSV = false;
List<Schema> schemas = Lists.newArrayList();
Connection conn = null;
try {
// ----------------------------------------
// parsing the source config
// ----------------------------------------
JSONObject src = (JSONObject) jsonObject.get("source");
String type = (String) src.get("type");
DBConfig dbConfig;
switch (type) {
case "csv":
isCSV = true;
dbConfig = NadeefConfiguration.getDbConfig();
break;
default:
// TODO: support different type of DB.
SQLDialect sqlDialect = SQLDialect.POSTGRES;
DBConfig.Builder builder = new DBConfig.Builder();
dbConfig =
builder.username((String) src.get("username"))
.password((String) src.get("password"))
.url((String) src.get("url")).dialect(sqlDialect)
.build();
}
// Initialize the connection pool
DBConnectionFactory.initializeSource(dbConfig);
// ----------------------------------------
// parsing the rules
// ----------------------------------------
// TODO: use token.matches("^\\s*(\\w+\\.?){0,3}\\w\\s*$") to match
// the table pattern.
JSONArray ruleArray = (JSONArray) jsonObject.get("rule");
ArrayList<Rule> rules = Lists.newArrayList();
List<String> targetTableNames;
List<String> fileNames = Lists.newArrayList();
HashSet<String> copiedTables = Sets.newHashSet();
for (int i = 0; i < ruleArray.size(); i++) {
schemas.clear();
fileNames.clear();
JSONObject ruleObj = (JSONObject) ruleArray.get(i);
if (isCSV) {
// working with CSV
List<String> fullFileNames = (List<String>) src.get("file");
for (String fullFileName : fullFileNames) {
fileNames.add(Files.getNameWithoutExtension(fullFileName));
}
if (ruleObj.containsKey("table")) {
targetTableNames = (List<String>) ruleObj.get("table");
Preconditions.checkArgument(
targetTableNames.size() <= 2,
"NADEEF only supports MAX 2 tables per rule."
);
for (String targetTableName : targetTableNames) {
if (!fileNames.contains(targetTableName)) {
throw new InvalidCleanPlanException("Unknown table name.");
}
}
} else {
// if the target table names does not exist, we use
// default naming and only the first two tables are touched.
targetTableNames = Lists.newArrayList();
for (String fileName : fileNames) {
targetTableNames.add(fileName);
if (targetTableNames.size() == 2) {
break;
}
}
}
// source is a CSV file, dump it to NADEEF database.
conn = DBConnectionFactory.getNadeefConnection();
// This hashset is to prevent that tables are dumped for multiple times.
for (int j = 0; j < targetTableNames.size(); j++) {
File file = CommonTools.getFile(fullFileNames.get(j));
// target table name already exists in the hashset.
if (!copiedTables.contains(targetTableNames.get(j))) {
String tableName = CSVDumper.dump(conn, file, targetTableNames.get(j));
+ copiedTables.add(targetTableNames.get(j));
targetTableNames.set(j, tableName);
schemas.add(DBMetaDataTool.getSchema(tableName));
- copiedTables.add(targetTableNames.get(j));
}
}
} else {
// working with database
List<String> sourceTableNames = (List<String>) ruleObj.get("table");
for (String tableName : sourceTableNames) {
if (!DBMetaDataTool.isTableExist(tableName)) {
throw new InvalidCleanPlanException(
"The specified table " +
tableName +
" cannot be found in the source database.");
}
}
if (ruleObj.containsKey("target")) {
targetTableNames = (List<String>) ruleObj.get("target");
} else {
// when user doesn't provide target tables we create a
// copy for them
// with default table names.
targetTableNames = Lists.newArrayList();
for (String sourceTableName : sourceTableNames) {
targetTableNames.add(sourceTableName + "_copy");
}
}
Preconditions.checkArgument(
sourceTableNames.size() == targetTableNames.size() &&
sourceTableNames.size() <= 2 &&
sourceTableNames.size() >= 1,
"Invalid Rule property, rule needs to have one or two tables.");
for (int j = 0; j < sourceTableNames.size(); j++) {
if (!copiedTables.contains(targetTableNames.get(j))) {
DBMetaDataTool.copy(
sourceTableNames.get(j),
targetTableNames.get(j)
);
schemas.add(
DBMetaDataTool.getSchema(
targetTableNames.get(j)
)
);
copiedTables.add(targetTableNames.get(j));
}
}
}
type = (String) ruleObj.get("type");
Rule rule;
JSONArray value;
value = (JSONArray) ruleObj.get("value");
String ruleName = (String) ruleObj.get("name");
if (Strings.isNullOrEmpty(ruleName)) {
// generate default rule name when it is not provided by the user, and
// distinguished by the value of the rule.
ruleName = "Rule" + CommonTools.toHashCode((String)value.get(0));
}
switch (type) {
case "udf":
value = (JSONArray) ruleObj.get("value");
Class udfClass =
CommonTools.loadClass((String) value.get(0));
if (!Rule.class.isAssignableFrom(udfClass)) {
throw new InvalidRuleException(
"The specified class is not a Rule class."
);
}
rule = (Rule) udfClass.newInstance();
// call internal initialization on the rule.
rule.initialize(ruleName, targetTableNames);
rules.add(rule);
break;
default:
RuleBuilder ruleBuilder = NadeefConfiguration.tryGetRuleBuilder(type);
if (ruleBuilder != null) {
rules.addAll(
ruleBuilder.name(ruleName)
.schema(schemas)
.table(targetTableNames)
.value(value)
.build()
);
} else {
tracer.err("Unknown Rule type: " + type, null);
}
break;
}
}
for (int i = 0; i < rules.size(); i++) {
result.add(new CleanPlan(dbConfig, rules.get(i)));
}
return result;
} catch (Exception ex) {
ex.printStackTrace();
if (ex instanceof InvalidRuleException) {
throw (InvalidRuleException) ex;
}
throw new InvalidCleanPlanException(ex);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
}
}
}
}
// <editor-fold desc="Property Getters">
/**
* Gets the <code>DBConfig</code> for the clean source.
*
* @return <code>DBConfig</code>.
*/
public DBConfig getSourceDBConfig() {
return source;
}
/**
* Gets the rule.
*
* @return rule.
*/
public Rule getRule() {
return rule;
}
// </editor-fold>
}
| false | true |
public static List<CleanPlan> createCleanPlanFromJSON(Reader reader)
throws InvalidRuleException, InvalidCleanPlanException {
Preconditions.checkNotNull(reader);
JSONObject jsonObject = (JSONObject) JSONValue.parse(reader);
// a set which prevents generating new tables whenever encounters among
// multiple rules.
List<CleanPlan> result = Lists.newArrayList();
boolean isCSV = false;
List<Schema> schemas = Lists.newArrayList();
Connection conn = null;
try {
// ----------------------------------------
// parsing the source config
// ----------------------------------------
JSONObject src = (JSONObject) jsonObject.get("source");
String type = (String) src.get("type");
DBConfig dbConfig;
switch (type) {
case "csv":
isCSV = true;
dbConfig = NadeefConfiguration.getDbConfig();
break;
default:
// TODO: support different type of DB.
SQLDialect sqlDialect = SQLDialect.POSTGRES;
DBConfig.Builder builder = new DBConfig.Builder();
dbConfig =
builder.username((String) src.get("username"))
.password((String) src.get("password"))
.url((String) src.get("url")).dialect(sqlDialect)
.build();
}
// Initialize the connection pool
DBConnectionFactory.initializeSource(dbConfig);
// ----------------------------------------
// parsing the rules
// ----------------------------------------
// TODO: use token.matches("^\\s*(\\w+\\.?){0,3}\\w\\s*$") to match
// the table pattern.
JSONArray ruleArray = (JSONArray) jsonObject.get("rule");
ArrayList<Rule> rules = Lists.newArrayList();
List<String> targetTableNames;
List<String> fileNames = Lists.newArrayList();
HashSet<String> copiedTables = Sets.newHashSet();
for (int i = 0; i < ruleArray.size(); i++) {
schemas.clear();
fileNames.clear();
JSONObject ruleObj = (JSONObject) ruleArray.get(i);
if (isCSV) {
// working with CSV
List<String> fullFileNames = (List<String>) src.get("file");
for (String fullFileName : fullFileNames) {
fileNames.add(Files.getNameWithoutExtension(fullFileName));
}
if (ruleObj.containsKey("table")) {
targetTableNames = (List<String>) ruleObj.get("table");
Preconditions.checkArgument(
targetTableNames.size() <= 2,
"NADEEF only supports MAX 2 tables per rule."
);
for (String targetTableName : targetTableNames) {
if (!fileNames.contains(targetTableName)) {
throw new InvalidCleanPlanException("Unknown table name.");
}
}
} else {
// if the target table names does not exist, we use
// default naming and only the first two tables are touched.
targetTableNames = Lists.newArrayList();
for (String fileName : fileNames) {
targetTableNames.add(fileName);
if (targetTableNames.size() == 2) {
break;
}
}
}
// source is a CSV file, dump it to NADEEF database.
conn = DBConnectionFactory.getNadeefConnection();
// This hashset is to prevent that tables are dumped for multiple times.
for (int j = 0; j < targetTableNames.size(); j++) {
File file = CommonTools.getFile(fullFileNames.get(j));
// target table name already exists in the hashset.
if (!copiedTables.contains(targetTableNames.get(j))) {
String tableName = CSVDumper.dump(conn, file, targetTableNames.get(j));
targetTableNames.set(j, tableName);
schemas.add(DBMetaDataTool.getSchema(tableName));
copiedTables.add(targetTableNames.get(j));
}
}
} else {
// working with database
List<String> sourceTableNames = (List<String>) ruleObj.get("table");
for (String tableName : sourceTableNames) {
if (!DBMetaDataTool.isTableExist(tableName)) {
throw new InvalidCleanPlanException(
"The specified table " +
tableName +
" cannot be found in the source database.");
}
}
if (ruleObj.containsKey("target")) {
targetTableNames = (List<String>) ruleObj.get("target");
} else {
// when user doesn't provide target tables we create a
// copy for them
// with default table names.
targetTableNames = Lists.newArrayList();
for (String sourceTableName : sourceTableNames) {
targetTableNames.add(sourceTableName + "_copy");
}
}
Preconditions.checkArgument(
sourceTableNames.size() == targetTableNames.size() &&
sourceTableNames.size() <= 2 &&
sourceTableNames.size() >= 1,
"Invalid Rule property, rule needs to have one or two tables.");
for (int j = 0; j < sourceTableNames.size(); j++) {
if (!copiedTables.contains(targetTableNames.get(j))) {
DBMetaDataTool.copy(
sourceTableNames.get(j),
targetTableNames.get(j)
);
schemas.add(
DBMetaDataTool.getSchema(
targetTableNames.get(j)
)
);
copiedTables.add(targetTableNames.get(j));
}
}
}
type = (String) ruleObj.get("type");
Rule rule;
JSONArray value;
value = (JSONArray) ruleObj.get("value");
String ruleName = (String) ruleObj.get("name");
if (Strings.isNullOrEmpty(ruleName)) {
// generate default rule name when it is not provided by the user, and
// distinguished by the value of the rule.
ruleName = "Rule" + CommonTools.toHashCode((String)value.get(0));
}
switch (type) {
case "udf":
value = (JSONArray) ruleObj.get("value");
Class udfClass =
CommonTools.loadClass((String) value.get(0));
if (!Rule.class.isAssignableFrom(udfClass)) {
throw new InvalidRuleException(
"The specified class is not a Rule class."
);
}
rule = (Rule) udfClass.newInstance();
// call internal initialization on the rule.
rule.initialize(ruleName, targetTableNames);
rules.add(rule);
break;
default:
RuleBuilder ruleBuilder = NadeefConfiguration.tryGetRuleBuilder(type);
if (ruleBuilder != null) {
rules.addAll(
ruleBuilder.name(ruleName)
.schema(schemas)
.table(targetTableNames)
.value(value)
.build()
);
} else {
tracer.err("Unknown Rule type: " + type, null);
}
break;
}
}
for (int i = 0; i < rules.size(); i++) {
result.add(new CleanPlan(dbConfig, rules.get(i)));
}
return result;
} catch (Exception ex) {
ex.printStackTrace();
if (ex instanceof InvalidRuleException) {
throw (InvalidRuleException) ex;
}
throw new InvalidCleanPlanException(ex);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
}
}
}
}
|
public static List<CleanPlan> createCleanPlanFromJSON(Reader reader)
throws InvalidRuleException, InvalidCleanPlanException {
Preconditions.checkNotNull(reader);
JSONObject jsonObject = (JSONObject) JSONValue.parse(reader);
// a set which prevents generating new tables whenever encounters among
// multiple rules.
List<CleanPlan> result = Lists.newArrayList();
boolean isCSV = false;
List<Schema> schemas = Lists.newArrayList();
Connection conn = null;
try {
// ----------------------------------------
// parsing the source config
// ----------------------------------------
JSONObject src = (JSONObject) jsonObject.get("source");
String type = (String) src.get("type");
DBConfig dbConfig;
switch (type) {
case "csv":
isCSV = true;
dbConfig = NadeefConfiguration.getDbConfig();
break;
default:
// TODO: support different type of DB.
SQLDialect sqlDialect = SQLDialect.POSTGRES;
DBConfig.Builder builder = new DBConfig.Builder();
dbConfig =
builder.username((String) src.get("username"))
.password((String) src.get("password"))
.url((String) src.get("url")).dialect(sqlDialect)
.build();
}
// Initialize the connection pool
DBConnectionFactory.initializeSource(dbConfig);
// ----------------------------------------
// parsing the rules
// ----------------------------------------
// TODO: use token.matches("^\\s*(\\w+\\.?){0,3}\\w\\s*$") to match
// the table pattern.
JSONArray ruleArray = (JSONArray) jsonObject.get("rule");
ArrayList<Rule> rules = Lists.newArrayList();
List<String> targetTableNames;
List<String> fileNames = Lists.newArrayList();
HashSet<String> copiedTables = Sets.newHashSet();
for (int i = 0; i < ruleArray.size(); i++) {
schemas.clear();
fileNames.clear();
JSONObject ruleObj = (JSONObject) ruleArray.get(i);
if (isCSV) {
// working with CSV
List<String> fullFileNames = (List<String>) src.get("file");
for (String fullFileName : fullFileNames) {
fileNames.add(Files.getNameWithoutExtension(fullFileName));
}
if (ruleObj.containsKey("table")) {
targetTableNames = (List<String>) ruleObj.get("table");
Preconditions.checkArgument(
targetTableNames.size() <= 2,
"NADEEF only supports MAX 2 tables per rule."
);
for (String targetTableName : targetTableNames) {
if (!fileNames.contains(targetTableName)) {
throw new InvalidCleanPlanException("Unknown table name.");
}
}
} else {
// if the target table names does not exist, we use
// default naming and only the first two tables are touched.
targetTableNames = Lists.newArrayList();
for (String fileName : fileNames) {
targetTableNames.add(fileName);
if (targetTableNames.size() == 2) {
break;
}
}
}
// source is a CSV file, dump it to NADEEF database.
conn = DBConnectionFactory.getNadeefConnection();
// This hashset is to prevent that tables are dumped for multiple times.
for (int j = 0; j < targetTableNames.size(); j++) {
File file = CommonTools.getFile(fullFileNames.get(j));
// target table name already exists in the hashset.
if (!copiedTables.contains(targetTableNames.get(j))) {
String tableName = CSVDumper.dump(conn, file, targetTableNames.get(j));
copiedTables.add(targetTableNames.get(j));
targetTableNames.set(j, tableName);
schemas.add(DBMetaDataTool.getSchema(tableName));
}
}
} else {
// working with database
List<String> sourceTableNames = (List<String>) ruleObj.get("table");
for (String tableName : sourceTableNames) {
if (!DBMetaDataTool.isTableExist(tableName)) {
throw new InvalidCleanPlanException(
"The specified table " +
tableName +
" cannot be found in the source database.");
}
}
if (ruleObj.containsKey("target")) {
targetTableNames = (List<String>) ruleObj.get("target");
} else {
// when user doesn't provide target tables we create a
// copy for them
// with default table names.
targetTableNames = Lists.newArrayList();
for (String sourceTableName : sourceTableNames) {
targetTableNames.add(sourceTableName + "_copy");
}
}
Preconditions.checkArgument(
sourceTableNames.size() == targetTableNames.size() &&
sourceTableNames.size() <= 2 &&
sourceTableNames.size() >= 1,
"Invalid Rule property, rule needs to have one or two tables.");
for (int j = 0; j < sourceTableNames.size(); j++) {
if (!copiedTables.contains(targetTableNames.get(j))) {
DBMetaDataTool.copy(
sourceTableNames.get(j),
targetTableNames.get(j)
);
schemas.add(
DBMetaDataTool.getSchema(
targetTableNames.get(j)
)
);
copiedTables.add(targetTableNames.get(j));
}
}
}
type = (String) ruleObj.get("type");
Rule rule;
JSONArray value;
value = (JSONArray) ruleObj.get("value");
String ruleName = (String) ruleObj.get("name");
if (Strings.isNullOrEmpty(ruleName)) {
// generate default rule name when it is not provided by the user, and
// distinguished by the value of the rule.
ruleName = "Rule" + CommonTools.toHashCode((String)value.get(0));
}
switch (type) {
case "udf":
value = (JSONArray) ruleObj.get("value");
Class udfClass =
CommonTools.loadClass((String) value.get(0));
if (!Rule.class.isAssignableFrom(udfClass)) {
throw new InvalidRuleException(
"The specified class is not a Rule class."
);
}
rule = (Rule) udfClass.newInstance();
// call internal initialization on the rule.
rule.initialize(ruleName, targetTableNames);
rules.add(rule);
break;
default:
RuleBuilder ruleBuilder = NadeefConfiguration.tryGetRuleBuilder(type);
if (ruleBuilder != null) {
rules.addAll(
ruleBuilder.name(ruleName)
.schema(schemas)
.table(targetTableNames)
.value(value)
.build()
);
} else {
tracer.err("Unknown Rule type: " + type, null);
}
break;
}
}
for (int i = 0; i < rules.size(); i++) {
result.add(new CleanPlan(dbConfig, rules.get(i)));
}
return result;
} catch (Exception ex) {
ex.printStackTrace();
if (ex instanceof InvalidRuleException) {
throw (InvalidRuleException) ex;
}
throw new InvalidCleanPlanException(ex);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
}
}
}
}
|
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ScrollPane.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ScrollPane.java
index acc41d32e..c4c4e2409 100644
--- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ScrollPane.java
+++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ScrollPane.java
@@ -1,972 +1,972 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.scenes.scene2d.ui;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Event;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.utils.ActorGestureListener;
import com.badlogic.gdx.scenes.scene2d.utils.Cullable;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.scenes.scene2d.utils.Layout;
import com.badlogic.gdx.scenes.scene2d.utils.ScissorStack;
/** A group that scrolls a child widget using scrollbars and/or mouse or touch dragging.
* <p>
* The widget is sized to its preferred size. If the widget's preferred width or height is less than the size of this scroll pane,
* it is set to the size of this scroll pane. Scrollbars appear when the widget is larger than the scroll pane.
* <p>
* The scroll pane's preferred size is that of the child widget. At this size, the child widget will not need to scroll, so the
* scroll pane is typically sized by ignoring the preferred size in one or both directions.
* @author mzechner
* @author Nathan Sweet */
public class ScrollPane extends WidgetGroup {
private ScrollPaneStyle style;
private Actor widget;
final Rectangle hScrollBounds = new Rectangle();
final Rectangle vScrollBounds = new Rectangle();
final Rectangle hKnobBounds = new Rectangle();
final Rectangle vKnobBounds = new Rectangle();
private final Rectangle widgetAreaBounds = new Rectangle();
private final Rectangle widgetCullingArea = new Rectangle();
private final Rectangle scissorBounds = new Rectangle();
private ActorGestureListener flickScrollListener;
boolean scrollX, scrollY;
boolean vScrollOnRight = true;
boolean hScrollOnBottom = true;
float amountX, amountY;
float visualAmountX, visualAmountY;
float maxX, maxY;
boolean touchScrollH, touchScrollV;
final Vector2 lastPoint = new Vector2();
float areaWidth, areaHeight;
private boolean fadeScrollBars = true, smoothScrolling = true;
float fadeAlpha, fadeAlphaSeconds = 1, fadeDelay, fadeDelaySeconds = 1;
boolean cancelTouchFocus = true;
boolean flickScroll = true;
float velocityX, velocityY;
float flingTimer;
private boolean overscrollX = true, overscrollY = true;
float flingTime = 1f;
private float overscrollDistance = 50, overscrollSpeedMin = 30, overscrollSpeedMax = 200;
private boolean forceScrollX, forceScrollY;
private boolean disableX, disableY;
private boolean clamp = true;
private boolean scrollbarsOnTop;
int draggingPointer = -1;
/** @param widget May be null. */
public ScrollPane (Actor widget) {
this(widget, new ScrollPaneStyle());
}
/** @param widget May be null. */
public ScrollPane (Actor widget, Skin skin) {
this(widget, skin.get(ScrollPaneStyle.class));
}
/** @param widget May be null. */
public ScrollPane (Actor widget, Skin skin, String styleName) {
this(widget, skin.get(styleName, ScrollPaneStyle.class));
}
/** @param widget May be null. */
public ScrollPane (Actor widget, ScrollPaneStyle style) {
if (style == null) throw new IllegalArgumentException("style cannot be null.");
this.style = style;
setWidget(widget);
setWidth(150);
setHeight(150);
addCaptureListener(new InputListener() {
private float handlePosition;
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
if (draggingPointer != -1) return false;
if (pointer == 0 && button != 0) return false;
getStage().setScrollFocus(ScrollPane.this);
if (!flickScroll) resetFade();
if (fadeAlpha == 0) return false;
if (scrollX && hScrollBounds.contains(x, y)) {
event.stop();
resetFade();
if (hKnobBounds.contains(x, y)) {
lastPoint.set(x, y);
handlePosition = hKnobBounds.x;
touchScrollH = true;
draggingPointer = pointer;
return true;
}
setScrollX(amountX + areaWidth * (x < hKnobBounds.x ? -1 : 1));
return true;
}
if (scrollY && vScrollBounds.contains(x, y)) {
event.stop();
resetFade();
if (vKnobBounds.contains(x, y)) {
lastPoint.set(x, y);
handlePosition = vKnobBounds.y;
touchScrollV = true;
draggingPointer = pointer;
return true;
}
setScrollY(amountY + areaHeight * (y < vKnobBounds.y ? 1 : -1));
return true;
}
return false;
}
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
if (pointer != draggingPointer) return;
cancel();
}
public void touchDragged (InputEvent event, float x, float y, int pointer) {
if (pointer != draggingPointer) return;
if (touchScrollH) {
float delta = x - lastPoint.x;
float scrollH = handlePosition + delta;
handlePosition = scrollH;
scrollH = Math.max(hScrollBounds.x, scrollH);
scrollH = Math.min(hScrollBounds.x + hScrollBounds.width - hKnobBounds.width, scrollH);
float total = hScrollBounds.width - hKnobBounds.width;
if (total != 0) setScrollPercentX((scrollH - hScrollBounds.x) / total);
lastPoint.set(x, y);
} else if (touchScrollV) {
float delta = y - lastPoint.y;
float scrollV = handlePosition + delta;
handlePosition = scrollV;
scrollV = Math.max(vScrollBounds.y, scrollV);
scrollV = Math.min(vScrollBounds.y + vScrollBounds.height - vKnobBounds.height, scrollV);
float total = vScrollBounds.height - vKnobBounds.height;
if (total != 0) setScrollPercentY(1 - ((scrollV - vScrollBounds.y) / total));
lastPoint.set(x, y);
}
}
public boolean mouseMoved (InputEvent event, float x, float y) {
if (!flickScroll) resetFade();
return false;
}
});
flickScrollListener = new ActorGestureListener() {
public void pan (InputEvent event, float x, float y, float deltaX, float deltaY) {
resetFade();
amountX -= deltaX;
amountY += deltaY;
clamp();
cancelTouchFocusedChild(event);
}
public void fling (InputEvent event, float x, float y, int button) {
if (Math.abs(x) > 150) {
flingTimer = flingTime;
velocityX = x;
cancelTouchFocusedChild(event);
}
if (Math.abs(y) > 150) {
flingTimer = flingTime;
velocityY = -y;
cancelTouchFocusedChild(event);
}
}
public boolean handle (Event event) {
if (super.handle(event)) {
if (((InputEvent)event).getType() == InputEvent.Type.touchDown) flingTimer = 0;
return true;
}
return false;
}
};
addListener(flickScrollListener);
addListener(new InputListener() {
public boolean scrolled (InputEvent event, float x, float y, int amount) {
resetFade();
if (scrollY)
setScrollY(amountY + getMouseWheelY() * amount);
else if (scrollX) //
setScrollX(amountX + getMouseWheelX() * amount);
return true;
}
});
}
void resetFade () {
fadeAlpha = fadeAlphaSeconds;
fadeDelay = fadeDelaySeconds;
}
void cancelTouchFocusedChild (InputEvent event) {
if (!cancelTouchFocus) return;
Stage stage = getStage();
if (stage != null) stage.cancelTouchFocus(flickScrollListener, this);
}
/** If currently scrolling by tracking a touch down, stop scrolling. */
public void cancel () {
draggingPointer = -1;
touchScrollH = false;
touchScrollV = false;
flickScrollListener.getGestureDetector().cancel();
}
void clamp () {
if (!clamp) return;
scrollX(overscrollX ? MathUtils.clamp(amountX, -overscrollDistance, maxX + overscrollDistance) : MathUtils.clamp(amountX,
0, maxX));
scrollY(overscrollY ? MathUtils.clamp(amountY, -overscrollDistance, maxY + overscrollDistance) : MathUtils.clamp(amountY,
0, maxY));
}
public void setStyle (ScrollPaneStyle style) {
if (style == null) throw new IllegalArgumentException("style cannot be null.");
this.style = style;
invalidateHierarchy();
}
/** Returns the scroll pane's style. Modifying the returned style may not have an effect until
* {@link #setStyle(ScrollPaneStyle)} is called. */
public ScrollPaneStyle getStyle () {
return style;
}
public void act (float delta) {
super.act(delta);
boolean panning = flickScrollListener.getGestureDetector().isPanning();
if (fadeAlpha > 0 && fadeScrollBars && !panning && !touchScrollH && !touchScrollV) {
fadeDelay -= delta;
if (fadeDelay <= 0) fadeAlpha = Math.max(0, fadeAlpha - delta);
}
if (flingTimer > 0) {
resetFade();
float alpha = flingTimer / flingTime;
amountX -= velocityX * alpha * delta;
amountY -= velocityY * alpha * delta;
clamp();
// Stop fling if hit overscroll distance.
if (amountX == -overscrollDistance) velocityX = 0;
if (amountX >= maxX + overscrollDistance) velocityX = 0;
if (amountY == -overscrollDistance) velocityY = 0;
if (amountY >= maxY + overscrollDistance) velocityY = 0;
flingTimer -= delta;
if (flingTimer <= 0) {
velocityX = 0;
velocityY = 0;
}
}
if (smoothScrolling && flingTimer <= 0 && !touchScrollH && !touchScrollV && !panning) {
if (visualAmountX != amountX) {
if (visualAmountX < amountX)
visualScrollX(Math.min(amountX, visualAmountX + Math.max(150 * delta, (amountX - visualAmountX) * 5 * delta)));
else
visualScrollX(Math.max(amountX, visualAmountX - Math.max(150 * delta, (visualAmountX - amountX) * 5 * delta)));
}
if (visualAmountY != amountY) {
if (visualAmountY < amountY)
visualScrollY(Math.min(amountY, visualAmountY + Math.max(150 * delta, (amountY - visualAmountY) * 5 * delta)));
else
visualScrollY(Math.max(amountY, visualAmountY - Math.max(150 * delta, (visualAmountY - amountY) * 5 * delta)));
}
} else {
if (visualAmountX != amountX) visualScrollX(amountX);
if (visualAmountY != amountY) visualScrollY(amountY);
}
if (!panning) {
if (overscrollX && scrollX) {
if (amountX < 0) {
resetFade();
amountX += (overscrollSpeedMin + (overscrollSpeedMax - overscrollSpeedMin) * -amountX / overscrollDistance)
* delta;
if (amountX > 0) scrollX(0);
} else if (amountX > maxX) {
resetFade();
amountX -= (overscrollSpeedMin + (overscrollSpeedMax - overscrollSpeedMin) * -(maxX - amountX)
/ overscrollDistance)
* delta;
if (amountX < maxX) scrollX(maxX);
}
}
if (overscrollY && scrollY) {
if (amountY < 0) {
resetFade();
amountY += (overscrollSpeedMin + (overscrollSpeedMax - overscrollSpeedMin) * -amountY / overscrollDistance)
* delta;
if (amountY > 0) scrollY(0);
} else if (amountY > maxY) {
resetFade();
amountY -= (overscrollSpeedMin + (overscrollSpeedMax - overscrollSpeedMin) * -(maxY - amountY)
/ overscrollDistance)
* delta;
if (amountY < maxY) scrollY(maxY);
}
}
}
}
public void layout () {
final Drawable bg = style.background;
final Drawable hScrollKnob = style.hScrollKnob;
final Drawable vScrollKnob = style.vScrollKnob;
float bgLeftWidth = 0, bgRightWidth = 0, bgTopHeight = 0, bgBottomHeight = 0;
if (bg != null) {
bgLeftWidth = bg.getLeftWidth();
bgRightWidth = bg.getRightWidth();
bgTopHeight = bg.getTopHeight();
bgBottomHeight = bg.getBottomHeight();
}
float width = getWidth();
float height = getHeight();
float scrollbarHeight = 0;
if (hScrollKnob != null) scrollbarHeight = hScrollKnob.getMinHeight();
if (style.hScroll != null) scrollbarHeight = Math.max(scrollbarHeight, style.hScroll.getMinHeight());
float scrollbarWidth = 0;
if (vScrollKnob != null) scrollbarWidth = vScrollKnob.getMinWidth();
if (style.vScroll != null) scrollbarWidth = Math.max(scrollbarWidth, style.vScroll.getMinWidth());
// Get available space size by subtracting background's padded area.
areaWidth = width - bgLeftWidth - bgRightWidth;
areaHeight = height - bgTopHeight - bgBottomHeight;
if (widget == null) return;
// Get widget's desired width.
float widgetWidth, widgetHeight;
if (widget instanceof Layout) {
Layout layout = (Layout)widget;
widgetWidth = layout.getPrefWidth();
widgetHeight = layout.getPrefHeight();
} else {
widgetWidth = widget.getWidth();
widgetHeight = widget.getHeight();
}
// Determine if horizontal/vertical scrollbars are needed.
scrollX = forceScrollX || (widgetWidth > areaWidth && !disableX);
scrollY = forceScrollY || (widgetHeight > areaHeight && !disableY);
boolean fade = fadeScrollBars;
if (!fade) {
// Check again, now taking into account the area that's taken up by any enabled scrollbars.
if (scrollY) {
areaWidth -= scrollbarWidth;
if (!scrollX && widgetWidth > areaWidth && !disableX) {
scrollX = true;
}
}
if (scrollX) {
areaHeight -= scrollbarHeight;
if (!scrollY && widgetHeight > areaHeight && !disableY) {
scrollY = true;
areaWidth -= scrollbarWidth;
}
}
}
// Set the widget area bounds.
widgetAreaBounds.set(bgLeftWidth, bgBottomHeight, areaWidth, areaHeight);
if (fade) {
// Make sure widget is drawn under fading scrollbars.
if (scrollX) areaHeight -= scrollbarHeight;
if (scrollY) areaWidth -= scrollbarWidth;
} else {
if (scrollbarsOnTop) {
// Make sure widget is drawn under non-fading scrollbars.
if (scrollX) widgetAreaBounds.height += scrollbarHeight;
if (scrollY) widgetAreaBounds.width += scrollbarWidth;
} else {
// Offset widget area y for horizontal scrollbar.
if (scrollX) {
if (hScrollOnBottom) {
widgetAreaBounds.y += scrollbarHeight;
} else {
widgetAreaBounds.y = 0;
}
}
// Offset widget area x for vertical scrollbar.
if (scrollY) {
if (vScrollOnRight) {
widgetAreaBounds.x = 0;
} else {
widgetAreaBounds.x += scrollbarWidth;
}
}
}
}
// If the widget is smaller than the available space, make it take up the available space.
widgetWidth = disableX ? width : Math.max(areaWidth, widgetWidth);
widgetHeight = disableY ? height : Math.max(areaHeight, widgetHeight);
maxX = widgetWidth - areaWidth;
maxY = widgetHeight - areaHeight;
if (fade) {
// Make sure widget is drawn under fading scrollbars.
if (scrollX) maxY -= scrollbarHeight;
if (scrollY) maxX -= scrollbarWidth;
}
scrollX(MathUtils.clamp(amountX, 0, maxX));
scrollY(MathUtils.clamp(amountY, 0, maxY));
// Set the bounds and scroll knob sizes if scrollbars are needed.
if (scrollX) {
if (hScrollKnob != null) {
float hScrollHeight = style.hScroll != null ? style.hScroll.getMinHeight() : hScrollKnob.getMinHeight();
// the small gap where the two scroll bars intersect might have to flip from right to left
float boundsX, boundsY;
if (vScrollOnRight) {
boundsX = bgLeftWidth;
} else {
boundsX = bgLeftWidth + scrollbarWidth;
}
// bar on the top or bottom
if (hScrollOnBottom) {
boundsY = bgBottomHeight;
} else {
boundsY = height - bgTopHeight - hScrollHeight;
}
hScrollBounds.set(boundsX, boundsY, areaWidth, hScrollHeight);
hKnobBounds.width = Math.max(hScrollKnob.getMinWidth(), (int)(hScrollBounds.width * areaWidth / widgetWidth));
hKnobBounds.height = hScrollKnob.getMinHeight();
hKnobBounds.x = hScrollBounds.x + (int)((hScrollBounds.width - hKnobBounds.width) * getScrollPercentX());
hKnobBounds.y = hScrollBounds.y;
} else {
hScrollBounds.set(0, 0, 0, 0);
hKnobBounds.set(0, 0, 0, 0);
}
}
if (scrollY) {
if (vScrollKnob != null) {
float vScrollWidth = style.vScroll != null ? style.vScroll.getMinWidth() : vScrollKnob.getMinWidth();
// the small gap where the two scroll bars intersect might have to flip from bottom to top
float boundsX, boundsY;
if (hScrollOnBottom) {
boundsY = height - bgTopHeight - areaHeight;
} else {
boundsY = bgBottomHeight;
}
// bar on the left or right
if (vScrollOnRight) {
boundsX = width - bgRightWidth - vScrollWidth;
} else {
boundsX = bgLeftWidth;
}
vScrollBounds.set(boundsX, boundsY, vScrollWidth, areaHeight);
vKnobBounds.width = vScrollKnob.getMinWidth();
vKnobBounds.height = Math.max(vScrollKnob.getMinHeight(), (int)(vScrollBounds.height * areaHeight / widgetHeight));
if (vScrollOnRight) {
vKnobBounds.x = width - bgRightWidth - vScrollKnob.getMinWidth();
} else {
- vKnobBounds.x = 0;
+ vKnobBounds.x = bgLeftWidth;
}
vKnobBounds.y = vScrollBounds.y + (int)((vScrollBounds.height - vKnobBounds.height) * (1 - getScrollPercentY()));
} else {
vScrollBounds.set(0, 0, 0, 0);
vKnobBounds.set(0, 0, 0, 0);
}
}
if (widget.getWidth() != widgetWidth || widget.getHeight() != widgetHeight) {
widget.setWidth(widgetWidth);
widget.setHeight(widgetHeight);
if (widget instanceof Layout) {
Layout layout = (Layout)widget;
layout.invalidate();
layout.validate();
}
} else {
if (widget instanceof Layout) ((Layout)widget).validate();
}
}
@Override
public void draw (SpriteBatch batch, float parentAlpha) {
if (widget == null) return;
validate();
// Setup transform for this group.
applyTransform(batch, computeTransform());
if (scrollX) hKnobBounds.x = hScrollBounds.x + (int)((hScrollBounds.width - hKnobBounds.width) * getScrollPercentX());
if (scrollY)
vKnobBounds.y = vScrollBounds.y + (int)((vScrollBounds.height - vKnobBounds.height) * (1 - getScrollPercentY()));
// Calculate the widget's position depending on the scroll state and available widget area.
float y = widgetAreaBounds.y;
if (!scrollY)
y -= (int)maxY;
else
y -= (int)(maxY - visualAmountY);
if (!fadeScrollBars && scrollbarsOnTop && scrollX) {
float scrollbarHeight = 0;
if (style.hScrollKnob != null) scrollbarHeight = style.hScrollKnob.getMinHeight();
if (style.hScroll != null) scrollbarHeight = Math.max(scrollbarHeight, style.hScroll.getMinHeight());
y += scrollbarHeight;
}
float x = widgetAreaBounds.x;
if (scrollX) x -= (int)visualAmountX;
widget.setPosition(x, y);
if (widget instanceof Cullable) {
widgetCullingArea.x = -widget.getX() + widgetAreaBounds.x;
widgetCullingArea.y = -widget.getY() + widgetAreaBounds.y;
widgetCullingArea.width = widgetAreaBounds.width;
widgetCullingArea.height = widgetAreaBounds.height;
((Cullable)widget).setCullingArea(widgetCullingArea);
}
// Caculate the scissor bounds based on the batch transform, the available widget area and the camera transform. We need to
// project those to screen coordinates for OpenGL ES to consume.
getStage().calculateScissors(widgetAreaBounds, scissorBounds);
// Draw the background ninepatch.
Color color = getColor();
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
if (style.background != null) style.background.draw(batch, 0, 0, getWidth(), getHeight());
batch.flush();
// Enable scissors for widget area and draw the widget.
if (ScissorStack.pushScissors(scissorBounds)) {
drawChildren(batch, parentAlpha);
ScissorStack.popScissors();
}
// Render scrollbars and knobs on top.
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha * Interpolation.fade.apply(fadeAlpha / fadeAlphaSeconds));
if (scrollX && scrollY) {
if (style.corner != null) {
style.corner
.draw(batch, hScrollBounds.x + hScrollBounds.width, hScrollBounds.y, vScrollBounds.width, vScrollBounds.y);
}
}
if (scrollX) {
if (style.hScroll != null)
style.hScroll.draw(batch, hScrollBounds.x, hScrollBounds.y, hScrollBounds.width, hScrollBounds.height);
if (style.hScrollKnob != null)
style.hScrollKnob.draw(batch, hKnobBounds.x, hKnobBounds.y, hKnobBounds.width, hKnobBounds.height);
}
if (scrollY) {
if (style.vScroll != null)
style.vScroll.draw(batch, vScrollBounds.x, vScrollBounds.y, vScrollBounds.width, vScrollBounds.height);
if (style.vScrollKnob != null)
style.vScrollKnob.draw(batch, vKnobBounds.x, vKnobBounds.y, vKnobBounds.width, vKnobBounds.height);
}
resetTransform(batch);
}
public float getPrefWidth () {
if (widget instanceof Layout) {
float width = ((Layout)widget).getPrefWidth();
if (style.background != null) width += style.background.getLeftWidth() + style.background.getRightWidth();
return width;
}
return 150;
}
public float getPrefHeight () {
if (widget instanceof Layout) {
float height = ((Layout)widget).getPrefHeight();
if (style.background != null) height += style.background.getTopHeight() + style.background.getBottomHeight();
return height;
}
return 150;
}
public float getMinWidth () {
return 0;
}
public float getMinHeight () {
return 0;
}
/** Sets the {@link Actor} embedded in this scroll pane.
* @param widget May be null to remove any current actor. */
public void setWidget (Actor widget) {
if (widget == this) throw new IllegalArgumentException("widget cannot be same object");
if (this.widget != null) super.removeActor(this.widget);
this.widget = widget;
if (widget != null) super.addActor(widget);
}
/** Returns the actor embedded in this scroll pane, or null. */
public Actor getWidget () {
return widget;
}
/** @deprecated */
public void addActor (Actor actor) {
throw new UnsupportedOperationException("Use ScrollPane#setWidget.");
}
/** @deprecated */
public void addActorAt (int index, Actor actor) {
throw new UnsupportedOperationException("Use ScrollPane#setWidget.");
}
/** @deprecated */
public void addActorBefore (Actor actorBefore, Actor actor) {
throw new UnsupportedOperationException("Use ScrollPane#setWidget.");
}
/** @deprecated */
public void addActorAfter (Actor actorAfter, Actor actor) {
throw new UnsupportedOperationException("Use ScrollPane#setWidget.");
}
public boolean removeActor (Actor actor) {
if (actor != widget) return false;
setWidget(null);
return true;
}
public Actor hit (float x, float y, boolean touchable) {
if (x < 0 || x >= getWidth() || y < 0 || y >= getHeight()) return null;
if (scrollX && hScrollBounds.contains(x, y)) return this;
if (scrollY && vScrollBounds.contains(x, y)) return this;
return super.hit(x, y, touchable);
}
/** Called whenever the x scroll amount is changed. */
protected void scrollX (float pixelsX) {
this.amountX = pixelsX;
}
/** Called whenever the y scroll amount is changed. */
protected void scrollY (float pixelsY) {
this.amountY = pixelsY;
}
/** Called whenever the visual x scroll amount is changed. */
protected void visualScrollX (float pixelsX) {
this.visualAmountX = pixelsX;
}
/** Called whenever the visual y scroll amount is changed. */
protected void visualScrollY (float pixelsY) {
this.visualAmountY = pixelsY;
}
/** Returns the amount to scroll horizontally when the mouse wheel is scrolled. */
protected float getMouseWheelX () {
return Math.max(areaWidth * 0.9f, maxX * 0.1f) / 4;
}
/** Returns the amount to scroll vertically when the mouse wheel is scrolled. */
protected float getMouseWheelY () {
return Math.max(areaHeight * 0.9f, maxY * 0.1f) / 4;
}
public void setScrollX (float pixels) {
scrollX(MathUtils.clamp(pixels, 0, maxX));
}
/** Returns the x scroll position in pixels. */
public float getScrollX () {
return amountX;
}
public void setScrollY (float pixels) {
scrollY(MathUtils.clamp(pixels, 0, maxY));
}
/** Returns the y scroll position in pixels. */
public float getScrollY () {
return amountY;
}
/** Sets the visual scroll amount equal to the scroll amount. This can be used when setting the scroll amount without animating. */
public void updateVisualScroll () {
visualAmountX = amountX;
visualAmountY = amountY;
}
public float getVisualScrollX () {
return !scrollX ? 0 : visualAmountX;
}
public float getVisualScrollY () {
return !scrollY ? 0 : visualAmountY;
}
public float getScrollPercentX () {
return MathUtils.clamp(amountX / maxX, 0, 1);
}
public void setScrollPercentX (float percentX) {
scrollX(maxX * MathUtils.clamp(percentX, 0, 1));
}
public float getScrollPercentY () {
return MathUtils.clamp(amountY / maxY, 0, 1);
}
public void setScrollPercentY (float percentY) {
scrollY(maxY * MathUtils.clamp(percentY, 0, 1));
}
public void setFlickScroll (boolean flickScroll) {
if (this.flickScroll == flickScroll) return;
this.flickScroll = flickScroll;
if (flickScroll)
addListener(flickScrollListener);
else
removeListener(flickScrollListener);
invalidate();
}
/** Sets the scroll offset so the specified rectangle is fully in view, if possible. Coordinates are in the scroll pane widget's
* coordinate system. */
public void scrollTo (float x, float y, float width, float height) {
float amountX = this.amountX;
if (x + width > amountX + areaWidth) amountX = x + width - areaWidth;
if (x < amountX) amountX = x;
scrollX(MathUtils.clamp(amountX, 0, maxX));
float amountY = this.amountY;
if (amountY > maxY - y - height + areaHeight) amountY = maxY - y - height + areaHeight;
if (amountY < maxY - y) amountY = maxY - y;
scrollY(MathUtils.clamp(amountY, 0, maxY));
}
/** Sets the scroll offset so the specified rectangle is fully in view and centered vertically in the scroll pane, if possible.
* Coordinates are in the scroll pane widget's coordinate system. */
public void scrollToCenter (float x, float y, float width, float height) {
float amountX = this.amountX;
if (x + width > amountX + areaWidth) amountX = x + width - areaWidth;
if (x < amountX) amountX = x;
scrollX(MathUtils.clamp(amountX, 0, maxX));
float amountY = this.amountY;
float centerY = maxY - y + areaHeight / 2 - height / 2;
if (amountY < centerY - areaHeight / 4 || amountY > centerY + areaHeight / 4) amountY = centerY;
scrollY(MathUtils.clamp(amountY, 0, maxY));
}
/** Returns the maximum scroll value in the x direction. */
public float getMaxX () {
return maxX;
}
/** Returns the maximum scroll value in the y direction. */
public float getMaxY () {
return maxY;
}
public float getScrollBarHeight () {
return style.hScrollKnob == null || !scrollX ? 0 : style.hScrollKnob.getMinHeight();
}
public float getScrollBarWidth () {
return style.vScrollKnob == null || !scrollY ? 0 : style.vScrollKnob.getMinWidth();
}
public boolean isScrollX () {
return scrollX;
}
public boolean isScrollY () {
return scrollY;
}
/** Disables scrolling in a direction. The widget will be sized to the FlickScrollPane in the disabled direction. */
public void setScrollingDisabled (boolean x, boolean y) {
disableX = x;
disableY = y;
}
public boolean isDragging () {
return draggingPointer != -1;
}
public boolean isPanning () {
return flickScrollListener.getGestureDetector().isPanning();
}
public boolean isFlinging () {
return flingTimer > 0;
}
public void setVelocityX (float velocityX) {
this.velocityX = velocityX;
}
/** Gets the flick scroll y velocity. */
public float getVelocityX () {
if (flingTimer <= 0) return 0;
float alpha = flingTimer / flingTime;
alpha = alpha * alpha * alpha;
return velocityX * alpha * alpha * alpha;
}
public void setVelocityY (float velocityY) {
this.velocityY = velocityY;
}
/** Gets the flick scroll y velocity. */
public float getVelocityY () {
return velocityY;
}
/** For flick scroll, if true the widget can be scrolled slightly past its bounds and will animate back to its bounds when
* scrolling is stopped. Default is true. */
public void setOverscroll (boolean overscrollX, boolean overscrollY) {
this.overscrollX = overscrollX;
this.overscrollY = overscrollY;
}
/** For flick scroll, sets the overscroll distance in pixels and the speed it returns to the widget's bounds in seconds. Default
* is 50, 30, 200. */
public void setupOverscroll (float distance, float speedMin, float speedMax) {
overscrollDistance = distance;
overscrollSpeedMin = speedMin;
overscrollSpeedMax = speedMax;
}
/** Forces enabling scrollbars (for non-flick scroll) and overscrolling (for flick scroll) in a direction, even if the contents
* do not exceed the bounds in that direction. */
public void setForceScroll (boolean x, boolean y) {
forceScrollX = x;
forceScrollY = y;
}
public boolean isForceScrollX () {
return forceScrollX;
}
public boolean isForceScrollY () {
return forceScrollY;
}
/** For flick scroll, sets the amount of time in seconds that a fling will continue to scroll. Default is 1. */
public void setFlingTime (float flingTime) {
this.flingTime = flingTime;
}
/** For flick scroll, prevents scrolling out of the widget's bounds. Default is true. */
public void setClamp (boolean clamp) {
this.clamp = clamp;
}
/** Put the vertical scroll bar and knob on the left or right side of the ScrollPane
* @param atRight set to true to draw on the right, false to draw on the left (default : right)
*/
public void setVScrollBarAtRight(boolean atRight) {
vScrollOnRight = atRight;
}
/** Put the vertical scroll bar and knob on the top (y coords, not draw order) or bottom of the ScrollPane
* @param atBottom set to true to draw on the bottom, false to draw on the top (default : bottom)
*/
public void setHScrollBarAtBottom(boolean atBottom) {
hScrollOnBottom = atBottom;
}
/** When true the scroll bars fade out after some time of not being used. */
public void setFadeScrollBars (boolean fadeScrollBars) {
if (this.fadeScrollBars == fadeScrollBars) return;
this.fadeScrollBars = fadeScrollBars;
if (!fadeScrollBars) fadeAlpha = fadeAlphaSeconds;
invalidate();
}
public void setupFadeScrollBars (float fadeAlphaSeconds, float fadeDelaySeconds) {
this.fadeAlphaSeconds = fadeAlphaSeconds;
this.fadeDelaySeconds = fadeDelaySeconds;
}
public void setSmoothScrolling (boolean smoothScrolling) {
this.smoothScrolling = smoothScrolling;
}
/** When false (the default), the widget is clipped so it is not drawn under the scrollbars. When true, the widget is clipped to
* the entire scroll pane bounds and the scrollbars are drawn on top of the widget. If {@link #setFadeScrollBars(boolean)} is
* true, the scroll bars are always drawn on top. */
public void setScrollbarsOnTop (boolean scrollbarsOnTop) {
this.scrollbarsOnTop = scrollbarsOnTop;
invalidate();
}
/** When true (default), the {@link Stage#cancelTouchFocus()} touch focus} is cancelled when flick scrolling begins. This causes
* widgets inside the scrollpane that have received touchDown to receive touchUp when flick scrolling begins. */
public void setCancelTouchFocus (boolean cancelTouchFocus) {
this.cancelTouchFocus = cancelTouchFocus;
}
/** The style for a scroll pane, see {@link ScrollPane}.
* @author mzechner
* @author Nathan Sweet */
static public class ScrollPaneStyle {
/** Optional. */
public Drawable background, corner;
/** Optional. */
public Drawable hScroll, hScrollKnob;
/** Optional. */
public Drawable vScroll, vScrollKnob;
public ScrollPaneStyle () {
}
public ScrollPaneStyle (Drawable background, Drawable hScroll, Drawable hScrollKnob, Drawable vScroll, Drawable vScrollKnob) {
this.background = background;
this.hScroll = hScroll;
this.hScrollKnob = hScrollKnob;
this.vScroll = vScroll;
this.vScrollKnob = vScrollKnob;
}
public ScrollPaneStyle (ScrollPaneStyle style) {
this.background = style.background;
this.hScroll = style.hScroll;
this.hScrollKnob = style.hScrollKnob;
this.vScroll = style.vScroll;
this.vScrollKnob = style.vScrollKnob;
}
}
}
| true | true |
public void layout () {
final Drawable bg = style.background;
final Drawable hScrollKnob = style.hScrollKnob;
final Drawable vScrollKnob = style.vScrollKnob;
float bgLeftWidth = 0, bgRightWidth = 0, bgTopHeight = 0, bgBottomHeight = 0;
if (bg != null) {
bgLeftWidth = bg.getLeftWidth();
bgRightWidth = bg.getRightWidth();
bgTopHeight = bg.getTopHeight();
bgBottomHeight = bg.getBottomHeight();
}
float width = getWidth();
float height = getHeight();
float scrollbarHeight = 0;
if (hScrollKnob != null) scrollbarHeight = hScrollKnob.getMinHeight();
if (style.hScroll != null) scrollbarHeight = Math.max(scrollbarHeight, style.hScroll.getMinHeight());
float scrollbarWidth = 0;
if (vScrollKnob != null) scrollbarWidth = vScrollKnob.getMinWidth();
if (style.vScroll != null) scrollbarWidth = Math.max(scrollbarWidth, style.vScroll.getMinWidth());
// Get available space size by subtracting background's padded area.
areaWidth = width - bgLeftWidth - bgRightWidth;
areaHeight = height - bgTopHeight - bgBottomHeight;
if (widget == null) return;
// Get widget's desired width.
float widgetWidth, widgetHeight;
if (widget instanceof Layout) {
Layout layout = (Layout)widget;
widgetWidth = layout.getPrefWidth();
widgetHeight = layout.getPrefHeight();
} else {
widgetWidth = widget.getWidth();
widgetHeight = widget.getHeight();
}
// Determine if horizontal/vertical scrollbars are needed.
scrollX = forceScrollX || (widgetWidth > areaWidth && !disableX);
scrollY = forceScrollY || (widgetHeight > areaHeight && !disableY);
boolean fade = fadeScrollBars;
if (!fade) {
// Check again, now taking into account the area that's taken up by any enabled scrollbars.
if (scrollY) {
areaWidth -= scrollbarWidth;
if (!scrollX && widgetWidth > areaWidth && !disableX) {
scrollX = true;
}
}
if (scrollX) {
areaHeight -= scrollbarHeight;
if (!scrollY && widgetHeight > areaHeight && !disableY) {
scrollY = true;
areaWidth -= scrollbarWidth;
}
}
}
// Set the widget area bounds.
widgetAreaBounds.set(bgLeftWidth, bgBottomHeight, areaWidth, areaHeight);
if (fade) {
// Make sure widget is drawn under fading scrollbars.
if (scrollX) areaHeight -= scrollbarHeight;
if (scrollY) areaWidth -= scrollbarWidth;
} else {
if (scrollbarsOnTop) {
// Make sure widget is drawn under non-fading scrollbars.
if (scrollX) widgetAreaBounds.height += scrollbarHeight;
if (scrollY) widgetAreaBounds.width += scrollbarWidth;
} else {
// Offset widget area y for horizontal scrollbar.
if (scrollX) {
if (hScrollOnBottom) {
widgetAreaBounds.y += scrollbarHeight;
} else {
widgetAreaBounds.y = 0;
}
}
// Offset widget area x for vertical scrollbar.
if (scrollY) {
if (vScrollOnRight) {
widgetAreaBounds.x = 0;
} else {
widgetAreaBounds.x += scrollbarWidth;
}
}
}
}
// If the widget is smaller than the available space, make it take up the available space.
widgetWidth = disableX ? width : Math.max(areaWidth, widgetWidth);
widgetHeight = disableY ? height : Math.max(areaHeight, widgetHeight);
maxX = widgetWidth - areaWidth;
maxY = widgetHeight - areaHeight;
if (fade) {
// Make sure widget is drawn under fading scrollbars.
if (scrollX) maxY -= scrollbarHeight;
if (scrollY) maxX -= scrollbarWidth;
}
scrollX(MathUtils.clamp(amountX, 0, maxX));
scrollY(MathUtils.clamp(amountY, 0, maxY));
// Set the bounds and scroll knob sizes if scrollbars are needed.
if (scrollX) {
if (hScrollKnob != null) {
float hScrollHeight = style.hScroll != null ? style.hScroll.getMinHeight() : hScrollKnob.getMinHeight();
// the small gap where the two scroll bars intersect might have to flip from right to left
float boundsX, boundsY;
if (vScrollOnRight) {
boundsX = bgLeftWidth;
} else {
boundsX = bgLeftWidth + scrollbarWidth;
}
// bar on the top or bottom
if (hScrollOnBottom) {
boundsY = bgBottomHeight;
} else {
boundsY = height - bgTopHeight - hScrollHeight;
}
hScrollBounds.set(boundsX, boundsY, areaWidth, hScrollHeight);
hKnobBounds.width = Math.max(hScrollKnob.getMinWidth(), (int)(hScrollBounds.width * areaWidth / widgetWidth));
hKnobBounds.height = hScrollKnob.getMinHeight();
hKnobBounds.x = hScrollBounds.x + (int)((hScrollBounds.width - hKnobBounds.width) * getScrollPercentX());
hKnobBounds.y = hScrollBounds.y;
} else {
hScrollBounds.set(0, 0, 0, 0);
hKnobBounds.set(0, 0, 0, 0);
}
}
if (scrollY) {
if (vScrollKnob != null) {
float vScrollWidth = style.vScroll != null ? style.vScroll.getMinWidth() : vScrollKnob.getMinWidth();
// the small gap where the two scroll bars intersect might have to flip from bottom to top
float boundsX, boundsY;
if (hScrollOnBottom) {
boundsY = height - bgTopHeight - areaHeight;
} else {
boundsY = bgBottomHeight;
}
// bar on the left or right
if (vScrollOnRight) {
boundsX = width - bgRightWidth - vScrollWidth;
} else {
boundsX = bgLeftWidth;
}
vScrollBounds.set(boundsX, boundsY, vScrollWidth, areaHeight);
vKnobBounds.width = vScrollKnob.getMinWidth();
vKnobBounds.height = Math.max(vScrollKnob.getMinHeight(), (int)(vScrollBounds.height * areaHeight / widgetHeight));
if (vScrollOnRight) {
vKnobBounds.x = width - bgRightWidth - vScrollKnob.getMinWidth();
} else {
vKnobBounds.x = 0;
}
vKnobBounds.y = vScrollBounds.y + (int)((vScrollBounds.height - vKnobBounds.height) * (1 - getScrollPercentY()));
} else {
vScrollBounds.set(0, 0, 0, 0);
vKnobBounds.set(0, 0, 0, 0);
}
}
if (widget.getWidth() != widgetWidth || widget.getHeight() != widgetHeight) {
widget.setWidth(widgetWidth);
widget.setHeight(widgetHeight);
if (widget instanceof Layout) {
Layout layout = (Layout)widget;
layout.invalidate();
layout.validate();
}
} else {
if (widget instanceof Layout) ((Layout)widget).validate();
}
}
|
public void layout () {
final Drawable bg = style.background;
final Drawable hScrollKnob = style.hScrollKnob;
final Drawable vScrollKnob = style.vScrollKnob;
float bgLeftWidth = 0, bgRightWidth = 0, bgTopHeight = 0, bgBottomHeight = 0;
if (bg != null) {
bgLeftWidth = bg.getLeftWidth();
bgRightWidth = bg.getRightWidth();
bgTopHeight = bg.getTopHeight();
bgBottomHeight = bg.getBottomHeight();
}
float width = getWidth();
float height = getHeight();
float scrollbarHeight = 0;
if (hScrollKnob != null) scrollbarHeight = hScrollKnob.getMinHeight();
if (style.hScroll != null) scrollbarHeight = Math.max(scrollbarHeight, style.hScroll.getMinHeight());
float scrollbarWidth = 0;
if (vScrollKnob != null) scrollbarWidth = vScrollKnob.getMinWidth();
if (style.vScroll != null) scrollbarWidth = Math.max(scrollbarWidth, style.vScroll.getMinWidth());
// Get available space size by subtracting background's padded area.
areaWidth = width - bgLeftWidth - bgRightWidth;
areaHeight = height - bgTopHeight - bgBottomHeight;
if (widget == null) return;
// Get widget's desired width.
float widgetWidth, widgetHeight;
if (widget instanceof Layout) {
Layout layout = (Layout)widget;
widgetWidth = layout.getPrefWidth();
widgetHeight = layout.getPrefHeight();
} else {
widgetWidth = widget.getWidth();
widgetHeight = widget.getHeight();
}
// Determine if horizontal/vertical scrollbars are needed.
scrollX = forceScrollX || (widgetWidth > areaWidth && !disableX);
scrollY = forceScrollY || (widgetHeight > areaHeight && !disableY);
boolean fade = fadeScrollBars;
if (!fade) {
// Check again, now taking into account the area that's taken up by any enabled scrollbars.
if (scrollY) {
areaWidth -= scrollbarWidth;
if (!scrollX && widgetWidth > areaWidth && !disableX) {
scrollX = true;
}
}
if (scrollX) {
areaHeight -= scrollbarHeight;
if (!scrollY && widgetHeight > areaHeight && !disableY) {
scrollY = true;
areaWidth -= scrollbarWidth;
}
}
}
// Set the widget area bounds.
widgetAreaBounds.set(bgLeftWidth, bgBottomHeight, areaWidth, areaHeight);
if (fade) {
// Make sure widget is drawn under fading scrollbars.
if (scrollX) areaHeight -= scrollbarHeight;
if (scrollY) areaWidth -= scrollbarWidth;
} else {
if (scrollbarsOnTop) {
// Make sure widget is drawn under non-fading scrollbars.
if (scrollX) widgetAreaBounds.height += scrollbarHeight;
if (scrollY) widgetAreaBounds.width += scrollbarWidth;
} else {
// Offset widget area y for horizontal scrollbar.
if (scrollX) {
if (hScrollOnBottom) {
widgetAreaBounds.y += scrollbarHeight;
} else {
widgetAreaBounds.y = 0;
}
}
// Offset widget area x for vertical scrollbar.
if (scrollY) {
if (vScrollOnRight) {
widgetAreaBounds.x = 0;
} else {
widgetAreaBounds.x += scrollbarWidth;
}
}
}
}
// If the widget is smaller than the available space, make it take up the available space.
widgetWidth = disableX ? width : Math.max(areaWidth, widgetWidth);
widgetHeight = disableY ? height : Math.max(areaHeight, widgetHeight);
maxX = widgetWidth - areaWidth;
maxY = widgetHeight - areaHeight;
if (fade) {
// Make sure widget is drawn under fading scrollbars.
if (scrollX) maxY -= scrollbarHeight;
if (scrollY) maxX -= scrollbarWidth;
}
scrollX(MathUtils.clamp(amountX, 0, maxX));
scrollY(MathUtils.clamp(amountY, 0, maxY));
// Set the bounds and scroll knob sizes if scrollbars are needed.
if (scrollX) {
if (hScrollKnob != null) {
float hScrollHeight = style.hScroll != null ? style.hScroll.getMinHeight() : hScrollKnob.getMinHeight();
// the small gap where the two scroll bars intersect might have to flip from right to left
float boundsX, boundsY;
if (vScrollOnRight) {
boundsX = bgLeftWidth;
} else {
boundsX = bgLeftWidth + scrollbarWidth;
}
// bar on the top or bottom
if (hScrollOnBottom) {
boundsY = bgBottomHeight;
} else {
boundsY = height - bgTopHeight - hScrollHeight;
}
hScrollBounds.set(boundsX, boundsY, areaWidth, hScrollHeight);
hKnobBounds.width = Math.max(hScrollKnob.getMinWidth(), (int)(hScrollBounds.width * areaWidth / widgetWidth));
hKnobBounds.height = hScrollKnob.getMinHeight();
hKnobBounds.x = hScrollBounds.x + (int)((hScrollBounds.width - hKnobBounds.width) * getScrollPercentX());
hKnobBounds.y = hScrollBounds.y;
} else {
hScrollBounds.set(0, 0, 0, 0);
hKnobBounds.set(0, 0, 0, 0);
}
}
if (scrollY) {
if (vScrollKnob != null) {
float vScrollWidth = style.vScroll != null ? style.vScroll.getMinWidth() : vScrollKnob.getMinWidth();
// the small gap where the two scroll bars intersect might have to flip from bottom to top
float boundsX, boundsY;
if (hScrollOnBottom) {
boundsY = height - bgTopHeight - areaHeight;
} else {
boundsY = bgBottomHeight;
}
// bar on the left or right
if (vScrollOnRight) {
boundsX = width - bgRightWidth - vScrollWidth;
} else {
boundsX = bgLeftWidth;
}
vScrollBounds.set(boundsX, boundsY, vScrollWidth, areaHeight);
vKnobBounds.width = vScrollKnob.getMinWidth();
vKnobBounds.height = Math.max(vScrollKnob.getMinHeight(), (int)(vScrollBounds.height * areaHeight / widgetHeight));
if (vScrollOnRight) {
vKnobBounds.x = width - bgRightWidth - vScrollKnob.getMinWidth();
} else {
vKnobBounds.x = bgLeftWidth;
}
vKnobBounds.y = vScrollBounds.y + (int)((vScrollBounds.height - vKnobBounds.height) * (1 - getScrollPercentY()));
} else {
vScrollBounds.set(0, 0, 0, 0);
vKnobBounds.set(0, 0, 0, 0);
}
}
if (widget.getWidth() != widgetWidth || widget.getHeight() != widgetHeight) {
widget.setWidth(widgetWidth);
widget.setHeight(widgetHeight);
if (widget instanceof Layout) {
Layout layout = (Layout)widget;
layout.invalidate();
layout.validate();
}
} else {
if (widget instanceof Layout) ((Layout)widget).validate();
}
}
|
diff --git a/modules/android-client/src/com/df/android/ui/MenuView.java b/modules/android-client/src/com/df/android/ui/MenuView.java
index bfcf80f..9804f4e 100644
--- a/modules/android-client/src/com/df/android/ui/MenuView.java
+++ b/modules/android-client/src/com/df/android/ui/MenuView.java
@@ -1,92 +1,94 @@
package com.df.android.ui;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import com.df.android.R;
import com.df.android.entity.ItemCategory;
import com.df.android.entity.Shop;
import com.df.android.menu.MenuPagerAdapter;
public class MenuView extends LinearLayout{
public MenuView(Context context) {
super(context);
}
public MenuView(Context context, AttributeSet attrs) {
super(context, attrs);
}
private Shop shop;
public void setShop(final Shop shop) {
this.shop = shop;
loadMenu();
}
private void loadMenu() {
LayoutInflater li = LayoutInflater.from(this.getContext());
// Add menu navigator
final RadioGroup menuNavigator = (RadioGroup) li.inflate(R.layout.menunavigator,
this, false);
+ int i = 0;
for (ItemCategory category : shop.getNavigatableMenuItemCategories()) {
RadioButton rb = (RadioButton) li.inflate(R.layout.menunavigatorbutton,
menuNavigator, false);
+ rb.setId(i++);
rb.setText(getContext().getResources().getString(getContext().getResources().getIdentifier(getContext().getPackageName() + ":string/" + category.toString(), null, null)));
menuNavigator.addView(rb);
}
// Add menu pager
final ViewPager menuPager = (ViewPager) li.inflate(R.layout.menupager,
this, false);
MenuPagerAdapter menuPagerAdapter = new MenuPagerAdapter(this.getContext(), shop);
menuPager.setAdapter(menuPagerAdapter);
menuPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int position) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int position) {
- if(menuNavigator.getCheckedRadioButtonId() != position + 1)
- menuNavigator.check(position + 1);
+ if(menuNavigator.getCheckedRadioButtonId() != position)
+ menuNavigator.check(position);
}
});
menuNavigator.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
- public void onCheckedChanged(RadioGroup view, int position) {
- if(menuPager.getCurrentItem() != position - 1)
- menuPager.setCurrentItem(position - 1);
+ public void onCheckedChanged(RadioGroup view, int checkedId) {
+ if(menuPager.getCurrentItem() != checkedId)
+ menuPager.setCurrentItem(checkedId);
}
});
this.addView(menuNavigator);
this.addView(menuPager);
- menuNavigator.check(1);
+ menuNavigator.check(0);
}
}
| false | true |
private void loadMenu() {
LayoutInflater li = LayoutInflater.from(this.getContext());
// Add menu navigator
final RadioGroup menuNavigator = (RadioGroup) li.inflate(R.layout.menunavigator,
this, false);
for (ItemCategory category : shop.getNavigatableMenuItemCategories()) {
RadioButton rb = (RadioButton) li.inflate(R.layout.menunavigatorbutton,
menuNavigator, false);
rb.setText(getContext().getResources().getString(getContext().getResources().getIdentifier(getContext().getPackageName() + ":string/" + category.toString(), null, null)));
menuNavigator.addView(rb);
}
// Add menu pager
final ViewPager menuPager = (ViewPager) li.inflate(R.layout.menupager,
this, false);
MenuPagerAdapter menuPagerAdapter = new MenuPagerAdapter(this.getContext(), shop);
menuPager.setAdapter(menuPagerAdapter);
menuPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int position) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int position) {
if(menuNavigator.getCheckedRadioButtonId() != position + 1)
menuNavigator.check(position + 1);
}
});
menuNavigator.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup view, int position) {
if(menuPager.getCurrentItem() != position - 1)
menuPager.setCurrentItem(position - 1);
}
});
this.addView(menuNavigator);
this.addView(menuPager);
menuNavigator.check(1);
}
|
private void loadMenu() {
LayoutInflater li = LayoutInflater.from(this.getContext());
// Add menu navigator
final RadioGroup menuNavigator = (RadioGroup) li.inflate(R.layout.menunavigator,
this, false);
int i = 0;
for (ItemCategory category : shop.getNavigatableMenuItemCategories()) {
RadioButton rb = (RadioButton) li.inflate(R.layout.menunavigatorbutton,
menuNavigator, false);
rb.setId(i++);
rb.setText(getContext().getResources().getString(getContext().getResources().getIdentifier(getContext().getPackageName() + ":string/" + category.toString(), null, null)));
menuNavigator.addView(rb);
}
// Add menu pager
final ViewPager menuPager = (ViewPager) li.inflate(R.layout.menupager,
this, false);
MenuPagerAdapter menuPagerAdapter = new MenuPagerAdapter(this.getContext(), shop);
menuPager.setAdapter(menuPagerAdapter);
menuPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int position) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int position) {
if(menuNavigator.getCheckedRadioButtonId() != position)
menuNavigator.check(position);
}
});
menuNavigator.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup view, int checkedId) {
if(menuPager.getCurrentItem() != checkedId)
menuPager.setCurrentItem(checkedId);
}
});
this.addView(menuNavigator);
this.addView(menuPager);
menuNavigator.check(0);
}
|
diff --git a/src/main/java/tschumacher/playground/sorters/TimedSorter.java b/src/main/java/tschumacher/playground/sorters/TimedSorter.java
index f09efa0..de8f706 100644
--- a/src/main/java/tschumacher/playground/sorters/TimedSorter.java
+++ b/src/main/java/tschumacher/playground/sorters/TimedSorter.java
@@ -1,33 +1,33 @@
package tschumacher.playground.sorters;
import tschumacher.playground.ArraySorter;
/**
* <p>A simple wrapper class that logs timing information for an array sorter implementation.</p>
*/
public class TimedSorter implements ArraySorter {
private final ArraySorter sorter;
/**
* <p>Create a new timed sorter.</p>
*
* @arg sorter The underlying sorting implementation. Cannot be null.
*/
public TimedSorter(ArraySorter sorter) {
if(sorter == null) {
throw new NullPointerException("The sorter cannot be null");
}
this.sorter = sorter;
}
@Override
public void sort(int[] arr) {
long a, b;
- a = System.getCurrentTime();
+ a = System.currentTimeMillis();
this.sorter.sort(arr);
- b = System.getCurrentTime();
+ b = System.currentTimeMillis();
System.out.println("Sorted in " + (b-a) + " millis.");
}
}
| false | true |
public void sort(int[] arr) {
long a, b;
a = System.getCurrentTime();
this.sorter.sort(arr);
b = System.getCurrentTime();
System.out.println("Sorted in " + (b-a) + " millis.");
}
|
public void sort(int[] arr) {
long a, b;
a = System.currentTimeMillis();
this.sorter.sort(arr);
b = System.currentTimeMillis();
System.out.println("Sorted in " + (b-a) + " millis.");
}
|
diff --git a/src/com/zavteam/plugins/RunnableMessager.java b/src/com/zavteam/plugins/RunnableMessager.java
index 054986c..b292c75 100644
--- a/src/com/zavteam/plugins/RunnableMessager.java
+++ b/src/com/zavteam/plugins/RunnableMessager.java
@@ -1,83 +1,88 @@
package com.zavteam.plugins;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.util.ChatPaginator;
public class RunnableMessager implements Runnable {
public ZavAutoMessager plugin;
public RunnableMessager(ZavAutoMessager plugin) {
this.plugin = plugin;
}
private int previousMessage;
private static ChatColor[] COLOR_LIST = {ChatColor.AQUA, ChatColor.BLACK, ChatColor.BLUE, ChatColor.DARK_AQUA, ChatColor.DARK_BLUE, ChatColor.DARK_GRAY,
ChatColor.DARK_GREEN, ChatColor.DARK_PURPLE, ChatColor.DARK_RED, ChatColor.GOLD, ChatColor.GRAY, ChatColor.GREEN, ChatColor.LIGHT_PURPLE,
ChatColor.RED, ChatColor.YELLOW};
@Override
public void run() {
boolean messageRandom = (Boolean) plugin.mainConfig.get("messageinrandomorder", false);
if ((Boolean) plugin.mainConfig.get("enabled", true)) {
String[] cutMessageList = new String[10];
if (plugin.messages.size() == 1) {
plugin.messageIt = 0;
} else {
if (messageRandom) {
plugin.messageIt = getRandomMessage();
}
}
ChatMessage cm = null;
try {
cm = plugin.messages.get(plugin.messageIt);
} catch (Exception e) {
e.printStackTrace();
ZavAutoMessager.log.severe("Cannot load messages. There is most likely an error with your config. Please check");
ZavAutoMessager.log.severe("Shutting down plugin.");
plugin.disableZavAutoMessager();
}
if (cm.isCommand()) {
cm.processAsCommand();
+ if (plugin.messageIt == plugin.messages.size() - 1) {
+ plugin.messageIt = 0;
+ } else {
+ plugin.messageIt = plugin.messageIt + 1;
+ }
return;
}
cutMessageList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cm.getMessage());
cutMessageList[0] = cutMessageList[0].replace("&random", getRandomChatColor());
cutMessageList[0] = ChatColor.translateAlternateColorCodes('&', cutMessageList[0]);
if ((Boolean) plugin.mainConfig.get("wordwrap", true)) {
cutMessageList = cutMessageList[0].split("%n");
} else {
cutMessageList = ChatPaginator.wordWrap(cutMessageList[0], 59);
}
plugin.MessagesHandler.handleChatMessage(cutMessageList, cm);
if (plugin.messageIt == plugin.messages.size() - 1) {
plugin.messageIt = 0;
} else {
plugin.messageIt = plugin.messageIt + 1;
}
}
}
private String getRandomChatColor() {
Random random = new Random();
return COLOR_LIST[random.nextInt(COLOR_LIST.length)].toString();
}
private int getRandomMessage() {
Random random = new Random();
if ((Boolean) plugin.mainConfig.get("dontrepeatrandommessages", true)) {
int i = random.nextInt(plugin.messages.size());
if (!(i == previousMessage)) {
previousMessage = i;
return i;
}
return getRandomMessage();
}
return random.nextInt(plugin.messages.size());
}
}
| true | true |
public void run() {
boolean messageRandom = (Boolean) plugin.mainConfig.get("messageinrandomorder", false);
if ((Boolean) plugin.mainConfig.get("enabled", true)) {
String[] cutMessageList = new String[10];
if (plugin.messages.size() == 1) {
plugin.messageIt = 0;
} else {
if (messageRandom) {
plugin.messageIt = getRandomMessage();
}
}
ChatMessage cm = null;
try {
cm = plugin.messages.get(plugin.messageIt);
} catch (Exception e) {
e.printStackTrace();
ZavAutoMessager.log.severe("Cannot load messages. There is most likely an error with your config. Please check");
ZavAutoMessager.log.severe("Shutting down plugin.");
plugin.disableZavAutoMessager();
}
if (cm.isCommand()) {
cm.processAsCommand();
return;
}
cutMessageList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cm.getMessage());
cutMessageList[0] = cutMessageList[0].replace("&random", getRandomChatColor());
cutMessageList[0] = ChatColor.translateAlternateColorCodes('&', cutMessageList[0]);
if ((Boolean) plugin.mainConfig.get("wordwrap", true)) {
cutMessageList = cutMessageList[0].split("%n");
} else {
cutMessageList = ChatPaginator.wordWrap(cutMessageList[0], 59);
}
plugin.MessagesHandler.handleChatMessage(cutMessageList, cm);
if (plugin.messageIt == plugin.messages.size() - 1) {
plugin.messageIt = 0;
} else {
plugin.messageIt = plugin.messageIt + 1;
}
}
}
|
public void run() {
boolean messageRandom = (Boolean) plugin.mainConfig.get("messageinrandomorder", false);
if ((Boolean) plugin.mainConfig.get("enabled", true)) {
String[] cutMessageList = new String[10];
if (plugin.messages.size() == 1) {
plugin.messageIt = 0;
} else {
if (messageRandom) {
plugin.messageIt = getRandomMessage();
}
}
ChatMessage cm = null;
try {
cm = plugin.messages.get(plugin.messageIt);
} catch (Exception e) {
e.printStackTrace();
ZavAutoMessager.log.severe("Cannot load messages. There is most likely an error with your config. Please check");
ZavAutoMessager.log.severe("Shutting down plugin.");
plugin.disableZavAutoMessager();
}
if (cm.isCommand()) {
cm.processAsCommand();
if (plugin.messageIt == plugin.messages.size() - 1) {
plugin.messageIt = 0;
} else {
plugin.messageIt = plugin.messageIt + 1;
}
return;
}
cutMessageList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cm.getMessage());
cutMessageList[0] = cutMessageList[0].replace("&random", getRandomChatColor());
cutMessageList[0] = ChatColor.translateAlternateColorCodes('&', cutMessageList[0]);
if ((Boolean) plugin.mainConfig.get("wordwrap", true)) {
cutMessageList = cutMessageList[0].split("%n");
} else {
cutMessageList = ChatPaginator.wordWrap(cutMessageList[0], 59);
}
plugin.MessagesHandler.handleChatMessage(cutMessageList, cm);
if (plugin.messageIt == plugin.messages.size() - 1) {
plugin.messageIt = 0;
} else {
plugin.messageIt = plugin.messageIt + 1;
}
}
}
|
diff --git a/mpicbg/ij/plugin/ElasticMontage.java b/mpicbg/ij/plugin/ElasticMontage.java
index 6555927..0e8a1ba 100644
--- a/mpicbg/ij/plugin/ElasticMontage.java
+++ b/mpicbg/ij/plugin/ElasticMontage.java
@@ -1,832 +1,832 @@
/**
* License: GPL
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License 2
* 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.
*
* 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 mpicbg.ij.plugin;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.WindowManager;
import ij.gui.GenericDialog;
import ij.io.DirectoryChooser;
import ij.plugin.PlugIn;
import ij.process.FloatProcessor;
import ij.process.ImageProcessor;
import java.awt.TextField;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import mpicbg.ij.SIFT;
import mpicbg.ij.TransformMeshMapping;
import mpicbg.ij.blockmatching.BlockMatching;
import mpicbg.imagefeatures.Feature;
import mpicbg.imagefeatures.FloatArray2DSIFT;
import mpicbg.models.AbstractModel;
import mpicbg.models.AffineModel2D;
import mpicbg.models.CoordinateTransformMesh;
import mpicbg.models.ErrorStatistic;
import mpicbg.models.HomographyModel2D;
import mpicbg.models.InvertibleCoordinateTransform;
import mpicbg.models.MovingLeastSquaresTransform;
import mpicbg.models.NotEnoughDataPointsException;
import mpicbg.models.PointMatch;
import mpicbg.models.RigidModel2D;
import mpicbg.models.SimilarityModel2D;
import mpicbg.models.Spring;
import mpicbg.models.SpringMesh;
import mpicbg.models.Tile;
import mpicbg.models.TileConfiguration;
import mpicbg.models.TranslationModel2D;
import mpicbg.models.Vertex;
import mpicbg.util.Util;
/**
* @author Stephan Saalfeld <[email protected]>
* @version 0.1a
*/
public class ElasticMontage implements PlugIn, KeyListener
{
final static private class Triple< A, B, C >
{
final public A a;
final public B b;
final public C c;
Triple( final A a, final B b, final C c )
{
this.a = a;
this.b = b;
this.c = c;
}
}
final static private class Param implements Serializable
{
private static final long serialVersionUID = 3816564377727147658L;
public String outputPath = "";
final public FloatArray2DSIFT.Param sift = new FloatArray2DSIFT.Param();
/**
* Closest/next closest neighbor distance ratio
*/
public float rod = 0.92f;
/**
* Maximal accepted alignment error in px
*/
public float maxEpsilon = 25.0f;
/**
* Inlier/candidates ratio
*/
public float minInlierRatio = 0.1f;
/**
* Minimal absolute number of inliers
*/
public int minNumInliers = 7;
/**
* Transformation models for choice
*/
final static public String[] modelStrings = new String[]{ "Translation", "Rigid", "Similarity", "Affine", "Perspective" };
public int modelIndex = 1;
/**
* Maximal number of consecutive slices for which no model could be found
*/
public int maxNumFailures = 3;
public int maxImageSize = 1024;
public float minR = 0.8f;
public float maxCurvatureR = 3f;
public float rodR = 0.8f;
public int modelIndexOptimize = 1;
public int maxIterationsOptimize = 1000;
public int maxPlateauwidthOptimize = 200;
public int resolutionSpringMesh = 16;
public float stiffnessSpringMesh = 0.1f;
public float dampSpringMesh = 0.6f;
public float maxStretchSpringMesh = 2000.0f;
public int maxIterationsSpringMesh = 1000;
public int maxPlateauwidthSpringMesh = 200;
public boolean interpolate = true;
public boolean visualize = true;
public int resolutionOutput = 128;
public int maxNumThreads = Runtime.getRuntime().availableProcessors();
public boolean setup()
{
DirectoryChooser.setDefaultDirectory( outputPath );
final DirectoryChooser dc = new DirectoryChooser( "Elastically align stack: Output directory" );
outputPath = dc.getDirectory();
if ( outputPath == null )
{
outputPath = "";
return false;
}
else
{
final File d = new File( p.outputPath );
if ( d.exists() && d.isDirectory() )
p.outputPath += "/";
else
return false;
}
final GenericDialog gdOutput = new GenericDialog( "Elastically align stack: Output" );
gdOutput.addCheckbox( "interpolate", p.interpolate );
gdOutput.addCheckbox( "visualize", p.visualize );
gdOutput.addNumericField( "resolution :", p.resolutionOutput, 0 );
gdOutput.showDialog();
if ( gdOutput.wasCanceled() )
return false;
p.interpolate = gdOutput.getNextBoolean();
p.visualize = gdOutput.getNextBoolean();
p.resolutionOutput = ( int )gdOutput.getNextNumber();
/* SIFT */
final GenericDialog gd = new GenericDialog( "Elastically align stack: SIFT parameters" );
SIFT.addFields( gd, sift );
gd.addNumericField( "closest/next_closest_ratio :", p.rod, 2 );
gd.addMessage( "Geometric Consensus Filter:" );
gd.addNumericField( "maximal_alignment_error :", p.maxEpsilon, 2, 6, "px" );
gd.addNumericField( "minimal_inlier_ratio :", p.minInlierRatio, 2 );
gd.addNumericField( "minimal_number_of_inliers :", p.minNumInliers, 0 );
gd.addChoice( "approximate_transformation :", Param.modelStrings, Param.modelStrings[ p.modelIndex ] );
gd.addMessage( "Matching:" );
gd.addNumericField( "give_up_after :", p.maxNumFailures, 0, 6, "failures" );
gd.showDialog();
if ( gd.wasCanceled() )
return false;
SIFT.readFields( gd, sift );
p.rod = ( float )gd.getNextNumber();
p.maxEpsilon = ( float )gd.getNextNumber();
p.minInlierRatio = ( float )gd.getNextNumber();
p.minNumInliers = ( int )gd.getNextNumber();
p.modelIndex = gd.getNextChoiceIndex();
p.maxNumFailures = ( int )gd.getNextNumber();
/* Block Matching */
final GenericDialog gdBlockMatching = new GenericDialog( "Elastically align stack: Block Matching parameters" );
gdBlockMatching.addMessage( "Block Matching:" );
gdBlockMatching.addNumericField( "maximal_image_size :", p.maxImageSize, 0, 6, "px" );
gdBlockMatching.addNumericField( "minimal_R :", p.minR, 2 );
gdBlockMatching.addNumericField( "maximal_curvature_factor :", p.maxCurvatureR, 2 );
gdBlockMatching.addNumericField( "closest/next_closest_ratio :", p.rodR, 2 );
gdBlockMatching.addNumericField( "resolution :", p.resolutionSpringMesh, 0 );
gdBlockMatching.showDialog();
if ( gdBlockMatching.wasCanceled() )
return false;
p.maxImageSize = ( int )gdBlockMatching.getNextNumber();
p.minR = ( float )gdBlockMatching.getNextNumber();
p.maxCurvatureR = ( float )gdBlockMatching.getNextNumber();
p.rodR = ( float )gdBlockMatching.getNextNumber();
p.resolutionSpringMesh = ( int )gdBlockMatching.getNextNumber();
/* Optimization */
final GenericDialog gdOptimize = new GenericDialog( "Elastically align stack: Optimization" );
gdOptimize.addMessage( "Approximate Optimizer:" );
gdOptimize.addChoice( "approximate_transformation :", Param.modelStrings, Param.modelStrings[ p.modelIndexOptimize ] );
gdOptimize.addNumericField( "maximal_iterations :", p.maxIterationsOptimize, 0 );
gdOptimize.addNumericField( "maximal_plateauwidth :", p.maxPlateauwidthOptimize, 0 );
gdOptimize.addMessage( "Spring Mesh:" );
gdOptimize.addNumericField( "stiffness :", p.stiffnessSpringMesh, 2 );
gdOptimize.addNumericField( "maximal_stretch :", p.maxStretchSpringMesh, 2, 6, "px" );
gdOptimize.addNumericField( "maximal_iterations :", p.maxIterationsSpringMesh, 0 );
gdOptimize.addNumericField( "maximal_plateauwidth :", p.maxPlateauwidthSpringMesh, 0 );
gdOptimize.showDialog();
if ( gdOptimize.wasCanceled() )
return false;
p.modelIndexOptimize = gdOptimize.getNextChoiceIndex();
p.maxIterationsOptimize = ( int )gdOptimize.getNextNumber();
p.maxPlateauwidthOptimize = ( int )gdOptimize.getNextNumber();
p.stiffnessSpringMesh = ( float )gdOptimize.getNextNumber();
p.maxStretchSpringMesh = ( float )gdOptimize.getNextNumber();
p.maxIterationsSpringMesh = ( int )gdOptimize.getNextNumber();
p.maxPlateauwidthSpringMesh = ( int )gdOptimize.getNextNumber();
return true;
}
public boolean equalSiftPointMatchParams( final Param param )
{
return sift.equals( param.sift )
&& maxEpsilon == param.maxEpsilon
&& minInlierRatio == param.minInlierRatio
&& minNumInliers == param.minNumInliers
&& modelIndex == param.modelIndex;
}
}
final static Param p = new Param();
final public void run( final String args )
{
if ( IJ.versionLessThan( "1.41n" ) ) return;
try { run(); }
catch ( Throwable t ) { t.printStackTrace(); }
}
final public void run() throws Exception
{
final ImagePlus imp = WindowManager.getCurrentImage();
if ( imp == null ) { System.err.println( "There are no images open" ); return; }
if ( !p.setup() ) return;
final ImageStack stack = imp.getStack();
final double displayRangeMin = imp.getDisplayRangeMin();
final double displayRangeMax = imp.getDisplayRangeMax();
final ArrayList< Tile< ? > > tiles = new ArrayList< Tile<?> >();
for ( int i = 0; i < stack.getSize(); ++i )
{
switch ( p.modelIndexOptimize )
{
case 0:
tiles.add( new Tile< TranslationModel2D >( new TranslationModel2D() ) );
break;
case 1:
tiles.add( new Tile< RigidModel2D >( new RigidModel2D() ) );
break;
case 2:
tiles.add( new Tile< SimilarityModel2D >( new SimilarityModel2D() ) );
break;
case 3:
tiles.add( new Tile< AffineModel2D >( new AffineModel2D() ) );
break;
case 4:
tiles.add( new Tile< HomographyModel2D >( new HomographyModel2D() ) );
break;
default:
return;
}
}
final ExecutorService exec = Executors.newFixedThreadPool( p.maxNumThreads );
/* extract features for all slices and store them to disk */
final AtomicInteger counter = new AtomicInteger( 0 );
final ArrayList< Future< ArrayList< Feature > > > siftTasks = new ArrayList< Future< ArrayList< Feature > > >();
for ( int i = 1; i <= stack.getSize(); i++ )
{
final int slice = i;
siftTasks.add(
exec.submit( new Callable< ArrayList< Feature > >()
{
public ArrayList< Feature > call()
{
IJ.showProgress( counter.getAndIncrement(), stack.getSize() );
//final String path = p.outputPath + stack.getSliceLabel( slice ) + ".features";
final String path = p.outputPath + String.format( "%05d", slice - 1 ) + ".features";
ArrayList< Feature > fs = deserializeFeatures( p.sift, path );
if ( null == fs )
{
final FloatArray2DSIFT sift = new FloatArray2DSIFT( p.sift );
final SIFT ijSIFT = new SIFT( sift );
fs = new ArrayList< Feature >();
final ImageProcessor ip = stack.getProcessor( slice );
ip.setMinAndMax( displayRangeMin, displayRangeMax );
ijSIFT.extractFeatures( ip, fs );
if ( ! serializeFeatures( p.sift, fs, path ) )
{
//IJ.log( "FAILED to store serialized features for " + stack.getSliceLabel( slice ) );
IJ.log( "FAILED to store serialized features for " + String.format( "%05d", slice - 1 ) );
}
}
//IJ.log( fs.size() + " features extracted for slice " + stack.getSliceLabel ( slice ) );
IJ.log( fs.size() + " features extracted for slice " + String.format( "%05d", slice - 1 ) );
return fs;
}
} ) );
}
/* join */
for ( Future< ArrayList< Feature > > fu : siftTasks )
fu.get();
/* collect all pairs of slices for which a model could be found */
final ArrayList< Triple< Integer, Integer, AbstractModel< ? > > > pairs = new ArrayList< Triple< Integer, Integer, AbstractModel< ? > > >();
counter.set( 0 );
int numFailures = 0;
for ( int i = 0; i < stack.getSize(); ++i )
{
final ArrayList< Thread > threads = new ArrayList< Thread >( p.maxNumThreads );
final int sliceA = i;
J: for ( int j = i + 1; j < stack.getSize(); )
{
final int numThreads = Math.min( p.maxNumThreads, stack.getSize() - j );
final ArrayList< Triple< Integer, Integer, AbstractModel< ? > > > models =
new ArrayList< Triple< Integer, Integer, AbstractModel< ? > > >( numThreads );
for ( int k = 0; k < numThreads; ++k )
models.add( null );
for ( int t = 0; t < p.maxNumThreads && j < stack.getSize(); ++t, ++j )
{
final int sliceB = j;
final int ti = t;
final Thread thread = new Thread()
{
public void run()
{
IJ.showProgress( counter.getAndIncrement(), stack.getSize() - 1 );
IJ.log( "matching " + sliceB + " -> " + sliceA + "..." );
//String path = p.outputPath + stack.getSliceLabel( slice ) + ".pointmatches";
String path = p.outputPath + String.format( "%05d", sliceB ) + "-" + String.format( "%05d", sliceA ) + ".pointmatches";
ArrayList< PointMatch > candidates = deserializePointMatches( p, path );
if ( null == candidates )
{
//ArrayList< Feature > fs1 = deserializeFeatures( p.sift, p.outputPath + stack.getSliceLabel( slice - 1 ) + ".features" );
ArrayList< Feature > fs1 = deserializeFeatures( p.sift, p.outputPath + String.format( "%05d", sliceA ) + ".features" );
//ArrayList< Feature > fs2 = deserializeFeatures( p.sift, p.outputPath + stack.getSliceLabel( slice ) + ".features" );
ArrayList< Feature > fs2 = deserializeFeatures( p.sift, p.outputPath + String.format( "%05d", sliceB ) + ".features" );
candidates = new ArrayList< PointMatch >( FloatArray2DSIFT.createMatches( fs2, fs1, p.rod ) );
if ( !serializePointMatches( p, candidates, path ) )
IJ.log( "Could not store point matches!" );
}
AbstractModel< ? > model;
switch ( p.modelIndex )
{
case 0:
model = new TranslationModel2D();
break;
case 1:
model = new RigidModel2D();
break;
case 2:
model = new SimilarityModel2D();
break;
case 3:
model = new AffineModel2D();
break;
case 4:
model = new HomographyModel2D();
break;
default:
return;
}
final ArrayList< PointMatch > inliers = new ArrayList< PointMatch >();
boolean modelFound;
try
{
modelFound = model.filterRansac(
candidates,
inliers,
1000,
p.maxEpsilon,
p.minInlierRatio,
p.minNumInliers );
}
catch ( Exception e )
{
modelFound = false;
System.err.println( e.getMessage() );
}
if ( modelFound )
{
IJ.log( sliceB + " -> " + sliceA + ": " + inliers.size() + " corresponding features with an average displacement of " + PointMatch.meanDistance( inliers ) + "px identified." );
IJ.log( "Estimated transformation model: " + model );
models.set( ti, new Triple< Integer, Integer, AbstractModel< ? > >( sliceA, sliceB, model ) );
}
else
{
IJ.log( sliceB + " -> " + sliceA + ": no correspondences found." );
return;
}
}
};
threads.add( thread );
thread.start();
}
for ( final Thread thread : threads )
{
thread.join();
}
/* collect successfully matches pairs and break the search on gaps */
for ( int t = 0; t < models.size(); ++t )
{
final Triple< Integer, Integer, AbstractModel< ? > > pair = models.get( t );
if ( pair == null )
{
if ( ++numFailures > p.maxNumFailures )
break J;
}
else
{
numFailures = 0;
pairs.add( pair );
}
}
}
}
/* Elastic alignment */
/* Initialization */
final TileConfiguration initMeshes = new TileConfiguration();
initMeshes.addTiles( tiles );
final ArrayList< SpringMesh > meshes = new ArrayList< SpringMesh >( stack.getSize() );
for ( int i = 0; i < stack.getSize(); ++i )
meshes.add( new SpringMesh( p.resolutionSpringMesh, stack.getWidth(), stack.getHeight(), p.stiffnessSpringMesh, p.maxStretchSpringMesh, p.dampSpringMesh ) );
final int blockRadius = Math.max( 32, stack.getWidth() / p.resolutionSpringMesh / 2 );
/** TODO set this something more than the largest error by the approximate model */
final int searchRadius = Math.round( p.maxEpsilon );
for ( final Triple< Integer, Integer, AbstractModel< ? > > pair : pairs )
{
final SpringMesh m1 = meshes.get( pair.a );
final SpringMesh m2 = meshes.get( pair.b );
ArrayList< PointMatch > pm12 = new ArrayList< PointMatch >();
ArrayList< PointMatch > pm21 = new ArrayList< PointMatch >();
final Collection< Vertex > v1 = m1.getVertices();
final Collection< Vertex > v2 = m2.getVertices();
final FloatProcessor ip1 = ( FloatProcessor )stack.getProcessor( pair.a + 1 ).convertToFloat().duplicate();
final FloatProcessor ip2 = ( FloatProcessor )stack.getProcessor( pair.b + 1 ).convertToFloat().duplicate();
BlockMatching.matchByMaximalPMCC(
ip1,
ip2,
Math.min( 1.0f, ( float )p.maxImageSize / ip1.getWidth() ),
( ( InvertibleCoordinateTransform )pair.c ).createInverse(),
blockRadius,
blockRadius,
searchRadius,
searchRadius,
p.minR,
p.rodR,
p.maxCurvatureR,
v1,
pm12,
new ErrorStatistic( 1 ) );
IJ.log( pair.a + " > " + pair.b + ": found " + pm12.size() + " correspondences." );
/* <visualisation> */
// final List< Point > s1 = new ArrayList< Point >();
// PointMatch.sourcePoints( pm12, s1 );
// final ImagePlus imp1 = new ImagePlus( i + " >", ip1 );
// imp1.show();
// imp1.setOverlay( BlockMatching.illustrateMatches( pm12 ), Color.yellow, null );
// imp1.setRoi( Util.pointsToPointRoi( s1 ) );
// imp1.updateAndDraw();
/* </visualisation> */
BlockMatching.matchByMaximalPMCC(
ip2,
ip1,
Math.min( 1.0f, ( float )p.maxImageSize / ip1.getWidth() ),
pair.c,
blockRadius,
blockRadius,
searchRadius,
searchRadius,
p.minR,
p.rodR,
p.maxCurvatureR,
v2,
pm21,
new ErrorStatistic( 1 ) );
IJ.log( pair.a + " < " + pair.b + ": found " + pm21.size() + " correspondences." );
/* <visualisation> */
// final List< Point > s2 = new ArrayList< Point >();
// PointMatch.sourcePoints( pm21, s2 );
// final ImagePlus imp2 = new ImagePlus( i + " <", ip2 );
// imp2.show();
// imp2.setOverlay( BlockMatching.illustrateMatches( pm21 ), Color.yellow, null );
// imp2.setRoi( Util.pointsToPointRoi( s2 ) );
// imp2.updateAndDraw();
/* </visualisation> */
final float springConstant = 1.0f / ( pair.b - pair.a );
IJ.log( pair.a + " <> " + pair.b );
for ( final PointMatch pm : pm12 )
{
final Vertex p1 = ( Vertex )pm.getP1();
final Vertex p2 = new Vertex( pm.getP2() );
p1.addSpring( p2, new Spring( 0, 1.0f ) );
m2.addPassiveVertex( p2 );
}
for ( final PointMatch pm : pm21 )
{
final Vertex p1 = ( Vertex )pm.getP1();
final Vertex p2 = new Vertex( pm.getP2() );
p1.addSpring( p2, new Spring( 0, 1.0f ) );
m1.addPassiveVertex( p2 );
}
final Tile< ? > t1 = tiles.get( pair.a );
final Tile< ? > t2 = tiles.get( pair.b );
if ( pm12.size() > pair.c.getMinNumMatches() )
t1.connect( t2, pm12 );
if ( pm21.size() > pair.c.getMinNumMatches() )
t2.connect( t1, pm21 );
}
/* initialize meshes */
/* TODO this is accumulative and thus not perfect, change to analytical concatenation later */
// for ( int i = 1; i < stack.getSize(); ++i )
// {
// final CoordinateTransformList< CoordinateTransform > ctl = new CoordinateTransformList< CoordinateTransform >();
// for ( int j = 0; j < i; ++j )
// {
// for ( final Triple< Integer, Integer, AbstractModel< ? > > pair : pairs )
// {
// if ( pair.a == j && pair.b == i )
// {
// ctl.add( pair.c );
// break;
// }
// }
// }
// meshes[ i ].init( ctl );
// }
initMeshes.optimize( p.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh );
for ( int i = 0; i < stack.getSize(); ++i )
meshes.get( i ).init( tiles.get( i ).getModel() );
/* optimize */
try
{
long t0 = System.currentTimeMillis();
IJ.log("Optimizing spring meshes...");
SpringMesh.optimizeMeshes( meshes, p.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh, p.visualize );
IJ.log("Done optimizing spring meshes. Took " + (System.currentTimeMillis() - t0) + " ms");
}
catch ( NotEnoughDataPointsException e ) { e.printStackTrace(); }
/* calculate bounding box */
final float[] min = new float[ 2 ];
final float[] max = new float[ 2 ];
for ( final SpringMesh mesh : meshes )
{
final float[] meshMin = new float[ 2 ];
final float[] meshMax = new float[ 2 ];
mesh.bounds( meshMin, meshMax );
Util.min( min, meshMin );
Util.max( max, meshMax );
}
/* translate relative to bounding box */
for ( final SpringMesh mesh : meshes )
{
for ( final Vertex vertex : mesh.getVertices() )
{
final float[] w = vertex.getW();
w[ 0 ] -= min[ 0 ];
w[ 1 ] -= min[ 1 ];
}
mesh.updateAffines();
mesh.updatePassiveVertices();
}
//final ImageStack stackAlignedMeshes = new ImageStack( ( int )Math.ceil( max[ 0 ] - min[ 0 ] ), ( int )Math.ceil( max[ 1 ] - min[ 1 ] ) );
final int width = ( int )Math.ceil( max[ 0 ] - min[ 0 ] );
final int height = ( int )Math.ceil( max[ 1 ] - min[ 1 ] );
- final ImageProcessor ip = stack.getProcessor( 0 ).createProcessor( width, height );
+ final ImageProcessor ip = stack.getProcessor( 1 ).createProcessor( width, height );
for ( int i = 0; i < stack.getSize(); ++i )
{
final int slice = i + 1;
// final TransformMeshMapping< SpringMesh > meshMapping = new TransformMeshMapping< SpringMesh >( meshes[ i - 1 ] );
final MovingLeastSquaresTransform mlt = new MovingLeastSquaresTransform();
mlt.setModel( AffineModel2D.class );
mlt.setAlpha( 2.0f );
mlt.setMatches( meshes.get( i ).getVA().keySet() );
final TransformMeshMapping< CoordinateTransformMesh > mltMapping = new TransformMeshMapping< CoordinateTransformMesh >( new CoordinateTransformMesh( mlt, p.resolutionOutput, width, height ) );
// final ImageProcessor ipMesh = stack.getProcessor( slice ).createProcessor( width, height );
if ( p.interpolate )
{
// meshMapping.mapInterpolated( stack.getProcessor( slice ), ipMesh );
mltMapping.mapInterpolated( stack.getProcessor( slice ), ip );
}
else
{
// meshMapping.map( stack.getProcessor( slice ), ipMesh );
mltMapping.map( stack.getProcessor( slice ), ip );
}
// IJ.save( new ImagePlus( "elastic " + i, ipMesh ), p.outputPath + "elastic-" + String.format( "%05d", i ) + ".tif" );
//stackAlignedMeshes.addSlice( "" + i, ip );
}
IJ.save( new ImagePlus( "elastic mlt montage", ip ), p.outputPath + "elastic-mlt-montage.tif" );
IJ.log( "Done." );
}
public void keyPressed(KeyEvent e)
{
if (
( e.getKeyCode() == KeyEvent.VK_F1 ) &&
( e.getSource() instanceof TextField ) )
{
}
}
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
final static private class Features implements Serializable
{
private static final long serialVersionUID = 2689219384710526198L;
final FloatArray2DSIFT.Param param;
final ArrayList< Feature > features;
Features( final FloatArray2DSIFT.Param p, final ArrayList< Feature > features )
{
this.param = p;
this.features = features;
}
}
final static private boolean serializeFeatures(
final FloatArray2DSIFT.Param param,
final ArrayList< Feature > fs,
final String path )
{
return serialize( new Features( param, fs ), path );
}
final static private ArrayList< Feature > deserializeFeatures( final FloatArray2DSIFT.Param param, final String path )
{
Object o = deserialize( path );
if ( null == o ) return null;
Features fs = (Features) o;
if ( param.equals( fs.param ) )
return fs.features;
return null;
}
final static private class PointMatches implements Serializable
{
private static final long serialVersionUID = -2564147268101223484L;
ElasticMontage.Param param;
ArrayList< PointMatch > pointMatches;
PointMatches( final ElasticMontage.Param p, final ArrayList< PointMatch > pointMatches )
{
this.param = p;
this.pointMatches = pointMatches;
}
}
final static private boolean serializePointMatches(
final ElasticMontage.Param param,
final ArrayList< PointMatch > pms,
final String path )
{
return serialize( new PointMatches( param, pms ), path );
}
final static private ArrayList< PointMatch > deserializePointMatches( final ElasticMontage.Param param, final String path )
{
Object o = deserialize( path );
if ( null == o ) return null;
PointMatches pms = (PointMatches) o;
if ( param.equalSiftPointMatchParams( pms.param ) )
return pms.pointMatches;
return null;
}
/** Serializes the given object into the path. Returns false on failure. */
static public boolean serialize(final Object ob, final String path) {
try {
// 1 - Check that the parent chain of folders exists, and attempt to create it when not:
File fdir = new File(path).getParentFile();
if (null == fdir) return false;
fdir.mkdirs();
if (!fdir.exists()) {
IJ.log("Could not create folder " + fdir.getAbsolutePath());
return false;
}
// 2 - Serialize the given object:
final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path));
out.writeObject(ob);
out.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/** Attempts to find a file containing a serialized object. Returns null if no suitable file is found, or an error occurs while deserializing. */
static public Object deserialize(final String path) {
try {
if (!new File(path).exists()) return null;
final ObjectInputStream in = new ObjectInputStream(new FileInputStream(path));
final Object ob = in.readObject();
in.close();
return ob;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| true | true |
final public void run() throws Exception
{
final ImagePlus imp = WindowManager.getCurrentImage();
if ( imp == null ) { System.err.println( "There are no images open" ); return; }
if ( !p.setup() ) return;
final ImageStack stack = imp.getStack();
final double displayRangeMin = imp.getDisplayRangeMin();
final double displayRangeMax = imp.getDisplayRangeMax();
final ArrayList< Tile< ? > > tiles = new ArrayList< Tile<?> >();
for ( int i = 0; i < stack.getSize(); ++i )
{
switch ( p.modelIndexOptimize )
{
case 0:
tiles.add( new Tile< TranslationModel2D >( new TranslationModel2D() ) );
break;
case 1:
tiles.add( new Tile< RigidModel2D >( new RigidModel2D() ) );
break;
case 2:
tiles.add( new Tile< SimilarityModel2D >( new SimilarityModel2D() ) );
break;
case 3:
tiles.add( new Tile< AffineModel2D >( new AffineModel2D() ) );
break;
case 4:
tiles.add( new Tile< HomographyModel2D >( new HomographyModel2D() ) );
break;
default:
return;
}
}
final ExecutorService exec = Executors.newFixedThreadPool( p.maxNumThreads );
/* extract features for all slices and store them to disk */
final AtomicInteger counter = new AtomicInteger( 0 );
final ArrayList< Future< ArrayList< Feature > > > siftTasks = new ArrayList< Future< ArrayList< Feature > > >();
for ( int i = 1; i <= stack.getSize(); i++ )
{
final int slice = i;
siftTasks.add(
exec.submit( new Callable< ArrayList< Feature > >()
{
public ArrayList< Feature > call()
{
IJ.showProgress( counter.getAndIncrement(), stack.getSize() );
//final String path = p.outputPath + stack.getSliceLabel( slice ) + ".features";
final String path = p.outputPath + String.format( "%05d", slice - 1 ) + ".features";
ArrayList< Feature > fs = deserializeFeatures( p.sift, path );
if ( null == fs )
{
final FloatArray2DSIFT sift = new FloatArray2DSIFT( p.sift );
final SIFT ijSIFT = new SIFT( sift );
fs = new ArrayList< Feature >();
final ImageProcessor ip = stack.getProcessor( slice );
ip.setMinAndMax( displayRangeMin, displayRangeMax );
ijSIFT.extractFeatures( ip, fs );
if ( ! serializeFeatures( p.sift, fs, path ) )
{
//IJ.log( "FAILED to store serialized features for " + stack.getSliceLabel( slice ) );
IJ.log( "FAILED to store serialized features for " + String.format( "%05d", slice - 1 ) );
}
}
//IJ.log( fs.size() + " features extracted for slice " + stack.getSliceLabel ( slice ) );
IJ.log( fs.size() + " features extracted for slice " + String.format( "%05d", slice - 1 ) );
return fs;
}
} ) );
}
/* join */
for ( Future< ArrayList< Feature > > fu : siftTasks )
fu.get();
/* collect all pairs of slices for which a model could be found */
final ArrayList< Triple< Integer, Integer, AbstractModel< ? > > > pairs = new ArrayList< Triple< Integer, Integer, AbstractModel< ? > > >();
counter.set( 0 );
int numFailures = 0;
for ( int i = 0; i < stack.getSize(); ++i )
{
final ArrayList< Thread > threads = new ArrayList< Thread >( p.maxNumThreads );
final int sliceA = i;
J: for ( int j = i + 1; j < stack.getSize(); )
{
final int numThreads = Math.min( p.maxNumThreads, stack.getSize() - j );
final ArrayList< Triple< Integer, Integer, AbstractModel< ? > > > models =
new ArrayList< Triple< Integer, Integer, AbstractModel< ? > > >( numThreads );
for ( int k = 0; k < numThreads; ++k )
models.add( null );
for ( int t = 0; t < p.maxNumThreads && j < stack.getSize(); ++t, ++j )
{
final int sliceB = j;
final int ti = t;
final Thread thread = new Thread()
{
public void run()
{
IJ.showProgress( counter.getAndIncrement(), stack.getSize() - 1 );
IJ.log( "matching " + sliceB + " -> " + sliceA + "..." );
//String path = p.outputPath + stack.getSliceLabel( slice ) + ".pointmatches";
String path = p.outputPath + String.format( "%05d", sliceB ) + "-" + String.format( "%05d", sliceA ) + ".pointmatches";
ArrayList< PointMatch > candidates = deserializePointMatches( p, path );
if ( null == candidates )
{
//ArrayList< Feature > fs1 = deserializeFeatures( p.sift, p.outputPath + stack.getSliceLabel( slice - 1 ) + ".features" );
ArrayList< Feature > fs1 = deserializeFeatures( p.sift, p.outputPath + String.format( "%05d", sliceA ) + ".features" );
//ArrayList< Feature > fs2 = deserializeFeatures( p.sift, p.outputPath + stack.getSliceLabel( slice ) + ".features" );
ArrayList< Feature > fs2 = deserializeFeatures( p.sift, p.outputPath + String.format( "%05d", sliceB ) + ".features" );
candidates = new ArrayList< PointMatch >( FloatArray2DSIFT.createMatches( fs2, fs1, p.rod ) );
if ( !serializePointMatches( p, candidates, path ) )
IJ.log( "Could not store point matches!" );
}
AbstractModel< ? > model;
switch ( p.modelIndex )
{
case 0:
model = new TranslationModel2D();
break;
case 1:
model = new RigidModel2D();
break;
case 2:
model = new SimilarityModel2D();
break;
case 3:
model = new AffineModel2D();
break;
case 4:
model = new HomographyModel2D();
break;
default:
return;
}
final ArrayList< PointMatch > inliers = new ArrayList< PointMatch >();
boolean modelFound;
try
{
modelFound = model.filterRansac(
candidates,
inliers,
1000,
p.maxEpsilon,
p.minInlierRatio,
p.minNumInliers );
}
catch ( Exception e )
{
modelFound = false;
System.err.println( e.getMessage() );
}
if ( modelFound )
{
IJ.log( sliceB + " -> " + sliceA + ": " + inliers.size() + " corresponding features with an average displacement of " + PointMatch.meanDistance( inliers ) + "px identified." );
IJ.log( "Estimated transformation model: " + model );
models.set( ti, new Triple< Integer, Integer, AbstractModel< ? > >( sliceA, sliceB, model ) );
}
else
{
IJ.log( sliceB + " -> " + sliceA + ": no correspondences found." );
return;
}
}
};
threads.add( thread );
thread.start();
}
for ( final Thread thread : threads )
{
thread.join();
}
/* collect successfully matches pairs and break the search on gaps */
for ( int t = 0; t < models.size(); ++t )
{
final Triple< Integer, Integer, AbstractModel< ? > > pair = models.get( t );
if ( pair == null )
{
if ( ++numFailures > p.maxNumFailures )
break J;
}
else
{
numFailures = 0;
pairs.add( pair );
}
}
}
}
/* Elastic alignment */
/* Initialization */
final TileConfiguration initMeshes = new TileConfiguration();
initMeshes.addTiles( tiles );
final ArrayList< SpringMesh > meshes = new ArrayList< SpringMesh >( stack.getSize() );
for ( int i = 0; i < stack.getSize(); ++i )
meshes.add( new SpringMesh( p.resolutionSpringMesh, stack.getWidth(), stack.getHeight(), p.stiffnessSpringMesh, p.maxStretchSpringMesh, p.dampSpringMesh ) );
final int blockRadius = Math.max( 32, stack.getWidth() / p.resolutionSpringMesh / 2 );
/** TODO set this something more than the largest error by the approximate model */
final int searchRadius = Math.round( p.maxEpsilon );
for ( final Triple< Integer, Integer, AbstractModel< ? > > pair : pairs )
{
final SpringMesh m1 = meshes.get( pair.a );
final SpringMesh m2 = meshes.get( pair.b );
ArrayList< PointMatch > pm12 = new ArrayList< PointMatch >();
ArrayList< PointMatch > pm21 = new ArrayList< PointMatch >();
final Collection< Vertex > v1 = m1.getVertices();
final Collection< Vertex > v2 = m2.getVertices();
final FloatProcessor ip1 = ( FloatProcessor )stack.getProcessor( pair.a + 1 ).convertToFloat().duplicate();
final FloatProcessor ip2 = ( FloatProcessor )stack.getProcessor( pair.b + 1 ).convertToFloat().duplicate();
BlockMatching.matchByMaximalPMCC(
ip1,
ip2,
Math.min( 1.0f, ( float )p.maxImageSize / ip1.getWidth() ),
( ( InvertibleCoordinateTransform )pair.c ).createInverse(),
blockRadius,
blockRadius,
searchRadius,
searchRadius,
p.minR,
p.rodR,
p.maxCurvatureR,
v1,
pm12,
new ErrorStatistic( 1 ) );
IJ.log( pair.a + " > " + pair.b + ": found " + pm12.size() + " correspondences." );
/* <visualisation> */
// final List< Point > s1 = new ArrayList< Point >();
// PointMatch.sourcePoints( pm12, s1 );
// final ImagePlus imp1 = new ImagePlus( i + " >", ip1 );
// imp1.show();
// imp1.setOverlay( BlockMatching.illustrateMatches( pm12 ), Color.yellow, null );
// imp1.setRoi( Util.pointsToPointRoi( s1 ) );
// imp1.updateAndDraw();
/* </visualisation> */
BlockMatching.matchByMaximalPMCC(
ip2,
ip1,
Math.min( 1.0f, ( float )p.maxImageSize / ip1.getWidth() ),
pair.c,
blockRadius,
blockRadius,
searchRadius,
searchRadius,
p.minR,
p.rodR,
p.maxCurvatureR,
v2,
pm21,
new ErrorStatistic( 1 ) );
IJ.log( pair.a + " < " + pair.b + ": found " + pm21.size() + " correspondences." );
/* <visualisation> */
// final List< Point > s2 = new ArrayList< Point >();
// PointMatch.sourcePoints( pm21, s2 );
// final ImagePlus imp2 = new ImagePlus( i + " <", ip2 );
// imp2.show();
// imp2.setOverlay( BlockMatching.illustrateMatches( pm21 ), Color.yellow, null );
// imp2.setRoi( Util.pointsToPointRoi( s2 ) );
// imp2.updateAndDraw();
/* </visualisation> */
final float springConstant = 1.0f / ( pair.b - pair.a );
IJ.log( pair.a + " <> " + pair.b );
for ( final PointMatch pm : pm12 )
{
final Vertex p1 = ( Vertex )pm.getP1();
final Vertex p2 = new Vertex( pm.getP2() );
p1.addSpring( p2, new Spring( 0, 1.0f ) );
m2.addPassiveVertex( p2 );
}
for ( final PointMatch pm : pm21 )
{
final Vertex p1 = ( Vertex )pm.getP1();
final Vertex p2 = new Vertex( pm.getP2() );
p1.addSpring( p2, new Spring( 0, 1.0f ) );
m1.addPassiveVertex( p2 );
}
final Tile< ? > t1 = tiles.get( pair.a );
final Tile< ? > t2 = tiles.get( pair.b );
if ( pm12.size() > pair.c.getMinNumMatches() )
t1.connect( t2, pm12 );
if ( pm21.size() > pair.c.getMinNumMatches() )
t2.connect( t1, pm21 );
}
/* initialize meshes */
/* TODO this is accumulative and thus not perfect, change to analytical concatenation later */
// for ( int i = 1; i < stack.getSize(); ++i )
// {
// final CoordinateTransformList< CoordinateTransform > ctl = new CoordinateTransformList< CoordinateTransform >();
// for ( int j = 0; j < i; ++j )
// {
// for ( final Triple< Integer, Integer, AbstractModel< ? > > pair : pairs )
// {
// if ( pair.a == j && pair.b == i )
// {
// ctl.add( pair.c );
// break;
// }
// }
// }
// meshes[ i ].init( ctl );
// }
initMeshes.optimize( p.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh );
for ( int i = 0; i < stack.getSize(); ++i )
meshes.get( i ).init( tiles.get( i ).getModel() );
/* optimize */
try
{
long t0 = System.currentTimeMillis();
IJ.log("Optimizing spring meshes...");
SpringMesh.optimizeMeshes( meshes, p.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh, p.visualize );
IJ.log("Done optimizing spring meshes. Took " + (System.currentTimeMillis() - t0) + " ms");
}
catch ( NotEnoughDataPointsException e ) { e.printStackTrace(); }
/* calculate bounding box */
final float[] min = new float[ 2 ];
final float[] max = new float[ 2 ];
for ( final SpringMesh mesh : meshes )
{
final float[] meshMin = new float[ 2 ];
final float[] meshMax = new float[ 2 ];
mesh.bounds( meshMin, meshMax );
Util.min( min, meshMin );
Util.max( max, meshMax );
}
/* translate relative to bounding box */
for ( final SpringMesh mesh : meshes )
{
for ( final Vertex vertex : mesh.getVertices() )
{
final float[] w = vertex.getW();
w[ 0 ] -= min[ 0 ];
w[ 1 ] -= min[ 1 ];
}
mesh.updateAffines();
mesh.updatePassiveVertices();
}
//final ImageStack stackAlignedMeshes = new ImageStack( ( int )Math.ceil( max[ 0 ] - min[ 0 ] ), ( int )Math.ceil( max[ 1 ] - min[ 1 ] ) );
final int width = ( int )Math.ceil( max[ 0 ] - min[ 0 ] );
final int height = ( int )Math.ceil( max[ 1 ] - min[ 1 ] );
final ImageProcessor ip = stack.getProcessor( 0 ).createProcessor( width, height );
for ( int i = 0; i < stack.getSize(); ++i )
{
final int slice = i + 1;
// final TransformMeshMapping< SpringMesh > meshMapping = new TransformMeshMapping< SpringMesh >( meshes[ i - 1 ] );
final MovingLeastSquaresTransform mlt = new MovingLeastSquaresTransform();
mlt.setModel( AffineModel2D.class );
mlt.setAlpha( 2.0f );
mlt.setMatches( meshes.get( i ).getVA().keySet() );
final TransformMeshMapping< CoordinateTransformMesh > mltMapping = new TransformMeshMapping< CoordinateTransformMesh >( new CoordinateTransformMesh( mlt, p.resolutionOutput, width, height ) );
// final ImageProcessor ipMesh = stack.getProcessor( slice ).createProcessor( width, height );
if ( p.interpolate )
{
// meshMapping.mapInterpolated( stack.getProcessor( slice ), ipMesh );
mltMapping.mapInterpolated( stack.getProcessor( slice ), ip );
}
else
{
// meshMapping.map( stack.getProcessor( slice ), ipMesh );
mltMapping.map( stack.getProcessor( slice ), ip );
}
// IJ.save( new ImagePlus( "elastic " + i, ipMesh ), p.outputPath + "elastic-" + String.format( "%05d", i ) + ".tif" );
//stackAlignedMeshes.addSlice( "" + i, ip );
}
IJ.save( new ImagePlus( "elastic mlt montage", ip ), p.outputPath + "elastic-mlt-montage.tif" );
IJ.log( "Done." );
}
|
final public void run() throws Exception
{
final ImagePlus imp = WindowManager.getCurrentImage();
if ( imp == null ) { System.err.println( "There are no images open" ); return; }
if ( !p.setup() ) return;
final ImageStack stack = imp.getStack();
final double displayRangeMin = imp.getDisplayRangeMin();
final double displayRangeMax = imp.getDisplayRangeMax();
final ArrayList< Tile< ? > > tiles = new ArrayList< Tile<?> >();
for ( int i = 0; i < stack.getSize(); ++i )
{
switch ( p.modelIndexOptimize )
{
case 0:
tiles.add( new Tile< TranslationModel2D >( new TranslationModel2D() ) );
break;
case 1:
tiles.add( new Tile< RigidModel2D >( new RigidModel2D() ) );
break;
case 2:
tiles.add( new Tile< SimilarityModel2D >( new SimilarityModel2D() ) );
break;
case 3:
tiles.add( new Tile< AffineModel2D >( new AffineModel2D() ) );
break;
case 4:
tiles.add( new Tile< HomographyModel2D >( new HomographyModel2D() ) );
break;
default:
return;
}
}
final ExecutorService exec = Executors.newFixedThreadPool( p.maxNumThreads );
/* extract features for all slices and store them to disk */
final AtomicInteger counter = new AtomicInteger( 0 );
final ArrayList< Future< ArrayList< Feature > > > siftTasks = new ArrayList< Future< ArrayList< Feature > > >();
for ( int i = 1; i <= stack.getSize(); i++ )
{
final int slice = i;
siftTasks.add(
exec.submit( new Callable< ArrayList< Feature > >()
{
public ArrayList< Feature > call()
{
IJ.showProgress( counter.getAndIncrement(), stack.getSize() );
//final String path = p.outputPath + stack.getSliceLabel( slice ) + ".features";
final String path = p.outputPath + String.format( "%05d", slice - 1 ) + ".features";
ArrayList< Feature > fs = deserializeFeatures( p.sift, path );
if ( null == fs )
{
final FloatArray2DSIFT sift = new FloatArray2DSIFT( p.sift );
final SIFT ijSIFT = new SIFT( sift );
fs = new ArrayList< Feature >();
final ImageProcessor ip = stack.getProcessor( slice );
ip.setMinAndMax( displayRangeMin, displayRangeMax );
ijSIFT.extractFeatures( ip, fs );
if ( ! serializeFeatures( p.sift, fs, path ) )
{
//IJ.log( "FAILED to store serialized features for " + stack.getSliceLabel( slice ) );
IJ.log( "FAILED to store serialized features for " + String.format( "%05d", slice - 1 ) );
}
}
//IJ.log( fs.size() + " features extracted for slice " + stack.getSliceLabel ( slice ) );
IJ.log( fs.size() + " features extracted for slice " + String.format( "%05d", slice - 1 ) );
return fs;
}
} ) );
}
/* join */
for ( Future< ArrayList< Feature > > fu : siftTasks )
fu.get();
/* collect all pairs of slices for which a model could be found */
final ArrayList< Triple< Integer, Integer, AbstractModel< ? > > > pairs = new ArrayList< Triple< Integer, Integer, AbstractModel< ? > > >();
counter.set( 0 );
int numFailures = 0;
for ( int i = 0; i < stack.getSize(); ++i )
{
final ArrayList< Thread > threads = new ArrayList< Thread >( p.maxNumThreads );
final int sliceA = i;
J: for ( int j = i + 1; j < stack.getSize(); )
{
final int numThreads = Math.min( p.maxNumThreads, stack.getSize() - j );
final ArrayList< Triple< Integer, Integer, AbstractModel< ? > > > models =
new ArrayList< Triple< Integer, Integer, AbstractModel< ? > > >( numThreads );
for ( int k = 0; k < numThreads; ++k )
models.add( null );
for ( int t = 0; t < p.maxNumThreads && j < stack.getSize(); ++t, ++j )
{
final int sliceB = j;
final int ti = t;
final Thread thread = new Thread()
{
public void run()
{
IJ.showProgress( counter.getAndIncrement(), stack.getSize() - 1 );
IJ.log( "matching " + sliceB + " -> " + sliceA + "..." );
//String path = p.outputPath + stack.getSliceLabel( slice ) + ".pointmatches";
String path = p.outputPath + String.format( "%05d", sliceB ) + "-" + String.format( "%05d", sliceA ) + ".pointmatches";
ArrayList< PointMatch > candidates = deserializePointMatches( p, path );
if ( null == candidates )
{
//ArrayList< Feature > fs1 = deserializeFeatures( p.sift, p.outputPath + stack.getSliceLabel( slice - 1 ) + ".features" );
ArrayList< Feature > fs1 = deserializeFeatures( p.sift, p.outputPath + String.format( "%05d", sliceA ) + ".features" );
//ArrayList< Feature > fs2 = deserializeFeatures( p.sift, p.outputPath + stack.getSliceLabel( slice ) + ".features" );
ArrayList< Feature > fs2 = deserializeFeatures( p.sift, p.outputPath + String.format( "%05d", sliceB ) + ".features" );
candidates = new ArrayList< PointMatch >( FloatArray2DSIFT.createMatches( fs2, fs1, p.rod ) );
if ( !serializePointMatches( p, candidates, path ) )
IJ.log( "Could not store point matches!" );
}
AbstractModel< ? > model;
switch ( p.modelIndex )
{
case 0:
model = new TranslationModel2D();
break;
case 1:
model = new RigidModel2D();
break;
case 2:
model = new SimilarityModel2D();
break;
case 3:
model = new AffineModel2D();
break;
case 4:
model = new HomographyModel2D();
break;
default:
return;
}
final ArrayList< PointMatch > inliers = new ArrayList< PointMatch >();
boolean modelFound;
try
{
modelFound = model.filterRansac(
candidates,
inliers,
1000,
p.maxEpsilon,
p.minInlierRatio,
p.minNumInliers );
}
catch ( Exception e )
{
modelFound = false;
System.err.println( e.getMessage() );
}
if ( modelFound )
{
IJ.log( sliceB + " -> " + sliceA + ": " + inliers.size() + " corresponding features with an average displacement of " + PointMatch.meanDistance( inliers ) + "px identified." );
IJ.log( "Estimated transformation model: " + model );
models.set( ti, new Triple< Integer, Integer, AbstractModel< ? > >( sliceA, sliceB, model ) );
}
else
{
IJ.log( sliceB + " -> " + sliceA + ": no correspondences found." );
return;
}
}
};
threads.add( thread );
thread.start();
}
for ( final Thread thread : threads )
{
thread.join();
}
/* collect successfully matches pairs and break the search on gaps */
for ( int t = 0; t < models.size(); ++t )
{
final Triple< Integer, Integer, AbstractModel< ? > > pair = models.get( t );
if ( pair == null )
{
if ( ++numFailures > p.maxNumFailures )
break J;
}
else
{
numFailures = 0;
pairs.add( pair );
}
}
}
}
/* Elastic alignment */
/* Initialization */
final TileConfiguration initMeshes = new TileConfiguration();
initMeshes.addTiles( tiles );
final ArrayList< SpringMesh > meshes = new ArrayList< SpringMesh >( stack.getSize() );
for ( int i = 0; i < stack.getSize(); ++i )
meshes.add( new SpringMesh( p.resolutionSpringMesh, stack.getWidth(), stack.getHeight(), p.stiffnessSpringMesh, p.maxStretchSpringMesh, p.dampSpringMesh ) );
final int blockRadius = Math.max( 32, stack.getWidth() / p.resolutionSpringMesh / 2 );
/** TODO set this something more than the largest error by the approximate model */
final int searchRadius = Math.round( p.maxEpsilon );
for ( final Triple< Integer, Integer, AbstractModel< ? > > pair : pairs )
{
final SpringMesh m1 = meshes.get( pair.a );
final SpringMesh m2 = meshes.get( pair.b );
ArrayList< PointMatch > pm12 = new ArrayList< PointMatch >();
ArrayList< PointMatch > pm21 = new ArrayList< PointMatch >();
final Collection< Vertex > v1 = m1.getVertices();
final Collection< Vertex > v2 = m2.getVertices();
final FloatProcessor ip1 = ( FloatProcessor )stack.getProcessor( pair.a + 1 ).convertToFloat().duplicate();
final FloatProcessor ip2 = ( FloatProcessor )stack.getProcessor( pair.b + 1 ).convertToFloat().duplicate();
BlockMatching.matchByMaximalPMCC(
ip1,
ip2,
Math.min( 1.0f, ( float )p.maxImageSize / ip1.getWidth() ),
( ( InvertibleCoordinateTransform )pair.c ).createInverse(),
blockRadius,
blockRadius,
searchRadius,
searchRadius,
p.minR,
p.rodR,
p.maxCurvatureR,
v1,
pm12,
new ErrorStatistic( 1 ) );
IJ.log( pair.a + " > " + pair.b + ": found " + pm12.size() + " correspondences." );
/* <visualisation> */
// final List< Point > s1 = new ArrayList< Point >();
// PointMatch.sourcePoints( pm12, s1 );
// final ImagePlus imp1 = new ImagePlus( i + " >", ip1 );
// imp1.show();
// imp1.setOverlay( BlockMatching.illustrateMatches( pm12 ), Color.yellow, null );
// imp1.setRoi( Util.pointsToPointRoi( s1 ) );
// imp1.updateAndDraw();
/* </visualisation> */
BlockMatching.matchByMaximalPMCC(
ip2,
ip1,
Math.min( 1.0f, ( float )p.maxImageSize / ip1.getWidth() ),
pair.c,
blockRadius,
blockRadius,
searchRadius,
searchRadius,
p.minR,
p.rodR,
p.maxCurvatureR,
v2,
pm21,
new ErrorStatistic( 1 ) );
IJ.log( pair.a + " < " + pair.b + ": found " + pm21.size() + " correspondences." );
/* <visualisation> */
// final List< Point > s2 = new ArrayList< Point >();
// PointMatch.sourcePoints( pm21, s2 );
// final ImagePlus imp2 = new ImagePlus( i + " <", ip2 );
// imp2.show();
// imp2.setOverlay( BlockMatching.illustrateMatches( pm21 ), Color.yellow, null );
// imp2.setRoi( Util.pointsToPointRoi( s2 ) );
// imp2.updateAndDraw();
/* </visualisation> */
final float springConstant = 1.0f / ( pair.b - pair.a );
IJ.log( pair.a + " <> " + pair.b );
for ( final PointMatch pm : pm12 )
{
final Vertex p1 = ( Vertex )pm.getP1();
final Vertex p2 = new Vertex( pm.getP2() );
p1.addSpring( p2, new Spring( 0, 1.0f ) );
m2.addPassiveVertex( p2 );
}
for ( final PointMatch pm : pm21 )
{
final Vertex p1 = ( Vertex )pm.getP1();
final Vertex p2 = new Vertex( pm.getP2() );
p1.addSpring( p2, new Spring( 0, 1.0f ) );
m1.addPassiveVertex( p2 );
}
final Tile< ? > t1 = tiles.get( pair.a );
final Tile< ? > t2 = tiles.get( pair.b );
if ( pm12.size() > pair.c.getMinNumMatches() )
t1.connect( t2, pm12 );
if ( pm21.size() > pair.c.getMinNumMatches() )
t2.connect( t1, pm21 );
}
/* initialize meshes */
/* TODO this is accumulative and thus not perfect, change to analytical concatenation later */
// for ( int i = 1; i < stack.getSize(); ++i )
// {
// final CoordinateTransformList< CoordinateTransform > ctl = new CoordinateTransformList< CoordinateTransform >();
// for ( int j = 0; j < i; ++j )
// {
// for ( final Triple< Integer, Integer, AbstractModel< ? > > pair : pairs )
// {
// if ( pair.a == j && pair.b == i )
// {
// ctl.add( pair.c );
// break;
// }
// }
// }
// meshes[ i ].init( ctl );
// }
initMeshes.optimize( p.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh );
for ( int i = 0; i < stack.getSize(); ++i )
meshes.get( i ).init( tiles.get( i ).getModel() );
/* optimize */
try
{
long t0 = System.currentTimeMillis();
IJ.log("Optimizing spring meshes...");
SpringMesh.optimizeMeshes( meshes, p.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh, p.visualize );
IJ.log("Done optimizing spring meshes. Took " + (System.currentTimeMillis() - t0) + " ms");
}
catch ( NotEnoughDataPointsException e ) { e.printStackTrace(); }
/* calculate bounding box */
final float[] min = new float[ 2 ];
final float[] max = new float[ 2 ];
for ( final SpringMesh mesh : meshes )
{
final float[] meshMin = new float[ 2 ];
final float[] meshMax = new float[ 2 ];
mesh.bounds( meshMin, meshMax );
Util.min( min, meshMin );
Util.max( max, meshMax );
}
/* translate relative to bounding box */
for ( final SpringMesh mesh : meshes )
{
for ( final Vertex vertex : mesh.getVertices() )
{
final float[] w = vertex.getW();
w[ 0 ] -= min[ 0 ];
w[ 1 ] -= min[ 1 ];
}
mesh.updateAffines();
mesh.updatePassiveVertices();
}
//final ImageStack stackAlignedMeshes = new ImageStack( ( int )Math.ceil( max[ 0 ] - min[ 0 ] ), ( int )Math.ceil( max[ 1 ] - min[ 1 ] ) );
final int width = ( int )Math.ceil( max[ 0 ] - min[ 0 ] );
final int height = ( int )Math.ceil( max[ 1 ] - min[ 1 ] );
final ImageProcessor ip = stack.getProcessor( 1 ).createProcessor( width, height );
for ( int i = 0; i < stack.getSize(); ++i )
{
final int slice = i + 1;
// final TransformMeshMapping< SpringMesh > meshMapping = new TransformMeshMapping< SpringMesh >( meshes[ i - 1 ] );
final MovingLeastSquaresTransform mlt = new MovingLeastSquaresTransform();
mlt.setModel( AffineModel2D.class );
mlt.setAlpha( 2.0f );
mlt.setMatches( meshes.get( i ).getVA().keySet() );
final TransformMeshMapping< CoordinateTransformMesh > mltMapping = new TransformMeshMapping< CoordinateTransformMesh >( new CoordinateTransformMesh( mlt, p.resolutionOutput, width, height ) );
// final ImageProcessor ipMesh = stack.getProcessor( slice ).createProcessor( width, height );
if ( p.interpolate )
{
// meshMapping.mapInterpolated( stack.getProcessor( slice ), ipMesh );
mltMapping.mapInterpolated( stack.getProcessor( slice ), ip );
}
else
{
// meshMapping.map( stack.getProcessor( slice ), ipMesh );
mltMapping.map( stack.getProcessor( slice ), ip );
}
// IJ.save( new ImagePlus( "elastic " + i, ipMesh ), p.outputPath + "elastic-" + String.format( "%05d", i ) + ".tif" );
//stackAlignedMeshes.addSlice( "" + i, ip );
}
IJ.save( new ImagePlus( "elastic mlt montage", ip ), p.outputPath + "elastic-mlt-montage.tif" );
IJ.log( "Done." );
}
|
diff --git a/pdfbox/src/main/java/org/apache/pdfbox/Decrypt.java b/pdfbox/src/main/java/org/apache/pdfbox/Decrypt.java
index 140355f..f4bd230 100644
--- a/pdfbox/src/main/java/org/apache/pdfbox/Decrypt.java
+++ b/pdfbox/src/main/java/org/apache/pdfbox/Decrypt.java
@@ -1,190 +1,190 @@
/*
* 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.pdfbox;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.DecryptionMaterial;
import org.apache.pdfbox.pdmodel.encryption.PublicKeyDecryptionMaterial;
import org.apache.pdfbox.pdmodel.encryption.StandardDecryptionMaterial;
/**
* This will read a document from the filesystem, decrypt it and and then write
* the results to the filesystem. <br/><br/>
*
* usage: java org.apache.pdfbox.Decrypt <password> <inputfile> <outputfile>
*
* @author <a href="mailto:[email protected]">Ben Litchfield</a>
* @version $Revision: 1.5 $
*/
public class Decrypt
{
private static final String ALIAS = "-alias";
private static final String PASSWORD = "-password";
private static final String KEYSTORE = "-keyStore";
private Decrypt()
{
}
/**
* This is the entry point for the application.
*
* @param args The command-line arguments.
*
* @throws Exception If there is an error decrypting the document.
*/
public static void main( String[] args ) throws Exception
{
Decrypt decrypt = new Decrypt();
decrypt.decrypt( args );
}
private void decrypt( String[] args ) throws Exception
{
- if( args.length < 2 || args.length > 3 )
+ if( args.length < 2 || args.length > 5 )
{
usage();
}
else
{
String password = null;
String infile = null;
String outfile = null;
String alias = null;
String keyStore = null;
for( int i=0; i<args.length; i++ )
{
if( args[i].equals( ALIAS ) )
{
i++;
if( i >= args.length )
{
usage();
}
alias = args[i];
}
else if( args[i].equals( KEYSTORE ) )
{
i++;
if( i >= args.length )
{
usage();
}
keyStore = args[i];
}
else if( args[i].equals( PASSWORD ) )
{
i++;
if( i >= args.length )
{
usage();
}
password = args[i];
}
else if( infile == null )
{
infile = args[i];
}
else if( outfile == null )
{
outfile = args[i];
}
else
{
usage();
}
}
if( infile == null )
{
usage();
}
if( outfile == null )
{
outfile = infile;
}
if( password == null )
{
password = "";
}
PDDocument document = null;
try
{
document = PDDocument.load( infile );
if( document.isEncrypted() )
{
DecryptionMaterial decryptionMaterial = null;
if( keyStore != null )
{
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream(keyStore), password.toCharArray());
decryptionMaterial = new PublicKeyDecryptionMaterial(ks, alias, password);
}
else
{
decryptionMaterial = new StandardDecryptionMaterial(password);
}
document.openProtection(decryptionMaterial);
AccessPermission ap = document.getCurrentAccessPermission();
if(ap.isOwnerPermission())
{
document.save( outfile );
}
else
{
throw new IOException(
"Error: You are only allowed to decrypt a document with the owner password." );
}
}
else
{
System.err.println( "Error: Document is not encrypted." );
}
}
finally
{
if( document != null )
{
document.close();
}
}
}
}
/**
* This will print a usage message.
*/
private static void usage()
{
System.err.println( "usage: java org.apache.pdfbox.Decrypt " +
"[options] <inputfile> [outputfile]" );
System.err.println( "-alias The alias of the key in the certificate file " +
"(mandatory if several keys are available)");
System.err.println( "-password The password to open the certificate and extract the private key from it." );
System.err.println( "-keyStore The KeyStore that holds the certificate." );
System.exit( -1 );
}
}
| true | true |
private void decrypt( String[] args ) throws Exception
{
if( args.length < 2 || args.length > 3 )
{
usage();
}
else
{
String password = null;
String infile = null;
String outfile = null;
String alias = null;
String keyStore = null;
for( int i=0; i<args.length; i++ )
{
if( args[i].equals( ALIAS ) )
{
i++;
if( i >= args.length )
{
usage();
}
alias = args[i];
}
else if( args[i].equals( KEYSTORE ) )
{
i++;
if( i >= args.length )
{
usage();
}
keyStore = args[i];
}
else if( args[i].equals( PASSWORD ) )
{
i++;
if( i >= args.length )
{
usage();
}
password = args[i];
}
else if( infile == null )
{
infile = args[i];
}
else if( outfile == null )
{
outfile = args[i];
}
else
{
usage();
}
}
if( infile == null )
{
usage();
}
if( outfile == null )
{
outfile = infile;
}
if( password == null )
{
password = "";
}
PDDocument document = null;
try
{
document = PDDocument.load( infile );
if( document.isEncrypted() )
{
DecryptionMaterial decryptionMaterial = null;
if( keyStore != null )
{
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream(keyStore), password.toCharArray());
decryptionMaterial = new PublicKeyDecryptionMaterial(ks, alias, password);
}
else
{
decryptionMaterial = new StandardDecryptionMaterial(password);
}
document.openProtection(decryptionMaterial);
AccessPermission ap = document.getCurrentAccessPermission();
if(ap.isOwnerPermission())
{
document.save( outfile );
}
else
{
throw new IOException(
"Error: You are only allowed to decrypt a document with the owner password." );
}
}
else
{
System.err.println( "Error: Document is not encrypted." );
}
}
finally
{
if( document != null )
{
document.close();
}
}
}
}
|
private void decrypt( String[] args ) throws Exception
{
if( args.length < 2 || args.length > 5 )
{
usage();
}
else
{
String password = null;
String infile = null;
String outfile = null;
String alias = null;
String keyStore = null;
for( int i=0; i<args.length; i++ )
{
if( args[i].equals( ALIAS ) )
{
i++;
if( i >= args.length )
{
usage();
}
alias = args[i];
}
else if( args[i].equals( KEYSTORE ) )
{
i++;
if( i >= args.length )
{
usage();
}
keyStore = args[i];
}
else if( args[i].equals( PASSWORD ) )
{
i++;
if( i >= args.length )
{
usage();
}
password = args[i];
}
else if( infile == null )
{
infile = args[i];
}
else if( outfile == null )
{
outfile = args[i];
}
else
{
usage();
}
}
if( infile == null )
{
usage();
}
if( outfile == null )
{
outfile = infile;
}
if( password == null )
{
password = "";
}
PDDocument document = null;
try
{
document = PDDocument.load( infile );
if( document.isEncrypted() )
{
DecryptionMaterial decryptionMaterial = null;
if( keyStore != null )
{
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream(keyStore), password.toCharArray());
decryptionMaterial = new PublicKeyDecryptionMaterial(ks, alias, password);
}
else
{
decryptionMaterial = new StandardDecryptionMaterial(password);
}
document.openProtection(decryptionMaterial);
AccessPermission ap = document.getCurrentAccessPermission();
if(ap.isOwnerPermission())
{
document.save( outfile );
}
else
{
throw new IOException(
"Error: You are only allowed to decrypt a document with the owner password." );
}
}
else
{
System.err.println( "Error: Document is not encrypted." );
}
}
finally
{
if( document != null )
{
document.close();
}
}
}
}
|
diff --git a/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/taglib/ReportTag.java b/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/taglib/ReportTag.java
index a05a1f62..2a1d98cd 100644
--- a/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/taglib/ReportTag.java
+++ b/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/taglib/ReportTag.java
@@ -1,743 +1,743 @@
/*************************************************************************************
* Copyright (c) 2004 Actuate 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:
* Actuate Corporation - Initial implementation.
************************************************************************************/
package org.eclipse.birt.report.taglib;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;
import org.eclipse.birt.report.IBirtConstants;
import org.eclipse.birt.report.engine.api.IReportDocument;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.exception.ViewerException;
import org.eclipse.birt.report.model.api.IModuleOption;
import org.eclipse.birt.report.model.api.ScalarParameterHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.resource.ResourceConstants;
import org.eclipse.birt.report.service.BirtReportServiceFactory;
import org.eclipse.birt.report.service.BirtViewerReportDesignHandle;
import org.eclipse.birt.report.service.ReportEngineService;
import org.eclipse.birt.report.service.api.IViewerReportDesignHandle;
import org.eclipse.birt.report.service.api.IViewerReportService;
import org.eclipse.birt.report.service.api.InputOptions;
import org.eclipse.birt.report.taglib.component.ParameterField;
import org.eclipse.birt.report.taglib.util.BirtTagUtil;
import org.eclipse.birt.report.utility.BirtUtility;
import org.eclipse.birt.report.utility.DataUtil;
import org.eclipse.birt.report.utility.ParameterAccessor;
/**
* This tag is used to preview report content fast. This tag will output report
* to browser directly.
*
*/
public class ReportTag extends AbstractViewerTag
{
/**
* Serial Version UID
*/
private static final long serialVersionUID = -5017824486972742042L;
/**
* Report output format
*/
private String outputFormat;
/**
* Viewer Report Design Handle
*/
private IViewerReportDesignHandle reportDesignHandle;
/**
* Check whether document existed in URL
*/
private boolean documentInUrl = false;
/**
* Input Options information
*/
private InputOptions options;
/**
* process tag function
*
* @see org.eclipse.birt.report.taglib.AbstractBaseTag#__process()
*/
public void __process( ) throws Exception
{
// output format
outputFormat = BirtTagUtil.getFormat( viewer.getFormat( ) );
// if output format isn't html or allowParameterPrompting is
// true, use IFrame to load report.
if ( !outputFormat
.equalsIgnoreCase( ParameterAccessor.PARAM_FORMAT_HTML )
|| BirtTagUtil.convertToBoolean( viewer
.getForceParameterPrompting( ) ) )
{
__handleIFrame( viewer.createURI( IBirtConstants.VIEWER_PREVIEW ),
viewer.getId( ) );
return;
}
// Create Input Options
this.options = new InputOptions( );
options.setOption( InputOptions.OPT_REQUEST,
(HttpServletRequest) pageContext.getRequest( ) );
options.setOption( InputOptions.OPT_LOCALE, this.locale );
options.setOption( InputOptions.OPT_RTL, Boolean.valueOf( viewer
.getRtl( ) ) );
options.setOption( InputOptions.OPT_IS_MASTER_PAGE_CONTENT, Boolean
.valueOf( viewer.getAllowMasterPage( ) ) );
options.setOption( InputOptions.OPT_SVG_FLAG, Boolean.valueOf( viewer
.getSvg( ) ) );
options.setOption( InputOptions.OPT_FORMAT, outputFormat );
options.setOption( InputOptions.OPT_IS_DESIGNER, new Boolean( false ) );
options.setOption( InputOptions.OPT_SERVLET_PATH,
IBirtConstants.SERVLET_PATH_PREVIEW );
// initialize engine context
BirtReportServiceFactory.getReportService( ).setContext(
pageContext.getServletContext( ), this.options );
// get report design handle
reportDesignHandle = getDesignHandle( );
// Get parameter definition list
Collection parameterDefList = getReportService( )
.getParameterDefinitions( this.reportDesignHandle, options,
false );
if ( BirtUtility.validateParameters( parameterDefList,
getParameterMap( ) ) )
{
// if miss parameters, use IFrame to load report.
__handleIFrame( viewer.createURI( IBirtConstants.VIEWER_PREVIEW ),
viewer.getId( ) );
}
else
{
// output to byte array
ByteArrayOutputStream out = new ByteArrayOutputStream( );
__handleOutputReport( out );
String content = out.toString( );
JspWriter writer = pageContext.getOut( );
if ( viewer.isHostPage( ) )
{
// if set isHostPage is true, output report directly
writer.write( content );
}
else
{
// write style
writer.write( __handleStyle( content ) );
// write script
writer.write( __handleScript( content ) );
// use <div> to control report content display
writer.write( "<div id='" + viewer.getId( ) + "'" //$NON-NLS-1$ //$NON-NLS-2$
+ __handleDivAppearance( ) + ">\n" ); //$NON-NLS-1$
writer.write( "<div class='" + __handleBodyStyle( content ) //$NON-NLS-1$
+ "'>\n" ); //$NON-NLS-1$
writer.write( __handleBody( content ) + "\n" ); //$NON-NLS-1$
writer.write( "</div>\n" ); //$NON-NLS-1$
writer.write( "</div>\n" ); //$NON-NLS-1$
}
}
}
/**
* DIV Appearance style
*
* @return
*/
protected String __handleDivAppearance( )
{
String style = " style='"; //$NON-NLS-1$
// position
if ( viewer.getPosition( ) != null )
style += "position:" + viewer.getPosition( ) + ";"; //$NON-NLS-1$//$NON-NLS-2$
// height
if ( viewer.getHeight( ) >= 0 )
style += "height:" + viewer.getHeight( ) + "px;"; //$NON-NLS-1$//$NON-NLS-2$
// width
if ( viewer.getWidth( ) >= 0 )
style += "width:" + viewer.getWidth( ) + "px;"; //$NON-NLS-1$//$NON-NLS-2$
// top
if ( viewer.getTop( ) >= 0 )
style += "top:" + viewer.getTop( ) + "px;"; //$NON-NLS-1$//$NON-NLS-2$
// left
if ( viewer.getLeft( ) >= 0 )
style = style + "left:" + viewer.getLeft( ) + "px;"; //$NON-NLS-1$//$NON-NLS-2$
// scroll
if ( SCROLLING_YES.equalsIgnoreCase( viewer.getScrolling( ) ) )
{
style = style + "overflow:scroll"; //$NON-NLS-1$
}
else if ( SCROLLING_AUTO.equalsIgnoreCase( viewer.getScrolling( ) ) )
{
style = style + "overflow:auto"; //$NON-NLS-1$
}
// style
if ( viewer.getStyle( ) != null )
style += viewer.getStyle( ) + ";"; //$NON-NLS-1$
style += "' "; //$NON-NLS-1$
return style;
}
/**
* Handle style content
*
* @param content
* @param Exception
* @return
*/
protected String __handleStyle( String content ) throws Exception
{
String style = BLANK_STRING;
if ( content == null )
return style;
// parse style content
Pattern p = Pattern.compile( "<\\s*style[^\\>]*\\>", //$NON-NLS-1$
Pattern.CASE_INSENSITIVE );
Matcher m = p.matcher( content );
while ( m.find( ) )
{
int start = m.end( );
int end = content.toLowerCase( ).indexOf( "</style>", start ); //$NON-NLS-1$
style = style + content.substring( start + 1, end ) + "\n"; //$NON-NLS-1$
}
// replace the style section with id
style = style.replaceAll( ".style", ".style" + viewer.getId( ) ); //$NON-NLS-1$//$NON-NLS-2$
style = "<style type=\"text/css\">\n" + style + "\n</style>\n"; //$NON-NLS-1$ //$NON-NLS-2$
return style;
}
/**
* Returns body style content
*
* @param content
* @return
*/
protected String __handleBodyStyle( String content )
{
String bodyStyleId = BLANK_STRING;
if ( content == null )
return bodyStyleId;
Pattern p = Pattern.compile( "<\\s*body([^\\>]*)\\>", //$NON-NLS-1$
Pattern.CASE_INSENSITIVE );
Matcher m = p.matcher( content );
if ( m.find( ) )
{
for ( int i = 1; i < m.groupCount( ) + 1; i++ )
{
String group = m.group( i );
if ( group == null )
continue;
Pattern pl = Pattern.compile( "class\\s*=\\s*\"([^\"]+)\"", //$NON-NLS-1$
Pattern.CASE_INSENSITIVE );
Matcher ml = pl.matcher( group.trim( ) );
if ( ml.find( ) )
{
// find body style id
bodyStyleId = ml.group( 1 ).trim( );
break;
}
}
}
bodyStyleId = bodyStyleId.replaceAll( "style", "style" //$NON-NLS-1$ //$NON-NLS-2$
+ viewer.getId( ) );
return bodyStyleId;
}
/**
* Handle script content
*
* @param content
* @return
*/
protected String __handleScript( String content )
{
String script = BLANK_STRING;
if ( content == null )
return script;
// get head content
String head = __handleHead( content );
if ( head == null )
return script;
// clear the comment fragments
Pattern p = Pattern.compile( "<\\s*!--" ); //$NON-NLS-1$
Matcher m = p.matcher( head );
while ( m.find( ) )
{
int start = m.start( );
int end = head.indexOf( "-->", start ); //$NON-NLS-1$
if ( end > 0 )
{
String preTemp = head.substring( 0, start );
String lastTemp = head.substring( end + 3 );
head = preTemp + lastTemp;
}
}
// parse the script fragments
p = Pattern.compile( "<\\s*script[^\\>]*\\>", //$NON-NLS-1$
Pattern.CASE_INSENSITIVE );
m = p.matcher( head );
while ( m.find( ) )
{
int start = m.start( );
int end = head.toLowerCase( ).indexOf( "</script>", start ); //$NON-NLS-1$
if ( end > 0 )
script = script + head.substring( start, end + 9 ) + "\n"; //$NON-NLS-1$
}
return script;
}
/**
* Handle head content
*
* @param content
* @return
*/
protected String __handleHead( String content )
{
if ( content == null )
return BLANK_STRING;
String head = BLANK_STRING;
try
{
Pattern p = Pattern.compile( "<\\s*head[^\\>]*\\>", //$NON-NLS-1$
Pattern.CASE_INSENSITIVE );
Matcher m = p.matcher( content );
if ( m.find( ) )
{
int start = m.end( );
int end = content.toLowerCase( ).indexOf( "</head>" ); //$NON-NLS-1$
head = content.substring( start + 1, end );
}
}
catch ( Exception e )
{
}
return head;
}
/**
* Handle body content
*
* @param content
* @return
*/
protected String __handleBody( String content )
{
String body = content;
if ( content == null )
return BLANK_STRING;
try
{
Pattern p = Pattern.compile( "<\\s*body[^\\>]*\\>", //$NON-NLS-1$
Pattern.CASE_INSENSITIVE );
Matcher m = p.matcher( content );
if ( m.find( ) )
{
int start = m.end( );
int end = content.toLowerCase( ).indexOf( "</body>" ); //$NON-NLS-1$
body = content.substring( start + 1, end );
}
}
catch ( Exception e )
{
body = content;
}
// handle style class
body = body.replaceAll( "class=\"style", "class=\"style" //$NON-NLS-1$ //$NON-NLS-2$
+ viewer.getId( ) );
return body;
}
/**
* handle generate report content
*
* @param out
* @throws Exception
*/
protected void __handleOutputReport( OutputStream out ) throws Exception
{
if ( this.documentInUrl )
{
String doc = createAbsolutePath( viewer.getReportDocument( ) );
if ( viewer.getReportletId( ) != null )
{
// Render the reportlet
getReportService( ).renderReportlet( doc,
viewer.getReportletId( ), this.options,
new ArrayList( ), out );
}
else
{
// Render the report document file
getReportService( ).renderReport( doc, null, this.options, out );
}
}
else
{
// Prepare the report parameters
Map params = __handleParameters( reportDesignHandle, null );
// Prepare the display text of report parameters
Map displayTexts = BirtUtility.getDisplayTexts( null,
(HttpServletRequest) pageContext.getRequest( ) );
// RunAndRender the report design file
getReportService( ).runAndRenderReport( reportDesignHandle, null,
this.options, params, out, new ArrayList( ), displayTexts );
}
}
/**
* Handle report parameters
*
* @param reportDesignHandle
* @param params
* @return
*/
protected Map __handleParameters(
IViewerReportDesignHandle reportDesignHandle, Map params )
throws Exception
{
if ( params == null )
params = new HashMap( );
// get report parameter handle list
List parameterList = BirtUtility.getParameterList( reportDesignHandle );
if ( parameterList == null )
return params;
// get parameter map
Map paramMap = viewer.getParameters( );
Iterator it = parameterList.iterator( );
while ( it.hasNext( ) )
{
Object handle = it.next( );
if ( handle instanceof ScalarParameterHandle )
{
ScalarParameterHandle parameterHandle = (ScalarParameterHandle) handle;
String paramName = parameterHandle.getName( );
ParameterField field = (ParameterField) paramMap
.get( paramName );
String paramValue;
Object paramObj;
if ( field != null )
{
paramObj = field.getValue( );
if ( paramObj == null )
{
// if set null parameter value
params.put( paramName, null );
continue;
}
// if set parameter object
if ( !( paramObj instanceof String ) )
{
params.put( paramName, paramObj );
continue;
}
else
{
paramValue = (String) paramObj;
}
// handle parameter using String value
params.put( paramName, getParameterValue( parameterHandle,
field, paramValue ) );
}
else
{
// set default value as parameter value;
paramObj = getReportService( ).getParameterDefaultValue(
reportDesignHandle, paramName, this.options );
params.put( paramName, paramObj );
}
}
}
return params;
}
/**
* Create Map containing parameter name and value
*
* @return
*/
private Map getParameterMap( )
{
Map map = new HashMap( );
Iterator it = viewer.getParameters( ).values( ).iterator( );
while ( it.hasNext( ) )
{
ParameterField field = (ParameterField) it.next( );
if ( field == null )
continue;
map.put( field.getName( ), field.getValue( ) );
}
return map;
}
/**
* parse parameter value by string value
*
* @param handle
* @param field
* @param value
* @return
* @throws Exception
*/
private Object getParameterValue( ScalarParameterHandle handle,
ParameterField field, String value ) throws Exception
{
// get parameter data type
String dataType = handle.getDataType( );
// if String type, return String value
if ( DesignChoiceConstants.PARAM_TYPE_STRING
.equalsIgnoreCase( dataType ) )
{
return value;
}
// convert parameter to object
String pattern = field.getPattern( );
if ( pattern == null || pattern.length( ) <= 0 )
{
pattern = handle.getPattern( );
}
return DataUtil.validate( handle.getDataType( ), pattern, value,
this.locale, field.isLocale( ) );
}
/**
* Returns Report Service Object
*
* @return
*/
protected IViewerReportService getReportService( )
{
return BirtReportServiceFactory.getReportService( );
}
/**
* If a report file name is a relative path, it is relative to document
* folder. So if a report file path is relative path, it's absolute path is
* synthesized by appending file path to the document folder path.
*
* @param file
* @return
*/
protected String createAbsolutePath( String filePath )
{
if ( filePath != null && filePath.trim( ).length( ) > 0
&& ParameterAccessor.isRelativePath( filePath ) )
{
return ParameterAccessor.documentFolder + File.separator + filePath;
}
return filePath;
}
/**
* Returns report design handle
*
* @return IViewerReportDesignHandle
* @throws Exception
*/
protected IViewerReportDesignHandle getDesignHandle( ) throws Exception
{
if ( viewer == null )
return null;
IViewerReportDesignHandle design = null;
IReportRunnable reportRunnable = null;
// Get the absolute report design and document file path
String designFile = createAbsolutePath( viewer.getReportDesign( ) );
String documentFile = createAbsolutePath( viewer.getReportDocument( ) );
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest( );
// check if document file path is valid
boolean isValidDocument = ParameterAccessor
.isValidFilePath( documentFile );
- if ( isValidDocument )
+ if ( documentFile != null && isValidDocument )
{
// open the document instance
IReportDocument reportDocumentInstance = ReportEngineService
.getInstance( ).openReportDocument( designFile,
documentFile, getModuleOptions( ) );
if ( reportDocumentInstance != null )
{
this.documentInUrl = true;
reportRunnable = reportDocumentInstance.getReportRunnable( );
reportDocumentInstance.close( );
}
}
// if report runnable is null, then get it from design file
if ( reportRunnable == null )
{
// if only set __document parameter, throw exception directly
if ( documentFile != null && designFile == null )
{
if ( isValidDocument )
throw new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_DOCUMENT_FILE_ERROR,
new String[]{documentFile} );
else
throw new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_DOCUMENT_ACCESS_ERROR,
new String[]{documentFile} );
}
// check if the report file path is valid
if ( !ParameterAccessor.isValidFilePath( designFile ) )
{
throw new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_REPORT_ACCESS_ERROR,
new String[]{designFile} );
}
else
{
// check the design file if exist
File file = new File( designFile );
if ( file.exists( ) )
{
reportRunnable = ReportEngineService.getInstance( )
.openReportDesign( designFile, getModuleOptions( ) );
}
else if ( !ParameterAccessor.isWorkingFolderAccessOnly( ) )
{
InputStream is = null;
URL url = null;
try
{
- String reportPath = designFile;
+ String reportPath = viewer.getReportDesign( );
if ( !reportPath.startsWith( "/" ) ) //$NON-NLS-1$
reportPath = "/" + reportPath; //$NON-NLS-1$
url = request.getSession( ).getServletContext( )
.getResource( reportPath );
if ( url != null )
is = url.openStream( );
if ( is != null )
reportRunnable = ReportEngineService.getInstance( )
.openReportDesign( url.toString( ), is,
getModuleOptions( ) );
}
catch ( Exception e )
{
}
}
if ( reportRunnable == null )
{
throw new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_REPORT_FILE_ERROR,
new String[]{designFile} );
}
}
}
if ( reportRunnable != null )
{
design = new BirtViewerReportDesignHandle(
IViewerReportDesignHandle.RPT_RUNNABLE_OBJECT,
reportRunnable );
}
return design;
}
/**
* Create Module Options
*
* @param viewer
* @return
*/
protected Map getModuleOptions( )
{
Map options = new HashMap( );
String resourceFolder = viewer.getResourceFolder( );
if ( resourceFolder == null || resourceFolder.trim( ).length( ) <= 0 )
resourceFolder = ParameterAccessor.birtResourceFolder;
options.put( IModuleOption.RESOURCE_FOLDER_KEY, resourceFolder );
return options;
}
}
| false | true |
protected IViewerReportDesignHandle getDesignHandle( ) throws Exception
{
if ( viewer == null )
return null;
IViewerReportDesignHandle design = null;
IReportRunnable reportRunnable = null;
// Get the absolute report design and document file path
String designFile = createAbsolutePath( viewer.getReportDesign( ) );
String documentFile = createAbsolutePath( viewer.getReportDocument( ) );
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest( );
// check if document file path is valid
boolean isValidDocument = ParameterAccessor
.isValidFilePath( documentFile );
if ( isValidDocument )
{
// open the document instance
IReportDocument reportDocumentInstance = ReportEngineService
.getInstance( ).openReportDocument( designFile,
documentFile, getModuleOptions( ) );
if ( reportDocumentInstance != null )
{
this.documentInUrl = true;
reportRunnable = reportDocumentInstance.getReportRunnable( );
reportDocumentInstance.close( );
}
}
// if report runnable is null, then get it from design file
if ( reportRunnable == null )
{
// if only set __document parameter, throw exception directly
if ( documentFile != null && designFile == null )
{
if ( isValidDocument )
throw new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_DOCUMENT_FILE_ERROR,
new String[]{documentFile} );
else
throw new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_DOCUMENT_ACCESS_ERROR,
new String[]{documentFile} );
}
// check if the report file path is valid
if ( !ParameterAccessor.isValidFilePath( designFile ) )
{
throw new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_REPORT_ACCESS_ERROR,
new String[]{designFile} );
}
else
{
// check the design file if exist
File file = new File( designFile );
if ( file.exists( ) )
{
reportRunnable = ReportEngineService.getInstance( )
.openReportDesign( designFile, getModuleOptions( ) );
}
else if ( !ParameterAccessor.isWorkingFolderAccessOnly( ) )
{
InputStream is = null;
URL url = null;
try
{
String reportPath = designFile;
if ( !reportPath.startsWith( "/" ) ) //$NON-NLS-1$
reportPath = "/" + reportPath; //$NON-NLS-1$
url = request.getSession( ).getServletContext( )
.getResource( reportPath );
if ( url != null )
is = url.openStream( );
if ( is != null )
reportRunnable = ReportEngineService.getInstance( )
.openReportDesign( url.toString( ), is,
getModuleOptions( ) );
}
catch ( Exception e )
{
}
}
if ( reportRunnable == null )
{
throw new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_REPORT_FILE_ERROR,
new String[]{designFile} );
}
}
}
if ( reportRunnable != null )
{
design = new BirtViewerReportDesignHandle(
IViewerReportDesignHandle.RPT_RUNNABLE_OBJECT,
reportRunnable );
}
return design;
}
|
protected IViewerReportDesignHandle getDesignHandle( ) throws Exception
{
if ( viewer == null )
return null;
IViewerReportDesignHandle design = null;
IReportRunnable reportRunnable = null;
// Get the absolute report design and document file path
String designFile = createAbsolutePath( viewer.getReportDesign( ) );
String documentFile = createAbsolutePath( viewer.getReportDocument( ) );
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest( );
// check if document file path is valid
boolean isValidDocument = ParameterAccessor
.isValidFilePath( documentFile );
if ( documentFile != null && isValidDocument )
{
// open the document instance
IReportDocument reportDocumentInstance = ReportEngineService
.getInstance( ).openReportDocument( designFile,
documentFile, getModuleOptions( ) );
if ( reportDocumentInstance != null )
{
this.documentInUrl = true;
reportRunnable = reportDocumentInstance.getReportRunnable( );
reportDocumentInstance.close( );
}
}
// if report runnable is null, then get it from design file
if ( reportRunnable == null )
{
// if only set __document parameter, throw exception directly
if ( documentFile != null && designFile == null )
{
if ( isValidDocument )
throw new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_DOCUMENT_FILE_ERROR,
new String[]{documentFile} );
else
throw new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_DOCUMENT_ACCESS_ERROR,
new String[]{documentFile} );
}
// check if the report file path is valid
if ( !ParameterAccessor.isValidFilePath( designFile ) )
{
throw new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_REPORT_ACCESS_ERROR,
new String[]{designFile} );
}
else
{
// check the design file if exist
File file = new File( designFile );
if ( file.exists( ) )
{
reportRunnable = ReportEngineService.getInstance( )
.openReportDesign( designFile, getModuleOptions( ) );
}
else if ( !ParameterAccessor.isWorkingFolderAccessOnly( ) )
{
InputStream is = null;
URL url = null;
try
{
String reportPath = viewer.getReportDesign( );
if ( !reportPath.startsWith( "/" ) ) //$NON-NLS-1$
reportPath = "/" + reportPath; //$NON-NLS-1$
url = request.getSession( ).getServletContext( )
.getResource( reportPath );
if ( url != null )
is = url.openStream( );
if ( is != null )
reportRunnable = ReportEngineService.getInstance( )
.openReportDesign( url.toString( ), is,
getModuleOptions( ) );
}
catch ( Exception e )
{
}
}
if ( reportRunnable == null )
{
throw new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_REPORT_FILE_ERROR,
new String[]{designFile} );
}
}
}
if ( reportRunnable != null )
{
design = new BirtViewerReportDesignHandle(
IViewerReportDesignHandle.RPT_RUNNABLE_OBJECT,
reportRunnable );
}
return design;
}
|
diff --git a/api/src/main/java/net/md_5/bungee/api/event/AsyncEvent.java b/api/src/main/java/net/md_5/bungee/api/event/AsyncEvent.java
index 4c90ffac..c35df7b6 100644
--- a/api/src/main/java/net/md_5/bungee/api/event/AsyncEvent.java
+++ b/api/src/main/java/net/md_5/bungee/api/event/AsyncEvent.java
@@ -1,75 +1,75 @@
package net.md_5.bungee.api.event;
import com.google.common.base.Preconditions;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import net.md_5.bungee.api.Callback;
import net.md_5.bungee.api.plugin.Event;
import net.md_5.bungee.api.plugin.Plugin;
/**
* Represents an event which depends on the result of asynchronous operations.
*
* @param <T> Type of this event
*/
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class AsyncEvent<T> extends Event
{
private final Callback<T> done;
private final Set<Plugin> intents = Collections.newSetFromMap( new ConcurrentHashMap<Plugin, Boolean>() );
private final AtomicBoolean fired = new AtomicBoolean();
private final AtomicInteger latch = new AtomicInteger();
@Override
@SuppressWarnings("unchecked")
public void postCall()
{
fired.set( true );
if ( latch.get() == 0 )
{
done.done( (T) this, null );
}
}
/**
* Register an intent that this plugin will continue to perform work on a
* background task, and wishes to let the event proceed once the registered
* background task has completed.
*
* @param plugin the plugin registering this intent
*/
public void registerIntent(Plugin plugin)
{
Preconditions.checkState( !fired.get(), "Event %s has already been fired", this );
Preconditions.checkState( !intents.contains( plugin ), "Plugin %s already registered intent for event %s", plugin, this );
intents.add( plugin );
latch.incrementAndGet();
}
/**
* Notifies this event that this plugin has done all its required processing
* and wishes to let the event proceed.
*
* @param plugin a plugin which has an intent registered for this event
*/
@SuppressWarnings("unchecked")
public void completeIntent(Plugin plugin)
{
Preconditions.checkState( intents.contains( plugin ), "Plugin %s has not registered intent for event %s", plugin, this );
intents.remove( plugin );
- if ( latch.decrementAndGet() == 0 )
+ if ( fired.get() && latch.decrementAndGet() == 0 )
{
done.done( (T) this, null );
}
}
}
| true | true |
public void completeIntent(Plugin plugin)
{
Preconditions.checkState( intents.contains( plugin ), "Plugin %s has not registered intent for event %s", plugin, this );
intents.remove( plugin );
if ( latch.decrementAndGet() == 0 )
{
done.done( (T) this, null );
}
}
|
public void completeIntent(Plugin plugin)
{
Preconditions.checkState( intents.contains( plugin ), "Plugin %s has not registered intent for event %s", plugin, this );
intents.remove( plugin );
if ( fired.get() && latch.decrementAndGet() == 0 )
{
done.done( (T) this, null );
}
}
|
diff --git a/src/org/usfirst/frc1923/events/ShooterAngleControllerEvent.java b/src/org/usfirst/frc1923/events/ShooterAngleControllerEvent.java
index 1a01e8c..223c098 100644
--- a/src/org/usfirst/frc1923/events/ShooterAngleControllerEvent.java
+++ b/src/org/usfirst/frc1923/events/ShooterAngleControllerEvent.java
@@ -1,42 +1,42 @@
package org.usfirst.frc1923.events;
import org.usfirst.frc1923.components.ShooterAngleController;
/**
* An event to handle the Angle of the shooter
* @author Pavan Hegde, Nabeel Rangwala
* @version 1.0
* @since 1/26/13
*/
public class ShooterAngleControllerEvent implements Event {
private boolean canShoot;
private ShooterAngleController motor;
/**
* Constructor to create the event
* @param motor the Shooter Angle Controller
* @param canShoot boolean to define which direction to go
*/
public ShooterAngleControllerEvent(ShooterAngleController motor, boolean canShoot) {
this.canShoot = canShoot;
this.motor = motor;
}
/**
* Moves up or down depending on canShoot
*/
public void run() {
if (canShoot){
motor.up(motor.getXboxLeftJoystick());
}
else {
- motor.down(motor.getXboxLeftJoystick());
+ motor.down(-motor.getXboxLeftJoystick());
}
}
/**
* destroys motor
*/
public void reset() {
motor.destroy();
}
}
| true | true |
public void run() {
if (canShoot){
motor.up(motor.getXboxLeftJoystick());
}
else {
motor.down(motor.getXboxLeftJoystick());
}
}
|
public void run() {
if (canShoot){
motor.up(motor.getXboxLeftJoystick());
}
else {
motor.down(-motor.getXboxLeftJoystick());
}
}
|
diff --git a/Sparx/src/java/main/com/netspective/sparx/navigate/fts/SearchHitsTemplateRenderer.java b/Sparx/src/java/main/com/netspective/sparx/navigate/fts/SearchHitsTemplateRenderer.java
index ed101c32..34899275 100644
--- a/Sparx/src/java/main/com/netspective/sparx/navigate/fts/SearchHitsTemplateRenderer.java
+++ b/Sparx/src/java/main/com/netspective/sparx/navigate/fts/SearchHitsTemplateRenderer.java
@@ -1,307 +1,307 @@
/*
* Copyright (c) 2000-2004 Netspective Communications LLC. All rights reserved.
*
* Netspective Communications LLC ("Netspective") permits redistribution, modification and use of this file in source
* and binary form ("The Software") under the Netspective Source License ("NSL" or "The License"). The following
* conditions are provided as a summary of the NSL but the NSL remains the canonical license and must be accepted
* before using The Software. Any use of The Software indicates agreement with the NSL.
*
* 1. Each copy or derived work of The Software must preserve the copyright notice and this notice unmodified.
*
* 2. Redistribution of The Software is allowed in object code form only (as Java .class files or a .jar file
* containing the .class files) and only as part of an application that uses The Software as part of its primary
* functionality. No distribution of the package is allowed as part of a software development kit, other library,
* or development tool without written consent of Netspective. Any modified form of The Software is bound by these
* same restrictions.
*
* 3. Redistributions of The Software in any form must include an unmodified copy of The License, normally in a plain
* ASCII text file unless otherwise agreed to, in writing, by Netspective.
*
* 4. The names "Netspective", "Axiom", "Commons", "Junxion", and "Sparx" are trademarks of Netspective and may not be
* used to endorse or appear in products derived from The Software without written consent of Netspective.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT A WARRANTY OF ANY KIND. ALL EXPRESS OR IMPLIED REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT,
* ARE HEREBY DISCLAIMED.
*
* NETSPECTIVE AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE OR ANY THIRD PARTY AS A
* RESULT OF USING OR DISTRIBUTING THE SOFTWARE. IN NO EVENT WILL NETSPECTIVE OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THE SOFTWARE, EVEN
* IF IT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*/
package com.netspective.sparx.navigate.fts;
import java.io.IOException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletRequest;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import com.netspective.commons.template.TemplateProcessor;
import com.netspective.commons.text.TextUtils;
import com.netspective.commons.xdm.XmlDataModelSchema;
import com.netspective.sparx.navigate.NavigationContext;
import com.netspective.sparx.template.freemarker.FreeMarkerTemplateProcessor;
public class SearchHitsTemplateRenderer implements SearchHitsRenderer
{
public static final XmlDataModelSchema.Options XML_DATA_MODEL_SCHEMA_OPTIONS = new XmlDataModelSchema.Options().setIgnorePcData(true);
private TemplateProcessor requestTemplate;
private TemplateProcessor resultsTemplate;
private TemplateProcessor queryErrorBodyTemplate;
private String expressionFormFieldName = "expression";
private String searchWithinSearchResultsFormFieldName = "searchWithinResults";
private String requestFormFieldTemplateVarName = "formFieldName";
private String searchWithinCheckboxFormFieldTemplateVarName = "searchWithinFieldName";
private String rendererTemplateVarName = "renderer";
private String searchResultsTemplateVarName = "searchResults";
private String expressionTemplateVarName = "expression";
private String exceptionTemplateVarName = "exception";
private String[] hitsMatrixFieldNames;
public SearchHitsTemplateRenderer()
{
FreeMarkerTemplateProcessor renderer = (FreeMarkerTemplateProcessor) createRequestBody();
renderer.addTemplateContent("You have not provided any search request renderer content.");
renderer.finalizeContents();
addRequestBody(renderer);
renderer = (FreeMarkerTemplateProcessor) createResultsBody();
renderer.addTemplateContent("You have not provided any search results renderer content.");
renderer.finalizeContents();
addResultsBody(renderer);
}
protected Map createDefaultTemplateVars(FullTextSearchResults searchResults)
{
final Map templateVars = new HashMap();
templateVars.put(rendererTemplateVarName, this);
templateVars.put(requestFormFieldTemplateVarName, expressionFormFieldName);
templateVars.put(searchWithinCheckboxFormFieldTemplateVarName, searchWithinSearchResultsFormFieldName);
if(searchResults != null)
{
templateVars.put(searchResultsTemplateVarName, searchResults);
templateVars.put(expressionTemplateVarName, searchResults.getExpression().getExprText());
}
return templateVars;
}
public String getAdvancedSearchExpression(NavigationContext nc)
{
final ServletRequest request = nc.getRequest();
// we create a hidden field in the advanced data dialog telling us we have advanced data
if(request.getParameter("hasAdvancedData") == null)
return null;
final FullTextSearchPage searchPage = (FullTextSearchPage) nc.getActivePage();
final String defaultFieldName = searchPage.getDefaultAdvancedSearchFieldName();
final String allWordsParamValue = request.getParameter("all");
final String exactPhraseParamValue = request.getParameter("phrase");
final String atLeastOneWordParamValue = request.getParameter("one");
BooleanQuery advancedQuery = new BooleanQuery();
if(allWordsParamValue != null && allWordsParamValue.trim().length() > 0)
{
String[] words = TextUtils.getInstance().split(allWordsParamValue, " ", true);
for(int i = 0; i < words.length; i++)
advancedQuery.add(new TermQuery(new Term(defaultFieldName, words[i])), true, false);
}
if(exactPhraseParamValue != null && exactPhraseParamValue.trim().length() > 0)
{
final PhraseQuery phraseQuery = new PhraseQuery();
phraseQuery.add(new Term(defaultFieldName, exactPhraseParamValue));
advancedQuery.add(phraseQuery, true, false);
}
if(atLeastOneWordParamValue != null && atLeastOneWordParamValue.trim().length() > 0)
{
String[] words = TextUtils.getInstance().split(atLeastOneWordParamValue, " ", true);
for(int i = 0; i < words.length; i++)
advancedQuery.add(new TermQuery(new Term(defaultFieldName, words[i])), false, false);
}
String[] advancedSearchFieldNames = searchPage.getAdvancedSearchFieldNames();
for(int i = 0; i < advancedSearchFieldNames.length; i++)
{
final String fieldName = advancedSearchFieldNames[i];
final String fieldParamValue = request.getParameter("field_" + fieldName);
if(fieldParamValue != null && fieldParamValue.trim().length() > 0)
{
Query fieldQuery = null;
try
{
fieldQuery = QueryParser.parse(fieldParamValue, fieldName, searchPage.getAnalyzer());
}
catch(ParseException e)
{
searchPage.getLog().error("Error parsing field '" + fieldName + "' query '" + fieldParamValue + "', ignoring", e);
continue;
}
advancedQuery.add(fieldQuery, true, false);
}
}
- return advancedQuery.toString(defaultFieldName);
+ return advancedQuery.toString();
}
public SearchExpression getSearchExpression(NavigationContext nc)
{
final ServletRequest request = nc.getRequest();
final String advancedExpression = getAdvancedSearchExpression(nc);
final String exprText = advancedExpression != null
? advancedExpression : request.getParameter(getExpressionFormFieldName());
return exprText == null ? null : new SearchExpression()
{
public String getExprText()
{
return exprText;
}
public boolean isEmptyExpression()
{
return exprText.length() == 0;
}
public boolean isSearchWithinPreviousResults()
{
return request.getParameter(searchWithinSearchResultsFormFieldName) != null;
}
public String getRewrittenExpressionRedirectParams()
{
return advancedExpression != null
? getExpressionFormFieldName() + "=" + URLEncoder.encode(exprText) : null;
}
};
}
public void renderSearchRequest(Writer writer, NavigationContext nc) throws IOException
{
final Map templateVars = createDefaultTemplateVars(null);
requestTemplate.process(writer, nc, templateVars);
}
public void renderEmptyQuery(Writer writer, NavigationContext nc) throws IOException
{
final Map templateVars = createDefaultTemplateVars(null);
templateVars.put(expressionTemplateVarName, "");
requestTemplate.process(writer, nc, templateVars);
}
public void renderQueryError(Writer writer, NavigationContext nc, SearchExpression expression, ParseException exception) throws IOException
{
final Map templateVars = createDefaultTemplateVars(null);
templateVars.put(expressionTemplateVarName, expression);
templateVars.put(exceptionTemplateVarName, exception);
if(queryErrorBodyTemplate != null)
queryErrorBodyTemplate.process(writer, nc, templateVars);
else
requestTemplate.process(writer, nc, templateVars);
}
public void renderSearchResults(Writer writer, NavigationContext nc, FullTextSearchResults searchResults) throws IOException
{
final Map templateVars = createDefaultTemplateVars(searchResults);
resultsTemplate.process(writer, nc, templateVars);
}
public String getExpressionFormFieldName()
{
return expressionFormFieldName;
}
public void setExpressionFormFieldName(String expressionFormFieldName)
{
this.expressionFormFieldName = expressionFormFieldName;
}
public TemplateProcessor createRequestBody()
{
return new FreeMarkerTemplateProcessor();
}
public void addRequestBody(TemplateProcessor templateProcessor)
{
requestTemplate = templateProcessor;
}
public TemplateProcessor getRequestBody()
{
return requestTemplate;
}
public TemplateProcessor createResultsBody()
{
return new FreeMarkerTemplateProcessor();
}
public void addResultsBody(TemplateProcessor templateProcessor)
{
resultsTemplate = templateProcessor;
}
public TemplateProcessor getResultsBody()
{
return resultsTemplate;
}
public TemplateProcessor createQueryErrorBody()
{
return new FreeMarkerTemplateProcessor();
}
public void addQueryErrorBody(TemplateProcessor templateProcessor)
{
queryErrorBodyTemplate = templateProcessor;
}
public TemplateProcessor getQueryErrorBody()
{
return queryErrorBodyTemplate;
}
public String[] getHitsMatrixFieldNames()
{
return hitsMatrixFieldNames;
}
public void setHitsMatrixFieldNames(String[] hitsMatrixFieldNames)
{
this.hitsMatrixFieldNames = hitsMatrixFieldNames;
}
public String getExpressionTemplateVarName()
{
return expressionTemplateVarName;
}
public void setExpressionTemplateVarName(String expressionTemplateVarName)
{
this.expressionTemplateVarName = expressionTemplateVarName;
}
public String getExceptionTemplateVarName()
{
return exceptionTemplateVarName;
}
public void setExceptionTemplateVarName(String exceptionTemplateVarName)
{
this.exceptionTemplateVarName = exceptionTemplateVarName;
}
}
| true | true |
public String getAdvancedSearchExpression(NavigationContext nc)
{
final ServletRequest request = nc.getRequest();
// we create a hidden field in the advanced data dialog telling us we have advanced data
if(request.getParameter("hasAdvancedData") == null)
return null;
final FullTextSearchPage searchPage = (FullTextSearchPage) nc.getActivePage();
final String defaultFieldName = searchPage.getDefaultAdvancedSearchFieldName();
final String allWordsParamValue = request.getParameter("all");
final String exactPhraseParamValue = request.getParameter("phrase");
final String atLeastOneWordParamValue = request.getParameter("one");
BooleanQuery advancedQuery = new BooleanQuery();
if(allWordsParamValue != null && allWordsParamValue.trim().length() > 0)
{
String[] words = TextUtils.getInstance().split(allWordsParamValue, " ", true);
for(int i = 0; i < words.length; i++)
advancedQuery.add(new TermQuery(new Term(defaultFieldName, words[i])), true, false);
}
if(exactPhraseParamValue != null && exactPhraseParamValue.trim().length() > 0)
{
final PhraseQuery phraseQuery = new PhraseQuery();
phraseQuery.add(new Term(defaultFieldName, exactPhraseParamValue));
advancedQuery.add(phraseQuery, true, false);
}
if(atLeastOneWordParamValue != null && atLeastOneWordParamValue.trim().length() > 0)
{
String[] words = TextUtils.getInstance().split(atLeastOneWordParamValue, " ", true);
for(int i = 0; i < words.length; i++)
advancedQuery.add(new TermQuery(new Term(defaultFieldName, words[i])), false, false);
}
String[] advancedSearchFieldNames = searchPage.getAdvancedSearchFieldNames();
for(int i = 0; i < advancedSearchFieldNames.length; i++)
{
final String fieldName = advancedSearchFieldNames[i];
final String fieldParamValue = request.getParameter("field_" + fieldName);
if(fieldParamValue != null && fieldParamValue.trim().length() > 0)
{
Query fieldQuery = null;
try
{
fieldQuery = QueryParser.parse(fieldParamValue, fieldName, searchPage.getAnalyzer());
}
catch(ParseException e)
{
searchPage.getLog().error("Error parsing field '" + fieldName + "' query '" + fieldParamValue + "', ignoring", e);
continue;
}
advancedQuery.add(fieldQuery, true, false);
}
}
return advancedQuery.toString(defaultFieldName);
}
|
public String getAdvancedSearchExpression(NavigationContext nc)
{
final ServletRequest request = nc.getRequest();
// we create a hidden field in the advanced data dialog telling us we have advanced data
if(request.getParameter("hasAdvancedData") == null)
return null;
final FullTextSearchPage searchPage = (FullTextSearchPage) nc.getActivePage();
final String defaultFieldName = searchPage.getDefaultAdvancedSearchFieldName();
final String allWordsParamValue = request.getParameter("all");
final String exactPhraseParamValue = request.getParameter("phrase");
final String atLeastOneWordParamValue = request.getParameter("one");
BooleanQuery advancedQuery = new BooleanQuery();
if(allWordsParamValue != null && allWordsParamValue.trim().length() > 0)
{
String[] words = TextUtils.getInstance().split(allWordsParamValue, " ", true);
for(int i = 0; i < words.length; i++)
advancedQuery.add(new TermQuery(new Term(defaultFieldName, words[i])), true, false);
}
if(exactPhraseParamValue != null && exactPhraseParamValue.trim().length() > 0)
{
final PhraseQuery phraseQuery = new PhraseQuery();
phraseQuery.add(new Term(defaultFieldName, exactPhraseParamValue));
advancedQuery.add(phraseQuery, true, false);
}
if(atLeastOneWordParamValue != null && atLeastOneWordParamValue.trim().length() > 0)
{
String[] words = TextUtils.getInstance().split(atLeastOneWordParamValue, " ", true);
for(int i = 0; i < words.length; i++)
advancedQuery.add(new TermQuery(new Term(defaultFieldName, words[i])), false, false);
}
String[] advancedSearchFieldNames = searchPage.getAdvancedSearchFieldNames();
for(int i = 0; i < advancedSearchFieldNames.length; i++)
{
final String fieldName = advancedSearchFieldNames[i];
final String fieldParamValue = request.getParameter("field_" + fieldName);
if(fieldParamValue != null && fieldParamValue.trim().length() > 0)
{
Query fieldQuery = null;
try
{
fieldQuery = QueryParser.parse(fieldParamValue, fieldName, searchPage.getAnalyzer());
}
catch(ParseException e)
{
searchPage.getLog().error("Error parsing field '" + fieldName + "' query '" + fieldParamValue + "', ignoring", e);
continue;
}
advancedQuery.add(fieldQuery, true, false);
}
}
return advancedQuery.toString();
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/server/DebugUtilities.java b/src/com/itmill/toolkit/terminal/gwt/server/DebugUtilities.java
index 3200791f4..ee3661563 100644
--- a/src/com/itmill/toolkit/terminal/gwt/server/DebugUtilities.java
+++ b/src/com/itmill/toolkit/terminal/gwt/server/DebugUtilities.java
@@ -1,358 +1,358 @@
package com.itmill.toolkit.terminal.gwt.server;
import java.util.Iterator;
import java.util.Stack;
import com.itmill.toolkit.terminal.Sizeable;
import com.itmill.toolkit.ui.Component;
import com.itmill.toolkit.ui.ComponentContainer;
import com.itmill.toolkit.ui.CustomLayout;
import com.itmill.toolkit.ui.GridLayout;
import com.itmill.toolkit.ui.OrderedLayout;
import com.itmill.toolkit.ui.Panel;
import com.itmill.toolkit.ui.Window;
import com.itmill.toolkit.ui.GridLayout.Area;
public class DebugUtilities {
private final static int LAYERS_SHOWN = 4;
/**
* Recursively checks given component and its subtree for invalid layout
* setups. Prints errors to std err stream.
*
* @param component
* component to check
*/
public static boolean validateComponentRelativeSizes(Component component,
boolean recursive) {
boolean valid = true;
if (!(component instanceof Window)) {
valid = valid && checkWidths(component);
valid = valid && checkHeights(component);
}
if (recursive) {
if (component instanceof Panel) {
Panel panel = (Panel) component;
if (!validateComponentRelativeSizes(panel.getLayout(), false)) {
valid = false;
}
} else if (component instanceof ComponentContainer) {
ComponentContainer lo = (ComponentContainer) component;
Iterator it = lo.getComponentIterator();
while (it.hasNext()) {
if (!validateComponentRelativeSizes((Component) it.next(),
false)) {
valid = false;
}
}
}
}
return valid;
}
private static void showError(String msg, Stack<ComponentInfo> attributes) {
StringBuffer err = new StringBuffer();
err.append("IT MILL Toolkit DEBUG\n");
StringBuilder indent = new StringBuilder("");
ComponentInfo ci;
if (attributes != null) {
while (attributes.size() > LAYERS_SHOWN) {
attributes.pop();
}
while (!attributes.empty()) {
ci = attributes.pop();
showComponent(ci.component, ci.info, err, indent);
}
}
err.append("Invalid layout detected. ");
err.append(msg);
err.append("\n");
err
.append("Components may be invisible or not render as expected. Relative sizes were replaced by undefined sizes.\n");
System.err.println(err);
}
private static boolean checkHeights(Component component) {
Component parent = component.getParent();
String msg = null;
Stack<ComponentInfo> attributes = null;
if (hasRelativeHeight(component) && hasUndefinedHeight(parent)) {
if (parent instanceof OrderedLayout) {
OrderedLayout ol = (OrderedLayout) parent;
if (ol.getOrientation() == OrderedLayout.ORIENTATION_VERTICAL) {
msg = "Relative height for component inside non sized vertical ordered layout.";
attributes = getHeightAttributes(component);
} else if (!hasNonRelativeHeightComponent(ol)) {
msg = "At least one of horizontal orderedlayout's components must have non relative height if layout has no height defined";
attributes = getHeightAttributes(component);
} else {
// valid situation, other components defined height
}
} else if (parent instanceof GridLayout) {
GridLayout gl = (GridLayout) parent;
Area componentArea = gl.getComponentArea(component);
boolean rowHasHeight = false;
for (int row = componentArea.getRow1(); !rowHasHeight
&& row <= componentArea.getRow2(); row++) {
for (int column = 0; !rowHasHeight
&& column < gl.getColumns(); column++) {
Component c = gl.getComponent(column, row);
if (c != null) {
rowHasHeight = !hasRelativeHeight(c);
}
}
}
if (!rowHasHeight) {
msg = "At least one component in each row should have non relative height in GridLayout with undefined height.";
attributes = getHeightAttributes(component);
}
- } else {
+ } else if (!(parent instanceof CustomLayout)) {
// default error for non sized parent issue
msg = "Relative height component's parent should not have undefined height.";
attributes = getHeightAttributes(component);
}
}
if (msg != null) {
showError(msg, attributes);
}
return (msg == null);
}
private static boolean checkWidths(Component component) {
Component parent = component.getParent();
String msg = null;
Stack<ComponentInfo> attributes = null;
if (hasRelativeWidth(component) && hasUndefinedWidth(parent)) {
if (parent instanceof OrderedLayout) {
OrderedLayout ol = (OrderedLayout) parent;
if (ol.getOrientation() == OrderedLayout.ORIENTATION_HORIZONTAL) {
msg = "Relative width for component inside non sized horizontal ordered layout.";
attributes = getWidthAttributes(component);
} else if (!hasNonRelativeWidthComponent(ol)) {
msg = "At least one of vertical orderedlayout's components must have non relative width if layout has no width defined";
attributes = getWidthAttributes(component);
} else {
// valid situation, other components defined width
}
} else if (parent instanceof GridLayout) {
GridLayout gl = (GridLayout) parent;
Area componentArea = gl.getComponentArea(component);
boolean columnHasWidth = false;
for (int col = componentArea.getColumn1(); !columnHasWidth
&& col <= componentArea.getColumn2(); col++) {
for (int row = 0; !columnHasWidth && row < gl.getRows(); row++) {
Component c = gl.getComponent(col, row);
if (c != null) {
columnHasWidth = !hasRelativeWidth(c);
}
}
}
if (!columnHasWidth) {
msg = "At least one component in each column should have non relative width in GridLayout with undefined width.";
attributes = getWidthAttributes(component);
}
} else if (!(parent instanceof CustomLayout)) {
// default error for non sized parent issue
msg = "Relative width component's parent should not have undefined width.";
attributes = getWidthAttributes(component);
}
}
if (msg != null) {
showError(msg, attributes);
}
return (msg == null);
}
private static class ComponentInfo {
Component component;
String info;
public ComponentInfo(Component component, String info) {
this.component = component;
this.info = info;
}
}
private static Stack<ComponentInfo> getHeightAttributes(Component component) {
Stack<ComponentInfo> attributes = new Stack<ComponentInfo>();
attributes
.add(new ComponentInfo(component, getHeightString(component)));
Component parent = component.getParent();
attributes.add(new ComponentInfo(parent, getHeightString(parent)));
while ((parent = parent.getParent()) != null) {
attributes.add(new ComponentInfo(parent, getHeightString(parent)));
}
return attributes;
}
private static Stack<ComponentInfo> getWidthAttributes(Component component) {
Stack<ComponentInfo> attributes = new Stack<ComponentInfo>();
attributes.add(new ComponentInfo(component, getWidthString(component)));
Component parent = component.getParent();
attributes.add(new ComponentInfo(parent, getWidthString(parent)));
while ((parent = parent.getParent()) != null) {
attributes.add(new ComponentInfo(parent, getWidthString(parent)));
}
return attributes;
}
private static String getWidthString(Component component) {
String width = "width: ";
if (hasRelativeWidth(component)) {
width += "RELATIVE, " + component.getWidth() + " %";
} else if (hasUndefinedWidth(component)) {
width += "UNDEFINED";
} else if (component instanceof Window && component.getParent() == null) {
width += "MAIN WINDOW";
} else {
width += "ABSOLUTE, " + component.getWidth() + " "
+ Sizeable.UNIT_SYMBOLS[component.getWidthUnits()];
}
return width;
}
private static String getHeightString(Component component) {
String height = "height: ";
if (hasRelativeHeight(component)) {
height += "RELATIVE, " + component.getHeight() + " %";
} else if (hasUndefinedHeight(component)) {
height += "UNDEFINED";
} else if (component instanceof Window && component.getParent() == null) {
height += "MAIN WINDOW";
} else {
height += "ABSOLUTE, " + component.getHeight() + " "
+ Sizeable.UNIT_SYMBOLS[component.getHeightUnits()];
}
return height;
}
private static void showComponent(Component component, String attribute,
StringBuffer err, StringBuilder indent) {
err.append(indent);
indent.append(" ");
err.append("- ");
err.append(component.getClass().getSimpleName());
err.append("/").append(Integer.toHexString(component.hashCode()));
err.append(" (");
if (component.getCaption() != null) {
err.append("\"");
err.append(component.getCaption());
err.append("\"");
}
if (component.getDebugId() != null) {
err.append(" debugId: ");
err.append(component.getDebugId());
}
err.append(")");
if (attribute != null) {
err.append(" (");
err.append(attribute);
err.append(")");
}
err.append("\n");
}
private static String getRelativeHeight(Component component) {
return component.getHeight() + " %";
}
private static boolean hasNonRelativeHeightComponent(OrderedLayout ol) {
Iterator it = ol.getComponentIterator();
while (it.hasNext()) {
if (!hasRelativeHeight((Component) it.next())) {
return true;
}
}
return false;
}
private static boolean hasUndefinedHeight(Component parent) {
if (parent instanceof Window) {
Window w = (Window) parent;
if (w.getParent() == null) {
// main window is considered to have size
return false;
}
}
if (parent.getHeight() < 0) {
return true;
} else {
if (hasRelativeHeight(parent) && parent.getParent() != null) {
return hasUndefinedHeight(parent.getParent());
} else {
return false;
}
}
}
private static boolean hasRelativeHeight(Component component) {
return (component.getHeightUnits() == Sizeable.UNITS_PERCENTAGE && component
.getHeight() > 0);
}
private static boolean hasNonRelativeWidthComponent(OrderedLayout ol) {
Iterator it = ol.getComponentIterator();
while (it.hasNext()) {
if (!hasRelativeWidth((Component) it.next())) {
return true;
}
}
return false;
}
private static boolean hasRelativeWidth(Component paintable) {
return paintable.getWidth() > 0
&& paintable.getWidthUnits() == Sizeable.UNITS_PERCENTAGE;
}
private static boolean hasUndefinedWidth(Component component) {
if (component instanceof Window) {
Window w = (Window) component;
if (w.getParent() == null) {
// main window is considered to have size
return false;
}
}
if (component.getWidth() < 0) {
return true;
} else {
if (hasRelativeWidth(component) && component.getParent() != null) {
return hasUndefinedWidth(component.getParent());
} else {
return false;
}
}
}
}
| true | true |
private static boolean checkHeights(Component component) {
Component parent = component.getParent();
String msg = null;
Stack<ComponentInfo> attributes = null;
if (hasRelativeHeight(component) && hasUndefinedHeight(parent)) {
if (parent instanceof OrderedLayout) {
OrderedLayout ol = (OrderedLayout) parent;
if (ol.getOrientation() == OrderedLayout.ORIENTATION_VERTICAL) {
msg = "Relative height for component inside non sized vertical ordered layout.";
attributes = getHeightAttributes(component);
} else if (!hasNonRelativeHeightComponent(ol)) {
msg = "At least one of horizontal orderedlayout's components must have non relative height if layout has no height defined";
attributes = getHeightAttributes(component);
} else {
// valid situation, other components defined height
}
} else if (parent instanceof GridLayout) {
GridLayout gl = (GridLayout) parent;
Area componentArea = gl.getComponentArea(component);
boolean rowHasHeight = false;
for (int row = componentArea.getRow1(); !rowHasHeight
&& row <= componentArea.getRow2(); row++) {
for (int column = 0; !rowHasHeight
&& column < gl.getColumns(); column++) {
Component c = gl.getComponent(column, row);
if (c != null) {
rowHasHeight = !hasRelativeHeight(c);
}
}
}
if (!rowHasHeight) {
msg = "At least one component in each row should have non relative height in GridLayout with undefined height.";
attributes = getHeightAttributes(component);
}
} else {
// default error for non sized parent issue
msg = "Relative height component's parent should not have undefined height.";
attributes = getHeightAttributes(component);
}
}
if (msg != null) {
showError(msg, attributes);
}
return (msg == null);
}
|
private static boolean checkHeights(Component component) {
Component parent = component.getParent();
String msg = null;
Stack<ComponentInfo> attributes = null;
if (hasRelativeHeight(component) && hasUndefinedHeight(parent)) {
if (parent instanceof OrderedLayout) {
OrderedLayout ol = (OrderedLayout) parent;
if (ol.getOrientation() == OrderedLayout.ORIENTATION_VERTICAL) {
msg = "Relative height for component inside non sized vertical ordered layout.";
attributes = getHeightAttributes(component);
} else if (!hasNonRelativeHeightComponent(ol)) {
msg = "At least one of horizontal orderedlayout's components must have non relative height if layout has no height defined";
attributes = getHeightAttributes(component);
} else {
// valid situation, other components defined height
}
} else if (parent instanceof GridLayout) {
GridLayout gl = (GridLayout) parent;
Area componentArea = gl.getComponentArea(component);
boolean rowHasHeight = false;
for (int row = componentArea.getRow1(); !rowHasHeight
&& row <= componentArea.getRow2(); row++) {
for (int column = 0; !rowHasHeight
&& column < gl.getColumns(); column++) {
Component c = gl.getComponent(column, row);
if (c != null) {
rowHasHeight = !hasRelativeHeight(c);
}
}
}
if (!rowHasHeight) {
msg = "At least one component in each row should have non relative height in GridLayout with undefined height.";
attributes = getHeightAttributes(component);
}
} else if (!(parent instanceof CustomLayout)) {
// default error for non sized parent issue
msg = "Relative height component's parent should not have undefined height.";
attributes = getHeightAttributes(component);
}
}
if (msg != null) {
showError(msg, attributes);
}
return (msg == null);
}
|
diff --git a/eclipse_project/src/com/ptzlabs/wc/servlet/ReadingServlet.java b/eclipse_project/src/com/ptzlabs/wc/servlet/ReadingServlet.java
index cfc69df..4733eef 100644
--- a/eclipse_project/src/com/ptzlabs/wc/servlet/ReadingServlet.java
+++ b/eclipse_project/src/com/ptzlabs/wc/servlet/ReadingServlet.java
@@ -1,177 +1,177 @@
package com.ptzlabs.wc.servlet;
import static com.googlecode.objectify.ObjectifyService.ofy;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.util.Date;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.googlecode.objectify.Key;
import com.ptzlabs.wc.Chunk;
import com.ptzlabs.wc.Reading;
public class ReadingServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
if (req.getParameter("mode").equals("new")
&& req.getParameter("name") != null
&& req.getParameter("location") != null
&& req.getParameter("fbid") != null
&& req.getParameter("type") != null) {
Reading reading;
if (req.getParameter("dueDate") != null) {
reading = new Reading(req.getParameter("name"), new Date(
Long.parseLong(req.getParameter("dueDate"))),
Long.parseLong(req.getParameter("fbid")));
} else {
reading = new Reading(req.getParameter("name"),
Long.parseLong(req.getParameter("fbid")));
}
ofy().save().entity(reading).now();
Key<Reading> readingKey = Key.create(Reading.class, reading.id);
if (req.getParameter("type").equals("application/pdf")) {
PDDocument document = PDDocument.load(req
.getParameter("location"));
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
String[] line_arr = text.split("\\. ");
int sentence = 0;
int i = 0;
String data = "";
while (i < line_arr.length) {
data += line_arr[i];
sentence++;
if (sentence == 2) {
Chunk chunk = new Chunk(readingKey, data);
ofy().save().entity(chunk).now();
sentence = 0;
data = "";
}
i++;
}
if (sentence != 0) {
Chunk chunk = new Chunk(readingKey, data);
ofy().save().entity(chunk).now();
}
} else {
AppEngineFile file = readFileAndStore(req
.getParameter("location"));
FileService fileService = FileServiceFactory.getFileService();
// Later, read from the file using the file API
FileReadChannel readChannel = fileService.openReadChannel(file,
false);
// Again, different standard Java ways of reading from the
// channel.
BufferedReader reader = new BufferedReader(Channels.newReader(
readChannel, "UTF8"));
String line = reader.readLine();
String[] line_arr = line.split("\\. ");
String data = "";
int sentence = 0;
while (line != null) {
int i = 0;
while (i < line_arr.length) {
data += line_arr[i];
- if (line_arr[i].charAt(line_arr[i].length()) == '.') {
+ if (line_arr[i].charAt(line_arr[i].length() - 1) == '.') {
sentence++;
if (sentence == 2) {
Chunk chunk = new Chunk(readingKey, data);
ofy().save().entity(chunk).now();
sentence = 0;
data = "";
}
}
i++;
}
line = reader.readLine();
line_arr = line.split("\\. ");
}
if (data.equals("")) {
Chunk chunk = new Chunk(readingKey, data);
ofy().save().entity(chunk).now();
}
readChannel.close();
// remove blob from blobstore
BlobKey blobKey = fileService.getBlobKey(file);
BlobstoreService blobStoreService = BlobstoreServiceFactory
.getBlobstoreService();
blobStoreService.delete(blobKey);
}
resp.setContentType("text/plain");
resp.getWriter().println("OK");
}
}
private static AppEngineFile readFileAndStore(String location) throws IOException {
// Get a file service
FileService fileService = FileServiceFactory.getFileService();
// Create a new Blob file with mime-type "text/plain"
AppEngineFile file = fileService.createNewBlobFile("text/plain");
// Open a channel to write to it
boolean lock = false;
FileWriteChannel writeChannel = fileService.openWriteChannel(file,
lock);
BufferedReader reader;
// InputStream in = new BufferedInputStream(new
// URL(location).openStream());
reader = new BufferedReader(new InputStreamReader(
new URL(location).openStream()));
String line;
while ((line = reader.readLine()) != null) {
writeChannel.write(ByteBuffer.wrap(line.getBytes()));
}
reader.close();
/*
* byte data[] = new byte[1024]; int count; while ((count =
* in.read(data, 0, 1024)) != -1) {
* writeChannel.write(ByteBuffer.wrap(data)); } if (in != null)
* in.close();
*/
writeChannel.closeFinally();
return file;
}
}
| true | true |
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
if (req.getParameter("mode").equals("new")
&& req.getParameter("name") != null
&& req.getParameter("location") != null
&& req.getParameter("fbid") != null
&& req.getParameter("type") != null) {
Reading reading;
if (req.getParameter("dueDate") != null) {
reading = new Reading(req.getParameter("name"), new Date(
Long.parseLong(req.getParameter("dueDate"))),
Long.parseLong(req.getParameter("fbid")));
} else {
reading = new Reading(req.getParameter("name"),
Long.parseLong(req.getParameter("fbid")));
}
ofy().save().entity(reading).now();
Key<Reading> readingKey = Key.create(Reading.class, reading.id);
if (req.getParameter("type").equals("application/pdf")) {
PDDocument document = PDDocument.load(req
.getParameter("location"));
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
String[] line_arr = text.split("\\. ");
int sentence = 0;
int i = 0;
String data = "";
while (i < line_arr.length) {
data += line_arr[i];
sentence++;
if (sentence == 2) {
Chunk chunk = new Chunk(readingKey, data);
ofy().save().entity(chunk).now();
sentence = 0;
data = "";
}
i++;
}
if (sentence != 0) {
Chunk chunk = new Chunk(readingKey, data);
ofy().save().entity(chunk).now();
}
} else {
AppEngineFile file = readFileAndStore(req
.getParameter("location"));
FileService fileService = FileServiceFactory.getFileService();
// Later, read from the file using the file API
FileReadChannel readChannel = fileService.openReadChannel(file,
false);
// Again, different standard Java ways of reading from the
// channel.
BufferedReader reader = new BufferedReader(Channels.newReader(
readChannel, "UTF8"));
String line = reader.readLine();
String[] line_arr = line.split("\\. ");
String data = "";
int sentence = 0;
while (line != null) {
int i = 0;
while (i < line_arr.length) {
data += line_arr[i];
if (line_arr[i].charAt(line_arr[i].length()) == '.') {
sentence++;
if (sentence == 2) {
Chunk chunk = new Chunk(readingKey, data);
ofy().save().entity(chunk).now();
sentence = 0;
data = "";
}
}
i++;
}
line = reader.readLine();
line_arr = line.split("\\. ");
}
if (data.equals("")) {
Chunk chunk = new Chunk(readingKey, data);
ofy().save().entity(chunk).now();
}
readChannel.close();
// remove blob from blobstore
BlobKey blobKey = fileService.getBlobKey(file);
BlobstoreService blobStoreService = BlobstoreServiceFactory
.getBlobstoreService();
blobStoreService.delete(blobKey);
}
resp.setContentType("text/plain");
resp.getWriter().println("OK");
}
}
|
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
if (req.getParameter("mode").equals("new")
&& req.getParameter("name") != null
&& req.getParameter("location") != null
&& req.getParameter("fbid") != null
&& req.getParameter("type") != null) {
Reading reading;
if (req.getParameter("dueDate") != null) {
reading = new Reading(req.getParameter("name"), new Date(
Long.parseLong(req.getParameter("dueDate"))),
Long.parseLong(req.getParameter("fbid")));
} else {
reading = new Reading(req.getParameter("name"),
Long.parseLong(req.getParameter("fbid")));
}
ofy().save().entity(reading).now();
Key<Reading> readingKey = Key.create(Reading.class, reading.id);
if (req.getParameter("type").equals("application/pdf")) {
PDDocument document = PDDocument.load(req
.getParameter("location"));
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
String[] line_arr = text.split("\\. ");
int sentence = 0;
int i = 0;
String data = "";
while (i < line_arr.length) {
data += line_arr[i];
sentence++;
if (sentence == 2) {
Chunk chunk = new Chunk(readingKey, data);
ofy().save().entity(chunk).now();
sentence = 0;
data = "";
}
i++;
}
if (sentence != 0) {
Chunk chunk = new Chunk(readingKey, data);
ofy().save().entity(chunk).now();
}
} else {
AppEngineFile file = readFileAndStore(req
.getParameter("location"));
FileService fileService = FileServiceFactory.getFileService();
// Later, read from the file using the file API
FileReadChannel readChannel = fileService.openReadChannel(file,
false);
// Again, different standard Java ways of reading from the
// channel.
BufferedReader reader = new BufferedReader(Channels.newReader(
readChannel, "UTF8"));
String line = reader.readLine();
String[] line_arr = line.split("\\. ");
String data = "";
int sentence = 0;
while (line != null) {
int i = 0;
while (i < line_arr.length) {
data += line_arr[i];
if (line_arr[i].charAt(line_arr[i].length() - 1) == '.') {
sentence++;
if (sentence == 2) {
Chunk chunk = new Chunk(readingKey, data);
ofy().save().entity(chunk).now();
sentence = 0;
data = "";
}
}
i++;
}
line = reader.readLine();
line_arr = line.split("\\. ");
}
if (data.equals("")) {
Chunk chunk = new Chunk(readingKey, data);
ofy().save().entity(chunk).now();
}
readChannel.close();
// remove blob from blobstore
BlobKey blobKey = fileService.getBlobKey(file);
BlobstoreService blobStoreService = BlobstoreServiceFactory
.getBlobstoreService();
blobStoreService.delete(blobKey);
}
resp.setContentType("text/plain");
resp.getWriter().println("OK");
}
}
|
diff --git a/Tools/ChanServ/src/main/java/com/springrts/chanserv/Misc.java b/Tools/ChanServ/src/main/java/com/springrts/chanserv/Misc.java
index 947ff1d..92b871b 100644
--- a/Tools/ChanServ/src/main/java/com/springrts/chanserv/Misc.java
+++ b/Tools/ChanServ/src/main/java/com/springrts/chanserv/Misc.java
@@ -1,174 +1,174 @@
/*
* Created on 5.1.2006
*/
package com.springrts.chanserv;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Semaphore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Betalord
*/
public class Misc {
private static final Logger logger = LoggerFactory.getLogger(ChanServ.class);
public static final String EOL = "\n";
private static String hex = "0123456789ABCDEF";
private Misc() {
}
public static String easyDateFormat(String format) {
Date today = new Date();
DateFormat formatter = new SimpleDateFormat(format);
String datenewformat = formatter.format(today);
return datenewformat;
}
/** Returns a Unix-like timestamp */
public static long getUnixTimestamp() {
return (System.currentTimeMillis() / 1000);
}
/** Puts together strings from sl, starting at sl[startIndex] */
public static String makeSentence(String[] sl, int startIndex) {
if (startIndex > (sl.length - 1)) {
return "";
}
StringBuilder res = new StringBuilder(sl[startIndex]);
for (int i = startIndex+1; i < sl.length; i++) {
res.append(" ").append(sl[i]);
}
return res.toString();
}
public static String makeSentence(List<String> sl, int startIndex) {
if (startIndex > (sl.size() - 1)) {
return "";
}
StringBuilder res = new StringBuilder(sl.get(startIndex));
for (int i = startIndex+1; i < sl.size(); i++) {
res.append(" ").append(sl.get(i));
}
return res.toString();
}
public static String boolToStr(boolean b) {
return (b ? "1" : "0");
}
public static boolean strToBool(String s) {
return s.equals("1");
}
public static char[] byteToHex(byte b) {
char[] res = new char[2];
res[0] = hex.charAt((b & 0xF0) >> 4);
res[1] = hex.charAt(b & 0x0F);
return res;
}
/**
* Converts time (in milliseconds) to
* "<x> days, <y> hours and <z> minutes" string
*/
public static String timeToDHM(long duration) {
- long duration_left = duration;
+ long durationLeft = duration;
long days = duration / (1000 * 60 * 60 * 24);
- duration_left -= days * (1000 * 60 * 60 * 24);
- long hours = duration / (1000 * 60 * 60);
+ durationLeft -= days * (1000 * 60 * 60 * 24);
+ long hours = durationLeft / (1000 * 60 * 60);
- duration_left -= hours * (1000 * 60 * 60);
- long minutes = duration / (1000 * 60);
+ durationLeft -= hours * (1000 * 60 * 60);
+ long minutes = durationLeft / (1000 * 60);
String res = String.format(
"%i days, %i hours and %i minutes",
days, hours, minutes);
return res;
}
public static boolean appendTextToFile(String logFile, String text, boolean newLine) {
try {
PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(logFile, true)));
if (newLine) {
out.println(text);
} else {
out.print(text);
}
out.close();
} catch (Exception ex) {
logger.warn("Failed logging to file: " + logFile, ex);
return false;
}
return true;
}
private static Semaphore logToDiskLock = new Semaphore(1, true);
/** folder where log files are put */
private static final String LOG_FOLDER = "./log";
/**
* Timestamp is automatically added in front of the line.
* @param fname file name without path ("./logs" path is automatically added).
*/
private static boolean logToFile(String fname, String text, boolean newLine) {
try {
logToDiskLock.acquire();
return Misc.appendTextToFile(LOG_FOLDER + "/" + fname, Misc.getUnixTimestamp() + " " + text, newLine);
} catch (InterruptedException e) {
return false;
} finally {
logToDiskLock.release();
}
}
public static boolean logToFile(String fname, String text) {
return logToFile(fname, text, true);
}
/** Creates a string consisting of the specified amount of spaces */
public static String enumSpaces(int len) {
String result = "";
for (int i = 0; i < len; i++) {
result += " ";
}
return result;
}
/**
* Returns <code>false</code> if name (of a channel, username, ...)
* is invalid
*/
public static boolean isValidName(String name) {
return (name.length() > 0) && name.matches("^[0-9a-zA-Z_\\[\\]]*$");
}
}
| false | true |
public static String timeToDHM(long duration) {
long duration_left = duration;
long days = duration / (1000 * 60 * 60 * 24);
duration_left -= days * (1000 * 60 * 60 * 24);
long hours = duration / (1000 * 60 * 60);
duration_left -= hours * (1000 * 60 * 60);
long minutes = duration / (1000 * 60);
String res = String.format(
"%i days, %i hours and %i minutes",
days, hours, minutes);
return res;
}
|
public static String timeToDHM(long duration) {
long durationLeft = duration;
long days = duration / (1000 * 60 * 60 * 24);
durationLeft -= days * (1000 * 60 * 60 * 24);
long hours = durationLeft / (1000 * 60 * 60);
durationLeft -= hours * (1000 * 60 * 60);
long minutes = durationLeft / (1000 * 60);
String res = String.format(
"%i days, %i hours and %i minutes",
days, hours, minutes);
return res;
}
|
diff --git a/MODSRC/vazkii/tinkerer/common/research/ModRecipes.java b/MODSRC/vazkii/tinkerer/common/research/ModRecipes.java
index d31612a0..de4e1347 100644
--- a/MODSRC/vazkii/tinkerer/common/research/ModRecipes.java
+++ b/MODSRC/vazkii/tinkerer/common/research/ModRecipes.java
@@ -1,268 +1,268 @@
/**
* This class was created by <Vazkii>. It's distributed as
* part of the ThaumicTinkerer Mod.
*
* ThaumicTinkerer is Open Source and distributed under a
* Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License
* (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB)
*
* ThaumicTinkerer is a Derivative Work on Thaumcraft 4.
* Thaumcraft 4 (c) Azanor 2012
* (http://www.minecraftforum.net/topic/1585216-)
*
* File Created @ [4 Sep 2013, 17:02:48 (GMT)]
*/
package vazkii.tinkerer.common.research;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraftforge.oredict.OreDictionary;
import thaumcraft.api.ThaumcraftApi;
import thaumcraft.api.aspects.Aspect;
import thaumcraft.api.aspects.AspectList;
import thaumcraft.api.crafting.CrucibleRecipe;
import thaumcraft.api.crafting.InfusionRecipe;
import thaumcraft.api.crafting.ShapedArcaneRecipe;
import thaumcraft.common.config.ConfigBlocks;
import thaumcraft.common.config.ConfigItems;
import thaumcraft.common.config.ConfigResearch;
import vazkii.tinkerer.common.block.ModBlocks;
import vazkii.tinkerer.common.core.handler.ConfigHandler;
import vazkii.tinkerer.common.item.ModItems;
import vazkii.tinkerer.common.lib.LibResearch;
import cpw.mods.fml.common.registry.GameRegistry;
public final class ModRecipes {
public static void initRecipes() {
initCraftingRecipes();
initArcaneRecipes();
initInfusionRecipes();
initCrucibleRecipes();
}
private static void initCraftingRecipes() {
registerResearchItem(LibResearch.KEY_DARK_QUARTZ + 0, new ItemStack(ModItems.darkQuartz, 8),
"QQQ", "QCQ", "QQQ",
'Q', Item.netherQuartz,
'C', Item.coal);
registerResearchItem(LibResearch.KEY_DARK_QUARTZ + 0, new ItemStack(ModItems.darkQuartz, 8),
"QQQ", "QCQ", "QQQ",
'Q', Item.netherQuartz,
'C', new ItemStack(Item.coal, 1, 1));
registerResearchItem(LibResearch.KEY_DARK_QUARTZ + 1, new ItemStack(ModBlocks.darkQuartz),
"QQ", "QQ",
'Q', ModItems.darkQuartz);
registerResearchItem(LibResearch.KEY_DARK_QUARTZ + 2, new ItemStack(ModBlocks.darkQuartzSlab, 6),
"QQQ",
'Q', ModBlocks.darkQuartz);
registerResearchItem(LibResearch.KEY_DARK_QUARTZ + 3, new ItemStack(ModBlocks.darkQuartz, 2, 2),
"Q", "Q",
'Q', ModBlocks.darkQuartz);
registerResearchItem(LibResearch.KEY_DARK_QUARTZ + 4, new ItemStack(ModBlocks.darkQuartz, 1, 1),
"Q", "Q",
'Q', ModBlocks.darkQuartzSlab);
registerResearchItem(LibResearch.KEY_DARK_QUARTZ + 5, new ItemStack(ModBlocks.darkQuartzStairs, 4),
" Q", " QQ", "QQQ",
'Q', ModBlocks.darkQuartz);
registerResearchItem("", new ItemStack(ModBlocks.darkQuartzStairs, 4),
"Q ", "QQ ", "QQQ",
'Q', ModBlocks.darkQuartz);
registerResearchItem(LibResearch.KEY_INFUSED_INKWELL + 0, new ItemStack(ModItems.infusedInkwell),
"QQQ", "QCQ", "QQQ",
'Q', new ItemStack(Item.dyePowder, 1, 0),
'C', new ItemStack(ModItems.infusedInkwell, 1, 32767));
if(ConfigHandler.enableKami) {
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.kamiResource, 9, 3), new ItemStack(ModItems.kamiResource, 1, 2));
}
}
private static void initArcaneRecipes() {
registerResearchItem(LibResearch.KEY_INTERFACE, LibResearch.KEY_INTERFACE, new ItemStack(ModBlocks.interfase), new AspectList().add(Aspect.ORDER, 12).add(Aspect.ENTROPY, 16),
"BRB", "LEL", "BRB",
'B', new ItemStack(ConfigBlocks.blockCosmeticSolid, 1, 6),
'E', new ItemStack(Item.enderPearl),
'L', new ItemStack(Item.dyePowder, 1, 4),
'R', new ItemStack(Item.redstone));
registerResearchItem(LibResearch.KEY_CONNECTOR, LibResearch.KEY_INTERFACE, new ItemStack(ModItems.connector), new AspectList().add(Aspect.ORDER, 2),
" I ", " WI", "S ",
'I', new ItemStack(Item.ingotIron),
'W', new ItemStack(Item.stick),
'S', new ItemStack(ConfigItems.itemShard, 1, 4));
registerResearchItem(LibResearch.KEY_GAS_REMOVER, LibResearch.KEY_GAS_REMOVER, new ItemStack(ModItems.gasRemover), new AspectList().add(Aspect.AIR, 2).add(Aspect.ORDER, 2),
"DDD", "T G", "QQQ",
'D', new ItemStack(ModItems.darkQuartz),
'T', new ItemStack(ModItems.gaseousShadow),
'G', new ItemStack(ModItems.gaseousLight),
'Q', new ItemStack(Item.netherQuartz));
registerResearchItem(LibResearch.KEY_ANIMATION_TABLET, LibResearch.KEY_ANIMATION_TABLET, new ItemStack(ModBlocks.animationTablet), new AspectList().add(Aspect.AIR, 25).add(Aspect.ORDER, 15).add(Aspect.FIRE, 10),
"GIG", "ICI",
'G', new ItemStack(Item.ingotGold),
'I', new ItemStack(Item.ingotIron),
'C', new ItemStack(ConfigItems.itemGolemCore, 1, 100));
registerResearchItem(LibResearch.KEY_MAGNET, LibResearch.KEY_MAGNETS, new ItemStack(ModBlocks.magnet), new AspectList().add(Aspect.AIR, 20).add(Aspect.ORDER, 5).add(Aspect.EARTH, 15).add(Aspect.ENTROPY, 5),
" I ", "SIs", "WFW",
'I', new ItemStack(Item.ingotIron),
's', new ItemStack(ConfigItems.itemShard, 1, 3),
'S', new ItemStack(ConfigItems.itemShard),
'W', new ItemStack(ConfigBlocks.blockMagicalLog),
'F', new ItemStack(ModItems.focusTelekinesis));
registerResearchItem(LibResearch.KEY_MOB_MAGNET, LibResearch.KEY_MAGNETS, new ItemStack(ModBlocks.magnet, 1, 1), new AspectList().add(Aspect.AIR, 20).add(Aspect.ORDER, 5).add(Aspect.EARTH, 15).add(Aspect.ENTROPY, 5),
" G ", "SGs", "WFW",
'G', oreDictOrStack(new ItemStack(Item.ingotGold), "ingotCopper"),
's', new ItemStack(ConfigItems.itemShard, 1, 3),
'S', new ItemStack(ConfigItems.itemShard),
'W', new ItemStack(ConfigBlocks.blockMagicalLog),
'F', new ItemStack(ModItems.focusTelekinesis));
registerResearchItem(LibResearch.KEY_FUNNEL, LibResearch.KEY_FUNNEL, new ItemStack(ModBlocks.funnel), new AspectList().add(Aspect.ORDER, 1).add(Aspect.ENTROPY, 1),
"STS",
'S', new ItemStack(Block.stone),
'T', new ItemStack(ConfigItems.itemResource, 1, 2));
registerResearchItem(LibResearch.KEY_FOCUS_SMELT, LibResearch.KEY_FOCUS_SMELT, new ItemStack(ModItems.focusSmelt), new AspectList().add(Aspect.FIRE, 10).add(Aspect.ORDER, 5).add(Aspect.ENTROPY, 6),
"FNE",
'F', new ItemStack(ConfigItems.itemFocusFire),
'E', new ItemStack(ConfigItems.itemFocusExcavation),
'N', new ItemStack(ConfigItems.itemResource, 1, 1));
registerResearchItem(LibResearch.KEY_FOCUS_ENDER_CHEST, LibResearch.KEY_FOCUS_ENDER_CHEST, new ItemStack(ModItems.focusEnderChest), new AspectList().add(Aspect.ORDER, 10).add(Aspect.ENTROPY, 10),
"M", "E", "P",
'M', new ItemStack(ConfigBlocks.blockMirror),
'E', new ItemStack(Item.eyeOfEnder),
'P', new ItemStack(ConfigItems.itemFocusPortableHole));
registerResearchItem(LibResearch.KEY_DISLOCATOR, LibResearch.KEY_DISLOCATOR, new ItemStack(ModBlocks.dislocator), new AspectList().add(Aspect.EARTH, 5).add(Aspect.ENTROPY, 5),
" M ", " I ", " C ",
'M', new ItemStack(ConfigItems.itemResource, 1, 10),
'I', new ItemStack(ModBlocks.interfase),
'C', new ItemStack(Item.comparator));
registerResearchItem(LibResearch.KEY_REVEALING_HELM, LibResearch.KEY_REVEALING_HELM, new ItemStack(ModItems.revealingHelm), new AspectList().add(Aspect.EARTH, 5).add(Aspect.FIRE, 5).add(Aspect.WATER, 5).add(Aspect.AIR, 5).add(Aspect.ORDER, 5).add(Aspect.ENTROPY, 5),
"GH",
'G', new ItemStack(ConfigItems.itemGoggles),
'H', new ItemStack(ConfigItems.itemHelmetThaumium));
registerResearchItem(LibResearch.KEY_ASPECT_ANALYZER, LibResearch.KEY_ASPECT_ANALYZER, new ItemStack(ModBlocks.aspectAnalyzer), new AspectList().add(Aspect.ORDER, 1).add(Aspect.ENTROPY, 1),
"TWT", "WMW", "TWT",
'W', new ItemStack(ConfigBlocks.blockWoodenDevice, 1, 6),
'M', new ItemStack(ConfigItems.itemThaumometer),
'T', new ItemStack(ConfigItems.itemResource, 1, 2));
registerResearchItem(LibResearch.KEY_PLATFORM, LibResearch.KEY_PLATFORM, new ItemStack(ModBlocks.platform, 2), new AspectList().add(Aspect.AIR, 2).add(Aspect.ENTROPY, 4),
" S ", "G G",
'G', new ItemStack(ConfigBlocks.blockWoodenDevice, 1, 6),
'S', new ItemStack(ConfigBlocks.blockWoodenDevice, 1, 7));
if(ConfigHandler.enableKami) {
registerResearchItem(LibResearch.KEY_ICHOR_CLOTH, LibResearch.KEY_ICHOR_CLOTH, new ItemStack(ModItems.kamiResource, 3, 1), new AspectList().add(Aspect.FIRE, 125).add(Aspect.EARTH, 125).add(Aspect.WATER, 125).add(Aspect.AIR, 125).add(Aspect.ORDER, 125).add(Aspect.ENTROPY, 125),
"CCC", "III", "DDD",
'C', new ItemStack(ConfigItems.itemResource, 1, 7),
'I', new ItemStack(ModItems.kamiResource, 1, 0),
'D', new ItemStack(Item.diamond));
registerResearchItem(LibResearch.KEY_ICHORIUM, LibResearch.KEY_ICHORIUM, new ItemStack(ModItems.kamiResource, 1, 2), new AspectList().add(Aspect.FIRE, 100).add(Aspect.EARTH, 100).add(Aspect.WATER, 100).add(Aspect.AIR, 100).add(Aspect.ORDER, 100).add(Aspect.ENTROPY, 100),
" T ", "IDI", " I ",
'T', new ItemStack(ConfigItems.itemResource, 1, 2),
'I', new ItemStack(ModItems.kamiResource, 1, 0),
'D', new ItemStack(Item.diamond));
registerResearchItem(LibResearch.KEY_ICHOR_CAP, LibResearch.KEY_ICHOR_CAP, new ItemStack(ModItems.kamiResource, 2, 4), new AspectList().add(Aspect.FIRE, 100).add(Aspect.EARTH, 100).add(Aspect.WATER, 100).add(Aspect.AIR, 100).add(Aspect.ORDER, 100).add(Aspect.ENTROPY, 100),
"ICI", " M ", "ICI",
'M', new ItemStack(ModItems.kamiResource, 1, 2),
'I', new ItemStack(ModItems.kamiResource, 1, 0),
'C', new ItemStack(ConfigItems.itemWandCap, 1, 2));
- registerResearchItem(LibResearch.KEY_ICHORCLOTH_HELM, LibResearch.KEY_ICHORCLOTH_HELM, new ItemStack(ModItems.ichorHelm), new AspectList().add(Aspect.WATER, 75),
+ registerResearchItem(LibResearch.KEY_ICHORCLOTH_HELM, LibResearch.KEY_ICHORCLOTH_ARMOR, new ItemStack(ModItems.ichorHelm), new AspectList().add(Aspect.WATER, 75),
"CCC", "C C",
'C', new ItemStack(ModItems.kamiResource, 3, 1));
- registerResearchItem(LibResearch.KEY_ICHORCLOTH_CHEST, LibResearch.KEY_ICHORCLOTH_CHEST, new ItemStack(ModItems.ichorChest), new AspectList().add(Aspect.AIR, 75),
+ registerResearchItem(LibResearch.KEY_ICHORCLOTH_CHEST, LibResearch.KEY_ICHORCLOTH_ARMOR, new ItemStack(ModItems.ichorChest), new AspectList().add(Aspect.AIR, 75),
"C C", "CCC", "CCC",
'C', new ItemStack(ModItems.kamiResource, 3, 1));
- registerResearchItem(LibResearch.KEY_ICHORCLOTH_LEGS, LibResearch.KEY_ICHORCLOTH_LEGS, new ItemStack(ModItems.ichorLegs), new AspectList().add(Aspect.FIRE, 75),
+ registerResearchItem(LibResearch.KEY_ICHORCLOTH_LEGS, LibResearch.KEY_ICHORCLOTH_ARMOR, new ItemStack(ModItems.ichorLegs), new AspectList().add(Aspect.FIRE, 75),
"CCC", "C C", "C C",
'C', new ItemStack(ModItems.kamiResource, 3, 1));
- registerResearchItem(LibResearch.KEY_ICHORCLOTH_BOOTS, LibResearch.KEY_ICHORCLOTH_BOOTS, new ItemStack(ModItems.ichorBoots), new AspectList().add(Aspect.EARTH, 75),
+ registerResearchItem(LibResearch.KEY_ICHORCLOTH_BOOTS, LibResearch.KEY_ICHORCLOTH_ARMOR, new ItemStack(ModItems.ichorBoots), new AspectList().add(Aspect.EARTH, 75),
"C C", "C C",
'C', new ItemStack(ModItems.kamiResource, 3, 1));
}
}
private static void initInfusionRecipes() {
registerResearchItemI(LibResearch.KEY_FOCUS_FLIGHT, new ItemStack(ModItems.focusFlight), 3, new AspectList().add(Aspect.AIR, 15).add(Aspect.MOTION, 20).add(Aspect.TRAVEL, 10), new ItemStack(Item.enderPearl),
new ItemStack(Item.netherQuartz), new ItemStack(Item.netherQuartz), new ItemStack(Item.netherQuartz), new ItemStack(Item.netherQuartz), new ItemStack(Item.feather), new ItemStack(Item.feather), new ItemStack(ConfigItems.itemShard, 1, 0));
registerResearchItemI(LibResearch.KEY_FOCUS_DISLOCATION, new ItemStack(ModItems.focusDislocation), 8, new AspectList().add(Aspect.ELDRITCH, 20).add(Aspect.DARKNESS, 10).add(Aspect.VOID, 25).add(Aspect.MAGIC, 20).add(Aspect.TAINT, 5), new ItemStack(Item.enderPearl),
new ItemStack(Item.netherQuartz), new ItemStack(Item.netherQuartz), new ItemStack(Item.netherQuartz), new ItemStack(Item.netherQuartz), new ItemStack(ConfigItems.itemResource, 1, 6), new ItemStack(ConfigItems.itemResource, 1, 6), new ItemStack(ConfigItems.itemResource, 1, 6), new ItemStack(Item.diamond));
registerResearchItemI(LibResearch.KEY_FOCUS_TELEKINESIS, new ItemStack(ModItems.focusTelekinesis), 5, new AspectList().add(Aspect.MOTION, 10).add(Aspect.AIR, 20).add(Aspect.ENTROPY, 20).add(Aspect.MIND, 10), new ItemStack(Item.enderPearl),
new ItemStack(Item.netherQuartz), new ItemStack(Item.netherQuartz), new ItemStack(Item.netherQuartz), new ItemStack(Item.netherQuartz), new ItemStack(Item.ingotIron), new ItemStack(Item.ingotGold), new ItemStack(ConfigItems.itemShard, 1, 0));
registerResearchItemI(LibResearch.KEY_CLEANSING_TALISMAN, new ItemStack(ModItems.cleansingTalisman), 5, new AspectList().add(Aspect.HEAL, 10).add(Aspect.TOOL, 10).add(Aspect.MAN, 20).add(Aspect.LIFE, 10), new ItemStack(Item.enderPearl),
new ItemStack(ModItems.darkQuartz), new ItemStack(ModItems.darkQuartz), new ItemStack(ModItems.darkQuartz), new ItemStack(ModItems.darkQuartz), new ItemStack(Item.ghastTear), new ItemStack(ConfigItems.itemResource, 1, 1));
registerResearchItemI(LibResearch.KEY_ENCHANTER, new ItemStack(ModBlocks.enchanter), 15, new AspectList().add(Aspect.MAGIC, 50).add(Aspect.ENERGY, 20).add(Aspect.ELDRITCH, 20).add(Aspect.VOID, 20).add(Aspect.MIND, 10), new ItemStack(Block.enchantmentTable),
new ItemStack(ConfigBlocks.blockCosmeticSolid, 1, 1), new ItemStack(ConfigBlocks.blockCosmeticSolid, 1, 1), new ItemStack(ConfigBlocks.blockCosmeticSolid, 1, 1), new ItemStack(ConfigBlocks.blockCosmeticSolid, 1, 1), new ItemStack(ConfigBlocks.blockCosmeticSolid, 1, 1), new ItemStack(ConfigItems.itemResource, 1, 2), new ItemStack(ConfigItems.itemResource, 1, 2), new ItemStack(ModItems.spellCloth));
registerResearchItemI(LibResearch.KEY_XP_TALISMAN, new ItemStack(ModItems.xpTalisman), 6, new AspectList().add(Aspect.GREED, 20).add(Aspect.EXCHANGE, 10).add(Aspect.BEAST, 10).add(Aspect.MECHANISM, 5), new ItemStack(Item.ingotGold),
new ItemStack(Item.netherQuartz), new ItemStack(ModItems.darkQuartz), new ItemStack(ConfigItems.itemResource, 1, 5), new ItemStack(Item.diamond));
registerResearchItemI(LibResearch.KEY_FOCUS_HEAL,new ItemStack(ModItems.focusHeal), 4, new AspectList().add(Aspect.HEAL, 10).add(Aspect.SOUL, 10).add(Aspect.LIFE, 15), new ItemStack(ConfigItems.itemFocusPech),
new ItemStack(Item.goldenCarrot), new ItemStack(Item.appleGold), new ItemStack(Item.goldNugget), new ItemStack(Item.goldNugget));
registerResearchItemI(LibResearch.KEY_BLOOD_SWORD, new ItemStack(ModItems.bloodSword), 6, new AspectList().add(Aspect.HUNGER, 20).add(Aspect.DARKNESS, 5).add(Aspect.SOUL, 10).add(Aspect.MAN, 6), new ItemStack(ConfigItems.itemSwordThaumium),
new ItemStack(Item.rottenFlesh), new ItemStack(Item.porkRaw), new ItemStack(Item.beefRaw), new ItemStack(Item.bone), new ItemStack(Item.diamond), new ItemStack(Item.ghastTear));
registerResearchItemI(LibResearch.KEY_INFUSED_INKWELL, new ItemStack(ModItems.infusedInkwell), 2, new AspectList().add(Aspect.VOID, 8).add(Aspect.DARKNESS, 8), new ItemStack(ConfigItems.itemInkwell),
new ItemStack(ConfigItems.itemShard, 1, 0), new ItemStack(ConfigBlocks.blockJar), new ItemStack(ConfigItems.itemResource, 1, 3));
registerResearchItemI(LibResearch.KEY_REPAIRER, new ItemStack(ModBlocks.repairer), 8, new AspectList().add(Aspect.TOOL, 15).add(Aspect.CRAFT, 20).add(Aspect.ORDER, 10).add(Aspect.MAGIC, 15), new ItemStack(ConfigBlocks.blockCosmeticSolid, 1, 4),
new ItemStack(Item.ingotIron), new ItemStack(Item.ingotGold), new ItemStack(Item.diamond), new ItemStack(Block.cobblestone), new ItemStack(Block.planks), new ItemStack(Item.leather), new ItemStack(ConfigItems.itemResource, 1, 7), new ItemStack(ConfigItems.itemResource, 1, 2));
registerResearchItemI(LibResearch.KEY_FOCUS_DEFLECT, new ItemStack(ModItems.focusDeflect), 5, new AspectList().add(Aspect.AIR, 15).add(Aspect.ARMOR, 5).add(Aspect.ORDER, 20), new ItemStack(ModItems.focusFlight),
new ItemStack(ConfigItems.itemResource, 1, 10), new ItemStack(ConfigItems.itemResource, 1, 10), new ItemStack(ConfigBlocks.blockCosmeticSolid, 1, 3), new ItemStack(ConfigItems.itemShard, 1, 4));
if(ConfigHandler.enableKami) {
registerResearchItemI(LibResearch.KEY_ICHOR, new ItemStack(ModItems.kamiResource, 8, 0), 7, new AspectList().add(Aspect.MAN, 32).add(Aspect.LIGHT, 32).add(Aspect.SOUL, 64), new ItemStack(Item.netherStar),
new ItemStack(Item.diamond), new ItemStack(ModItems.kamiResource, 8, 7), new ItemStack(Item.eyeOfEnder), new ItemStack(ModItems.kamiResource, 8, 6));
registerResearchItemI(LibResearch.KEY_ICHORCLOTH_ROD, new ItemStack(ModItems.kamiResource, 1, 5), 9, new AspectList().add(Aspect.MAGIC, 100).add(Aspect.LIGHT, 32).add(Aspect.TOOL, 32), new ItemStack(ConfigItems.itemWandRod, 1, 2),
new ItemStack(ModItems.kamiResource), new ItemStack(ModItems.kamiResource, 1, 1), new ItemStack(ConfigItems.itemResource, 1, 14), new ItemStack(Item.ghastTear), new ItemStack(ConfigItems.itemResource, 1, 14), new ItemStack(ModItems.kamiResource, 1, 1));
registerResearchItemI(LibResearch.KEY_ICHORCLOTH_HELM_GEM, new ItemStack(ModItems.ichorHelmGem), 13, new AspectList().add(Aspect.WATER, 50).add(Aspect.ARMOR, 32).add(Aspect.HUNGER, 32).add(Aspect.AURA, 32).add(Aspect.LIGHT, 64).add(Aspect.FLESH, 16).add(Aspect.MIND, 16), new ItemStack(ModItems.ichorHelm),
new ItemStack(Item.diamond, 1), new ItemStack(ModItems.kamiResource), new ItemStack(ModItems.kamiResource), new ItemStack(ConfigItems.itemManaBean), new ItemStack(ConfigItems.itemWispEssence), new ItemStack(Item.helmetGold), new ItemStack(Item.potion, 1, 8198), new ItemStack(ConfigItems.itemGoggles), new ItemStack(ModItems.cleansingTalisman), new ItemStack(Item.fishRaw), new ItemStack(Item.cake), new ItemStack(Item.eyeOfEnder));
registerResearchItemI(LibResearch.KEY_ICHORCLOTH_CHEST_GEM, new ItemStack(ModItems.ichorChestGem), 13, new AspectList().add(Aspect.AIR, 50).add(Aspect.ARMOR, 32).add(Aspect.FLIGHT, 32).add(Aspect.ORDER, 32).add(Aspect.LIGHT, 64).add(Aspect.ELDRITCH, 16).add(Aspect.SENSES, 16), new ItemStack(ModItems.ichorChest),
new ItemStack(Item.diamond, 1), new ItemStack(ModItems.kamiResource), new ItemStack(ModItems.kamiResource), new ItemStack(ConfigItems.itemManaBean), new ItemStack(ConfigItems.itemWispEssence), new ItemStack(Item.plateGold), new ItemStack(ModItems.focusFlight), new ItemStack(ConfigItems.itemHoverHarness), new ItemStack(ModItems.focusDeflect), new ItemStack(Item.feather), new ItemStack(Item.firework), new ItemStack(Item.arrow));
registerResearchItemI(LibResearch.KEY_ICHORCLOTH_LEGS_GEM, new ItemStack(ModItems.ichorLegsGem), 13, new AspectList().add(Aspect.FIRE, 50).add(Aspect.ARMOR, 32).add(Aspect.HEAL, 32).add(Aspect.ENERGY, 32).add(Aspect.LIGHT, 64).add(Aspect.GREED, 16).add(Aspect.ELDRITCH, 16), new ItemStack(ModItems.ichorLegs),
new ItemStack(Item.diamond, 1), new ItemStack(ModItems.kamiResource), new ItemStack(ModItems.kamiResource), new ItemStack(ConfigItems.itemManaBean), new ItemStack(ConfigItems.itemWispEssence), new ItemStack(Item.legsGold), new ItemStack(Item.potion, 1, 8195), new ItemStack(ModItems.focusSmelt), new ItemStack(ModItems.brightNitor), new ItemStack(Item.bucketLava), new ItemStack(Item.fireballCharge), new ItemStack(Item.blazeRod));
registerResearchItemI(LibResearch.KEY_ICHORCLOTH_BOOTS_GEM, new ItemStack(ModItems.ichorBootsGem), 13, new AspectList().add(Aspect.EARTH, 50).add(Aspect.ARMOR, 32).add(Aspect.MINE, 32).add(Aspect.MOTION, 32).add(Aspect.LIGHT, 64).add(Aspect.PLANT, 16).add(Aspect.TRAVEL, 16), new ItemStack(ModItems.ichorBoots),
new ItemStack(Item.diamond, 1), new ItemStack(ModItems.kamiResource), new ItemStack(ModItems.kamiResource), new ItemStack(ConfigItems.itemManaBean), new ItemStack(ConfigItems.itemWispEssence), new ItemStack(Item.bootsGold), new ItemStack(Block.grass), new ItemStack(ConfigBlocks.blockWoodenDevice, 1, 5), new ItemStack(ConfigBlocks.blockMetalDevice, 1, 8), new ItemStack(Item.seeds), new ItemStack(Block.cloth), new ItemStack(Item.leash));
registerResearchItemI(LibResearch.KEY_CAT_AMULET, new ItemStack(ModItems.catAmulet), 8, new AspectList().add(Aspect.DARKNESS, 16).add(Aspect.ORDER, 32).add(Aspect.MIND, 16), new ItemStack(Block.blockNetherQuartz),
new ItemStack(ModItems.kamiResource), new ItemStack(Item.ingotGold), new ItemStack(Item.ingotGold), new ItemStack(Item.dyePowder, 1, 3), new ItemStack(Block.leaves, 1, 3), new ItemStack(Item.fishRaw));
}
}
private static void initCrucibleRecipes() {
registerResearchItem(LibResearch.KEY_GASEOUS_LIGHT, new ItemStack(ModItems.gaseousLight), new ItemStack(ConfigItems.itemEssence, 1, 0), new AspectList().add(Aspect.LIGHT, 16).add(Aspect.AIR, 10).add(Aspect.MOTION, 8));
registerResearchItem(LibResearch.KEY_GASEOUS_SHADOW, new ItemStack(ModItems.gaseousShadow), new ItemStack(ConfigItems.itemEssence, 1, 0), new AspectList().add(Aspect.DARKNESS, 16).add(Aspect.AIR, 10).add(Aspect.MOTION, 8));
registerResearchItem(LibResearch.KEY_SPELL_CLOTH, new ItemStack(ModItems.spellCloth), new ItemStack(ConfigItems.itemResource, 0, 7), new AspectList().add(Aspect.MAGIC, 10).add(Aspect.ENTROPY, 6).add(Aspect.EXCHANGE, 4));
registerResearchItem(LibResearch.KEY_BRIGHT_NITOR, new ItemStack(ModItems.brightNitor), new ItemStack(ConfigItems.itemResource, 1, 1), new AspectList().add(Aspect.ENERGY, 25).add(Aspect.LIGHT, 25).add(Aspect.AIR, 10).add(Aspect.FIRE, 10));
registerResearchItem(LibResearch.KEY_MAGNETS, new ItemStack(ModItems.soulMould), new ItemStack(Item.enderPearl), new AspectList().add(Aspect.BEAST, 4).add(Aspect.MIND, 8).add(Aspect.SENSES, 8));
}
private static void registerResearchItem(String name, String research, ItemStack output, AspectList aspects, Object... stuff) {
ShapedArcaneRecipe recipe = ThaumcraftApi.addArcaneCraftingRecipe(research, output, aspects, stuff);
ConfigResearch.recipes.put(name, recipe);
}
private static void registerResearchItem(String name, ItemStack output, Object... stuff) {
GameRegistry.addRecipe(output, stuff);
List<IRecipe> recipeList = CraftingManager.getInstance().getRecipeList();
if(name != null && name.length() != 0)
ConfigResearch.recipes.put(name, recipeList.get(recipeList.size() - 1));
}
private static void registerResearchItem(String name, ItemStack output, ItemStack input, AspectList aspects) {
CrucibleRecipe recipe = ThaumcraftApi.addCrucibleRecipe(name, output, input, aspects);
ConfigResearch.recipes.put(name, recipe);
}
private static void registerResearchItemI(String name, Object output, int instability, AspectList aspects, ItemStack input, ItemStack... stuff) {
InfusionRecipe recipe = ThaumcraftApi.addInfusionCraftingRecipe(name, output, instability, aspects, input, stuff);
ConfigResearch.recipes.put(name, recipe);
}
private static Object oreDictOrStack(ItemStack stack, String oreDict) {
return OreDictionary.getOres(oreDict).isEmpty() ? stack : oreDict;
}
}
| false | true |
private static void initArcaneRecipes() {
registerResearchItem(LibResearch.KEY_INTERFACE, LibResearch.KEY_INTERFACE, new ItemStack(ModBlocks.interfase), new AspectList().add(Aspect.ORDER, 12).add(Aspect.ENTROPY, 16),
"BRB", "LEL", "BRB",
'B', new ItemStack(ConfigBlocks.blockCosmeticSolid, 1, 6),
'E', new ItemStack(Item.enderPearl),
'L', new ItemStack(Item.dyePowder, 1, 4),
'R', new ItemStack(Item.redstone));
registerResearchItem(LibResearch.KEY_CONNECTOR, LibResearch.KEY_INTERFACE, new ItemStack(ModItems.connector), new AspectList().add(Aspect.ORDER, 2),
" I ", " WI", "S ",
'I', new ItemStack(Item.ingotIron),
'W', new ItemStack(Item.stick),
'S', new ItemStack(ConfigItems.itemShard, 1, 4));
registerResearchItem(LibResearch.KEY_GAS_REMOVER, LibResearch.KEY_GAS_REMOVER, new ItemStack(ModItems.gasRemover), new AspectList().add(Aspect.AIR, 2).add(Aspect.ORDER, 2),
"DDD", "T G", "QQQ",
'D', new ItemStack(ModItems.darkQuartz),
'T', new ItemStack(ModItems.gaseousShadow),
'G', new ItemStack(ModItems.gaseousLight),
'Q', new ItemStack(Item.netherQuartz));
registerResearchItem(LibResearch.KEY_ANIMATION_TABLET, LibResearch.KEY_ANIMATION_TABLET, new ItemStack(ModBlocks.animationTablet), new AspectList().add(Aspect.AIR, 25).add(Aspect.ORDER, 15).add(Aspect.FIRE, 10),
"GIG", "ICI",
'G', new ItemStack(Item.ingotGold),
'I', new ItemStack(Item.ingotIron),
'C', new ItemStack(ConfigItems.itemGolemCore, 1, 100));
registerResearchItem(LibResearch.KEY_MAGNET, LibResearch.KEY_MAGNETS, new ItemStack(ModBlocks.magnet), new AspectList().add(Aspect.AIR, 20).add(Aspect.ORDER, 5).add(Aspect.EARTH, 15).add(Aspect.ENTROPY, 5),
" I ", "SIs", "WFW",
'I', new ItemStack(Item.ingotIron),
's', new ItemStack(ConfigItems.itemShard, 1, 3),
'S', new ItemStack(ConfigItems.itemShard),
'W', new ItemStack(ConfigBlocks.blockMagicalLog),
'F', new ItemStack(ModItems.focusTelekinesis));
registerResearchItem(LibResearch.KEY_MOB_MAGNET, LibResearch.KEY_MAGNETS, new ItemStack(ModBlocks.magnet, 1, 1), new AspectList().add(Aspect.AIR, 20).add(Aspect.ORDER, 5).add(Aspect.EARTH, 15).add(Aspect.ENTROPY, 5),
" G ", "SGs", "WFW",
'G', oreDictOrStack(new ItemStack(Item.ingotGold), "ingotCopper"),
's', new ItemStack(ConfigItems.itemShard, 1, 3),
'S', new ItemStack(ConfigItems.itemShard),
'W', new ItemStack(ConfigBlocks.blockMagicalLog),
'F', new ItemStack(ModItems.focusTelekinesis));
registerResearchItem(LibResearch.KEY_FUNNEL, LibResearch.KEY_FUNNEL, new ItemStack(ModBlocks.funnel), new AspectList().add(Aspect.ORDER, 1).add(Aspect.ENTROPY, 1),
"STS",
'S', new ItemStack(Block.stone),
'T', new ItemStack(ConfigItems.itemResource, 1, 2));
registerResearchItem(LibResearch.KEY_FOCUS_SMELT, LibResearch.KEY_FOCUS_SMELT, new ItemStack(ModItems.focusSmelt), new AspectList().add(Aspect.FIRE, 10).add(Aspect.ORDER, 5).add(Aspect.ENTROPY, 6),
"FNE",
'F', new ItemStack(ConfigItems.itemFocusFire),
'E', new ItemStack(ConfigItems.itemFocusExcavation),
'N', new ItemStack(ConfigItems.itemResource, 1, 1));
registerResearchItem(LibResearch.KEY_FOCUS_ENDER_CHEST, LibResearch.KEY_FOCUS_ENDER_CHEST, new ItemStack(ModItems.focusEnderChest), new AspectList().add(Aspect.ORDER, 10).add(Aspect.ENTROPY, 10),
"M", "E", "P",
'M', new ItemStack(ConfigBlocks.blockMirror),
'E', new ItemStack(Item.eyeOfEnder),
'P', new ItemStack(ConfigItems.itemFocusPortableHole));
registerResearchItem(LibResearch.KEY_DISLOCATOR, LibResearch.KEY_DISLOCATOR, new ItemStack(ModBlocks.dislocator), new AspectList().add(Aspect.EARTH, 5).add(Aspect.ENTROPY, 5),
" M ", " I ", " C ",
'M', new ItemStack(ConfigItems.itemResource, 1, 10),
'I', new ItemStack(ModBlocks.interfase),
'C', new ItemStack(Item.comparator));
registerResearchItem(LibResearch.KEY_REVEALING_HELM, LibResearch.KEY_REVEALING_HELM, new ItemStack(ModItems.revealingHelm), new AspectList().add(Aspect.EARTH, 5).add(Aspect.FIRE, 5).add(Aspect.WATER, 5).add(Aspect.AIR, 5).add(Aspect.ORDER, 5).add(Aspect.ENTROPY, 5),
"GH",
'G', new ItemStack(ConfigItems.itemGoggles),
'H', new ItemStack(ConfigItems.itemHelmetThaumium));
registerResearchItem(LibResearch.KEY_ASPECT_ANALYZER, LibResearch.KEY_ASPECT_ANALYZER, new ItemStack(ModBlocks.aspectAnalyzer), new AspectList().add(Aspect.ORDER, 1).add(Aspect.ENTROPY, 1),
"TWT", "WMW", "TWT",
'W', new ItemStack(ConfigBlocks.blockWoodenDevice, 1, 6),
'M', new ItemStack(ConfigItems.itemThaumometer),
'T', new ItemStack(ConfigItems.itemResource, 1, 2));
registerResearchItem(LibResearch.KEY_PLATFORM, LibResearch.KEY_PLATFORM, new ItemStack(ModBlocks.platform, 2), new AspectList().add(Aspect.AIR, 2).add(Aspect.ENTROPY, 4),
" S ", "G G",
'G', new ItemStack(ConfigBlocks.blockWoodenDevice, 1, 6),
'S', new ItemStack(ConfigBlocks.blockWoodenDevice, 1, 7));
if(ConfigHandler.enableKami) {
registerResearchItem(LibResearch.KEY_ICHOR_CLOTH, LibResearch.KEY_ICHOR_CLOTH, new ItemStack(ModItems.kamiResource, 3, 1), new AspectList().add(Aspect.FIRE, 125).add(Aspect.EARTH, 125).add(Aspect.WATER, 125).add(Aspect.AIR, 125).add(Aspect.ORDER, 125).add(Aspect.ENTROPY, 125),
"CCC", "III", "DDD",
'C', new ItemStack(ConfigItems.itemResource, 1, 7),
'I', new ItemStack(ModItems.kamiResource, 1, 0),
'D', new ItemStack(Item.diamond));
registerResearchItem(LibResearch.KEY_ICHORIUM, LibResearch.KEY_ICHORIUM, new ItemStack(ModItems.kamiResource, 1, 2), new AspectList().add(Aspect.FIRE, 100).add(Aspect.EARTH, 100).add(Aspect.WATER, 100).add(Aspect.AIR, 100).add(Aspect.ORDER, 100).add(Aspect.ENTROPY, 100),
" T ", "IDI", " I ",
'T', new ItemStack(ConfigItems.itemResource, 1, 2),
'I', new ItemStack(ModItems.kamiResource, 1, 0),
'D', new ItemStack(Item.diamond));
registerResearchItem(LibResearch.KEY_ICHOR_CAP, LibResearch.KEY_ICHOR_CAP, new ItemStack(ModItems.kamiResource, 2, 4), new AspectList().add(Aspect.FIRE, 100).add(Aspect.EARTH, 100).add(Aspect.WATER, 100).add(Aspect.AIR, 100).add(Aspect.ORDER, 100).add(Aspect.ENTROPY, 100),
"ICI", " M ", "ICI",
'M', new ItemStack(ModItems.kamiResource, 1, 2),
'I', new ItemStack(ModItems.kamiResource, 1, 0),
'C', new ItemStack(ConfigItems.itemWandCap, 1, 2));
registerResearchItem(LibResearch.KEY_ICHORCLOTH_HELM, LibResearch.KEY_ICHORCLOTH_HELM, new ItemStack(ModItems.ichorHelm), new AspectList().add(Aspect.WATER, 75),
"CCC", "C C",
'C', new ItemStack(ModItems.kamiResource, 3, 1));
registerResearchItem(LibResearch.KEY_ICHORCLOTH_CHEST, LibResearch.KEY_ICHORCLOTH_CHEST, new ItemStack(ModItems.ichorChest), new AspectList().add(Aspect.AIR, 75),
"C C", "CCC", "CCC",
'C', new ItemStack(ModItems.kamiResource, 3, 1));
registerResearchItem(LibResearch.KEY_ICHORCLOTH_LEGS, LibResearch.KEY_ICHORCLOTH_LEGS, new ItemStack(ModItems.ichorLegs), new AspectList().add(Aspect.FIRE, 75),
"CCC", "C C", "C C",
'C', new ItemStack(ModItems.kamiResource, 3, 1));
registerResearchItem(LibResearch.KEY_ICHORCLOTH_BOOTS, LibResearch.KEY_ICHORCLOTH_BOOTS, new ItemStack(ModItems.ichorBoots), new AspectList().add(Aspect.EARTH, 75),
"C C", "C C",
'C', new ItemStack(ModItems.kamiResource, 3, 1));
}
}
|
private static void initArcaneRecipes() {
registerResearchItem(LibResearch.KEY_INTERFACE, LibResearch.KEY_INTERFACE, new ItemStack(ModBlocks.interfase), new AspectList().add(Aspect.ORDER, 12).add(Aspect.ENTROPY, 16),
"BRB", "LEL", "BRB",
'B', new ItemStack(ConfigBlocks.blockCosmeticSolid, 1, 6),
'E', new ItemStack(Item.enderPearl),
'L', new ItemStack(Item.dyePowder, 1, 4),
'R', new ItemStack(Item.redstone));
registerResearchItem(LibResearch.KEY_CONNECTOR, LibResearch.KEY_INTERFACE, new ItemStack(ModItems.connector), new AspectList().add(Aspect.ORDER, 2),
" I ", " WI", "S ",
'I', new ItemStack(Item.ingotIron),
'W', new ItemStack(Item.stick),
'S', new ItemStack(ConfigItems.itemShard, 1, 4));
registerResearchItem(LibResearch.KEY_GAS_REMOVER, LibResearch.KEY_GAS_REMOVER, new ItemStack(ModItems.gasRemover), new AspectList().add(Aspect.AIR, 2).add(Aspect.ORDER, 2),
"DDD", "T G", "QQQ",
'D', new ItemStack(ModItems.darkQuartz),
'T', new ItemStack(ModItems.gaseousShadow),
'G', new ItemStack(ModItems.gaseousLight),
'Q', new ItemStack(Item.netherQuartz));
registerResearchItem(LibResearch.KEY_ANIMATION_TABLET, LibResearch.KEY_ANIMATION_TABLET, new ItemStack(ModBlocks.animationTablet), new AspectList().add(Aspect.AIR, 25).add(Aspect.ORDER, 15).add(Aspect.FIRE, 10),
"GIG", "ICI",
'G', new ItemStack(Item.ingotGold),
'I', new ItemStack(Item.ingotIron),
'C', new ItemStack(ConfigItems.itemGolemCore, 1, 100));
registerResearchItem(LibResearch.KEY_MAGNET, LibResearch.KEY_MAGNETS, new ItemStack(ModBlocks.magnet), new AspectList().add(Aspect.AIR, 20).add(Aspect.ORDER, 5).add(Aspect.EARTH, 15).add(Aspect.ENTROPY, 5),
" I ", "SIs", "WFW",
'I', new ItemStack(Item.ingotIron),
's', new ItemStack(ConfigItems.itemShard, 1, 3),
'S', new ItemStack(ConfigItems.itemShard),
'W', new ItemStack(ConfigBlocks.blockMagicalLog),
'F', new ItemStack(ModItems.focusTelekinesis));
registerResearchItem(LibResearch.KEY_MOB_MAGNET, LibResearch.KEY_MAGNETS, new ItemStack(ModBlocks.magnet, 1, 1), new AspectList().add(Aspect.AIR, 20).add(Aspect.ORDER, 5).add(Aspect.EARTH, 15).add(Aspect.ENTROPY, 5),
" G ", "SGs", "WFW",
'G', oreDictOrStack(new ItemStack(Item.ingotGold), "ingotCopper"),
's', new ItemStack(ConfigItems.itemShard, 1, 3),
'S', new ItemStack(ConfigItems.itemShard),
'W', new ItemStack(ConfigBlocks.blockMagicalLog),
'F', new ItemStack(ModItems.focusTelekinesis));
registerResearchItem(LibResearch.KEY_FUNNEL, LibResearch.KEY_FUNNEL, new ItemStack(ModBlocks.funnel), new AspectList().add(Aspect.ORDER, 1).add(Aspect.ENTROPY, 1),
"STS",
'S', new ItemStack(Block.stone),
'T', new ItemStack(ConfigItems.itemResource, 1, 2));
registerResearchItem(LibResearch.KEY_FOCUS_SMELT, LibResearch.KEY_FOCUS_SMELT, new ItemStack(ModItems.focusSmelt), new AspectList().add(Aspect.FIRE, 10).add(Aspect.ORDER, 5).add(Aspect.ENTROPY, 6),
"FNE",
'F', new ItemStack(ConfigItems.itemFocusFire),
'E', new ItemStack(ConfigItems.itemFocusExcavation),
'N', new ItemStack(ConfigItems.itemResource, 1, 1));
registerResearchItem(LibResearch.KEY_FOCUS_ENDER_CHEST, LibResearch.KEY_FOCUS_ENDER_CHEST, new ItemStack(ModItems.focusEnderChest), new AspectList().add(Aspect.ORDER, 10).add(Aspect.ENTROPY, 10),
"M", "E", "P",
'M', new ItemStack(ConfigBlocks.blockMirror),
'E', new ItemStack(Item.eyeOfEnder),
'P', new ItemStack(ConfigItems.itemFocusPortableHole));
registerResearchItem(LibResearch.KEY_DISLOCATOR, LibResearch.KEY_DISLOCATOR, new ItemStack(ModBlocks.dislocator), new AspectList().add(Aspect.EARTH, 5).add(Aspect.ENTROPY, 5),
" M ", " I ", " C ",
'M', new ItemStack(ConfigItems.itemResource, 1, 10),
'I', new ItemStack(ModBlocks.interfase),
'C', new ItemStack(Item.comparator));
registerResearchItem(LibResearch.KEY_REVEALING_HELM, LibResearch.KEY_REVEALING_HELM, new ItemStack(ModItems.revealingHelm), new AspectList().add(Aspect.EARTH, 5).add(Aspect.FIRE, 5).add(Aspect.WATER, 5).add(Aspect.AIR, 5).add(Aspect.ORDER, 5).add(Aspect.ENTROPY, 5),
"GH",
'G', new ItemStack(ConfigItems.itemGoggles),
'H', new ItemStack(ConfigItems.itemHelmetThaumium));
registerResearchItem(LibResearch.KEY_ASPECT_ANALYZER, LibResearch.KEY_ASPECT_ANALYZER, new ItemStack(ModBlocks.aspectAnalyzer), new AspectList().add(Aspect.ORDER, 1).add(Aspect.ENTROPY, 1),
"TWT", "WMW", "TWT",
'W', new ItemStack(ConfigBlocks.blockWoodenDevice, 1, 6),
'M', new ItemStack(ConfigItems.itemThaumometer),
'T', new ItemStack(ConfigItems.itemResource, 1, 2));
registerResearchItem(LibResearch.KEY_PLATFORM, LibResearch.KEY_PLATFORM, new ItemStack(ModBlocks.platform, 2), new AspectList().add(Aspect.AIR, 2).add(Aspect.ENTROPY, 4),
" S ", "G G",
'G', new ItemStack(ConfigBlocks.blockWoodenDevice, 1, 6),
'S', new ItemStack(ConfigBlocks.blockWoodenDevice, 1, 7));
if(ConfigHandler.enableKami) {
registerResearchItem(LibResearch.KEY_ICHOR_CLOTH, LibResearch.KEY_ICHOR_CLOTH, new ItemStack(ModItems.kamiResource, 3, 1), new AspectList().add(Aspect.FIRE, 125).add(Aspect.EARTH, 125).add(Aspect.WATER, 125).add(Aspect.AIR, 125).add(Aspect.ORDER, 125).add(Aspect.ENTROPY, 125),
"CCC", "III", "DDD",
'C', new ItemStack(ConfigItems.itemResource, 1, 7),
'I', new ItemStack(ModItems.kamiResource, 1, 0),
'D', new ItemStack(Item.diamond));
registerResearchItem(LibResearch.KEY_ICHORIUM, LibResearch.KEY_ICHORIUM, new ItemStack(ModItems.kamiResource, 1, 2), new AspectList().add(Aspect.FIRE, 100).add(Aspect.EARTH, 100).add(Aspect.WATER, 100).add(Aspect.AIR, 100).add(Aspect.ORDER, 100).add(Aspect.ENTROPY, 100),
" T ", "IDI", " I ",
'T', new ItemStack(ConfigItems.itemResource, 1, 2),
'I', new ItemStack(ModItems.kamiResource, 1, 0),
'D', new ItemStack(Item.diamond));
registerResearchItem(LibResearch.KEY_ICHOR_CAP, LibResearch.KEY_ICHOR_CAP, new ItemStack(ModItems.kamiResource, 2, 4), new AspectList().add(Aspect.FIRE, 100).add(Aspect.EARTH, 100).add(Aspect.WATER, 100).add(Aspect.AIR, 100).add(Aspect.ORDER, 100).add(Aspect.ENTROPY, 100),
"ICI", " M ", "ICI",
'M', new ItemStack(ModItems.kamiResource, 1, 2),
'I', new ItemStack(ModItems.kamiResource, 1, 0),
'C', new ItemStack(ConfigItems.itemWandCap, 1, 2));
registerResearchItem(LibResearch.KEY_ICHORCLOTH_HELM, LibResearch.KEY_ICHORCLOTH_ARMOR, new ItemStack(ModItems.ichorHelm), new AspectList().add(Aspect.WATER, 75),
"CCC", "C C",
'C', new ItemStack(ModItems.kamiResource, 3, 1));
registerResearchItem(LibResearch.KEY_ICHORCLOTH_CHEST, LibResearch.KEY_ICHORCLOTH_ARMOR, new ItemStack(ModItems.ichorChest), new AspectList().add(Aspect.AIR, 75),
"C C", "CCC", "CCC",
'C', new ItemStack(ModItems.kamiResource, 3, 1));
registerResearchItem(LibResearch.KEY_ICHORCLOTH_LEGS, LibResearch.KEY_ICHORCLOTH_ARMOR, new ItemStack(ModItems.ichorLegs), new AspectList().add(Aspect.FIRE, 75),
"CCC", "C C", "C C",
'C', new ItemStack(ModItems.kamiResource, 3, 1));
registerResearchItem(LibResearch.KEY_ICHORCLOTH_BOOTS, LibResearch.KEY_ICHORCLOTH_ARMOR, new ItemStack(ModItems.ichorBoots), new AspectList().add(Aspect.EARTH, 75),
"C C", "C C",
'C', new ItemStack(ModItems.kamiResource, 3, 1));
}
}
|
diff --git a/src/plarktmaatsActions/gebruikers/VoegBodToe.java b/src/plarktmaatsActions/gebruikers/VoegBodToe.java
index 337f19e..cc6d30d 100644
--- a/src/plarktmaatsActions/gebruikers/VoegBodToe.java
+++ b/src/plarktmaatsActions/gebruikers/VoegBodToe.java
@@ -1,99 +1,91 @@
package plarktmaatsActions.gebruikers;
import java.util.Calendar;
import java.util.Date;
import plarktmaatsAware.UserAware;
import plarktmaatsDAO.BodDAOImpl;
import plarktmaatsDAO.VeilingDAOImpl;
import plarktmaatsDomein.Bod;
import plarktmaatsDomein.Gebruiker;
import plarktmaatsDomein.Persoon;
import plarktmaatsDomein.Veiling;
import tools.ProjectTools;
import com.opensymphony.xwork2.ActionSupport;
public class VoegBodToe extends ActionSupport implements UserAware {
private static final long serialVersionUID = 1L;
private String id;
private String credits;
private Persoon user;
public String execute() {
Gebruiker g = (Gebruiker)user;
int bedrag = Integer.parseInt(credits);
Bod b = new Bod(0, bedrag, g, id);
BodDAOImpl bodDAO = new BodDAOImpl();
bodDAO.create(b);
return SUCCESS;
}
public void validate() {
if(!ProjectTools.isNumeric(credits)) {
- addFieldError("credits", "Vul hier uw bod in");
- System.out.println("Vul hier uw bod in");
+ addFieldError("credits", "Vul een bod in");
return;
}
VeilingDAOImpl veilingDAO = new VeilingDAOImpl();
Veiling v = veilingDAO.read(id);
if(v == null) {
addFieldError("credits", "Deze veiling bestaat niet (meer)");
- System.out.println("Deze veiling bestaat niet (meer)");
return;
}
if(v.getGeblokkeerd()) {
addFieldError("credits", "Deze veiling is geblokkeerd");
- System.out.println("Deze veiling is geblokkeerd");
}
int creditsInt = Integer.parseInt(credits);
if(v.getMinBedrag() > creditsInt) {
addFieldError("credits", "Dit bod is onder het minimumbedrag");
- System.out.println("Dit bod is onder het minimumbedrag");
}
if(v.getHoogsteBod() != null) {
if(v.getHoogsteBod().getBedrag() >= creditsInt) {
addFieldError("credits", "Er is al hoger geboden");
- System.out.println("Er is al hoger geboden");
}
}
if(!(user instanceof Gebruiker)) {
addFieldError("credits", "Alleen gebruikers mogen bieden");
- System.out.println("Alleen gebruikers mogen bieden");
return;
}
Gebruiker usergebruiker = (Gebruiker)user;
if(usergebruiker.getGeblokkeerd()) {
addFieldError("credits", "U mag niet bieden");
- System.out.println("U mag niet bieden");
}
Date eindTijd = v.getEindTijd().getTime();
Date nu = Calendar.getInstance().getTime();
long diff = (eindTijd.getTime() - nu.getTime())/1000;
if(diff < 0) {
addFieldError("credits", "De veiling is gesloten");
- System.out.println("De veiling is gesloten");
}
}
public String getCredits() {
return credits;
}
public void setCredits(String credits) {
this.credits = credits;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public void setUser(Persoon user) {
this.user = user;
}
}
| false | true |
public void validate() {
if(!ProjectTools.isNumeric(credits)) {
addFieldError("credits", "Vul hier uw bod in");
System.out.println("Vul hier uw bod in");
return;
}
VeilingDAOImpl veilingDAO = new VeilingDAOImpl();
Veiling v = veilingDAO.read(id);
if(v == null) {
addFieldError("credits", "Deze veiling bestaat niet (meer)");
System.out.println("Deze veiling bestaat niet (meer)");
return;
}
if(v.getGeblokkeerd()) {
addFieldError("credits", "Deze veiling is geblokkeerd");
System.out.println("Deze veiling is geblokkeerd");
}
int creditsInt = Integer.parseInt(credits);
if(v.getMinBedrag() > creditsInt) {
addFieldError("credits", "Dit bod is onder het minimumbedrag");
System.out.println("Dit bod is onder het minimumbedrag");
}
if(v.getHoogsteBod() != null) {
if(v.getHoogsteBod().getBedrag() >= creditsInt) {
addFieldError("credits", "Er is al hoger geboden");
System.out.println("Er is al hoger geboden");
}
}
if(!(user instanceof Gebruiker)) {
addFieldError("credits", "Alleen gebruikers mogen bieden");
System.out.println("Alleen gebruikers mogen bieden");
return;
}
Gebruiker usergebruiker = (Gebruiker)user;
if(usergebruiker.getGeblokkeerd()) {
addFieldError("credits", "U mag niet bieden");
System.out.println("U mag niet bieden");
}
Date eindTijd = v.getEindTijd().getTime();
Date nu = Calendar.getInstance().getTime();
long diff = (eindTijd.getTime() - nu.getTime())/1000;
if(diff < 0) {
addFieldError("credits", "De veiling is gesloten");
System.out.println("De veiling is gesloten");
}
}
|
public void validate() {
if(!ProjectTools.isNumeric(credits)) {
addFieldError("credits", "Vul een bod in");
return;
}
VeilingDAOImpl veilingDAO = new VeilingDAOImpl();
Veiling v = veilingDAO.read(id);
if(v == null) {
addFieldError("credits", "Deze veiling bestaat niet (meer)");
return;
}
if(v.getGeblokkeerd()) {
addFieldError("credits", "Deze veiling is geblokkeerd");
}
int creditsInt = Integer.parseInt(credits);
if(v.getMinBedrag() > creditsInt) {
addFieldError("credits", "Dit bod is onder het minimumbedrag");
}
if(v.getHoogsteBod() != null) {
if(v.getHoogsteBod().getBedrag() >= creditsInt) {
addFieldError("credits", "Er is al hoger geboden");
}
}
if(!(user instanceof Gebruiker)) {
addFieldError("credits", "Alleen gebruikers mogen bieden");
return;
}
Gebruiker usergebruiker = (Gebruiker)user;
if(usergebruiker.getGeblokkeerd()) {
addFieldError("credits", "U mag niet bieden");
}
Date eindTijd = v.getEindTijd().getTime();
Date nu = Calendar.getInstance().getTime();
long diff = (eindTijd.getTime() - nu.getTime())/1000;
if(diff < 0) {
addFieldError("credits", "De veiling is gesloten");
}
}
|
diff --git a/restauranteClasses/src/restaurante/DaoPersistence/ReceiveDao.java b/restauranteClasses/src/restaurante/DaoPersistence/ReceiveDao.java
index 342f833..d39d400 100644
--- a/restauranteClasses/src/restaurante/DaoPersistence/ReceiveDao.java
+++ b/restauranteClasses/src/restaurante/DaoPersistence/ReceiveDao.java
@@ -1,101 +1,107 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package restaurante.DaoPersistence;
import java.sql.SQLException;
import java.text.ParseException;
import restaurante.Beans.Receive;
import restaurante.Beans.SalesOrder;
import restaurante.Utilities.ContentValues;
import restaurante.Utilities.Functions;
/**
*
* @author Alan
*/
public class ReceiveDao extends AbstractDao<Receive> {
public static final String TABLE = "receive";
/**
* "id_customer", "value", "emissionDate", "dueDate", "paymentDate", "interest",
* "discount", "id_salesorder", "species", "id_branch", "description", "documentNumber", "documentType"
*/
public static final String[] FIELDS = new String[] {
"id_customer", "value", "emissionDate", "dueDate", "paymentDate", "interest", "discount",
"id_salesorder", "species", "id_branch", "description", "documentNumber", "documentType"
};
public ReceiveDao() throws Exception { }
/*
* Insert the current Bean
*/
public int insert(Receive register) throws SQLException, Exception {
return insert(register.getCustomer().getId(), register.getValue(),
Functions.dateToDateStringSql(register.getEmissionDate()),
Functions.dateToDateStringSql(register.getDueDate()),
Functions.dateToDateStringSql(register.getPaymentDate()),
register.getInterest(), register.getDiscount(), register.getSaleOrder().getId(),
register.getSpecie().ordinal(), register.getBranch().getId(),
register.getDescription(), register.getDocumentNumber(), register.getDocumentType());
}
/*
* Update the current Bean
*/
public void update(Receive register) throws SQLException, ParseException, Exception {
update(register.getId(), register.getCustomer().getId(), register.getValue(),
Functions.dateToDateStringSql(register.getEmissionDate()),
Functions.dateToDateStringSql(register.getDueDate()),
Functions.dateToDateStringSql(register.getPaymentDate()),
register.getInterest(), register.getDiscount(), register.getSaleOrder().getId(),
register.getSpecie().ordinal(), register.getBranch().getId(),
register.getDescription(), register.getDocumentNumber(), register.getDocumentType());
}
@Override
protected Receive toBean(ContentValues values) throws SQLException, ClassNotFoundException, Exception {
Receive register = new Receive();
register.setId(values.getInt(FIELD_ID));
register.setCustomer(new CustomersDao().findById(values.getInt(FIELDS[0])));
register.setValue(values.getDouble(FIELDS[1]));
register.setEmissionDate(values.getDate(FIELDS[2]));
register.setDueDate(values.getDate(FIELDS[3]));
register.setPaymentDate(values.getDate(FIELDS[4]));
register.setInterest(values.getDouble(FIELDS[5]));
register.setDiscount(values.getDouble(FIELDS[6]));
- register.setSaleOrder(new SalesOrderDao().findById(values.getInt(FIELDS[7])));
+ try {
+ register.setSaleOrder(new SalesOrderDao().findById(values.getInt(FIELDS[7])));
+ } catch (Exception e) {
+ SalesOrder order = new SalesOrder();
+ order.setId(0);
+ register.setSaleOrder(order);
+ }
register.setSpecie(SalesOrder.PaymentMethod.values()[values.getInt(FIELDS[8])]);
register.setBranch(new BranchesDao().findById(values.getInt(FIELDS[9])));
register.setDescription(values.getString(FIELDS[10]));
register.setDocumentNumber(values.getString(FIELDS[11]));
register.setDocumentType(values.getString(FIELDS[12]));
return register;
}
@Override
protected String getTableName() {
return TABLE;
}
@Override
protected String[] getFields() {
return FIELDS;
}
public void saveBatch(Receive[] receiveList) throws Exception {
//Start the transaction to save batch of products from menu
try {
this.startTransation();
for(Receive receive : receiveList) {
update(receive);
}
this.finishTransaction();
} catch (Exception e) {
this.finishTransaction();
throw e;
}
//Remember to finish the transaction!
}
}
| true | true |
protected Receive toBean(ContentValues values) throws SQLException, ClassNotFoundException, Exception {
Receive register = new Receive();
register.setId(values.getInt(FIELD_ID));
register.setCustomer(new CustomersDao().findById(values.getInt(FIELDS[0])));
register.setValue(values.getDouble(FIELDS[1]));
register.setEmissionDate(values.getDate(FIELDS[2]));
register.setDueDate(values.getDate(FIELDS[3]));
register.setPaymentDate(values.getDate(FIELDS[4]));
register.setInterest(values.getDouble(FIELDS[5]));
register.setDiscount(values.getDouble(FIELDS[6]));
register.setSaleOrder(new SalesOrderDao().findById(values.getInt(FIELDS[7])));
register.setSpecie(SalesOrder.PaymentMethod.values()[values.getInt(FIELDS[8])]);
register.setBranch(new BranchesDao().findById(values.getInt(FIELDS[9])));
register.setDescription(values.getString(FIELDS[10]));
register.setDocumentNumber(values.getString(FIELDS[11]));
register.setDocumentType(values.getString(FIELDS[12]));
return register;
}
|
protected Receive toBean(ContentValues values) throws SQLException, ClassNotFoundException, Exception {
Receive register = new Receive();
register.setId(values.getInt(FIELD_ID));
register.setCustomer(new CustomersDao().findById(values.getInt(FIELDS[0])));
register.setValue(values.getDouble(FIELDS[1]));
register.setEmissionDate(values.getDate(FIELDS[2]));
register.setDueDate(values.getDate(FIELDS[3]));
register.setPaymentDate(values.getDate(FIELDS[4]));
register.setInterest(values.getDouble(FIELDS[5]));
register.setDiscount(values.getDouble(FIELDS[6]));
try {
register.setSaleOrder(new SalesOrderDao().findById(values.getInt(FIELDS[7])));
} catch (Exception e) {
SalesOrder order = new SalesOrder();
order.setId(0);
register.setSaleOrder(order);
}
register.setSpecie(SalesOrder.PaymentMethod.values()[values.getInt(FIELDS[8])]);
register.setBranch(new BranchesDao().findById(values.getInt(FIELDS[9])));
register.setDescription(values.getString(FIELDS[10]));
register.setDocumentNumber(values.getString(FIELDS[11]));
register.setDocumentType(values.getString(FIELDS[12]));
return register;
}
|
diff --git a/plugins/regexp_replace/src/main/java/com/rabbitmq/streams/plugins/regexp/replace/RegexpReplace.java b/plugins/regexp_replace/src/main/java/com/rabbitmq/streams/plugins/regexp/replace/RegexpReplace.java
index 6268f8b..5bfe9d6 100644
--- a/plugins/regexp_replace/src/main/java/com/rabbitmq/streams/plugins/regexp/replace/RegexpReplace.java
+++ b/plugins/regexp_replace/src/main/java/com/rabbitmq/streams/plugins/regexp/replace/RegexpReplace.java
@@ -1,60 +1,61 @@
package com.rabbitmq.streams.plugins.regexp.replace;
import com.rabbitmq.streams.harness.InputReader;
import com.rabbitmq.streams.harness.InputMessage;
import com.rabbitmq.streams.harness.NotificationType;
import com.rabbitmq.streams.harness.PipelineComponent;
import com.rabbitmq.streams.harness.PluginBuildException;
import com.rabbitmq.streams.harness.PluginException;
import java.nio.charset.CharacterCodingException;
import net.sf.json.*;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexpReplace extends PipelineComponent {
private class PatRep {
public Pattern pat; public String rep;
public PatRep(Pattern pat, String rep) {this.rep=rep; this.pat=pat;}
}
private LinkedList<PatRep> patReps = new LinkedList();
public void configure(final JSONObject config) throws PluginBuildException {
if (null == config) {
throw new PluginBuildException("Cannot configure a plugin with a null configuration.");
}
JSONArray rexConfigs = config.getJSONArray("expressions");
for (ListIterator iterator = rexConfigs.listIterator(rexConfigs.size()); iterator.hasPrevious();) {
JSONObject rexConfig = (JSONObject)iterator.previous();
String regexp = rexConfig.getString("regexp");
int flags = (rexConfig.optBoolean("multiline", false) ? Pattern.MULTILINE : 0)
| (rexConfig.optBoolean("caseinsensitive", false) ? Pattern.CASE_INSENSITIVE : 0)
- | (rexConfig.optBoolean("dotall", false) ? Pattern.DOTALL : 0);
+ | (rexConfig.optBoolean("dotall", false) ? Pattern.DOTALL : 0)
+ | Pattern.UNICODE_CASE;
patReps.addFirst(new PatRep(Pattern.compile(regexp, flags), rexConfig.getString("replacement")));
registerInput("input", input);
}
}
InputReader input = new InputReader() {
@Override
public void handleMessage(InputMessage msg) throws PluginException {
Matcher matcher;
String bodySoFar = null;
try{
bodySoFar = msg.bodyAsString();
} catch (CharacterCodingException ex) {
notifier.notify(NotificationType.BadData, "msg.body isn't valid utf-8");
throw new PluginException("Msg.body isn't valid utf-8", ex);
}
for (PatRep patRep : patReps) {
bodySoFar = patRep.pat.matcher(bodySoFar).replaceAll(patRep.rep);
}
publishToChannel("output", msg.withBody(bodySoFar));
}
};
}
| true | true |
public void configure(final JSONObject config) throws PluginBuildException {
if (null == config) {
throw new PluginBuildException("Cannot configure a plugin with a null configuration.");
}
JSONArray rexConfigs = config.getJSONArray("expressions");
for (ListIterator iterator = rexConfigs.listIterator(rexConfigs.size()); iterator.hasPrevious();) {
JSONObject rexConfig = (JSONObject)iterator.previous();
String regexp = rexConfig.getString("regexp");
int flags = (rexConfig.optBoolean("multiline", false) ? Pattern.MULTILINE : 0)
| (rexConfig.optBoolean("caseinsensitive", false) ? Pattern.CASE_INSENSITIVE : 0)
| (rexConfig.optBoolean("dotall", false) ? Pattern.DOTALL : 0);
patReps.addFirst(new PatRep(Pattern.compile(regexp, flags), rexConfig.getString("replacement")));
registerInput("input", input);
}
}
|
public void configure(final JSONObject config) throws PluginBuildException {
if (null == config) {
throw new PluginBuildException("Cannot configure a plugin with a null configuration.");
}
JSONArray rexConfigs = config.getJSONArray("expressions");
for (ListIterator iterator = rexConfigs.listIterator(rexConfigs.size()); iterator.hasPrevious();) {
JSONObject rexConfig = (JSONObject)iterator.previous();
String regexp = rexConfig.getString("regexp");
int flags = (rexConfig.optBoolean("multiline", false) ? Pattern.MULTILINE : 0)
| (rexConfig.optBoolean("caseinsensitive", false) ? Pattern.CASE_INSENSITIVE : 0)
| (rexConfig.optBoolean("dotall", false) ? Pattern.DOTALL : 0)
| Pattern.UNICODE_CASE;
patReps.addFirst(new PatRep(Pattern.compile(regexp, flags), rexConfig.getString("replacement")));
registerInput("input", input);
}
}
|
diff --git a/src/com/dmdirc/util/resourcemanager/ResourceManager.java b/src/com/dmdirc/util/resourcemanager/ResourceManager.java
index 60a5a486c..7157c2598 100644
--- a/src/com/dmdirc/util/resourcemanager/ResourceManager.java
+++ b/src/com/dmdirc/util/resourcemanager/ResourceManager.java
@@ -1,277 +1,277 @@
/*
* 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.util.resourcemanager;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Provides a launch method independant way of accessing resources.
*/
public abstract class ResourceManager {
/** Previously assigned ResourceManager. */
private static ResourceManager me;
/**
* Returns an appropriate instance of ResourceManager.
*
* @return ResourceManager implementation
*/
public static final synchronized ResourceManager getResourceManager() {
if (me == null) {
String path = Thread.currentThread().getContextClassLoader().
getResource("com/dmdirc/Main.class").getPath();
try {
path = java.net.URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException ex) {
Logger.userError(ErrorLevel.MEDIUM, "Unable to decode path");
}
final String protocol = Thread.currentThread().getContextClassLoader().
getResource("com/dmdirc/Main.class").getProtocol();
try {
if ("file".equals(protocol)) {
me = new FileResourceManager(Thread.currentThread().
getContextClassLoader().getResource("").getPath());
} else if ("jar".equals(protocol)) {
if (System.getProperty("os.name").startsWith("Windows")) {
me = new ZipResourceManager(path.substring(6, path.length() - 23));
} else {
me = new ZipResourceManager(path.substring(5, path.length() - 23));
}
}
} catch (IOException ex) {
Logger.appError(ErrorLevel.MEDIUM, "Unable to determine how DMDirc"
+ " has been executed", ex);
}
}
return me;
}
/**
* Returns a resource manager for the specified URL. The following URL types
* are valid:
*
* <ul>
* <li>file://path/</li>
* <li>zip://path/filename.zip</li>
* <li>jar://path/filename.jar</li>
* </ul>
*
* @param url The URL for which a resource manager is required
* @return A resource manager for the specified URL
*
* @throws IOException if an IO Error occurs opening the file
* @throws IllegalArgumentException if the URL type is not valid
*/
public static final ResourceManager getResourceManager(final String url)
throws IOException, IllegalArgumentException {
if (url.startsWith("file://")) {
return new FileResourceManager(url.substring(7));
} else if (url.startsWith("jar://") || url.startsWith("zip://")) {
return new ZipResourceManager(url.substring(6));
} else {
throw new IllegalArgumentException("Unknown resource manager type");
}
}
/**
* Writes a resource to a file.
*
* @param resource Resource to write
* @param file File to write to
*
* @throws IOException if the write operation fails
*/
public final void resourceToFile(final byte[] resource, final File file)
throws IOException {
final FileOutputStream out = new FileOutputStream(file, false);
out.write(resource);
out.flush();
out.close();
}
/**
* Extracts the specified resource to the specified directory.
*
* @param resourceName The name of the resource to extract
* @param directory The name of the directory to extract to
* @param usePath If true, append the path of the files in the resource
* to the extraction path
*
* @throws IOException if the write operation fails
*
* @return success of failure of the operation
*/
public final boolean extractResource(final String resourceName,
final String directory, final boolean usePath) throws IOException {
final byte[] resource = getResourceBytes(resourceName);
if (resource.length == 0) {
return false;
}
File newDir;
- if (usePath) {
+ if (usePath && resourceName.indexOf('/') > -1) {
newDir = new File(directory,
resourceName.substring(0, resourceName.lastIndexOf('/')) + "/");
} else {
newDir = new File(directory);
}
if (!newDir.exists()) {
newDir.mkdirs();
}
if (!newDir.exists()) {
return false;
}
final File newFile = new File(newDir,
resourceName.substring(resourceName.lastIndexOf('/') + 1,
resourceName.length()));
if (!newFile.isDirectory()) {
resourceToFile(resource, newFile);
}
return true;
}
/**
* Extracts the specified resources to the specified directory.
*
* @param resourcesPrefix The prefix of the resources to extract
* @param directory The name of the directory to extract to
* @param usePath If true, append the path of the files in the resource
* to the extraction path
*
* @throws IOException if the write operation fails
*/
public final void extractResources(final String resourcesPrefix,
final String directory, final boolean usePath) throws IOException {
final Map<String, byte[]> resourcesBytes =
getResourcesStartingWithAsBytes(resourcesPrefix);
for (Entry<String, byte[]> entry : resourcesBytes.entrySet()) {
extractResource(entry.getKey(), directory, usePath);
}
}
/**
* Extracts the specified resources to the specified directory.
*
* @param resourcesPrefix The prefix of the resources to extract
* @param directory The name of the directory to extract to
*
* @throws IOException if the write operation fails
*/
public final void extractResources(final String resourcesPrefix,
final String directory) throws IOException {
extractResources(resourcesPrefix, directory, true);
}
/**
* Checks if a resource exists.
*
* @param resource Resource to check
*
* @return true iif the resource exists
*/
public abstract boolean resourceExists(final String resource);
/**
* Gets a byte[] of the specified resource.
*
* @param resource Name of the resource to return
*
* @return byte[] for the resource, or an empty byte[] if not found
*/
public abstract byte[] getResourceBytes(final String resource);
/**
* Gets an InputStream for the specified resource.
*
* @param resource Name of the resource to return
*
* @return InputStream for the resource, or null if not found
*/
public abstract InputStream getResourceInputStream(final String resource);
/**
* Gets a Map of byte[]s of the resources ending with the specified
* suffix.
*
* @param resourcesSuffix Suffix of the resources to return
* @since 0.6
* @return Map of byte[]s of resources found
*/
public abstract Map<String, byte[]> getResourcesEndingWithAsBytes(
final String resourcesSuffix);
/**
* Gets a Map of byte[]s of the resources starting with the specified
* prefix.
*
* @param resourcesPrefix Prefix of the resources to return
*
* @return Map of byte[]s of resources found
*/
public abstract Map<String, byte[]> getResourcesStartingWithAsBytes(
final String resourcesPrefix);
/**
* Gets a Map of InputStreams of the resources starting with the specified
* prefix.
*
* @param resourcesPrefix Prefix of the resources to return
*
* @return Map of InputStreams of resources found
*/
public abstract Map<String, InputStream> getResourcesStartingWithAsInputStreams(
final String resourcesPrefix);
/**
* Gets a List of the resources starting with the specified
* prefix.
*
* @param resourcesPrefix Prefix of the resources to return
*
* @return List of resources found
*/
public abstract List<String> getResourcesStartingWith(final String resourcesPrefix);
}
| true | true |
public final boolean extractResource(final String resourceName,
final String directory, final boolean usePath) throws IOException {
final byte[] resource = getResourceBytes(resourceName);
if (resource.length == 0) {
return false;
}
File newDir;
if (usePath) {
newDir = new File(directory,
resourceName.substring(0, resourceName.lastIndexOf('/')) + "/");
} else {
newDir = new File(directory);
}
if (!newDir.exists()) {
newDir.mkdirs();
}
if (!newDir.exists()) {
return false;
}
final File newFile = new File(newDir,
resourceName.substring(resourceName.lastIndexOf('/') + 1,
resourceName.length()));
if (!newFile.isDirectory()) {
resourceToFile(resource, newFile);
}
return true;
}
|
public final boolean extractResource(final String resourceName,
final String directory, final boolean usePath) throws IOException {
final byte[] resource = getResourceBytes(resourceName);
if (resource.length == 0) {
return false;
}
File newDir;
if (usePath && resourceName.indexOf('/') > -1) {
newDir = new File(directory,
resourceName.substring(0, resourceName.lastIndexOf('/')) + "/");
} else {
newDir = new File(directory);
}
if (!newDir.exists()) {
newDir.mkdirs();
}
if (!newDir.exists()) {
return false;
}
final File newFile = new File(newDir,
resourceName.substring(resourceName.lastIndexOf('/') + 1,
resourceName.length()));
if (!newFile.isDirectory()) {
resourceToFile(resource, newFile);
}
return true;
}
|
diff --git a/MuleGame/src/gameObjects/PlayerToken.java b/MuleGame/src/gameObjects/PlayerToken.java
index af5d5e9..4094c27 100644
--- a/MuleGame/src/gameObjects/PlayerToken.java
+++ b/MuleGame/src/gameObjects/PlayerToken.java
@@ -1,71 +1,73 @@
package gameObjects;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
/**
* This class is the graphical representation of the player that is currently playing
* @author antonio
*
*/
public class PlayerToken extends Image{
private Color color;
private final int VELOCITY_X = 5;
private final int VELOCITY_Y = 5;
private final int WIDTH = 50;
private final int HEIGHT = 50;
private Rectangle rect;
public PlayerToken(Player p){
super();
color = p.getColor();
}
public PlayerToken(Player p, int x, int y){
this(p);
super.setX(x);
super.setY(y);
rect = new Rectangle(getX(), getY(), WIDTH, HEIGHT);
}
public void draw(SpriteBatch batch, float parentAlpha){
super.draw(batch, parentAlpha);
+ batch.end();
ShapeRenderer sr = new ShapeRenderer();
sr.begin(ShapeType.Filled);
sr.setColor(color);
sr.rect(getX(), getY(), WIDTH, HEIGHT);
sr.end();
+ batch.begin();
}
public void moveLeft(){
setX(getX() - VELOCITY_X);
rect.setX(getX() - VELOCITY_X);
}
public void moveRight(){
setX(getX() + VELOCITY_X);
rect.setX(getX() + VELOCITY_X);
}
public void moveDown(){
setY(getY() - VELOCITY_Y);
rect.setY(getY() - VELOCITY_Y);
}
public void moveUp(){
setY(getY() + VELOCITY_Y);
rect.setY(getY() + VELOCITY_Y);
}
public Rectangle getRect(){
return rect;
}
}
| false | true |
public void draw(SpriteBatch batch, float parentAlpha){
super.draw(batch, parentAlpha);
ShapeRenderer sr = new ShapeRenderer();
sr.begin(ShapeType.Filled);
sr.setColor(color);
sr.rect(getX(), getY(), WIDTH, HEIGHT);
sr.end();
}
|
public void draw(SpriteBatch batch, float parentAlpha){
super.draw(batch, parentAlpha);
batch.end();
ShapeRenderer sr = new ShapeRenderer();
sr.begin(ShapeType.Filled);
sr.setColor(color);
sr.rect(getX(), getY(), WIDTH, HEIGHT);
sr.end();
batch.begin();
}
|
diff --git a/itinerennes/src/fr/itinerennes/database/MarkerDao.java b/itinerennes/src/fr/itinerennes/database/MarkerDao.java
index b2198b3..1c87c0d 100644
--- a/itinerennes/src/fr/itinerennes/database/MarkerDao.java
+++ b/itinerennes/src/fr/itinerennes/database/MarkerDao.java
@@ -1,448 +1,450 @@
package fr.itinerennes.database;
import java.util.List;
import org.osmdroid.util.BoundingBoxE6;
import org.osmdroid.util.GeoPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.app.SearchManager;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteQueryBuilder;
import android.provider.BaseColumns;
import fr.itinerennes.R;
import fr.itinerennes.TypeConstants;
import fr.itinerennes.commons.utils.SearchUtils;
import fr.itinerennes.database.Columns.BookmarksColumns;
import fr.itinerennes.database.Columns.MarkersColumns;
import fr.itinerennes.ui.views.overlays.StopOverlayItem;
/**
* Fetch markers from the database.
*
* @author Olivier Boudet
*/
public class MarkerDao implements MarkersColumns {
/** The event logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(MarkerDao.class);
/** The context. */
private final Context context;
/** The database helper. */
private final DatabaseHelper dbHelper;
/** SQL query used to fetch suggestions from the database. */
private String getSuggestionsStatement;
/** Intent data id used when the line "search an address" is clicked in suggestions. */
public static final String NOMINATIM_INTENT_DATA_ID = "nominatim";
/**
* Constructor.
*
* @param context
* the context
* @param databaseHelper
* the itinerennes context
*/
public MarkerDao(final Context context, final DatabaseHelper databaseHelper) {
this.context = context;
dbHelper = databaseHelper;
}
/**
* Fetch markers contained in the given bounding box from the database.
*
* @param bbox
* the bounding box in which fetch markers
* @param types
* the types of markers to retrieve
* @return the list of Marker
*/
public final Cursor getMarkers(final BoundingBoxE6 bbox, final List<String> types) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getMarkers.start - bbox={}", bbox);
}
if (types.size() == 0) {
// no visible marker type is selected, we return nothing at all
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No layer visible, no marker will be displayed.");
}
return null;
}
final String tables = String.format("%s m left join %s b on m.%s=b.%s", MARKERS_TABLE_NAME,
Columns.BookmarksColumns.BOOKMARKS_TABLE_NAME, ID, Columns.BookmarksColumns.ID);
final String[] columns = new String[] { String.format("m.%s", ID),
String.format("m.%s", TYPE), String.format("m.%s", LABEL), LONGITUDE, LATITUDE,
String.format("b.%s is not null AS %s", ID, MarkersColumns.IS_BOOKMARKED) };
final StringBuilder selection = new StringBuilder();
selection.append(String.format("%s >= ? AND %s <= ? AND %s >= ? AND %s <= ?", LONGITUDE,
LONGITUDE, LATITUDE, LATITUDE));
- selection.append(" AND ( ");
- // filter on visible types
- for (int i = 0; i < types.size(); i++) {
- selection.append(String.format(" %s m.%s = '%s'", (i > 0) ? "OR" : "", TYPE,
- types.get(i)));
+ if (types.size() > 0) {
+ selection.append(" AND ( ");
+ // filter on visible types
+ for (int i = 0; i < types.size(); i++) {
+ selection.append(String.format(" %s m.%s = '%s'", (i > 0) ? "OR" : "", TYPE,
+ types.get(i)));
+ }
+ selection.append(")");
}
- selection.append(")");
final String[] selectionArgs = new String[] { String.valueOf(bbox.getLonWestE6()),
String.valueOf(bbox.getLonEastE6()), String.valueOf(bbox.getLatSouthE6()),
String.valueOf(bbox.getLatNorthE6()) };
final Cursor c = query(tables, selection.toString(), selectionArgs, columns, null,
"m._id ASC");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getMarkers.end - count={}", (c != null) ? c.getCount() : 0);
}
return c;
}
/**
* Fetch a single MarkerOverlayItem from the database based on an unique android id.
*
* @param id
* unique id of the marker ({@link BaseColumns#_ID})
* @return the Marker
*/
public final Cursor getMarker(final String id) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getMarker.start - id={}", id);
}
final String[] columns = new String[] { String.format("m.%s", ID),
String.format("m.%s", TYPE), String.format("m.%s", LABEL), LONGITUDE, LATITUDE,
String.format("b.%s is not null AS %s", ID, MarkersColumns.IS_BOOKMARKED) };
final String selection = String.format("m.%s = ?", BaseColumns._ID);
final String[] selectionArgs = new String[] { id };
final Cursor c = query(selection, selectionArgs, columns);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getMarkers.end - count={}", (c != null) ? c.getCount() : 0);
}
return c;
}
/**
* Fetch a single MarkerOverlayItem from the database based on a stop id and his type.
*
* @param id
* id of the marker
* @param type
* type of the marker
* @return the Marker
*/
public final Cursor getMarker(final String id, final String type) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getMarker.start - id={}, type={}", id, type);
}
final String[] columns = new String[] { String.format("m.%s", ID),
String.format("m.%s", TYPE), String.format("m.%s", LABEL), LONGITUDE, LATITUDE,
String.format("b.%s is not null AS %s", ID, MarkersColumns.IS_BOOKMARKED) };
final String selection = String.format("m.%s = ? AND m.%s = ?", ID, TYPE);
final String[] selectionArgs = new String[] { id, type };
final Cursor c = query(selection, selectionArgs, columns);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getMarkers.end - count={}", (c != null) ? c.getCount() : 0);
}
return c;
}
/**
* Fetch all markers from the database having the same label than the marker identified by its
* unique android id .
*
* @param id
* unique id of the marker
* @return all markers with same label
*/
public final Cursor getMarkersWithSameLabel(final String id) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getMarkersWithSameLabel.start - id={}", id);
}
final String[] selectionArgs = new String[] { id, id };
final Cursor c = dbHelper
.getReadableDatabase()
.rawQuery(
String.format(
"SELECT * FROM %s WHERE label=(SELECT %s FROM %s where %s = ?) AND type=(SELECT %s FROM %s WHERE %s = ?)",
MarkersColumns.MARKERS_TABLE_NAME, MarkersColumns.LABEL,
MarkersColumns.MARKERS_TABLE_NAME, MarkersColumns._ID,
MarkersColumns.TYPE, MarkersColumns.MARKERS_TABLE_NAME,
MarkersColumns._ID), selectionArgs);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getMarkersWithSameLabel.end - count={}", (c != null) ? c.getCount() : 0);
}
return c;
}
/**
* Fetch a list of marker of a given type from the database based. If a labelFilter is given,
* markers will be filtered based on the marker label.
*
* @param type
* type of markers to retrieve
* @param labelFilter
* an optional label filter
* @return a cursor with all markers of this type and matching the filter
*/
public final Cursor getMarkers(final String type, final String labelFilter) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getMarkers.start - type={}, labelFilter={}", type, labelFilter);
}
final String[] columns = new String[] { String.format("m.%s", _ID),
String.format("m.%s", ID), String.format("m.%s", LABEL) };
final String selection;
final String[] selectionArgs;
if (labelFilter != null && !labelFilter.equals("")) {
selection = String.format("m.%s = ? AND (m.%s LIKE ? OR m.%s LIKE ?)",
MarkersColumns.TYPE, MarkersColumns.LABEL, MarkersColumns.SEARCH_LABEL);
selectionArgs = new String[] { type, "%" + labelFilter + "%",
"%" + SearchUtils.canonicalize(labelFilter) + "%" };
} else {
selection = String.format("m.%s = ?", MarkersColumns.TYPE);
selectionArgs = new String[] { type };
}
final Cursor c = query(selection, selectionArgs, columns);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getMarkers.end - count={}", (c != null) ? c.getCount() : 0);
}
return c;
}
/**
* Search markers containing the given string. This method returns only one row with same label
* and same type.
*
* @param query
* string to search in markers' label
* @return search results
*/
public final Cursor searchMarkers(final String query) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("searchMarkers.start - query={}", query);
}
final String selection = String.format("%s LIKE ? OR %s LIKE ?", MarkersColumns.LABEL,
MarkersColumns.SEARCH_LABEL);
final String[] columns = new String[] { BaseColumns._ID, MarkersColumns.ID,
MarkersColumns.TYPE, MarkersColumns.LABEL, MarkersColumns.LONGITUDE,
MarkersColumns.LATITUDE };
final String[] selectionArgs = new String[] { "%" + query + "%",
"%" + SearchUtils.canonicalize(query) + "%" };
final String groupBy = String.format("%s, %s", MarkersColumns.LABEL, MarkersColumns.TYPE);
final Cursor c = query(MARKERS_TABLE_NAME, selection, selectionArgs, columns, groupBy, null);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("searchMarkers.end - query={}");
}
return c;
}
/**
* Fetches suggestions for searches. All markers containing the query in the label will be
* fetched.
*
* @param query
* string to search in markers' label
* @return search results
*/
public final Cursor getSuggestions(final String query) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getSuggestions.start - query={}", query);
}
final String[] selectionArgs = new String[] { "%" + query + "%",
"%" + SearchUtils.canonicalize(query) + "%" };
if (getSuggestionsStatement == null) {
getSuggestionsStatement = buildSuggestionsQuery();
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Marker query : %s", getSuggestionsStatement));
}
final Cursor c = dbHelper.getReadableDatabase().rawQuery(getSuggestionsStatement,
selectionArgs);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getSuggestions.end");
}
return c;
}
/**
* This method creates a select statement used to fetch suggestions data from the database.
*
* @return string representing the sql select statement.
*/
private String buildSuggestionsQuery() {
final StringBuffer sql = new StringBuffer();
sql.append(String.format("SELECT 'B', m.%s as %s,", BaseColumns._ID, BaseColumns._ID));
// building select clause part for the suggest_icon_id column
sql.append(String.format(" CASE WHEN m.%s = '%s' THEN '%s'", Columns.MarkersColumns.TYPE,
TypeConstants.TYPE_BUS, R.drawable.ic_mapbox_bus));
sql.append(String.format(" WHEN m.%s = '%s' THEN '%s'", Columns.MarkersColumns.TYPE,
TypeConstants.TYPE_BIKE, R.drawable.ic_mapbox_bike));
sql.append(String.format(" WHEN m.%s = '%s' THEN '%s'", Columns.MarkersColumns.TYPE,
TypeConstants.TYPE_SUBWAY, R.drawable.ic_mapbox_subway));
sql.append(String.format(" END AS %s,", SearchManager.SUGGEST_COLUMN_ICON_1));
sql.append(String.format(" m.%s AS %s,", Columns.MarkersColumns.LABEL,
SearchManager.SUGGEST_COLUMN_TEXT_1));
sql.append(String.format(" m.%s AS %s", BaseColumns._ID,
SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID));
sql.append(String.format(" ,CASE WHEN b.%s is not null = 1 THEN '%s' END AS %s", ID,
android.R.drawable.btn_star_big_on, SearchManager.SUGGEST_COLUMN_ICON_2));
sql.append(String.format(" FROM %s m LEFT JOIN %s b ON m.%s=b.%s", MARKERS_TABLE_NAME,
BookmarksColumns.BOOKMARKS_TABLE_NAME, ID, BookmarksColumns.ID));
sql.append(String.format(" WHERE m.%s LIKE ?", Columns.MarkersColumns.LABEL));
sql.append(String.format(" OR m.%s LIKE ?", Columns.MarkersColumns.SEARCH_LABEL));
sql.append(" GROUP BY suggest_text_1, m.type, suggest_icon_2");
sql.append(String.format(
" UNION ALL select 'A', 'nominatim','%s' as %s,'%s','%s' as %s,''",
R.drawable.ic_osm, SearchManager.SUGGEST_COLUMN_ICON_1, context.getResources()
.getString(R.string.search_address), NOMINATIM_INTENT_DATA_ID,
SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID));
sql.append(String.format(" ORDER BY 1,m.%s", Columns.MarkersColumns.LABEL));
return sql.toString();
}
/**
* Queries the database.
*
* @param selection
* the where clause
* @param selectionArgs
* parameters for the selection
* @param columns
* columns to retrieve
* @return results
*/
private Cursor query(final String selection, final String[] selectionArgs,
final String[] columns) {
final String tables = String.format("%s m left join %s b on m.%s=b.%s", MARKERS_TABLE_NAME,
Columns.BookmarksColumns.BOOKMARKS_TABLE_NAME, ID, Columns.BookmarksColumns.ID);
final String order = String.format("m.%s", MarkersColumns.LABEL);
return query(tables, selection, selectionArgs, columns, null, order);
}
/**
* Queries the database.
*
* @param tables
* the from clause
* @param selection
* the where clause
* @param selectionArgs
* parameters for the selection
* @param columns
* columns to retrieve
* @param groupBy
* group by clause
* @param orderBy
* order by clause
* @return results
*/
private Cursor query(final String tables, final String selection, final String[] selectionArgs,
final String[] columns, final String groupBy, final String orderBy) {
final SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(tables);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug(String.format("Marker query : %s", builder.buildQuery(columns, selection,
// selectionArgs, null, null, orderBy, null)));
// }
final Cursor c = builder.query(dbHelper.getReadableDatabase(), columns, selection,
selectionArgs, groupBy, null, orderBy);
if (c == null) {
return null;
} else if (!c.moveToFirst()) {
c.close();
return null;
}
return c;
}
/**
* Transforms single a row from a Cursor to a {@link StopOverlayItem}.
*
* @param c
* Cursor to use
* @return a {@link StopOverlayItem}
*/
public final StopOverlayItem getMarkerOverlayItem(final Cursor c) {
final StopOverlayItem marker = new StopOverlayItem();
marker.setId(c.getString(c.getColumnIndex(MarkersColumns.ID)));
marker.setType(c.getString(c.getColumnIndex(MarkersColumns.TYPE)));
marker.setLabel(c.getString(c.getColumnIndex(MarkersColumns.LABEL)));
marker.setLocation(new GeoPoint(c.getInt(c.getColumnIndex(MarkersColumns.LATITUDE)), c
.getInt(c.getColumnIndex(MarkersColumns.LONGITUDE))));
marker.setBookmarked(c.getInt(c.getColumnIndex(MarkersColumns.IS_BOOKMARKED)) != 0);
return marker;
}
}
| false | true |
public final Cursor getMarkers(final BoundingBoxE6 bbox, final List<String> types) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getMarkers.start - bbox={}", bbox);
}
if (types.size() == 0) {
// no visible marker type is selected, we return nothing at all
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No layer visible, no marker will be displayed.");
}
return null;
}
final String tables = String.format("%s m left join %s b on m.%s=b.%s", MARKERS_TABLE_NAME,
Columns.BookmarksColumns.BOOKMARKS_TABLE_NAME, ID, Columns.BookmarksColumns.ID);
final String[] columns = new String[] { String.format("m.%s", ID),
String.format("m.%s", TYPE), String.format("m.%s", LABEL), LONGITUDE, LATITUDE,
String.format("b.%s is not null AS %s", ID, MarkersColumns.IS_BOOKMARKED) };
final StringBuilder selection = new StringBuilder();
selection.append(String.format("%s >= ? AND %s <= ? AND %s >= ? AND %s <= ?", LONGITUDE,
LONGITUDE, LATITUDE, LATITUDE));
selection.append(" AND ( ");
// filter on visible types
for (int i = 0; i < types.size(); i++) {
selection.append(String.format(" %s m.%s = '%s'", (i > 0) ? "OR" : "", TYPE,
types.get(i)));
}
selection.append(")");
final String[] selectionArgs = new String[] { String.valueOf(bbox.getLonWestE6()),
String.valueOf(bbox.getLonEastE6()), String.valueOf(bbox.getLatSouthE6()),
String.valueOf(bbox.getLatNorthE6()) };
final Cursor c = query(tables, selection.toString(), selectionArgs, columns, null,
"m._id ASC");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getMarkers.end - count={}", (c != null) ? c.getCount() : 0);
}
return c;
}
|
public final Cursor getMarkers(final BoundingBoxE6 bbox, final List<String> types) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getMarkers.start - bbox={}", bbox);
}
if (types.size() == 0) {
// no visible marker type is selected, we return nothing at all
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No layer visible, no marker will be displayed.");
}
return null;
}
final String tables = String.format("%s m left join %s b on m.%s=b.%s", MARKERS_TABLE_NAME,
Columns.BookmarksColumns.BOOKMARKS_TABLE_NAME, ID, Columns.BookmarksColumns.ID);
final String[] columns = new String[] { String.format("m.%s", ID),
String.format("m.%s", TYPE), String.format("m.%s", LABEL), LONGITUDE, LATITUDE,
String.format("b.%s is not null AS %s", ID, MarkersColumns.IS_BOOKMARKED) };
final StringBuilder selection = new StringBuilder();
selection.append(String.format("%s >= ? AND %s <= ? AND %s >= ? AND %s <= ?", LONGITUDE,
LONGITUDE, LATITUDE, LATITUDE));
if (types.size() > 0) {
selection.append(" AND ( ");
// filter on visible types
for (int i = 0; i < types.size(); i++) {
selection.append(String.format(" %s m.%s = '%s'", (i > 0) ? "OR" : "", TYPE,
types.get(i)));
}
selection.append(")");
}
final String[] selectionArgs = new String[] { String.valueOf(bbox.getLonWestE6()),
String.valueOf(bbox.getLonEastE6()), String.valueOf(bbox.getLatSouthE6()),
String.valueOf(bbox.getLatNorthE6()) };
final Cursor c = query(tables, selection.toString(), selectionArgs, columns, null,
"m._id ASC");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("getMarkers.end - count={}", (c != null) ? c.getCount() : 0);
}
return c;
}
|
diff --git a/freeplane/src/org/freeplane/features/filter/AFilterComposerDialog.java b/freeplane/src/org/freeplane/features/filter/AFilterComposerDialog.java
index 88926a9f7..5977fce4b 100644
--- a/freeplane/src/org/freeplane/features/filter/AFilterComposerDialog.java
+++ b/freeplane/src/org/freeplane/features/filter/AFilterComposerDialog.java
@@ -1,636 +1,636 @@
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Dimitry Polivaev
*
* This file author is Dimitry Polivaev
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.features.filter;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.Collection;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileFilter;
import org.freeplane.core.ui.AFreeplaneAction;
import org.freeplane.core.ui.MenuBuilder;
import org.freeplane.core.ui.components.UITools;
import org.freeplane.core.util.FileUtils;
import org.freeplane.core.util.LogUtils;
import org.freeplane.core.util.TextUtils;
import org.freeplane.features.filter.condition.ASelectableCondition;
import org.freeplane.features.filter.condition.ConditionNotSatisfiedDecorator;
import org.freeplane.features.filter.condition.ConjunctConditions;
import org.freeplane.features.filter.condition.DisjunctConditions;
import org.freeplane.features.filter.condition.ICombinedCondition;
import org.freeplane.features.map.IMapSelectionListener;
import org.freeplane.features.map.MapModel;
import org.freeplane.features.mode.Controller;
import org.freeplane.features.url.UrlManager;
import org.freeplane.n3.nanoxml.XMLElement;
/**
* @author Dimitry Polivaev
*/
public abstract class AFilterComposerDialog extends JDialog implements IMapSelectionListener {
/**
* @author Dimitry Polivaev
*/
private class AddElementaryConditionAction extends AFreeplaneAction {
/**
*
*/
private static final long serialVersionUID = 1L;
AddElementaryConditionAction() {
super("AddElementaryConditionAction");
}
public void actionPerformed(final ActionEvent e) {
ASelectableCondition newCond;
newCond = editor.getCondition();
if (newCond != null) {
final DefaultComboBoxModel model = (DefaultComboBoxModel) elementaryConditionList.getModel();
model.addElement(newCond);
}
validate();
}
}
private class CloseAction implements ActionListener {
public void actionPerformed(final ActionEvent e) {
final Object source = e.getSource();
final boolean success;
if (source == btnOK || source == btnApply) {
success = applyChanges();
}
else {
success = true;
}
if (!success) {
return;
}
internalConditionsModel = null;
if (source == btnOK) {
dispose(true);
}
else if (source == btnCancel) {
dispose(false);
}
else {
initInternalConditionModel();
}
}
}
private boolean success;
public boolean isSuccess() {
return success;
}
private void dispose(boolean b) {
this.success = b;
dispose();
}
private class ConditionListMouseListener extends MouseAdapter {
@Override
public void mouseClicked(final MouseEvent e) {
if (e.getClickCount() == 2) {
EventQueue.invokeLater(new Runnable() {
public void run() {
if (selectCondition()) {
dispose(true);
}
}
});
}
}
}
private class ConditionListSelectionListener implements ListSelectionListener {
public void valueChanged(final ListSelectionEvent e) {
if (elementaryConditionList.getMinSelectionIndex() == -1) {
btnNot.setEnabled(false);
btnSplit.setEnabled(false);
btnAnd.setEnabled(false);
btnOr.setEnabled(false);
btnDelete.setEnabled(false);
btnName.setEnabled(false);
return;
}
else if (elementaryConditionList.getMinSelectionIndex() == elementaryConditionList.getMaxSelectionIndex()) {
btnNot.setEnabled(true);
btnSplit.setEnabled(elementaryConditionList.getSelectedValue() instanceof ICombinedCondition);
btnAnd.setEnabled(false);
btnOr.setEnabled(false);
btnDelete.setEnabled(true);
btnName.setEnabled(true);
return;
}
else {
btnNot.setEnabled(false);
btnSplit.setEnabled(false);
btnAnd.setEnabled(true);
btnOr.setEnabled(true);
btnDelete.setEnabled(true);
btnName.setEnabled(false);
}
}
}
private class CreateConjunctConditionAction extends AFreeplaneAction {
/**
*
*/
private static final long serialVersionUID = 1L;
CreateConjunctConditionAction() {
super("CreateConjunctConditionAction");
}
public void actionPerformed(final ActionEvent e) {
final ASelectableCondition[] selectedValues = toConditionsArray(elementaryConditionList.getSelectedValues());
if (selectedValues.length < 2) {
return;
}
final ASelectableCondition newCond = new ConjunctConditions(selectedValues);
final DefaultComboBoxModel model = (DefaultComboBoxModel) elementaryConditionList.getModel();
model.addElement(newCond);
validate();
}
}
private class CreateDisjunctConditionAction extends AFreeplaneAction {
/**
*
*/
private static final long serialVersionUID = 1L;
CreateDisjunctConditionAction() {
super("CreateDisjunctConditionAction");
}
public void actionPerformed(final ActionEvent e) {
final ASelectableCondition[] selectedValues = toConditionsArray(elementaryConditionList.getSelectedValues());
if (selectedValues.length < 2) {
return;
}
final ASelectableCondition newCond = new DisjunctConditions(selectedValues);
final DefaultComboBoxModel model = (DefaultComboBoxModel) elementaryConditionList.getModel();
model.addElement(newCond);
validate();
}
}
private ASelectableCondition[] toConditionsArray(final Object[] objects) {
final ASelectableCondition[] conditions = new ASelectableCondition[objects.length];
for (int i = 0; i < objects.length; i++) {
conditions[i] = (ASelectableCondition) objects[i];
}
return conditions;
}
private class CreateNotSatisfiedConditionAction extends AFreeplaneAction {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
CreateNotSatisfiedConditionAction() {
super("CreateNotSatisfiedConditionAction");
}
public void actionPerformed(final ActionEvent e) {
final int min = elementaryConditionList.getMinSelectionIndex();
if (min >= 0) {
final int max = elementaryConditionList.getMinSelectionIndex();
if (min == max) {
final ASelectableCondition oldCond = (ASelectableCondition) elementaryConditionList
.getSelectedValue();
final ASelectableCondition newCond = new ConditionNotSatisfiedDecorator(oldCond);
final DefaultComboBoxModel model = (DefaultComboBoxModel) elementaryConditionList.getModel();
model.addElement(newCond);
validate();
}
}
}
}
private class SplitConditionAction extends AFreeplaneAction {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
SplitConditionAction() {
super("SplitConditionAction");
}
public void actionPerformed(final ActionEvent e) {
final int min = elementaryConditionList.getMinSelectionIndex();
if (min >= 0) {
final int max = elementaryConditionList.getMinSelectionIndex();
if (min == max) {
final ASelectableCondition oldCond = (ASelectableCondition) elementaryConditionList
.getSelectedValue();
if (!(oldCond instanceof ICombinedCondition)) {
return;
}
final Collection<ASelectableCondition> newConditions = ((ICombinedCondition) oldCond).split();
final DefaultComboBoxModel model = (DefaultComboBoxModel) elementaryConditionList.getModel();
for (ASelectableCondition newCond : newConditions) {
final int index = model.getIndexOf(newCond);
if (-1 == index) {
model.addElement(newCond);
final int newIndex = model.getSize() - 1;
elementaryConditionList.addSelectionInterval(newIndex, newIndex);
}
else {
elementaryConditionList.addSelectionInterval(index, index);
}
}
elementaryConditionList.removeSelectionInterval(min, min);
validate();
}
}
}
}
private class DeleteConditionAction extends AFreeplaneAction {
/**
*
*/
private static final long serialVersionUID = 1L;
DeleteConditionAction() {
super("DeleteConditionAction");
}
public void actionPerformed(final ActionEvent e) {
final DefaultComboBoxModel model = (DefaultComboBoxModel) elementaryConditionList.getModel();
final int minSelectionIndex = elementaryConditionList.getMinSelectionIndex();
int selectedIndex;
while (0 <= (selectedIndex = elementaryConditionList.getSelectedIndex())) {
model.removeElementAt(selectedIndex);
}
final int size = elementaryConditionList.getModel().getSize();
if (size > 0) {
elementaryConditionList.setSelectedIndex(minSelectionIndex < size ? minSelectionIndex : size - 1);
}
validate();
}
}
private class NameConditionAction extends AFreeplaneAction {
/**
*
*/
private static final long serialVersionUID = 1L;
NameConditionAction() {
super("NameConditionAction");
}
public void actionPerformed(final ActionEvent e) {
final DefaultComboBoxModel model = (DefaultComboBoxModel) elementaryConditionList.getModel();
final int minSelectionIndex = elementaryConditionList.getMinSelectionIndex();
if (minSelectionIndex == -1) {
return;
}
final ASelectableCondition condition = (ASelectableCondition) model.getElementAt(minSelectionIndex);
final String userName = condition.getUserName();
final String newUserName = JOptionPane.showInputDialog(AFilterComposerDialog.this,
TextUtils.getText("enter_condition_name"), userName == null ? "" : userName);
if(newUserName == null)
return;
XMLElement xmlCondition = new XMLElement();
condition.toXml(xmlCondition);
ASelectableCondition newCondition = filterController.getConditionFactory().loadCondition(xmlCondition.getChildAtIndex(0));
if(newCondition== null)
return;
if (newUserName.equals("")) {
if(userName == null)
return;
newCondition.setUserName(null);
}
else {
if(newUserName.equals(userName))
return;
newCondition.setUserName(newUserName);
}
model.removeElementAt(minSelectionIndex);
model.insertElementAt(newCondition, minSelectionIndex);
}
}
private class LoadAction implements ActionListener {
public void actionPerformed(final ActionEvent e) {
final JFileChooser chooser = getFileChooser();
final int returnVal = chooser.showOpenDialog(AFilterComposerDialog.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
final File theFile = chooser.getSelectedFile();
internalConditionsModel.removeAllElements();
filterController.loadConditions(internalConditionsModel, theFile.getCanonicalPath());
}
catch (final Exception ex) {
LogUtils.severe(ex);
}
}
}
}
static private class MindMapFilterFileFilter extends FileFilter {
static FileFilter filter = new MindMapFilterFileFilter();
@Override
public boolean accept(final File f) {
if (f.isDirectory()) {
return true;
}
final String extension = FileUtils.getExtension(f.getName());
if (extension != null) {
if (extension.equals(FilterController.FREEPLANE_FILTER_EXTENSION_WITHOUT_DOT)) {
return true;
}
else {
return false;
}
}
return false;
}
@Override
public String getDescription() {
return TextUtils.getText("mindmaps_filter_desc");
}
}
private class SaveAction implements ActionListener {
public void actionPerformed(final ActionEvent e) {
final JFileChooser chooser = getFileChooser();
chooser.setDialogTitle(TextUtils.getText("SaveAsAction.text"));
final int returnVal = chooser.showSaveDialog(AFilterComposerDialog.this);
if (returnVal != JFileChooser.APPROVE_OPTION) {
return;
}
try {
final File f = chooser.getSelectedFile();
String canonicalPath = f.getCanonicalPath();
final String suffix = '.' + FilterController.FREEPLANE_FILTER_EXTENSION_WITHOUT_DOT;
if (!canonicalPath.endsWith(suffix)) {
canonicalPath = canonicalPath + suffix;
}
filterController.saveConditions(internalConditionsModel, canonicalPath);
}
catch (final Exception ex) {
LogUtils.severe(ex);
}
}
}
/**
*
*/
private static final long serialVersionUID = 1L;
final private JButton btnAdd;
final private JButton btnAnd;
final private JButton btnApply;
final private JButton btnCancel;
final private JButton btnDelete;
final private JButton btnName;
private JButton btnLoad;
final private JButton btnNot;
final private JButton btnSplit;
final private JButton btnOK;
final private JButton btnOr;
private JButton btnSave;
final private ConditionListSelectionListener conditionListListener;
// // final private Controller controller;
final private FilterConditionEditor editor;
final private JList elementaryConditionList;
final private FilterController filterController;
private DefaultComboBoxModel internalConditionsModel;
public AFilterComposerDialog(String title, boolean modal) {
super(Controller.getCurrentController().getViewController().getFrame(), title, modal);
filterController = FilterController.getCurrentFilterController();
editor = new FilterConditionEditor(filterController);
editor.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(),
BorderFactory.createEmptyBorder(5, 0, 5, 0)));
// this.controller = controller;
getContentPane().add(editor, BorderLayout.NORTH);
final Box conditionButtonBox = Box.createVerticalBox();
conditionButtonBox.setBorder(new EmptyBorder(0, 10, 0, 10));
getContentPane().add(conditionButtonBox, BorderLayout.EAST);
btnAdd = new JButton(new AddElementaryConditionAction());
btnAdd.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(Box.createVerticalGlue());
conditionButtonBox.add(btnAdd);
btnNot = new JButton(new CreateNotSatisfiedConditionAction());
conditionButtonBox.add(Box.createVerticalGlue());
btnNot.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnNot);
btnNot.setEnabled(false);
btnAnd = new JButton(new CreateConjunctConditionAction());
conditionButtonBox.add(Box.createVerticalGlue());
btnAnd.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnAnd);
btnAnd.setEnabled(false);
btnOr = new JButton(new CreateDisjunctConditionAction());
conditionButtonBox.add(Box.createVerticalGlue());
btnOr.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnOr);
btnOr.setEnabled(false);
btnSplit = new JButton(new SplitConditionAction());
conditionButtonBox.add(Box.createVerticalGlue());
btnSplit.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnSplit);
btnSplit.setEnabled(false);
btnDelete = new JButton(new DeleteConditionAction());
btnDelete.setEnabled(false);
conditionButtonBox.add(Box.createVerticalGlue());
btnDelete.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnDelete);
btnName = new JButton(new NameConditionAction());
btnName.setEnabled(false);
conditionButtonBox.add(Box.createVerticalGlue());
btnName.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnName);
conditionButtonBox.add(Box.createVerticalGlue());
final Box controllerBox = Box.createHorizontalBox();
controllerBox.setBorder(new EmptyBorder(5, 0, 5, 0));
getContentPane().add(controllerBox, BorderLayout.SOUTH);
final CloseAction closeAction = new CloseAction();
btnOK = new JButton();
MenuBuilder.setLabelAndMnemonic(btnOK, TextUtils.getRawText("ok"));
btnOK.addActionListener(closeAction);
btnOK.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
controllerBox.add(Box.createHorizontalGlue());
controllerBox.add(btnOK);
if (!isModal()) {
btnApply = new JButton();
MenuBuilder.setLabelAndMnemonic(btnApply, TextUtils.getRawText("apply"));
btnApply.addActionListener(closeAction);
btnApply.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
controllerBox.add(Box.createHorizontalGlue());
controllerBox.add(btnApply);
}
else {
btnApply = null;
}
btnCancel = new JButton();
MenuBuilder.setLabelAndMnemonic(btnCancel, TextUtils.getRawText("cancel"));
btnCancel.addActionListener(closeAction);
btnCancel.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
controllerBox.add(Box.createHorizontalGlue());
controllerBox.add(btnCancel);
controllerBox.add(Box.createHorizontalGlue());
Controller controller = Controller.getCurrentController();
if (!controller.getViewController().isApplet()) {
final ActionListener saveAction = new SaveAction();
btnSave = new JButton();
- MenuBuilder.setLabelAndMnemonic(btnSave, TextUtils.getRawText("SaveAction.text"));
+ MenuBuilder.setLabelAndMnemonic(btnSave, TextUtils.getRawText("FilterComposerDialog.save"));
btnSave.addActionListener(saveAction);
btnSave.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
final ActionListener loadAction = new LoadAction();
btnLoad = new JButton();
MenuBuilder.setLabelAndMnemonic(btnLoad, TextUtils.getRawText("load"));
btnLoad.addActionListener(loadAction);
btnLoad.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
controllerBox.add(btnSave);
controllerBox.add(Box.createHorizontalGlue());
controllerBox.add(btnLoad);
controllerBox.add(Box.createHorizontalGlue());
}
elementaryConditionList = new JList();
elementaryConditionList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
elementaryConditionList.setCellRenderer(filterController.getConditionRenderer());
elementaryConditionList.setLayoutOrientation(JList.VERTICAL);
elementaryConditionList.setAlignmentX(Component.LEFT_ALIGNMENT);
conditionListListener = new ConditionListSelectionListener();
elementaryConditionList.addListSelectionListener(conditionListListener);
elementaryConditionList.addMouseListener(new ConditionListMouseListener());
final JScrollPane conditionScrollPane = new JScrollPane(elementaryConditionList);
UITools.setScrollbarIncrement(conditionScrollPane);
UITools.addScrollbarIncrementPropertyListener(conditionScrollPane);
final JLabel conditionColumnHeader = new JLabel(TextUtils.getText("filter_conditions"));
conditionColumnHeader.setHorizontalAlignment(SwingConstants.CENTER);
conditionScrollPane.setColumnHeaderView(conditionColumnHeader);
conditionScrollPane.setPreferredSize(new Dimension(500, 200));
getContentPane().add(conditionScrollPane, BorderLayout.CENTER);
UITools.addEscapeActionToDialog(this);
pack();
}
public void afterMapChange(final MapModel oldMap, final MapModel newMap) {
editor.mapChanged(newMap);
}
public void afterMapClose(final MapModel oldMap) {
}
private boolean applyChanges() {
internalConditionsModel.setSelectedItem(elementaryConditionList.getSelectedValue());
final int[] selectedIndices = elementaryConditionList.getSelectedIndices();
if (applyModel(internalConditionsModel, selectedIndices)) {
internalConditionsModel = null;
return true;
}
else {
return false;
}
}
abstract protected boolean applyModel(DefaultComboBoxModel model, int[] selectedIndices);
public void beforeMapChange(final MapModel oldMap, final MapModel newMap) {
}
protected JFileChooser getFileChooser() {
final JFileChooser chooser = UrlManager.getController().getFileChooser(MindMapFilterFileFilter.filter, false);
return chooser;
}
private void initInternalConditionModel() {
internalConditionsModel = createModel();
elementaryConditionList.setModel(internalConditionsModel);
Object selectedItem = internalConditionsModel.getSelectedItem();
if (selectedItem != null) {
int selectedIndex = internalConditionsModel.getIndexOf(selectedItem);
if (selectedIndex >= 0) {
elementaryConditionList.setSelectedIndex(selectedIndex);
return;
}
}
}
abstract protected DefaultComboBoxModel createModel();
private boolean selectCondition() {
final int min = elementaryConditionList.getMinSelectionIndex();
if (min >= 0) {
final int max = elementaryConditionList.getMinSelectionIndex();
if (min == max) {
return applyChanges();
}
}
return false;
}
/**
*/
public void setSelectedItem(final Object selectedItem) {
elementaryConditionList.setSelectedValue(selectedItem, true);
}
@Override
public void show() {
initInternalConditionModel();
success = false;
super.show();
}
}
| true | true |
public AFilterComposerDialog(String title, boolean modal) {
super(Controller.getCurrentController().getViewController().getFrame(), title, modal);
filterController = FilterController.getCurrentFilterController();
editor = new FilterConditionEditor(filterController);
editor.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(),
BorderFactory.createEmptyBorder(5, 0, 5, 0)));
// this.controller = controller;
getContentPane().add(editor, BorderLayout.NORTH);
final Box conditionButtonBox = Box.createVerticalBox();
conditionButtonBox.setBorder(new EmptyBorder(0, 10, 0, 10));
getContentPane().add(conditionButtonBox, BorderLayout.EAST);
btnAdd = new JButton(new AddElementaryConditionAction());
btnAdd.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(Box.createVerticalGlue());
conditionButtonBox.add(btnAdd);
btnNot = new JButton(new CreateNotSatisfiedConditionAction());
conditionButtonBox.add(Box.createVerticalGlue());
btnNot.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnNot);
btnNot.setEnabled(false);
btnAnd = new JButton(new CreateConjunctConditionAction());
conditionButtonBox.add(Box.createVerticalGlue());
btnAnd.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnAnd);
btnAnd.setEnabled(false);
btnOr = new JButton(new CreateDisjunctConditionAction());
conditionButtonBox.add(Box.createVerticalGlue());
btnOr.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnOr);
btnOr.setEnabled(false);
btnSplit = new JButton(new SplitConditionAction());
conditionButtonBox.add(Box.createVerticalGlue());
btnSplit.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnSplit);
btnSplit.setEnabled(false);
btnDelete = new JButton(new DeleteConditionAction());
btnDelete.setEnabled(false);
conditionButtonBox.add(Box.createVerticalGlue());
btnDelete.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnDelete);
btnName = new JButton(new NameConditionAction());
btnName.setEnabled(false);
conditionButtonBox.add(Box.createVerticalGlue());
btnName.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnName);
conditionButtonBox.add(Box.createVerticalGlue());
final Box controllerBox = Box.createHorizontalBox();
controllerBox.setBorder(new EmptyBorder(5, 0, 5, 0));
getContentPane().add(controllerBox, BorderLayout.SOUTH);
final CloseAction closeAction = new CloseAction();
btnOK = new JButton();
MenuBuilder.setLabelAndMnemonic(btnOK, TextUtils.getRawText("ok"));
btnOK.addActionListener(closeAction);
btnOK.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
controllerBox.add(Box.createHorizontalGlue());
controllerBox.add(btnOK);
if (!isModal()) {
btnApply = new JButton();
MenuBuilder.setLabelAndMnemonic(btnApply, TextUtils.getRawText("apply"));
btnApply.addActionListener(closeAction);
btnApply.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
controllerBox.add(Box.createHorizontalGlue());
controllerBox.add(btnApply);
}
else {
btnApply = null;
}
btnCancel = new JButton();
MenuBuilder.setLabelAndMnemonic(btnCancel, TextUtils.getRawText("cancel"));
btnCancel.addActionListener(closeAction);
btnCancel.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
controllerBox.add(Box.createHorizontalGlue());
controllerBox.add(btnCancel);
controllerBox.add(Box.createHorizontalGlue());
Controller controller = Controller.getCurrentController();
if (!controller.getViewController().isApplet()) {
final ActionListener saveAction = new SaveAction();
btnSave = new JButton();
MenuBuilder.setLabelAndMnemonic(btnSave, TextUtils.getRawText("SaveAction.text"));
btnSave.addActionListener(saveAction);
btnSave.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
final ActionListener loadAction = new LoadAction();
btnLoad = new JButton();
MenuBuilder.setLabelAndMnemonic(btnLoad, TextUtils.getRawText("load"));
btnLoad.addActionListener(loadAction);
btnLoad.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
controllerBox.add(btnSave);
controllerBox.add(Box.createHorizontalGlue());
controllerBox.add(btnLoad);
controllerBox.add(Box.createHorizontalGlue());
}
elementaryConditionList = new JList();
elementaryConditionList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
elementaryConditionList.setCellRenderer(filterController.getConditionRenderer());
elementaryConditionList.setLayoutOrientation(JList.VERTICAL);
elementaryConditionList.setAlignmentX(Component.LEFT_ALIGNMENT);
conditionListListener = new ConditionListSelectionListener();
elementaryConditionList.addListSelectionListener(conditionListListener);
elementaryConditionList.addMouseListener(new ConditionListMouseListener());
final JScrollPane conditionScrollPane = new JScrollPane(elementaryConditionList);
UITools.setScrollbarIncrement(conditionScrollPane);
UITools.addScrollbarIncrementPropertyListener(conditionScrollPane);
final JLabel conditionColumnHeader = new JLabel(TextUtils.getText("filter_conditions"));
conditionColumnHeader.setHorizontalAlignment(SwingConstants.CENTER);
conditionScrollPane.setColumnHeaderView(conditionColumnHeader);
conditionScrollPane.setPreferredSize(new Dimension(500, 200));
getContentPane().add(conditionScrollPane, BorderLayout.CENTER);
UITools.addEscapeActionToDialog(this);
pack();
}
|
public AFilterComposerDialog(String title, boolean modal) {
super(Controller.getCurrentController().getViewController().getFrame(), title, modal);
filterController = FilterController.getCurrentFilterController();
editor = new FilterConditionEditor(filterController);
editor.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(),
BorderFactory.createEmptyBorder(5, 0, 5, 0)));
// this.controller = controller;
getContentPane().add(editor, BorderLayout.NORTH);
final Box conditionButtonBox = Box.createVerticalBox();
conditionButtonBox.setBorder(new EmptyBorder(0, 10, 0, 10));
getContentPane().add(conditionButtonBox, BorderLayout.EAST);
btnAdd = new JButton(new AddElementaryConditionAction());
btnAdd.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(Box.createVerticalGlue());
conditionButtonBox.add(btnAdd);
btnNot = new JButton(new CreateNotSatisfiedConditionAction());
conditionButtonBox.add(Box.createVerticalGlue());
btnNot.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnNot);
btnNot.setEnabled(false);
btnAnd = new JButton(new CreateConjunctConditionAction());
conditionButtonBox.add(Box.createVerticalGlue());
btnAnd.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnAnd);
btnAnd.setEnabled(false);
btnOr = new JButton(new CreateDisjunctConditionAction());
conditionButtonBox.add(Box.createVerticalGlue());
btnOr.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnOr);
btnOr.setEnabled(false);
btnSplit = new JButton(new SplitConditionAction());
conditionButtonBox.add(Box.createVerticalGlue());
btnSplit.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnSplit);
btnSplit.setEnabled(false);
btnDelete = new JButton(new DeleteConditionAction());
btnDelete.setEnabled(false);
conditionButtonBox.add(Box.createVerticalGlue());
btnDelete.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnDelete);
btnName = new JButton(new NameConditionAction());
btnName.setEnabled(false);
conditionButtonBox.add(Box.createVerticalGlue());
btnName.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
conditionButtonBox.add(btnName);
conditionButtonBox.add(Box.createVerticalGlue());
final Box controllerBox = Box.createHorizontalBox();
controllerBox.setBorder(new EmptyBorder(5, 0, 5, 0));
getContentPane().add(controllerBox, BorderLayout.SOUTH);
final CloseAction closeAction = new CloseAction();
btnOK = new JButton();
MenuBuilder.setLabelAndMnemonic(btnOK, TextUtils.getRawText("ok"));
btnOK.addActionListener(closeAction);
btnOK.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
controllerBox.add(Box.createHorizontalGlue());
controllerBox.add(btnOK);
if (!isModal()) {
btnApply = new JButton();
MenuBuilder.setLabelAndMnemonic(btnApply, TextUtils.getRawText("apply"));
btnApply.addActionListener(closeAction);
btnApply.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
controllerBox.add(Box.createHorizontalGlue());
controllerBox.add(btnApply);
}
else {
btnApply = null;
}
btnCancel = new JButton();
MenuBuilder.setLabelAndMnemonic(btnCancel, TextUtils.getRawText("cancel"));
btnCancel.addActionListener(closeAction);
btnCancel.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
controllerBox.add(Box.createHorizontalGlue());
controllerBox.add(btnCancel);
controllerBox.add(Box.createHorizontalGlue());
Controller controller = Controller.getCurrentController();
if (!controller.getViewController().isApplet()) {
final ActionListener saveAction = new SaveAction();
btnSave = new JButton();
MenuBuilder.setLabelAndMnemonic(btnSave, TextUtils.getRawText("FilterComposerDialog.save"));
btnSave.addActionListener(saveAction);
btnSave.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
final ActionListener loadAction = new LoadAction();
btnLoad = new JButton();
MenuBuilder.setLabelAndMnemonic(btnLoad, TextUtils.getRawText("load"));
btnLoad.addActionListener(loadAction);
btnLoad.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
controllerBox.add(btnSave);
controllerBox.add(Box.createHorizontalGlue());
controllerBox.add(btnLoad);
controllerBox.add(Box.createHorizontalGlue());
}
elementaryConditionList = new JList();
elementaryConditionList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
elementaryConditionList.setCellRenderer(filterController.getConditionRenderer());
elementaryConditionList.setLayoutOrientation(JList.VERTICAL);
elementaryConditionList.setAlignmentX(Component.LEFT_ALIGNMENT);
conditionListListener = new ConditionListSelectionListener();
elementaryConditionList.addListSelectionListener(conditionListListener);
elementaryConditionList.addMouseListener(new ConditionListMouseListener());
final JScrollPane conditionScrollPane = new JScrollPane(elementaryConditionList);
UITools.setScrollbarIncrement(conditionScrollPane);
UITools.addScrollbarIncrementPropertyListener(conditionScrollPane);
final JLabel conditionColumnHeader = new JLabel(TextUtils.getText("filter_conditions"));
conditionColumnHeader.setHorizontalAlignment(SwingConstants.CENTER);
conditionScrollPane.setColumnHeaderView(conditionColumnHeader);
conditionScrollPane.setPreferredSize(new Dimension(500, 200));
getContentPane().add(conditionScrollPane, BorderLayout.CENTER);
UITools.addEscapeActionToDialog(this);
pack();
}
|
diff --git a/src/main/java/test/cli/cloudify/cloud/services/azure/MicrosoftAzureCloudService.java b/src/main/java/test/cli/cloudify/cloud/services/azure/MicrosoftAzureCloudService.java
index 7987970e..0b018f6a 100644
--- a/src/main/java/test/cli/cloudify/cloud/services/azure/MicrosoftAzureCloudService.java
+++ b/src/main/java/test/cli/cloudify/cloud/services/azure/MicrosoftAzureCloudService.java
@@ -1,224 +1,224 @@
package test.cli.cloudify.cloud.services.azure;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import org.apache.commons.io.FileUtils;
import org.cloudifysource.esc.driver.provisioning.azure.client.MicrosoftAzureException;
import org.cloudifysource.esc.driver.provisioning.azure.client.MicrosoftAzureRestClient;
import org.cloudifysource.esc.driver.provisioning.azure.model.ConfigurationSet;
import org.cloudifysource.esc.driver.provisioning.azure.model.ConfigurationSets;
import org.cloudifysource.esc.driver.provisioning.azure.model.Deployment;
import org.cloudifysource.esc.driver.provisioning.azure.model.Deployments;
import org.cloudifysource.esc.driver.provisioning.azure.model.HostedService;
import org.cloudifysource.esc.driver.provisioning.azure.model.HostedServices;
import org.cloudifysource.esc.driver.provisioning.azure.model.NetworkConfigurationSet;
import org.cloudifysource.esc.driver.provisioning.azure.model.Role;
import test.cli.cloudify.cloud.services.AbstractCloudService;
import com.gigaspaces.internal.utils.StringUtils;
import framework.tools.SGTestHelper;
import framework.utils.IOUtils;
import framework.utils.LogUtils;
public class MicrosoftAzureCloudService extends AbstractCloudService {
private static final String AZURE_CERT_PFX = "azure-cert.pfx";
private static final String USER_NAME = System.getProperty("user.name");
private final MicrosoftAzureRestClient azureClient;
private static final String AZURE_SUBSCRIPTION_ID = "3226dcf0-3130-42f3-b68f-a2019c09431e";
private static final String PATH_TO_PFX = SGTestHelper.getSGTestRootDir() + "/src/main/resources/apps/cloudify/cloud/azure/azure-cert.pfx";
private static final String PFX_PASSWORD = "1408Rokk";
private static final String ADDRESS_SPACE = "10.4.0.0/16";
private static final long ESTIMATED_SHUTDOWN_TIME = 5 * 60 * 1000;
private static final long SCAN_INTERVAL = 10 * 1000; // 10 seconds. long time since it takes time to shutdown the machine
private static final long SCAN_TIMEOUT = 5 * 60 * 1000; // 5 minutes
public MicrosoftAzureCloudService() {
super("azure");
azureClient = new MicrosoftAzureRestClient(AZURE_SUBSCRIPTION_ID,
PATH_TO_PFX, PFX_PASSWORD,
null, null, null);
}
@Override
public void injectCloudAuthenticationDetails() throws IOException {
copyCustomCloudConfigurationFileToServiceFolder();
copyPrivateKeyToUploadFolder();
getProperties().put("subscriptionId", AZURE_SUBSCRIPTION_ID);
getProperties().put("username", USER_NAME);
getProperties().put("password", PFX_PASSWORD);
getProperties().put("pfxFile", AZURE_CERT_PFX);
getProperties().put("pfxPassword", PFX_PASSWORD);
final Map<String, String> propsToReplace = new HashMap<String, String>();
propsToReplace.put("cloudify_agent_", getMachinePrefix().toLowerCase() + "cloudify-agent");
propsToReplace.put("cloudify_manager", getMachinePrefix().toLowerCase() + "cloudify-manager");
propsToReplace.put("ENTER_AVAILABILITY_SET", USER_NAME);
propsToReplace.put("ENTER_DEPLOYMENT_SLOT", "Staging");
propsToReplace.put("ENTER_VIRTUAL_NETWORK_SITE_NAME", USER_NAME + "networksite");
propsToReplace.put("ENTER_ADDRESS_SPACE", ADDRESS_SPACE);
propsToReplace.put("ENTER_AFFINITY_GROUP", USER_NAME + "cloudifyaffinity");
propsToReplace.put("ENTER_LOCATION", "East US");
propsToReplace.put("ENTER_STORAGE_ACCOUNT", USER_NAME + "cloudifystorage");
IOUtils.replaceTextInFile(getPathToCloudGroovy(), propsToReplace);
}
@Override
public String getUser() {
return "sgtest";
}
@Override
public String getApiKey() {
throw new UnsupportedOperationException("Microsoft Azure Cloud Driver does not have an API key concept. this method should have never been called");
}
@Override
public boolean scanLeakedAgentNodes() {
return scanNodesWithPrefix("agent");
}
@Override
public boolean scanLeakedAgentAndManagementNodes() {
return scanNodesWithPrefix("agent" , "manager");
}
private boolean scanNodesWithPrefix(final String... prefixes) {
LogUtils.log("scanning leaking nodes with prefix " + StringUtils.arrayToCommaDelimitedString(prefixes));
long scanEndTime = System.currentTimeMillis() + SCAN_TIMEOUT;
try {
List<String> leakingAgentNodesPublicIps = new ArrayList<String>();
HostedServices listHostedServices = azureClient.listHostedServices();
Deployments deploymentsBeingDeleted = null;
do {
if (System.currentTimeMillis() > scanEndTime) {
throw new TimeoutException("Timed out waiting for deleting nodes to finish. last status was : " + deploymentsBeingDeleted.getDeployments());
}
Thread.sleep(SCAN_INTERVAL);
LogUtils.log("waiting for all deployments to reach a non 'Deleting' state");
for (HostedService hostedService : listHostedServices) {
try {
List<Deployment> deploymentsForHostedSerice = azureClient.getHostedService(hostedService.getServiceName(), true).getDeployments().getDeployments();
if (deploymentsForHostedSerice.size() > 0) {
Deployment deployment = deploymentsForHostedSerice.get(0); // each hosted service will have just one deployment.
if (deployment.getStatus().toLowerCase().equals("deleting")) {
LogUtils.log("Found a deployment with name : " + deployment.getName() + " and status : " + deployment.getStatus());
deploymentsBeingDeleted = new Deployments();
deploymentsBeingDeleted.getDeployments().add(deployment);
}
}
} catch (MicrosoftAzureException e) {
LogUtils.log("Failed retrieving deployments from hosted service : " + hostedService.getServiceName() + " Reason --> " + e.getMessage());
}
}
}
while (deploymentsBeingDeleted != null && !(deploymentsBeingDeleted.getDeployments().isEmpty()));
// now all deployment have reached a steady state.
// scan again to find out if there are any agents still running
- LogUtils.log("scanning all remaining hosted services for running agent nodes");
+ LogUtils.log("scanning all remaining hosted services for running nodes");
for (HostedService hostedService : listHostedServices) {
List<Deployment> deploymentsForHostedSerice = azureClient.getHostedService(hostedService.getServiceName(), true).getDeployments().getDeployments();
if (deploymentsForHostedSerice.size() > 0) {
Deployment deployment = deploymentsForHostedSerice.get(0); // each hosted service will have just one deployment.
Role role = deployment.getRoleList().getRoles().get(0);
String hostName = role.getRoleName(); // each deployment will have just one role.
for (String prefix : prefixes) {
if (hostName.contains(prefix)) {
String publicIpFromDeployment = getPublicIpFromDeployment(deployment,prefix);
LogUtils.log("Found a node with public ip : " + publicIpFromDeployment + " and hostName " + hostName);
leakingAgentNodesPublicIps.add(publicIpFromDeployment);
}
}
}
}
if (!leakingAgentNodesPublicIps.isEmpty()) {
for (String ip : leakingAgentNodesPublicIps) {
- LogUtils.log("attempting to kill agent node : " + ip);
+ LogUtils.log("attempting to kill node : " + ip);
long endTime = System.currentTimeMillis() + ESTIMATED_SHUTDOWN_TIME;
try {
azureClient.deleteVirtualMachineByIp(ip, false, endTime);
} catch (final Exception e) {
LogUtils.log("Failed deleting node with ip : " + ip + ". reason --> " + e.getMessage());
}
}
return false;
} else {
return true;
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
private String getPublicIpFromDeployment(Deployment deployment, final String prefix) {
String publicIp = null;
Role role = deployment.getRoleList().getRoles().get(0);
String hostName = role.getRoleName();
if (hostName.contains(prefix)) {
ConfigurationSets configurationSets = role.getConfigurationSets();
for (ConfigurationSet configurationSet : configurationSets) {
if (configurationSet instanceof NetworkConfigurationSet) {
NetworkConfigurationSet networkConfigurationSet = (NetworkConfigurationSet) configurationSet;
publicIp = networkConfigurationSet.getInputEndpoints()
.getInputEndpoints().get(0).getvIp();
}
}
}
return publicIp;
}
private void copyCustomCloudConfigurationFileToServiceFolder() throws IOException {
// copy custom cloud driver configuration to test folder
String cloudServiceFullPath = this.getPathToCloudFolder();
File originalCloudDriverConfigFile = new File(cloudServiceFullPath, "azure-cloud.groovy");
File customCloudDriverConfigFile = new File(SGTestHelper.getSGTestRootDir() + "/src/main/resources/apps/cloudify/cloud/azure", "azure-cloud.groovy");
Map<File, File> filesToReplace = new HashMap<File, File>();
filesToReplace.put(originalCloudDriverConfigFile, customCloudDriverConfigFile);
if (originalCloudDriverConfigFile.exists()) {
originalCloudDriverConfigFile.delete();
}
FileUtils.copyFile(customCloudDriverConfigFile, originalCloudDriverConfigFile);
}
private void copyPrivateKeyToUploadFolder() throws IOException {
File pfxFilePath = new File(SGTestHelper.getSGTestRootDir() + "/src/main/resources/apps/cloudify/cloud/azure/azure-cert.pfx");
File uploadDir = new File(getPathToCloudFolder() + "/upload");
FileUtils.copyFileToDirectory(pfxFilePath, uploadDir);
}
}
| false | true |
private boolean scanNodesWithPrefix(final String... prefixes) {
LogUtils.log("scanning leaking nodes with prefix " + StringUtils.arrayToCommaDelimitedString(prefixes));
long scanEndTime = System.currentTimeMillis() + SCAN_TIMEOUT;
try {
List<String> leakingAgentNodesPublicIps = new ArrayList<String>();
HostedServices listHostedServices = azureClient.listHostedServices();
Deployments deploymentsBeingDeleted = null;
do {
if (System.currentTimeMillis() > scanEndTime) {
throw new TimeoutException("Timed out waiting for deleting nodes to finish. last status was : " + deploymentsBeingDeleted.getDeployments());
}
Thread.sleep(SCAN_INTERVAL);
LogUtils.log("waiting for all deployments to reach a non 'Deleting' state");
for (HostedService hostedService : listHostedServices) {
try {
List<Deployment> deploymentsForHostedSerice = azureClient.getHostedService(hostedService.getServiceName(), true).getDeployments().getDeployments();
if (deploymentsForHostedSerice.size() > 0) {
Deployment deployment = deploymentsForHostedSerice.get(0); // each hosted service will have just one deployment.
if (deployment.getStatus().toLowerCase().equals("deleting")) {
LogUtils.log("Found a deployment with name : " + deployment.getName() + " and status : " + deployment.getStatus());
deploymentsBeingDeleted = new Deployments();
deploymentsBeingDeleted.getDeployments().add(deployment);
}
}
} catch (MicrosoftAzureException e) {
LogUtils.log("Failed retrieving deployments from hosted service : " + hostedService.getServiceName() + " Reason --> " + e.getMessage());
}
}
}
while (deploymentsBeingDeleted != null && !(deploymentsBeingDeleted.getDeployments().isEmpty()));
// now all deployment have reached a steady state.
// scan again to find out if there are any agents still running
LogUtils.log("scanning all remaining hosted services for running agent nodes");
for (HostedService hostedService : listHostedServices) {
List<Deployment> deploymentsForHostedSerice = azureClient.getHostedService(hostedService.getServiceName(), true).getDeployments().getDeployments();
if (deploymentsForHostedSerice.size() > 0) {
Deployment deployment = deploymentsForHostedSerice.get(0); // each hosted service will have just one deployment.
Role role = deployment.getRoleList().getRoles().get(0);
String hostName = role.getRoleName(); // each deployment will have just one role.
for (String prefix : prefixes) {
if (hostName.contains(prefix)) {
String publicIpFromDeployment = getPublicIpFromDeployment(deployment,prefix);
LogUtils.log("Found a node with public ip : " + publicIpFromDeployment + " and hostName " + hostName);
leakingAgentNodesPublicIps.add(publicIpFromDeployment);
}
}
}
}
if (!leakingAgentNodesPublicIps.isEmpty()) {
for (String ip : leakingAgentNodesPublicIps) {
LogUtils.log("attempting to kill agent node : " + ip);
long endTime = System.currentTimeMillis() + ESTIMATED_SHUTDOWN_TIME;
try {
azureClient.deleteVirtualMachineByIp(ip, false, endTime);
} catch (final Exception e) {
LogUtils.log("Failed deleting node with ip : " + ip + ". reason --> " + e.getMessage());
}
}
return false;
} else {
return true;
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
|
private boolean scanNodesWithPrefix(final String... prefixes) {
LogUtils.log("scanning leaking nodes with prefix " + StringUtils.arrayToCommaDelimitedString(prefixes));
long scanEndTime = System.currentTimeMillis() + SCAN_TIMEOUT;
try {
List<String> leakingAgentNodesPublicIps = new ArrayList<String>();
HostedServices listHostedServices = azureClient.listHostedServices();
Deployments deploymentsBeingDeleted = null;
do {
if (System.currentTimeMillis() > scanEndTime) {
throw new TimeoutException("Timed out waiting for deleting nodes to finish. last status was : " + deploymentsBeingDeleted.getDeployments());
}
Thread.sleep(SCAN_INTERVAL);
LogUtils.log("waiting for all deployments to reach a non 'Deleting' state");
for (HostedService hostedService : listHostedServices) {
try {
List<Deployment> deploymentsForHostedSerice = azureClient.getHostedService(hostedService.getServiceName(), true).getDeployments().getDeployments();
if (deploymentsForHostedSerice.size() > 0) {
Deployment deployment = deploymentsForHostedSerice.get(0); // each hosted service will have just one deployment.
if (deployment.getStatus().toLowerCase().equals("deleting")) {
LogUtils.log("Found a deployment with name : " + deployment.getName() + " and status : " + deployment.getStatus());
deploymentsBeingDeleted = new Deployments();
deploymentsBeingDeleted.getDeployments().add(deployment);
}
}
} catch (MicrosoftAzureException e) {
LogUtils.log("Failed retrieving deployments from hosted service : " + hostedService.getServiceName() + " Reason --> " + e.getMessage());
}
}
}
while (deploymentsBeingDeleted != null && !(deploymentsBeingDeleted.getDeployments().isEmpty()));
// now all deployment have reached a steady state.
// scan again to find out if there are any agents still running
LogUtils.log("scanning all remaining hosted services for running nodes");
for (HostedService hostedService : listHostedServices) {
List<Deployment> deploymentsForHostedSerice = azureClient.getHostedService(hostedService.getServiceName(), true).getDeployments().getDeployments();
if (deploymentsForHostedSerice.size() > 0) {
Deployment deployment = deploymentsForHostedSerice.get(0); // each hosted service will have just one deployment.
Role role = deployment.getRoleList().getRoles().get(0);
String hostName = role.getRoleName(); // each deployment will have just one role.
for (String prefix : prefixes) {
if (hostName.contains(prefix)) {
String publicIpFromDeployment = getPublicIpFromDeployment(deployment,prefix);
LogUtils.log("Found a node with public ip : " + publicIpFromDeployment + " and hostName " + hostName);
leakingAgentNodesPublicIps.add(publicIpFromDeployment);
}
}
}
}
if (!leakingAgentNodesPublicIps.isEmpty()) {
for (String ip : leakingAgentNodesPublicIps) {
LogUtils.log("attempting to kill node : " + ip);
long endTime = System.currentTimeMillis() + ESTIMATED_SHUTDOWN_TIME;
try {
azureClient.deleteVirtualMachineByIp(ip, false, endTime);
} catch (final Exception e) {
LogUtils.log("Failed deleting node with ip : " + ip + ". reason --> " + e.getMessage());
}
}
return false;
} else {
return true;
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
|
diff --git a/filters/regex-ui/src/main/java/net/sf/okapi/filters/regex/ui/Editor.java b/filters/regex-ui/src/main/java/net/sf/okapi/filters/regex/ui/Editor.java
index 58b0a937c..1f1743b23 100644
--- a/filters/regex-ui/src/main/java/net/sf/okapi/filters/regex/ui/Editor.java
+++ b/filters/regex-ui/src/main/java/net/sf/okapi/filters/regex/ui/Editor.java
@@ -1,648 +1,648 @@
/*===========================================================================
Copyright (C) 2008-2009 by the Okapi Framework contributors
-----------------------------------------------------------------------------
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
See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/
package net.sf.okapi.filters.regex.ui;
import java.util.ArrayList;
import java.util.regex.Pattern;
import net.sf.okapi.common.IContext;
import net.sf.okapi.common.IHelp;
import net.sf.okapi.common.IParameters;
import net.sf.okapi.common.IParametersEditor;
import net.sf.okapi.common.ui.Dialogs;
import net.sf.okapi.common.ui.InputDialog;
import net.sf.okapi.common.ui.OKCancelPanel;
import net.sf.okapi.common.ui.UIUtil;
import net.sf.okapi.common.ui.filters.InlineCodeFinderDialog;
import net.sf.okapi.common.ui.filters.LDPanel;
import net.sf.okapi.filters.regex.Parameters;
import net.sf.okapi.filters.regex.Rule;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
public class Editor implements IParametersEditor {
private Shell shell;
private boolean result = false;
private Text edExpression;
private Button chkExtractOuterStrings;
private Text edStartString;
private Text edEndString;
private List lbRules;
private Button btAdd;
private Button btEdit;
private Button btRename;
private Button btRemove;
private Button btMoveUp;
private Button btMoveDown;
private LDPanel pnlLD;
private Parameters params;
private ArrayList<Rule> rules;
private int ruleIndex = -1;
private Text edRuleType;
private Button chkPreserveWS;
private Button chkUseCodeFinder;
private Button btEditFinderRules;
private Button chkIgnoreCase;
private Button chkDotAll;
private Button chkMultiline;
private Text edMimeType;
private IHelp help;
private Button chkOneLevelGroups;
public boolean edit (IParameters p_Options,
boolean readOnly,
IContext context)
{
boolean bRes = false;
shell = null;
help = (IHelp)context.getObject("help");
params = (Parameters)p_Options;
// Make a work copy (in case of escape)
rules = new ArrayList<Rule>();
for ( Rule rule : params.getRules() ) {
rules.add(new Rule(rule));
}
try {
shell = new Shell((Shell)context.getObject("shell"), SWT.CLOSE | SWT.TITLE | SWT.RESIZE | SWT.APPLICATION_MODAL);
create((Shell)context.getObject("shell"), readOnly);
return showDialog();
}
catch ( Exception E ) {
Dialogs.showError(shell, E.getLocalizedMessage(), null);
bRes = false;
}
finally {
// Dispose of the shell, but not of the display
if ( shell != null ) shell.dispose();
}
return bRes;
}
public IParameters createParameters () {
return new Parameters();
}
private void create (Shell p_Parent,
boolean readOnly)
{
shell.setText(Res.getString("Editor.caption")); //$NON-NLS-1$
if ( p_Parent != null ) shell.setImage(p_Parent.getImage());
GridLayout layTmp = new GridLayout();
layTmp.marginBottom = 0;
layTmp.verticalSpacing = 0;
shell.setLayout(layTmp);
TabFolder tfTmp = new TabFolder(shell, SWT.NONE);
GridData gdTmp = new GridData(GridData.FILL_BOTH);
tfTmp.setLayoutData(gdTmp);
//--- Rules tab
Composite cmpTmp = new Composite(tfTmp, SWT.NONE);
layTmp = new GridLayout(2, false);
cmpTmp.setLayout(layTmp);
lbRules = new List(cmpTmp, SWT.BORDER | SWT.H_SCROLL);
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.horizontalSpan = 1;
gdTmp.grabExcessHorizontalSpace = true;
gdTmp.verticalSpan = 3;
lbRules.setLayoutData(gdTmp);
lbRules.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateRule();
updateMoveButtons();
};
});
lbRules.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
editRule(false);
}
public void mouseDown(MouseEvent e) {}
public void mouseUp(MouseEvent e) {}
});
//--- Rule properties
Group propGroup = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout();
propGroup.setLayout(layTmp);
propGroup.setText(Res.getString("Editor.ruleProperties")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.verticalSpan = 3;
propGroup.setLayoutData(gdTmp);
edExpression = new Text(propGroup, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
edExpression.setEditable(false);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.heightHint = 50;
edExpression.setLayoutData(gdTmp);
edRuleType = new Text(propGroup, SWT.BORDER);
edRuleType.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
edRuleType.setEditable(false);
chkPreserveWS = new Button(propGroup, SWT.CHECK);
chkPreserveWS.setText(Res.getString("Editor.preserveWS")); //$NON-NLS-1$
gdTmp = new GridData();
chkPreserveWS.setLayoutData(gdTmp);
chkUseCodeFinder = new Button(propGroup, SWT.CHECK);
chkUseCodeFinder.setText(Res.getString("Editor.hasInlines")); //$NON-NLS-1$
gdTmp = new GridData();
chkUseCodeFinder.setLayoutData(gdTmp);
chkUseCodeFinder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateEditFinderRulesButton();
};
});
btEditFinderRules = new Button(propGroup, SWT.PUSH);
btEditFinderRules.setText(Res.getString("Editor.editInlines")); //$NON-NLS-1$
gdTmp = new GridData();
gdTmp.horizontalIndent = 16;
btEditFinderRules.setLayoutData(gdTmp);
btEditFinderRules.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editFinderRules();
};
});
//--- Buttons
Composite cmpButtons = new Composite(cmpTmp, SWT.NONE);
layTmp = new GridLayout(2, true);
layTmp.marginWidth = 0;
cmpButtons.setLayout(layTmp);
gdTmp = new GridData(GridData.VERTICAL_ALIGN_BEGINNING);
gdTmp.verticalSpan = 2;
cmpButtons.setLayoutData(gdTmp);
int buttonWidth = 90;
btAdd = new Button(cmpButtons, SWT.PUSH);
btAdd.setText(Res.getString("Editor.add")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
btAdd.setLayoutData(gdTmp);
UIUtil.ensureWidth(btAdd, buttonWidth);
btAdd.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editRule(true);
};
});
btEdit = new Button(cmpButtons, SWT.PUSH);
btEdit.setText(Res.getString("Editor.edit")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
btEdit.setLayoutData(gdTmp);
btEdit.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editRule(false);
};
});
btRename = new Button(cmpButtons, SWT.PUSH);
btRename.setText(Res.getString("Editor.rename")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
btRename.setLayoutData(gdTmp);
btRename.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
renameRule();
};
});
btMoveUp = new Button(cmpButtons, SWT.PUSH);
btMoveUp.setText(Res.getString("Editor.moveUp")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
btMoveUp.setLayoutData(gdTmp);
btMoveUp.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
moveUpRule();
};
});
btRemove = new Button(cmpButtons, SWT.PUSH);
btRemove.setText(Res.getString("Editor.remove")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
btRemove.setLayoutData(gdTmp);
btRemove.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
removeRule();
};
});
btMoveDown = new Button(cmpButtons, SWT.PUSH);
btMoveDown.setText(Res.getString("Editor.moveDown")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
btMoveDown.setLayoutData(gdTmp);
btMoveDown.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
moveDownRule();
};
});
//--- Options
chkOneLevelGroups = new Button(cmpTmp, SWT.CHECK);
- chkOneLevelGroups.setText("Auto-close previous group when a new one starts");
+ chkOneLevelGroups.setText(Res.getString("Editor.autoClosegroup")); //$NON-NLS-1$
Group optionsGroup = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout(2, false);
optionsGroup.setLayout(layTmp);
optionsGroup.setText(Res.getString("Editor.regexOptions")); //$NON-NLS-1$
gdTmp = new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL);
optionsGroup.setLayoutData(gdTmp);
chkDotAll = new Button(optionsGroup, SWT.CHECK);
chkDotAll.setText(Res.getString("Editor.dotMatchesLF")); //$NON-NLS-1$
chkMultiline = new Button(optionsGroup, SWT.CHECK);
chkMultiline.setText(Res.getString("Editor.multiline")); //$NON-NLS-1$
chkIgnoreCase = new Button(optionsGroup, SWT.CHECK);
chkIgnoreCase.setText(Res.getString("Editor.ignoreCases")); //$NON-NLS-1$
//--- end Options
TabItem tiTmp = new TabItem(tfTmp, SWT.NONE);
tiTmp.setText(Res.getString("Editor.rules")); //$NON-NLS-1$
tiTmp.setControl(cmpTmp);
//--- Options tab
cmpTmp = new Composite(tfTmp, SWT.NONE);
layTmp = new GridLayout();
cmpTmp.setLayout(layTmp);
// Localization directives
Group grpTmp = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout();
grpTmp.setLayout(layTmp);
grpTmp.setText(Res.getString("Editor.locDir")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
grpTmp.setLayoutData(gdTmp);
pnlLD = new LDPanel(grpTmp, SWT.NONE);
// Strings
grpTmp = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout(2, false);
grpTmp.setLayout(layTmp);
grpTmp.setText(Res.getString("Editor.strings")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
grpTmp.setLayoutData(gdTmp);
chkExtractOuterStrings = new Button(grpTmp, SWT.CHECK);
chkExtractOuterStrings.setText(Res.getString("Editor.extractStringsOutside")); //$NON-NLS-1$
gdTmp = new GridData();
gdTmp.horizontalSpan = 2;
chkExtractOuterStrings.setLayoutData(gdTmp);
//TODO: implement chkExtractOuterStrings
chkExtractOuterStrings.setEnabled(false); // NOT WORKING YET
Label label = new Label(grpTmp, SWT.NONE);
label.setText(Res.getString("Editor.startOfString")); //$NON-NLS-1$
edStartString = new Text(grpTmp, SWT.BORDER);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
edStartString.setLayoutData(gdTmp);
label = new Label(grpTmp, SWT.NONE);
label.setText(Res.getString("Editor.endOfString")); //$NON-NLS-1$
edEndString = new Text(grpTmp, SWT.BORDER);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
edEndString.setLayoutData(gdTmp);
// Content type
grpTmp = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout(2, false);
grpTmp.setLayout(layTmp);
grpTmp.setText(Res.getString("Editor.contentType")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
grpTmp.setLayoutData(gdTmp);
label = new Label(grpTmp, SWT.NONE);
label.setText(Res.getString("Editor.mimeType")); //$NON-NLS-1$
edMimeType = new Text(grpTmp, SWT.BORDER);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
edMimeType.setLayoutData(gdTmp);
tiTmp = new TabItem(tfTmp, SWT.NONE);
tiTmp.setText(Res.getString("Editor.options")); //$NON-NLS-1$
tiTmp.setControl(cmpTmp);
//--- Dialog-level buttons
SelectionAdapter okCancelActions = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if ( e.widget.getData().equals("h") ) { //$NON-NLS-1$
if ( help != null ) help.showTopic(this, "index");
return;
}
if ( e.widget.getData().equals("o") ) saveData(); //$NON-NLS-1$
shell.close();
};
};
OKCancelPanel pnlActions = new OKCancelPanel(shell, SWT.NONE, okCancelActions, true);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
pnlActions.setLayoutData(gdTmp);
pnlActions.btOK.setEnabled(!readOnly);
if ( !readOnly ) {
shell.setDefaultButton(pnlActions.btOK);
}
shell.pack();
shell.setMinimumSize(shell.getSize());
Point startSize = shell.getMinimumSize();
if ( startSize.x < 600 ) startSize.x = 600;
if ( startSize.y < 450 ) startSize.y = 450;
shell.setSize(startSize);
Dialogs.centerWindow(shell, p_Parent);
setData();
}
private boolean showDialog () {
shell.open();
while ( !shell.isDisposed() ) {
if ( !shell.getDisplay().readAndDispatch() )
shell.getDisplay().sleep();
}
return result;
}
private void updateRule () {
saveRuleData(ruleIndex);
int newRuleIndex = lbRules.getSelectionIndex();
boolean enabled = (newRuleIndex > -1 );
edRuleType.setEnabled(enabled);
chkPreserveWS.setEnabled(enabled);
chkUseCodeFinder.setEnabled(enabled);
ruleIndex = newRuleIndex;
if ( ruleIndex < 0 ) {
edExpression.setText(""); //$NON-NLS-1$
edRuleType.setText(""); //$NON-NLS-1$
chkPreserveWS.setSelection(false);
chkUseCodeFinder.setSelection(false);
btEditFinderRules.setEnabled(false);
return;
}
Rule rule = rules.get(ruleIndex);
edExpression.setText(rule.getExpression());
switch ( rule.getRuleType() ) {
case Rule.RULETYPE_STRING:
edRuleType.setText(Res.getString("Editor.extractStringsInside")); //$NON-NLS-1$
break;
case Rule.RULETYPE_CONTENT:
edRuleType.setText(Res.getString("Editor.extractContent")); //$NON-NLS-1$
break;
case Rule.RULETYPE_COMMENT:
edRuleType.setText(Res.getString("Editor.treatAsComment")); //$NON-NLS-1$
break;
case Rule.RULETYPE_NOTRANS:
edRuleType.setText(Res.getString("Editor.doNotExtract")); //$NON-NLS-1$
break;
case Rule.RULETYPE_OPENGROUP:
edRuleType.setText(Res.getString("Editor.startGroup")); //$NON-NLS-1$
break;
case Rule.RULETYPE_CLOSEGROUP:
edRuleType.setText(Res.getString("Editor.endGroup")); //$NON-NLS-1$
break;
default:
edRuleType.setText(""); //$NON-NLS-1$
}
chkPreserveWS.setSelection(rule.preserveWS());
chkUseCodeFinder.setSelection(rule.useCodeFinder());
updateEditFinderRulesButton();
}
private void updateEditFinderRulesButton () {
btEditFinderRules.setEnabled(chkUseCodeFinder.getSelection());
}
private void editFinderRules () {
try {
Rule rule = rules.get(ruleIndex);
InlineCodeFinderDialog dlg =
new InlineCodeFinderDialog(shell, Res.getString("Editor.inlinesPatterns"), null); //$NON-NLS-1$
dlg.setData(rule.getCodeFinderRules());
String tmp = dlg.showDialog();
if ( tmp == null ) return;
rule.setCodeFinderRules(tmp);
}
catch ( Throwable e ) {
Dialogs.showError(shell, e.getMessage(), null);
}
}
private void saveRuleData (int index) {
if ( index < 0 ) return;
Rule rule = rules.get(index);
rule.setPreserveWS(chkPreserveWS.getSelection());
rule.setUseCodeFinder(chkUseCodeFinder.getSelection());
}
private void updateMoveButtons () {
int n = lbRules.getSelectionIndex();
btMoveUp.setEnabled(n > 0);
btMoveDown.setEnabled((n != -1) && ( n < lbRules.getItemCount()-1 ));
}
private void updateRuleButtons () {
int n = lbRules.getSelectionIndex();
btRemove.setEnabled(n != -1);
btEdit.setEnabled(n != -1);
btRename.setEnabled(n != -1);
updateMoveButtons();
}
private void renameRule () {
try {
int n = lbRules.getSelectionIndex();
if ( n == -1 ) return;
Rule rule = rules.get(n);
String name = rule.getRuleName();
InputDialog dlg = new InputDialog(shell, Res.getString("Editor.renameRule"), //$NON-NLS-1$
Res.getString("Editor.newRuleName"), name, null, 0, -1, -1); //$NON-NLS-1$
if ( (name = dlg.showDialog()) == null ) return;
rule.setRuleName(name);
lbRules.setItem(n, name);
}
catch ( Throwable e ) {
Dialogs.showError(shell, e.getMessage(), null);
}
}
private void editRule (boolean newRule) {
try {
Rule rule;
if ( newRule ) {
// Get the name
String name = Res.getString("Editor.defaultRuleName"); //$NON-NLS-1$
InputDialog dlg = new InputDialog(shell, Res.getString("Editor.newRuleCaption"), //$NON-NLS-1$
Res.getString("Editor.newRuleLabel"), name, null, 0, -1, -1); //$NON-NLS-1$
if ( (name = dlg.showDialog()) == null ) return;
rule = new Rule();
rule.setRuleName(name);
}
else {
int n = lbRules.getSelectionIndex();
if ( n == -1 ) return;
rule = rules.get(n);
}
RuleDialog dlg = new RuleDialog(shell, help, rule, getRegexOptions());
if ( !dlg.showDialog() ) return;
rule = dlg.getRule();
if ( newRule ) {
rules.add(rule);
lbRules.add(rule.getRuleName());
lbRules.select(lbRules.getItemCount()-1);
}
}
catch ( Throwable e ) {
Dialogs.showError(shell, e.getMessage(), null);
}
finally {
updateRule();
updateRuleButtons();
}
}
private void removeRule () {
int n = lbRules.getSelectionIndex();
if ( n == -1 ) return;
ruleIndex = -1;
rules.remove(n);
lbRules.remove(n);
if ( n > lbRules.getItemCount()-1 ) n = lbRules.getItemCount()-1;
lbRules.select(n);
updateRule();
updateRuleButtons();
}
private void moveUpRule () {
int n = lbRules.getSelectionIndex();
if ( n < 1 ) return;
saveRuleData(ruleIndex);
ruleIndex = -1;
// Move in the rules array
Rule tmp = rules.get(n);
rules.set(n, rules.get(n-1));
rules.set(n-1, tmp);
// Refresh the list box
lbRules.setItem(n, rules.get(n).getRuleName());
lbRules.setItem(n-1, rules.get(n-1).getRuleName());
lbRules.select(n-1);
updateRule();
updateRuleButtons();
}
private void moveDownRule () {
int n = lbRules.getSelectionIndex();
if ( n < 0 ) return;
saveRuleData(ruleIndex);
ruleIndex = -1;
// Move in the rules array
Rule tmp = rules.get(n);
rules.set(n, rules.get(n+1));
rules.set(n+1, tmp);
// Refresh the list box
lbRules.setItem(n, rules.get(n).getRuleName());
lbRules.setItem(n+1, rules.get(n+1).getRuleName());
lbRules.select(n+1);
updateRule();
updateRuleButtons();
}
private void setData () {
pnlLD.setOptions(params.locDir.useLD(), params.locDir.localizeOutside());
chkExtractOuterStrings.setSelection(params.extractOuterStrings);
edStartString.setText(params.startString);
edEndString.setText(params.endString);
edMimeType.setText(params.mimeType);
for ( Rule rule : rules ) {
lbRules.add(rule.getRuleName());
}
chkOneLevelGroups.setSelection(params.oneLevelGroups);
int tmp = params.regexOptions;
chkDotAll.setSelection((tmp & Pattern.DOTALL)==Pattern.DOTALL);
chkIgnoreCase.setSelection((tmp & Pattern.CASE_INSENSITIVE)==Pattern.CASE_INSENSITIVE);
chkMultiline.setSelection((tmp & Pattern.MULTILINE)==Pattern.MULTILINE);
pnlLD.updateDisplay();
if ( lbRules.getItemCount() > 0 ) lbRules.select(0);
updateRule();
updateRuleButtons();
}
private void saveData () {
saveRuleData(ruleIndex);
//TODO: validation
params.locDir.setOptions(pnlLD.getUseLD(), pnlLD.getLocalizeOutside());
params.extractOuterStrings = chkExtractOuterStrings.getSelection();
params.startString = edStartString.getText();
params.endString = edEndString.getText();
params.mimeType = edMimeType.getText();
ArrayList<Rule> paramRules = params.getRules();
paramRules.clear();
for ( Rule rule : rules ) {
paramRules.add(rule);
}
params.oneLevelGroups = chkOneLevelGroups.getSelection();
params.regexOptions = getRegexOptions();
result = true;
}
private int getRegexOptions () {
int tmp = 0;
if ( chkDotAll.getSelection() ) tmp |= Pattern.DOTALL;
if ( chkIgnoreCase.getSelection() ) tmp |= Pattern.CASE_INSENSITIVE;
if ( chkMultiline.getSelection() ) tmp |= Pattern.MULTILINE;
return tmp;
}
}
| true | true |
private void create (Shell p_Parent,
boolean readOnly)
{
shell.setText(Res.getString("Editor.caption")); //$NON-NLS-1$
if ( p_Parent != null ) shell.setImage(p_Parent.getImage());
GridLayout layTmp = new GridLayout();
layTmp.marginBottom = 0;
layTmp.verticalSpacing = 0;
shell.setLayout(layTmp);
TabFolder tfTmp = new TabFolder(shell, SWT.NONE);
GridData gdTmp = new GridData(GridData.FILL_BOTH);
tfTmp.setLayoutData(gdTmp);
//--- Rules tab
Composite cmpTmp = new Composite(tfTmp, SWT.NONE);
layTmp = new GridLayout(2, false);
cmpTmp.setLayout(layTmp);
lbRules = new List(cmpTmp, SWT.BORDER | SWT.H_SCROLL);
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.horizontalSpan = 1;
gdTmp.grabExcessHorizontalSpace = true;
gdTmp.verticalSpan = 3;
lbRules.setLayoutData(gdTmp);
lbRules.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateRule();
updateMoveButtons();
};
});
lbRules.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
editRule(false);
}
public void mouseDown(MouseEvent e) {}
public void mouseUp(MouseEvent e) {}
});
//--- Rule properties
Group propGroup = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout();
propGroup.setLayout(layTmp);
propGroup.setText(Res.getString("Editor.ruleProperties")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.verticalSpan = 3;
propGroup.setLayoutData(gdTmp);
edExpression = new Text(propGroup, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
edExpression.setEditable(false);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.heightHint = 50;
edExpression.setLayoutData(gdTmp);
edRuleType = new Text(propGroup, SWT.BORDER);
edRuleType.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
edRuleType.setEditable(false);
chkPreserveWS = new Button(propGroup, SWT.CHECK);
chkPreserveWS.setText(Res.getString("Editor.preserveWS")); //$NON-NLS-1$
gdTmp = new GridData();
chkPreserveWS.setLayoutData(gdTmp);
chkUseCodeFinder = new Button(propGroup, SWT.CHECK);
chkUseCodeFinder.setText(Res.getString("Editor.hasInlines")); //$NON-NLS-1$
gdTmp = new GridData();
chkUseCodeFinder.setLayoutData(gdTmp);
chkUseCodeFinder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateEditFinderRulesButton();
};
});
btEditFinderRules = new Button(propGroup, SWT.PUSH);
btEditFinderRules.setText(Res.getString("Editor.editInlines")); //$NON-NLS-1$
gdTmp = new GridData();
gdTmp.horizontalIndent = 16;
btEditFinderRules.setLayoutData(gdTmp);
btEditFinderRules.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editFinderRules();
};
});
//--- Buttons
Composite cmpButtons = new Composite(cmpTmp, SWT.NONE);
layTmp = new GridLayout(2, true);
layTmp.marginWidth = 0;
cmpButtons.setLayout(layTmp);
gdTmp = new GridData(GridData.VERTICAL_ALIGN_BEGINNING);
gdTmp.verticalSpan = 2;
cmpButtons.setLayoutData(gdTmp);
int buttonWidth = 90;
btAdd = new Button(cmpButtons, SWT.PUSH);
btAdd.setText(Res.getString("Editor.add")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
btAdd.setLayoutData(gdTmp);
UIUtil.ensureWidth(btAdd, buttonWidth);
btAdd.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editRule(true);
};
});
btEdit = new Button(cmpButtons, SWT.PUSH);
btEdit.setText(Res.getString("Editor.edit")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
btEdit.setLayoutData(gdTmp);
btEdit.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editRule(false);
};
});
btRename = new Button(cmpButtons, SWT.PUSH);
btRename.setText(Res.getString("Editor.rename")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
btRename.setLayoutData(gdTmp);
btRename.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
renameRule();
};
});
btMoveUp = new Button(cmpButtons, SWT.PUSH);
btMoveUp.setText(Res.getString("Editor.moveUp")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
btMoveUp.setLayoutData(gdTmp);
btMoveUp.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
moveUpRule();
};
});
btRemove = new Button(cmpButtons, SWT.PUSH);
btRemove.setText(Res.getString("Editor.remove")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
btRemove.setLayoutData(gdTmp);
btRemove.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
removeRule();
};
});
btMoveDown = new Button(cmpButtons, SWT.PUSH);
btMoveDown.setText(Res.getString("Editor.moveDown")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
btMoveDown.setLayoutData(gdTmp);
btMoveDown.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
moveDownRule();
};
});
//--- Options
chkOneLevelGroups = new Button(cmpTmp, SWT.CHECK);
chkOneLevelGroups.setText("Auto-close previous group when a new one starts");
Group optionsGroup = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout(2, false);
optionsGroup.setLayout(layTmp);
optionsGroup.setText(Res.getString("Editor.regexOptions")); //$NON-NLS-1$
gdTmp = new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL);
optionsGroup.setLayoutData(gdTmp);
chkDotAll = new Button(optionsGroup, SWT.CHECK);
chkDotAll.setText(Res.getString("Editor.dotMatchesLF")); //$NON-NLS-1$
chkMultiline = new Button(optionsGroup, SWT.CHECK);
chkMultiline.setText(Res.getString("Editor.multiline")); //$NON-NLS-1$
chkIgnoreCase = new Button(optionsGroup, SWT.CHECK);
chkIgnoreCase.setText(Res.getString("Editor.ignoreCases")); //$NON-NLS-1$
//--- end Options
TabItem tiTmp = new TabItem(tfTmp, SWT.NONE);
tiTmp.setText(Res.getString("Editor.rules")); //$NON-NLS-1$
tiTmp.setControl(cmpTmp);
//--- Options tab
cmpTmp = new Composite(tfTmp, SWT.NONE);
layTmp = new GridLayout();
cmpTmp.setLayout(layTmp);
// Localization directives
Group grpTmp = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout();
grpTmp.setLayout(layTmp);
grpTmp.setText(Res.getString("Editor.locDir")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
grpTmp.setLayoutData(gdTmp);
pnlLD = new LDPanel(grpTmp, SWT.NONE);
// Strings
grpTmp = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout(2, false);
grpTmp.setLayout(layTmp);
grpTmp.setText(Res.getString("Editor.strings")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
grpTmp.setLayoutData(gdTmp);
chkExtractOuterStrings = new Button(grpTmp, SWT.CHECK);
chkExtractOuterStrings.setText(Res.getString("Editor.extractStringsOutside")); //$NON-NLS-1$
gdTmp = new GridData();
gdTmp.horizontalSpan = 2;
chkExtractOuterStrings.setLayoutData(gdTmp);
//TODO: implement chkExtractOuterStrings
chkExtractOuterStrings.setEnabled(false); // NOT WORKING YET
Label label = new Label(grpTmp, SWT.NONE);
label.setText(Res.getString("Editor.startOfString")); //$NON-NLS-1$
edStartString = new Text(grpTmp, SWT.BORDER);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
edStartString.setLayoutData(gdTmp);
label = new Label(grpTmp, SWT.NONE);
label.setText(Res.getString("Editor.endOfString")); //$NON-NLS-1$
edEndString = new Text(grpTmp, SWT.BORDER);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
edEndString.setLayoutData(gdTmp);
// Content type
grpTmp = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout(2, false);
grpTmp.setLayout(layTmp);
grpTmp.setText(Res.getString("Editor.contentType")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
grpTmp.setLayoutData(gdTmp);
label = new Label(grpTmp, SWT.NONE);
label.setText(Res.getString("Editor.mimeType")); //$NON-NLS-1$
edMimeType = new Text(grpTmp, SWT.BORDER);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
edMimeType.setLayoutData(gdTmp);
tiTmp = new TabItem(tfTmp, SWT.NONE);
tiTmp.setText(Res.getString("Editor.options")); //$NON-NLS-1$
tiTmp.setControl(cmpTmp);
//--- Dialog-level buttons
SelectionAdapter okCancelActions = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if ( e.widget.getData().equals("h") ) { //$NON-NLS-1$
if ( help != null ) help.showTopic(this, "index");
return;
}
if ( e.widget.getData().equals("o") ) saveData(); //$NON-NLS-1$
shell.close();
};
};
OKCancelPanel pnlActions = new OKCancelPanel(shell, SWT.NONE, okCancelActions, true);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
pnlActions.setLayoutData(gdTmp);
pnlActions.btOK.setEnabled(!readOnly);
if ( !readOnly ) {
shell.setDefaultButton(pnlActions.btOK);
}
shell.pack();
shell.setMinimumSize(shell.getSize());
Point startSize = shell.getMinimumSize();
if ( startSize.x < 600 ) startSize.x = 600;
if ( startSize.y < 450 ) startSize.y = 450;
shell.setSize(startSize);
Dialogs.centerWindow(shell, p_Parent);
setData();
}
|
private void create (Shell p_Parent,
boolean readOnly)
{
shell.setText(Res.getString("Editor.caption")); //$NON-NLS-1$
if ( p_Parent != null ) shell.setImage(p_Parent.getImage());
GridLayout layTmp = new GridLayout();
layTmp.marginBottom = 0;
layTmp.verticalSpacing = 0;
shell.setLayout(layTmp);
TabFolder tfTmp = new TabFolder(shell, SWT.NONE);
GridData gdTmp = new GridData(GridData.FILL_BOTH);
tfTmp.setLayoutData(gdTmp);
//--- Rules tab
Composite cmpTmp = new Composite(tfTmp, SWT.NONE);
layTmp = new GridLayout(2, false);
cmpTmp.setLayout(layTmp);
lbRules = new List(cmpTmp, SWT.BORDER | SWT.H_SCROLL);
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.horizontalSpan = 1;
gdTmp.grabExcessHorizontalSpace = true;
gdTmp.verticalSpan = 3;
lbRules.setLayoutData(gdTmp);
lbRules.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateRule();
updateMoveButtons();
};
});
lbRules.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
editRule(false);
}
public void mouseDown(MouseEvent e) {}
public void mouseUp(MouseEvent e) {}
});
//--- Rule properties
Group propGroup = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout();
propGroup.setLayout(layTmp);
propGroup.setText(Res.getString("Editor.ruleProperties")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.verticalSpan = 3;
propGroup.setLayoutData(gdTmp);
edExpression = new Text(propGroup, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
edExpression.setEditable(false);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.heightHint = 50;
edExpression.setLayoutData(gdTmp);
edRuleType = new Text(propGroup, SWT.BORDER);
edRuleType.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
edRuleType.setEditable(false);
chkPreserveWS = new Button(propGroup, SWT.CHECK);
chkPreserveWS.setText(Res.getString("Editor.preserveWS")); //$NON-NLS-1$
gdTmp = new GridData();
chkPreserveWS.setLayoutData(gdTmp);
chkUseCodeFinder = new Button(propGroup, SWT.CHECK);
chkUseCodeFinder.setText(Res.getString("Editor.hasInlines")); //$NON-NLS-1$
gdTmp = new GridData();
chkUseCodeFinder.setLayoutData(gdTmp);
chkUseCodeFinder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateEditFinderRulesButton();
};
});
btEditFinderRules = new Button(propGroup, SWT.PUSH);
btEditFinderRules.setText(Res.getString("Editor.editInlines")); //$NON-NLS-1$
gdTmp = new GridData();
gdTmp.horizontalIndent = 16;
btEditFinderRules.setLayoutData(gdTmp);
btEditFinderRules.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editFinderRules();
};
});
//--- Buttons
Composite cmpButtons = new Composite(cmpTmp, SWT.NONE);
layTmp = new GridLayout(2, true);
layTmp.marginWidth = 0;
cmpButtons.setLayout(layTmp);
gdTmp = new GridData(GridData.VERTICAL_ALIGN_BEGINNING);
gdTmp.verticalSpan = 2;
cmpButtons.setLayoutData(gdTmp);
int buttonWidth = 90;
btAdd = new Button(cmpButtons, SWT.PUSH);
btAdd.setText(Res.getString("Editor.add")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
btAdd.setLayoutData(gdTmp);
UIUtil.ensureWidth(btAdd, buttonWidth);
btAdd.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editRule(true);
};
});
btEdit = new Button(cmpButtons, SWT.PUSH);
btEdit.setText(Res.getString("Editor.edit")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
btEdit.setLayoutData(gdTmp);
btEdit.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editRule(false);
};
});
btRename = new Button(cmpButtons, SWT.PUSH);
btRename.setText(Res.getString("Editor.rename")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
btRename.setLayoutData(gdTmp);
btRename.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
renameRule();
};
});
btMoveUp = new Button(cmpButtons, SWT.PUSH);
btMoveUp.setText(Res.getString("Editor.moveUp")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
btMoveUp.setLayoutData(gdTmp);
btMoveUp.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
moveUpRule();
};
});
btRemove = new Button(cmpButtons, SWT.PUSH);
btRemove.setText(Res.getString("Editor.remove")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
btRemove.setLayoutData(gdTmp);
btRemove.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
removeRule();
};
});
btMoveDown = new Button(cmpButtons, SWT.PUSH);
btMoveDown.setText(Res.getString("Editor.moveDown")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
btMoveDown.setLayoutData(gdTmp);
btMoveDown.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
moveDownRule();
};
});
//--- Options
chkOneLevelGroups = new Button(cmpTmp, SWT.CHECK);
chkOneLevelGroups.setText(Res.getString("Editor.autoClosegroup")); //$NON-NLS-1$
Group optionsGroup = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout(2, false);
optionsGroup.setLayout(layTmp);
optionsGroup.setText(Res.getString("Editor.regexOptions")); //$NON-NLS-1$
gdTmp = new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL);
optionsGroup.setLayoutData(gdTmp);
chkDotAll = new Button(optionsGroup, SWT.CHECK);
chkDotAll.setText(Res.getString("Editor.dotMatchesLF")); //$NON-NLS-1$
chkMultiline = new Button(optionsGroup, SWT.CHECK);
chkMultiline.setText(Res.getString("Editor.multiline")); //$NON-NLS-1$
chkIgnoreCase = new Button(optionsGroup, SWT.CHECK);
chkIgnoreCase.setText(Res.getString("Editor.ignoreCases")); //$NON-NLS-1$
//--- end Options
TabItem tiTmp = new TabItem(tfTmp, SWT.NONE);
tiTmp.setText(Res.getString("Editor.rules")); //$NON-NLS-1$
tiTmp.setControl(cmpTmp);
//--- Options tab
cmpTmp = new Composite(tfTmp, SWT.NONE);
layTmp = new GridLayout();
cmpTmp.setLayout(layTmp);
// Localization directives
Group grpTmp = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout();
grpTmp.setLayout(layTmp);
grpTmp.setText(Res.getString("Editor.locDir")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
grpTmp.setLayoutData(gdTmp);
pnlLD = new LDPanel(grpTmp, SWT.NONE);
// Strings
grpTmp = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout(2, false);
grpTmp.setLayout(layTmp);
grpTmp.setText(Res.getString("Editor.strings")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
grpTmp.setLayoutData(gdTmp);
chkExtractOuterStrings = new Button(grpTmp, SWT.CHECK);
chkExtractOuterStrings.setText(Res.getString("Editor.extractStringsOutside")); //$NON-NLS-1$
gdTmp = new GridData();
gdTmp.horizontalSpan = 2;
chkExtractOuterStrings.setLayoutData(gdTmp);
//TODO: implement chkExtractOuterStrings
chkExtractOuterStrings.setEnabled(false); // NOT WORKING YET
Label label = new Label(grpTmp, SWT.NONE);
label.setText(Res.getString("Editor.startOfString")); //$NON-NLS-1$
edStartString = new Text(grpTmp, SWT.BORDER);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
edStartString.setLayoutData(gdTmp);
label = new Label(grpTmp, SWT.NONE);
label.setText(Res.getString("Editor.endOfString")); //$NON-NLS-1$
edEndString = new Text(grpTmp, SWT.BORDER);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
edEndString.setLayoutData(gdTmp);
// Content type
grpTmp = new Group(cmpTmp, SWT.NONE);
layTmp = new GridLayout(2, false);
grpTmp.setLayout(layTmp);
grpTmp.setText(Res.getString("Editor.contentType")); //$NON-NLS-1$
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
grpTmp.setLayoutData(gdTmp);
label = new Label(grpTmp, SWT.NONE);
label.setText(Res.getString("Editor.mimeType")); //$NON-NLS-1$
edMimeType = new Text(grpTmp, SWT.BORDER);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
edMimeType.setLayoutData(gdTmp);
tiTmp = new TabItem(tfTmp, SWT.NONE);
tiTmp.setText(Res.getString("Editor.options")); //$NON-NLS-1$
tiTmp.setControl(cmpTmp);
//--- Dialog-level buttons
SelectionAdapter okCancelActions = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if ( e.widget.getData().equals("h") ) { //$NON-NLS-1$
if ( help != null ) help.showTopic(this, "index");
return;
}
if ( e.widget.getData().equals("o") ) saveData(); //$NON-NLS-1$
shell.close();
};
};
OKCancelPanel pnlActions = new OKCancelPanel(shell, SWT.NONE, okCancelActions, true);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
pnlActions.setLayoutData(gdTmp);
pnlActions.btOK.setEnabled(!readOnly);
if ( !readOnly ) {
shell.setDefaultButton(pnlActions.btOK);
}
shell.pack();
shell.setMinimumSize(shell.getSize());
Point startSize = shell.getMinimumSize();
if ( startSize.x < 600 ) startSize.x = 600;
if ( startSize.y < 450 ) startSize.y = 450;
shell.setSize(startSize);
Dialogs.centerWindow(shell, p_Parent);
setData();
}
|
diff --git a/src/tests/ControllerTest.java b/src/tests/ControllerTest.java
index 458273c..e2f3333 100644
--- a/src/tests/ControllerTest.java
+++ b/src/tests/ControllerTest.java
@@ -1,20 +1,20 @@
package tests;
import junit.framework.TestCase;
import com.example.controller.Controller;
import com.example.controller.TouchController;
import com.example.model.Position;
import com.example.starter.SurfaceViewActivity;
public class ControllerTest extends TestCase {
public void testReturnCoord() throws Throwable {
- Position aPos = new Position(3, 'b');
+ Position aPos = new Position(4, 'b');
Controller aCont = new TouchController();
System.out.println(aCont);
assertEquals(aPos, ((TouchController) aCont).returnCoord(33, 20));
}
}
| true | true |
public void testReturnCoord() throws Throwable {
Position aPos = new Position(3, 'b');
Controller aCont = new TouchController();
System.out.println(aCont);
assertEquals(aPos, ((TouchController) aCont).returnCoord(33, 20));
}
|
public void testReturnCoord() throws Throwable {
Position aPos = new Position(4, 'b');
Controller aCont = new TouchController();
System.out.println(aCont);
assertEquals(aPos, ((TouchController) aCont).returnCoord(33, 20));
}
|
diff --git a/services-hz/src/main/java/ru/taskurotta/service/hz/recovery/HzRecoveryProcessCoordinator.java b/services-hz/src/main/java/ru/taskurotta/service/hz/recovery/HzRecoveryProcessCoordinator.java
index 4867502a..78bc92e2 100644
--- a/services-hz/src/main/java/ru/taskurotta/service/hz/recovery/HzRecoveryProcessCoordinator.java
+++ b/services-hz/src/main/java/ru/taskurotta/service/hz/recovery/HzRecoveryProcessCoordinator.java
@@ -1,74 +1,75 @@
package ru.taskurotta.service.hz.recovery;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.Partition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.taskurotta.service.recovery.IncompleteProcessFinder;
import ru.taskurotta.service.recovery.RecoveryProcessService;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* User: stukushin
* Date: 18.12.13
* Time: 16:09
*/
public class HzRecoveryProcessCoordinator {
private static final Logger logger = LoggerFactory.getLogger(HzRecoveryProcessCoordinator.class);
private BlockingQueue<UUID> uuidQueue = new LinkedBlockingQueue<>();
public HzRecoveryProcessCoordinator(final HazelcastInstance hazelcastInstance, final IncompleteProcessFinder incompleteProcessFinder,
final RecoveryProcessService recoveryProcessService, final long incompleteTimeOutMillis,
+ final int incompleteProcessBatchSize,
long findIncompleteProcessPeriod, int recoveryTaskPoolSize) {
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
- Collection<UUID> incompleteProcessIds = incompleteProcessFinder.find(incompleteTimeOutMillis);
+ Collection<UUID> incompleteProcessIds = incompleteProcessFinder.find(incompleteTimeOutMillis, incompleteProcessBatchSize);
if (incompleteProcessIds == null || incompleteProcessIds.isEmpty()) {
return;
}
for (UUID uuid : incompleteProcessIds) {
if (isLocalItem(uuid)) {
uuidQueue.add(uuid);
}
}
}
private boolean isLocalItem(UUID id) {
Partition partition = hazelcastInstance.getPartitionService().getPartition(id);
return partition.getOwner().localMember();
}
}, 0l, findIncompleteProcessPeriod, TimeUnit.MILLISECONDS);
ExecutorService executorService = Executors.newFixedThreadPool(recoveryTaskPoolSize);
for (int i = 0; i < recoveryTaskPoolSize; i++) {
executorService.submit(new Runnable() {
@Override
public void run() {
while (true) {
try {
UUID processId = uuidQueue.take();
recoveryProcessService.restartProcess(processId);
} catch (InterruptedException e) {
logger.error("Catch exception while get processId for start recovery", e);
}
}
}
});
}
}
}
| false | true |
public HzRecoveryProcessCoordinator(final HazelcastInstance hazelcastInstance, final IncompleteProcessFinder incompleteProcessFinder,
final RecoveryProcessService recoveryProcessService, final long incompleteTimeOutMillis,
long findIncompleteProcessPeriod, int recoveryTaskPoolSize) {
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
Collection<UUID> incompleteProcessIds = incompleteProcessFinder.find(incompleteTimeOutMillis);
if (incompleteProcessIds == null || incompleteProcessIds.isEmpty()) {
return;
}
for (UUID uuid : incompleteProcessIds) {
if (isLocalItem(uuid)) {
uuidQueue.add(uuid);
}
}
}
private boolean isLocalItem(UUID id) {
Partition partition = hazelcastInstance.getPartitionService().getPartition(id);
return partition.getOwner().localMember();
}
}, 0l, findIncompleteProcessPeriod, TimeUnit.MILLISECONDS);
ExecutorService executorService = Executors.newFixedThreadPool(recoveryTaskPoolSize);
for (int i = 0; i < recoveryTaskPoolSize; i++) {
executorService.submit(new Runnable() {
@Override
public void run() {
while (true) {
try {
UUID processId = uuidQueue.take();
recoveryProcessService.restartProcess(processId);
} catch (InterruptedException e) {
logger.error("Catch exception while get processId for start recovery", e);
}
}
}
});
}
}
|
public HzRecoveryProcessCoordinator(final HazelcastInstance hazelcastInstance, final IncompleteProcessFinder incompleteProcessFinder,
final RecoveryProcessService recoveryProcessService, final long incompleteTimeOutMillis,
final int incompleteProcessBatchSize,
long findIncompleteProcessPeriod, int recoveryTaskPoolSize) {
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
Collection<UUID> incompleteProcessIds = incompleteProcessFinder.find(incompleteTimeOutMillis, incompleteProcessBatchSize);
if (incompleteProcessIds == null || incompleteProcessIds.isEmpty()) {
return;
}
for (UUID uuid : incompleteProcessIds) {
if (isLocalItem(uuid)) {
uuidQueue.add(uuid);
}
}
}
private boolean isLocalItem(UUID id) {
Partition partition = hazelcastInstance.getPartitionService().getPartition(id);
return partition.getOwner().localMember();
}
}, 0l, findIncompleteProcessPeriod, TimeUnit.MILLISECONDS);
ExecutorService executorService = Executors.newFixedThreadPool(recoveryTaskPoolSize);
for (int i = 0; i < recoveryTaskPoolSize; i++) {
executorService.submit(new Runnable() {
@Override
public void run() {
while (true) {
try {
UUID processId = uuidQueue.take();
recoveryProcessService.restartProcess(processId);
} catch (InterruptedException e) {
logger.error("Catch exception while get processId for start recovery", e);
}
}
}
});
}
}
|
diff --git a/src/be/ibridge/kettle/trans/step/exceloutput/ExcelOutput.java b/src/be/ibridge/kettle/trans/step/exceloutput/ExcelOutput.java
index 0403a8a0..bd3f8337 100644
--- a/src/be/ibridge/kettle/trans/step/exceloutput/ExcelOutput.java
+++ b/src/be/ibridge/kettle/trans/step/exceloutput/ExcelOutput.java
@@ -1,497 +1,498 @@
/**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.trans.step.exceloutput;
import java.io.File;
import java.util.Locale;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.biff.EmptyCell;
import jxl.write.DateFormat;
import jxl.write.DateFormats;
import jxl.write.DateTime;
import jxl.write.Label;
import jxl.write.NumberFormat;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.ResultFile;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStep;
import be.ibridge.kettle.trans.step.StepDataInterface;
import be.ibridge.kettle.trans.step.StepInterface;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
/**
* Converts input rows to excel cells and then writes this information to one or more files.
*
* @author Matt
* @since 7-sep-2006
*/
public class ExcelOutput extends BaseStep implements StepInterface
{
private ExcelOutputMeta meta;
private ExcelOutputData data;
public ExcelOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(ExcelOutputMeta)smi;
data=(ExcelOutputData)sdi;
Row r;
boolean result=true;
r=getRow(); // This also waits for a row to be finished.
if ( ( r==null && data.headerrow!=null && meta.isFooterEnabled() ) ||
( r!=null && linesOutput>0 && meta.getSplitEvery()>0 && ((linesOutput+1)%meta.getSplitEvery())==0)
)
{
if (data.headerrow!=null)
{
if ( meta.isFooterEnabled() )
{
writeHeader();
}
}
// Done with this part or with everything.
closeFile();
// Not finished: open another file...
if (r!=null)
{
if (!openNewFile())
{
logError("Unable to open new file (split #"+data.splitnr+"...");
setErrors(1);
return false;
}
if (meta.isHeaderEnabled() && data.headerrow!=null) if (writeHeader()) linesOutput++;
}
}
if (r==null) // no more input to be expected...
{
setOutputDone();
return false;
}
result=writeRowToFile(r);
if (!result)
{
setErrors(1);
stopAll();
return false;
}
putRow(r); // in case we want it to go further...
if ((linesOutput>0) && (linesOutput%Const.ROWS_UPDATE)==0)logBasic("linenr "+linesOutput);
return result;
}
private boolean writeRowToFile(Row r)
{
Value v;
try
{
if (first)
{
first=false;
if ( meta.isHeaderEnabled() || meta.isFooterEnabled()) // See if we have to write a header-line)
{
data.headerrow=new Row(r); // copy the row for the footer!
if (meta.isHeaderEnabled() && data.headerrow!=null)
{
if (writeHeader() )
{
return false;
}
}
}
data.fieldnrs=new int[meta.getOutputFields().length];
for (int i=0;i<meta.getOutputFields().length;i++)
{
data.fieldnrs[i]=r.searchValueIndex(meta.getOutputFields()[i].getName());
if (data.fieldnrs[i]<0)
{
logError("Field ["+meta.getOutputFields()[i].getName()+"] couldn't be found in the input stream!");
setErrors(1);
stopAll();
return false;
}
}
}
if (meta.getOutputFields()==null || meta.getOutputFields().length==0)
{
/*
* Write all values in stream to text file.
*/
for (int i=0;i<r.size();i++)
{
v=r.getValue(i);
if(!writeField(v, null)) return false;
}
// go to the next line
data.positionX = 0;
data.positionY++;
}
else
{
/*
* Only write the fields specified!
*/
for (int i=0;i<meta.getOutputFields().length;i++)
{
v=r.getValue(data.fieldnrs[i]);
if(!writeField(v, meta.getOutputFields()[i])) return false;
}
// go to the next line
data.positionX = 0;
data.positionY++;
}
}
catch(Exception e)
{
logError("Error writing line :"+e.toString());
return false;
}
linesOutput++;
return true;
}
/**
* Write a value to Excel, increasing data.positionX with one afterwards.
* @param v The value to write
* @param excelField the field information (if any, otherwise : null)
* @param isHeader true if this is part of the header/footer
* @return
*/
private boolean writeField(Value v, ExcelField excelField)
{
return writeField(v, excelField, false);
}
/**
* Write a value to Excel, increasing data.positionX with one afterwards.
* @param v The value to write
* @param excelField the field information (if any, otherwise : null)
* @param isHeader true if this is part of the header/footer
* @return
*/
private boolean writeField(Value v, ExcelField excelField, boolean isHeader)
{
try
{
String hashName = v.getName();
if (isHeader) hashName = "____header_field____"; // all strings, can map to the same format.
WritableCellFormat cellFormat=(WritableCellFormat) data.formats.get(hashName);
switch(v.getType())
{
case Value.VALUE_TYPE_DATE:
{
if (!v.isNull() && v.getDate()!=null)
{
if (cellFormat==null)
{
if (excelField!=null && excelField.getFormat()!=null)
{
DateFormat dateFormat = new DateFormat(excelField.getFormat());
cellFormat=new WritableCellFormat(dateFormat);
}
else
{
cellFormat = new WritableCellFormat(DateFormats.FORMAT9);
}
data.formats.put(hashName, cellFormat); // save for next time around...
}
DateTime dateTime = new DateTime(data.positionX, data.positionY, v.getDate(), cellFormat);
data.sheet.addCell(dateTime);
}
else
{
data.sheet.addCell(new EmptyCell(data.positionX, data.positionY));
}
}
break;
case Value.VALUE_TYPE_STRING:
case Value.VALUE_TYPE_BOOLEAN:
case Value.VALUE_TYPE_BINARY:
{
if (!v.isNull())
{
if (cellFormat==null)
{
cellFormat = new WritableCellFormat(data.writableFont);
data.formats.put(hashName, cellFormat);
}
Label label = new Label(data.positionX, data.positionY, v.getString(), cellFormat);
data.sheet.addCell(label);
}
else
{
data.sheet.addCell(new EmptyCell(data.positionX, data.positionY));
}
}
break;
case Value.VALUE_TYPE_NUMBER:
case Value.VALUE_TYPE_BIGNUMBER:
case Value.VALUE_TYPE_INTEGER:
{
if (cellFormat==null)
{
String format;
if (excelField!=null && excelField.getFormat()!=null)
{
format=excelField.getFormat();
}
else
{
format = "###,###.00";
}
NumberFormat numberFormat = new NumberFormat(format);
cellFormat = new WritableCellFormat(numberFormat);
data.formats.put(v.getName(), cellFormat); // save for next time around...
}
jxl.write.Number number = new jxl.write.Number(data.positionX, data.positionY, v.getNumber(), cellFormat);
data.sheet.addCell(number);
}
break;
default: break;
}
}
catch(Exception e)
{
logError("Error writing field ("+data.positionX+","+data.positionY+") : "+e.toString());
+ logError(Const.getStackTracker(e));
return false;
}
finally
{
data.positionX++; // always advance :-)
}
return true;
}
private boolean writeHeader()
{
boolean retval=false;
Row r=data.headerrow;
try
{
// If we have fields specified: list them in this order!
if (meta.getOutputFields()!=null && meta.getOutputFields().length>0)
{
for (int i=0;i<meta.getOutputFields().length;i++)
{
String fieldName = meta.getOutputFields()[i].getName();
Value headerValue = new Value(fieldName, fieldName);
writeField(headerValue, null, true);
}
}
else
if (r!=null) // Just put all field names in the header/footer
{
for (int i=0;i<r.size();i++)
{
String fieldName = r.getValue(i).getName();
Value headerValue = new Value(fieldName, fieldName);
writeField(headerValue, null, true);
}
}
}
catch(Exception e)
{
logError("Error writing header line: "+e.toString());
logError(Const.getStackTracker(e));
retval=true;
}
finally
{
data.positionX=0;
data.positionY++;
}
linesOutput++;
return retval;
}
public String buildFilename()
{
return meta.buildFilename(getCopy(), data.splitnr);
}
public boolean openNewFile()
{
boolean retval=false;
try
{
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(Locale.getDefault());
if (!Const.isEmpty(meta.getEncoding()))
{
ws.setEncoding(meta.getEncoding());
}
File file = new File(buildFilename());
// Add this to the result file names...
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, file, getTransMeta().getName(), getStepname());
resultFile.setComment("This file was created with a text file output step");
addResultFile(resultFile);
// Create the workboook
data.workbook = Workbook.createWorkbook(file, ws);
// Create a sheet?
data.sheet = data.workbook.createSheet("Sheet1", 0);
data.sheet.setName("Sheet1");
// Set the initial position...
data.positionX = 0;
data.positionY = 0;
retval=true;
}
catch(Exception e)
{
logError("Error opening new file : "+e.toString());
}
// System.out.println("end of newFile(), splitnr="+splitnr);
data.splitnr++;
return retval;
}
private boolean closeFile()
{
boolean retval=false;
try
{
data.workbook.write();
data.workbook.close();
data.formats.clear();
retval=true;
}
catch(Exception e)
{
logError("Unable to close workbook file : "+e.toString());
}
return retval;
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(ExcelOutputMeta)smi;
data=(ExcelOutputData)sdi;
if (super.init(smi, sdi))
{
data.splitnr=0;
try
{
// Create the default font TODO: allow to change this later on.
data.writableFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD);
}
catch(Exception we)
{
logError("Unexpected error preparing to write to Excel file : "+we.toString());
logError(Const.getStackTracker(we));
return false;
}
if (openNewFile())
{
return true;
}
else
{
logError("Couldn't open file "+meta.getFileName());
setErrors(1L);
stopAll();
}
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(ExcelOutputMeta)smi;
data=(ExcelOutputData)sdi;
super.dispose(smi, sdi);
closeFile();
}
//
// Run is were the action happens!
public void run()
{
try
{
logBasic("Starting to run...");
while (processRow(meta, data) && !isStopped());
}
catch(Exception e)
{
logError("Unexpected error : "+e.toString());
logError(Const.getStackTracker(e));
setErrors(1);
stopAll();
}
finally
{
dispose(meta, data);
logSummary();
markStop();
}
}
}
| true | true |
private boolean writeField(Value v, ExcelField excelField, boolean isHeader)
{
try
{
String hashName = v.getName();
if (isHeader) hashName = "____header_field____"; // all strings, can map to the same format.
WritableCellFormat cellFormat=(WritableCellFormat) data.formats.get(hashName);
switch(v.getType())
{
case Value.VALUE_TYPE_DATE:
{
if (!v.isNull() && v.getDate()!=null)
{
if (cellFormat==null)
{
if (excelField!=null && excelField.getFormat()!=null)
{
DateFormat dateFormat = new DateFormat(excelField.getFormat());
cellFormat=new WritableCellFormat(dateFormat);
}
else
{
cellFormat = new WritableCellFormat(DateFormats.FORMAT9);
}
data.formats.put(hashName, cellFormat); // save for next time around...
}
DateTime dateTime = new DateTime(data.positionX, data.positionY, v.getDate(), cellFormat);
data.sheet.addCell(dateTime);
}
else
{
data.sheet.addCell(new EmptyCell(data.positionX, data.positionY));
}
}
break;
case Value.VALUE_TYPE_STRING:
case Value.VALUE_TYPE_BOOLEAN:
case Value.VALUE_TYPE_BINARY:
{
if (!v.isNull())
{
if (cellFormat==null)
{
cellFormat = new WritableCellFormat(data.writableFont);
data.formats.put(hashName, cellFormat);
}
Label label = new Label(data.positionX, data.positionY, v.getString(), cellFormat);
data.sheet.addCell(label);
}
else
{
data.sheet.addCell(new EmptyCell(data.positionX, data.positionY));
}
}
break;
case Value.VALUE_TYPE_NUMBER:
case Value.VALUE_TYPE_BIGNUMBER:
case Value.VALUE_TYPE_INTEGER:
{
if (cellFormat==null)
{
String format;
if (excelField!=null && excelField.getFormat()!=null)
{
format=excelField.getFormat();
}
else
{
format = "###,###.00";
}
NumberFormat numberFormat = new NumberFormat(format);
cellFormat = new WritableCellFormat(numberFormat);
data.formats.put(v.getName(), cellFormat); // save for next time around...
}
jxl.write.Number number = new jxl.write.Number(data.positionX, data.positionY, v.getNumber(), cellFormat);
data.sheet.addCell(number);
}
break;
default: break;
}
}
catch(Exception e)
{
logError("Error writing field ("+data.positionX+","+data.positionY+") : "+e.toString());
return false;
}
finally
{
data.positionX++; // always advance :-)
}
return true;
}
|
private boolean writeField(Value v, ExcelField excelField, boolean isHeader)
{
try
{
String hashName = v.getName();
if (isHeader) hashName = "____header_field____"; // all strings, can map to the same format.
WritableCellFormat cellFormat=(WritableCellFormat) data.formats.get(hashName);
switch(v.getType())
{
case Value.VALUE_TYPE_DATE:
{
if (!v.isNull() && v.getDate()!=null)
{
if (cellFormat==null)
{
if (excelField!=null && excelField.getFormat()!=null)
{
DateFormat dateFormat = new DateFormat(excelField.getFormat());
cellFormat=new WritableCellFormat(dateFormat);
}
else
{
cellFormat = new WritableCellFormat(DateFormats.FORMAT9);
}
data.formats.put(hashName, cellFormat); // save for next time around...
}
DateTime dateTime = new DateTime(data.positionX, data.positionY, v.getDate(), cellFormat);
data.sheet.addCell(dateTime);
}
else
{
data.sheet.addCell(new EmptyCell(data.positionX, data.positionY));
}
}
break;
case Value.VALUE_TYPE_STRING:
case Value.VALUE_TYPE_BOOLEAN:
case Value.VALUE_TYPE_BINARY:
{
if (!v.isNull())
{
if (cellFormat==null)
{
cellFormat = new WritableCellFormat(data.writableFont);
data.formats.put(hashName, cellFormat);
}
Label label = new Label(data.positionX, data.positionY, v.getString(), cellFormat);
data.sheet.addCell(label);
}
else
{
data.sheet.addCell(new EmptyCell(data.positionX, data.positionY));
}
}
break;
case Value.VALUE_TYPE_NUMBER:
case Value.VALUE_TYPE_BIGNUMBER:
case Value.VALUE_TYPE_INTEGER:
{
if (cellFormat==null)
{
String format;
if (excelField!=null && excelField.getFormat()!=null)
{
format=excelField.getFormat();
}
else
{
format = "###,###.00";
}
NumberFormat numberFormat = new NumberFormat(format);
cellFormat = new WritableCellFormat(numberFormat);
data.formats.put(v.getName(), cellFormat); // save for next time around...
}
jxl.write.Number number = new jxl.write.Number(data.positionX, data.positionY, v.getNumber(), cellFormat);
data.sheet.addCell(number);
}
break;
default: break;
}
}
catch(Exception e)
{
logError("Error writing field ("+data.positionX+","+data.positionY+") : "+e.toString());
logError(Const.getStackTracker(e));
return false;
}
finally
{
data.positionX++; // always advance :-)
}
return true;
}
|
diff --git a/src/org/eclipse/jface/resource/CompositeImageDescriptor.java b/src/org/eclipse/jface/resource/CompositeImageDescriptor.java
index ca5e9761..008514cd 100644
--- a/src/org/eclipse/jface/resource/CompositeImageDescriptor.java
+++ b/src/org/eclipse/jface/resource/CompositeImageDescriptor.java
@@ -1,202 +1,210 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 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.jface.resource;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
/**
* Abstract base class for image descriptors that synthesize an image from other
* images in order to simulate the effect of custom drawing. For example, this
* could be used to superimpose a red bar dexter symbol across an image to
* indicate that something was disallowed.
* <p>
* Subclasses must implement the <code>getSize</code> and <code>fill</code>
* methods. Little or no work happens until the image descriptor's image is
* actually requested by a call to <code>createImage</code> (or to
* <code>getImageData</code> directly).
* </p>
*/
public abstract class CompositeImageDescriptor extends ImageDescriptor {
/**
* The image data for this composite image.
*/
private ImageData imageData;
/**
* Constructs an uninitialized composite image.
*/
protected CompositeImageDescriptor() {
}
/**
* Draw the composite images.
* <p>
* Subclasses must implement this framework method to paint images within
* the given bounds using one or more calls to the <code>drawImage</code>
* framework method.
* </p>
*
* @param width
* the width
* @param height
* the height
*/
protected abstract void drawCompositeImage(int width, int height);
/**
* Draws the given source image data into this composite image at the given
* position.
* <p>
* Call this internal framework method to superimpose another image atop
* this composite image.
* </p>
*
* @param src
* the source image data
* @param ox
* the x position
* @param oy
* the y position
*/
final protected void drawImage(ImageData src, int ox, int oy) {
ImageData dst = imageData;
PaletteData srcPalette = src.palette;
- ImageData srcMask = src.maskData != null ? src.getTransparencyMask() : null;
+ ImageData srcMask = null;
+ int alphaMask = 0, alphaShift = 0;
+ if (src.maskData != null) {
+ srcMask = src.getTransparencyMask ();
+ if (src.depth == 32) {
+ alphaMask = ~(srcPalette.redMask | srcPalette.greenMask | srcPalette.blueMask);
+ while (alphaMask != 0 && ((alphaMask >>> alphaShift) & 1) == 0) alphaShift++;
+ }
+ }
for (int srcY = 0, dstY = srcY + oy; srcY < src.height; srcY++, dstY++) {
for (int srcX = 0, dstX = srcX + ox; srcX < src.width; srcX++, dstX++) {
if (!(0 <= dstX && dstX < dst.width && 0 <= dstY && dstY < dst.height)) continue;
int srcPixel = src.getPixel(srcX, srcY);
int srcAlpha = 255;
if (src.maskData != null) {
if (src.depth == 32) {
- srcAlpha = srcPixel & 0xFF;
+ srcAlpha = (srcPixel & alphaMask) >>> alphaShift;
if (srcAlpha == 0) {
srcAlpha = srcMask.getPixel(srcX, srcY) != 0 ? 255 : 0;
}
} else {
if (srcMask.getPixel(srcX, srcY) == 0) srcAlpha = 0;
}
} else if (src.transparentPixel != -1) {
if (src.transparentPixel == srcPixel) srcAlpha = 0;
} else if (src.alpha != -1) {
srcAlpha = src.alpha;
} else if (src.alphaData != null) {
srcAlpha = src.getAlpha(srcX, srcY);
}
if (srcAlpha == 0) continue;
int srcRed, srcGreen, srcBlue;
if (srcPalette.isDirect) {
srcRed = srcPixel & srcPalette.redMask;
srcRed = (srcPalette.redShift < 0) ? srcRed >>> -srcPalette.redShift : srcRed << srcPalette.redShift;
srcGreen = srcPixel & srcPalette.greenMask;
srcGreen = (srcPalette.greenShift < 0) ? srcGreen >>> -srcPalette.greenShift : srcGreen << srcPalette.greenShift;
srcBlue = srcPixel & srcPalette.blueMask;
srcBlue = (srcPalette.blueShift < 0) ? srcBlue >>> -srcPalette.blueShift : srcBlue << srcPalette.blueShift;
} else {
RGB rgb = srcPalette.getRGB(srcPixel);
srcRed = rgb.red;
srcGreen = rgb.green;
srcBlue = rgb.blue;
}
int dstRed, dstGreen, dstBlue, dstAlpha;
if (srcAlpha == 255) {
dstRed = srcRed;
dstGreen = srcGreen;
dstBlue= srcBlue;
dstAlpha = srcAlpha;
} else {
int dstPixel = dst.getPixel(dstX, dstY);
dstAlpha = dst.getAlpha(dstX, dstY);
dstRed = (dstPixel & 0xFF) >>> 0;
dstGreen = (dstPixel & 0xFF00) >>> 8;
dstBlue = (dstPixel & 0xFF0000) >>> 16;
dstRed += (srcRed - dstRed) * srcAlpha / 255;
dstGreen += (srcGreen - dstGreen) * srcAlpha / 255;
dstBlue += (srcBlue - dstBlue) * srcAlpha / 255;
dstAlpha += (srcAlpha - dstAlpha) * srcAlpha / 255;
}
dst.setPixel(dstX, dstY, ((dstRed & 0xFF) << 0) | ((dstGreen & 0xFF) << 8) | ((dstBlue & 0xFF) << 16));
dst.setAlpha(dstX, dstY, dstAlpha);
}
}
}
/*
* (non-Javadoc) Method declared on ImageDesciptor.
*/
public ImageData getImageData() {
Point size = getSize();
/* Create a 24 bit image data with alpha channel */
imageData = new ImageData(size.x, size.y, 24, new PaletteData(0xFF, 0xFF00, 0xFF0000));
imageData.alphaData = new byte[imageData.width * imageData.height];
drawCompositeImage(size.x, size.y);
/* Detect minimum transparency */
boolean transparency = false;
byte[] alphaData = imageData.alphaData;
for (int i = 0; i < alphaData.length; i++) {
int alpha = alphaData[i] & 0xFF;
if (!(alpha == 0 || alpha == 255)) {
/* Full alpha channel transparency */
return imageData;
}
if (!transparency && alpha == 0) transparency = true;
}
if (transparency) {
/* Reduce to 1-bit alpha channel transparency */
PaletteData palette = new PaletteData(new RGB[]{new RGB(0, 0, 0), new RGB(255, 255, 255)});
ImageData mask = new ImageData(imageData.width, imageData.height, 1, palette);
for (int y = 0; y < mask.height; y++) {
for (int x = 0; x < mask.width; x++) {
mask.setPixel(x, y, imageData.getAlpha(x, y) == 255 ? 1 : 0);
}
}
} else {
/* no transparency */
imageData.alphaData = null;
}
return imageData;
}
/**
* Return the transparent pixel for the receiver.
* <strong>NOTE</strong> This value is not currently in use in the
* default implementation.
* @return int
*/
protected int getTransparentPixel() {
return 0;
}
/**
* Return the size of this composite image.
* <p>
* Subclasses must implement this framework method.
* </p>
*
* @return the x and y size of the image expressed as a point object
*/
protected abstract Point getSize();
/**
* @param imageData The imageData to set.
*/
protected void setImageData(ImageData imageData) {
this.imageData = imageData;
}
}
| false | true |
final protected void drawImage(ImageData src, int ox, int oy) {
ImageData dst = imageData;
PaletteData srcPalette = src.palette;
ImageData srcMask = src.maskData != null ? src.getTransparencyMask() : null;
for (int srcY = 0, dstY = srcY + oy; srcY < src.height; srcY++, dstY++) {
for (int srcX = 0, dstX = srcX + ox; srcX < src.width; srcX++, dstX++) {
if (!(0 <= dstX && dstX < dst.width && 0 <= dstY && dstY < dst.height)) continue;
int srcPixel = src.getPixel(srcX, srcY);
int srcAlpha = 255;
if (src.maskData != null) {
if (src.depth == 32) {
srcAlpha = srcPixel & 0xFF;
if (srcAlpha == 0) {
srcAlpha = srcMask.getPixel(srcX, srcY) != 0 ? 255 : 0;
}
} else {
if (srcMask.getPixel(srcX, srcY) == 0) srcAlpha = 0;
}
} else if (src.transparentPixel != -1) {
if (src.transparentPixel == srcPixel) srcAlpha = 0;
} else if (src.alpha != -1) {
srcAlpha = src.alpha;
} else if (src.alphaData != null) {
srcAlpha = src.getAlpha(srcX, srcY);
}
if (srcAlpha == 0) continue;
int srcRed, srcGreen, srcBlue;
if (srcPalette.isDirect) {
srcRed = srcPixel & srcPalette.redMask;
srcRed = (srcPalette.redShift < 0) ? srcRed >>> -srcPalette.redShift : srcRed << srcPalette.redShift;
srcGreen = srcPixel & srcPalette.greenMask;
srcGreen = (srcPalette.greenShift < 0) ? srcGreen >>> -srcPalette.greenShift : srcGreen << srcPalette.greenShift;
srcBlue = srcPixel & srcPalette.blueMask;
srcBlue = (srcPalette.blueShift < 0) ? srcBlue >>> -srcPalette.blueShift : srcBlue << srcPalette.blueShift;
} else {
RGB rgb = srcPalette.getRGB(srcPixel);
srcRed = rgb.red;
srcGreen = rgb.green;
srcBlue = rgb.blue;
}
int dstRed, dstGreen, dstBlue, dstAlpha;
if (srcAlpha == 255) {
dstRed = srcRed;
dstGreen = srcGreen;
dstBlue= srcBlue;
dstAlpha = srcAlpha;
} else {
int dstPixel = dst.getPixel(dstX, dstY);
dstAlpha = dst.getAlpha(dstX, dstY);
dstRed = (dstPixel & 0xFF) >>> 0;
dstGreen = (dstPixel & 0xFF00) >>> 8;
dstBlue = (dstPixel & 0xFF0000) >>> 16;
dstRed += (srcRed - dstRed) * srcAlpha / 255;
dstGreen += (srcGreen - dstGreen) * srcAlpha / 255;
dstBlue += (srcBlue - dstBlue) * srcAlpha / 255;
dstAlpha += (srcAlpha - dstAlpha) * srcAlpha / 255;
}
dst.setPixel(dstX, dstY, ((dstRed & 0xFF) << 0) | ((dstGreen & 0xFF) << 8) | ((dstBlue & 0xFF) << 16));
dst.setAlpha(dstX, dstY, dstAlpha);
}
}
}
|
final protected void drawImage(ImageData src, int ox, int oy) {
ImageData dst = imageData;
PaletteData srcPalette = src.palette;
ImageData srcMask = null;
int alphaMask = 0, alphaShift = 0;
if (src.maskData != null) {
srcMask = src.getTransparencyMask ();
if (src.depth == 32) {
alphaMask = ~(srcPalette.redMask | srcPalette.greenMask | srcPalette.blueMask);
while (alphaMask != 0 && ((alphaMask >>> alphaShift) & 1) == 0) alphaShift++;
}
}
for (int srcY = 0, dstY = srcY + oy; srcY < src.height; srcY++, dstY++) {
for (int srcX = 0, dstX = srcX + ox; srcX < src.width; srcX++, dstX++) {
if (!(0 <= dstX && dstX < dst.width && 0 <= dstY && dstY < dst.height)) continue;
int srcPixel = src.getPixel(srcX, srcY);
int srcAlpha = 255;
if (src.maskData != null) {
if (src.depth == 32) {
srcAlpha = (srcPixel & alphaMask) >>> alphaShift;
if (srcAlpha == 0) {
srcAlpha = srcMask.getPixel(srcX, srcY) != 0 ? 255 : 0;
}
} else {
if (srcMask.getPixel(srcX, srcY) == 0) srcAlpha = 0;
}
} else if (src.transparentPixel != -1) {
if (src.transparentPixel == srcPixel) srcAlpha = 0;
} else if (src.alpha != -1) {
srcAlpha = src.alpha;
} else if (src.alphaData != null) {
srcAlpha = src.getAlpha(srcX, srcY);
}
if (srcAlpha == 0) continue;
int srcRed, srcGreen, srcBlue;
if (srcPalette.isDirect) {
srcRed = srcPixel & srcPalette.redMask;
srcRed = (srcPalette.redShift < 0) ? srcRed >>> -srcPalette.redShift : srcRed << srcPalette.redShift;
srcGreen = srcPixel & srcPalette.greenMask;
srcGreen = (srcPalette.greenShift < 0) ? srcGreen >>> -srcPalette.greenShift : srcGreen << srcPalette.greenShift;
srcBlue = srcPixel & srcPalette.blueMask;
srcBlue = (srcPalette.blueShift < 0) ? srcBlue >>> -srcPalette.blueShift : srcBlue << srcPalette.blueShift;
} else {
RGB rgb = srcPalette.getRGB(srcPixel);
srcRed = rgb.red;
srcGreen = rgb.green;
srcBlue = rgb.blue;
}
int dstRed, dstGreen, dstBlue, dstAlpha;
if (srcAlpha == 255) {
dstRed = srcRed;
dstGreen = srcGreen;
dstBlue= srcBlue;
dstAlpha = srcAlpha;
} else {
int dstPixel = dst.getPixel(dstX, dstY);
dstAlpha = dst.getAlpha(dstX, dstY);
dstRed = (dstPixel & 0xFF) >>> 0;
dstGreen = (dstPixel & 0xFF00) >>> 8;
dstBlue = (dstPixel & 0xFF0000) >>> 16;
dstRed += (srcRed - dstRed) * srcAlpha / 255;
dstGreen += (srcGreen - dstGreen) * srcAlpha / 255;
dstBlue += (srcBlue - dstBlue) * srcAlpha / 255;
dstAlpha += (srcAlpha - dstAlpha) * srcAlpha / 255;
}
dst.setPixel(dstX, dstY, ((dstRed & 0xFF) << 0) | ((dstGreen & 0xFF) << 8) | ((dstBlue & 0xFF) << 16));
dst.setAlpha(dstX, dstY, dstAlpha);
}
}
}
|
diff --git a/src/main/java/me/limebyte/battlenight/core/BattleNight.java b/src/main/java/me/limebyte/battlenight/core/BattleNight.java
index b420515..eafd463 100644
--- a/src/main/java/me/limebyte/battlenight/core/BattleNight.java
+++ b/src/main/java/me/limebyte/battlenight/core/BattleNight.java
@@ -1,1254 +1,1254 @@
package me.limebyte.battlenight.core;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Logger;
import me.limebyte.battlenight.core.Hooks.Metrics;
import me.limebyte.battlenight.core.Hooks.Nameplates;
import me.limebyte.battlenight.core.Listeners.CheatListener;
import me.limebyte.battlenight.core.Listeners.CommandBlocker;
import me.limebyte.battlenight.core.Listeners.DamageListener;
import me.limebyte.battlenight.core.Listeners.DeathListener;
import me.limebyte.battlenight.core.Listeners.DisconnectListener;
import me.limebyte.battlenight.core.Listeners.DropListener;
import me.limebyte.battlenight.core.Listeners.NameplateListener;
import me.limebyte.battlenight.core.Listeners.ReadyListener;
import me.limebyte.battlenight.core.Listeners.RespawnListener;
import me.limebyte.battlenight.core.Listeners.SignChanger;
import me.limebyte.battlenight.core.Listeners.SignListener;
import me.limebyte.battlenight.core.Other.Tracks.Track;
import me.limebyte.battlenight.core.Other.Waypoint;
import me.limebyte.battlenight.core.commands.WaypointCommand;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Sign;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.kitteh.tag.TagAPI;
public class BattleNight extends JavaPlugin {
// Variables
public static Logger log;
public static final String BNTag = ChatColor.GRAY + "[BattleNight] " + ChatColor.WHITE;
public static final String BNKTag = ChatColor.GRAY + "[BattleNight KillFeed] " + ChatColor.WHITE;
public Set<String> ClassList;
// HashMaps
public final Map<String, Team> BattleUsersTeam = new HashMap<String, Team>();
public final Map<String, String> BattleUsersClass = new HashMap<String, String>();
public final Map<String, String> BattleClasses = new HashMap<String, String>();
public final Map<String, String> BattleArmor = new HashMap<String, String>();
public final Map<String, Sign> BattleSigns = new HashMap<String, Sign>();
public final Map<String, String> BattleUsersRespawn = new HashMap<String, String>();
public final Map<String, String> BattleTelePass = new HashMap<String, String>();
public final Map<String, String> BattleSpectators = new HashMap<String, String>();
// Other Classes
public final Battle battle = new Battle(this);
private final SignListener signListener = new SignListener(this);
private final ReadyListener readyListener = new ReadyListener(this);
private final RespawnListener respawnListener = new RespawnListener(this);
private final DeathListener deathListener = new DeathListener(this);
private final DamageListener damageListener = new DamageListener(this);
private final DropListener dropListener = new DropListener(this);
private final DisconnectListener disconnectListener = new DisconnectListener(this);
private final SignChanger blockListener = new SignChanger(this);
private final CheatListener cheatListener = new CheatListener(this);
private final CommandBlocker commandBlocker = new CommandBlocker(this);
public boolean redTeamIronClicked = false;
public boolean blueTeamIronClicked = false;
public boolean battleInProgress = false;
public boolean playersInLounge = false;
// config.yml Values
public boolean configUsePermissions = false;
public boolean configFriendlyFire = false;
public boolean configStopHealthRegen = true;
public String configInventoryType = "prompt";
public int configReadyBlock = 42;
public boolean configDebug = false;
// classes.yml Values
public int classesDummyItem = 6;
// Declare Files and FileConfigurations
static File configFile;
static File classesFile;
static File waypointsFile;
static File playerFile;
public static FileConfiguration config;
static FileConfiguration classes;
static FileConfiguration waypoints;
static FileConfiguration players;
// ////////////////////
// Plug-in Disable //
// ////////////////////
@Override
public void onDisable() {
if (battleInProgress || playersInLounge) {
log.info("Ending current Battle...");
battle.end();
}
this.cleanSigns();
final PluginDescriptionFile pdfFile = getDescription();
log.info("Version " + pdfFile.getVersion() + " has been disabled.");
}
// ///////////////////
// Plug-in Enable //
// ////////////////////
@Override
public void onEnable() {
// Set instances
log = getLogger();
// Initialise Files and FileConfigurations
configFile = new File(getDataFolder(), "config.yml");
classesFile = new File(getDataFolder(), "classes.yml");
waypointsFile = new File(getDataFolder() + "/PluginData", "waypoints.dat");
playerFile = new File(getDataFolder() + "/PluginData", "players.dat");
// Use firstRun(); method
try {
firstRun();
} catch (final Exception e) {
e.printStackTrace();
}
// Declare and Load the FileConfigurations
config = new YamlConfiguration();
classes = new YamlConfiguration();
waypoints = new YamlConfiguration();
players = new YamlConfiguration();
loadYamls();
// Metrics
try {
final Metrics metrics = new Metrics(this);
metrics.start();
} catch (final IOException e) {
// Failed to submit the stats :-(
}
// Configuration
configUsePermissions = config.getBoolean("UsePermissions");
configFriendlyFire = config.getBoolean("FriendlyFire");
configStopHealthRegen = config.getBoolean("StopHealthRegen");
configInventoryType = config.getString("InventoryType").toLowerCase();
configReadyBlock = config.getInt("ReadyBlock");
configDebug = config.getBoolean("Debug");
classesDummyItem = classes.getInt("DummyItem");
for (final String className : classes.getConfigurationSection("Classes")
.getKeys(false)) {
BattleClasses.put(className,
classes.getString("Classes." + className + ".Items", null));
}
for (final String className : classes.getConfigurationSection("Classes")
.getKeys(false)) {
BattleArmor.put(className,
classes.getString("Classes." + className + ".Armor", null));
}
ClassList = classes.getConfigurationSection("Classes").getKeys(false);
// Debug
if (configDebug) {
if (configUsePermissions) {
log.info("Permissions Enabled.");
} else if (!configUsePermissions) {
log.info("Permissions Disabled, using Op.");
} else {
log.warning("Permissions not setup in config!");
}
log.info("Classes: " + BattleClasses);
log.info("Armor: " + BattleArmor);
}
final PluginManager pm = getServer().getPluginManager();
if (Nameplates.init(this)) {
// Event Registration
final PluginDescriptionFile pdfFile = getDescription();
pm.registerEvents(new NameplateListener(this), this);
pm.registerEvents(signListener, this);
pm.registerEvents(readyListener, this);
pm.registerEvents(respawnListener, this);
pm.registerEvents(deathListener, this);
pm.registerEvents(dropListener, this);
pm.registerEvents(damageListener, this);
pm.registerEvents(disconnectListener, this);
pm.registerEvents(blockListener, this);
pm.registerEvents(cheatListener, this);
pm.registerEvents(commandBlocker, this);
// Enable Message
log.info("Version " + pdfFile.getVersion() + " enabled successfully.");
log.info("Made by LimeByte.");
} else {
pm.disablePlugin(this);
}
}
// Fill Configuration Files with Defaults
private void firstRun() throws Exception {
if (!configFile.exists()) { // Checks If The YAML File Does Not Exist
configFile.getParentFile().mkdirs(); // Creates the
// /Plugins/BattleNight/
// Directory If Not Found
copy(getResource("config.yml"), configFile); // Copies the YAML From
// Your Jar to the
// Folder
}
if (!classesFile.exists()) {
classesFile.getParentFile().mkdirs();
copy(getResource("classes.yml"), classesFile);
}
if (!waypointsFile.exists()) {
waypointsFile.getParentFile().mkdirs();
copy(getResource("waypoints.dat"), waypointsFile);
}
if (!playerFile.exists()) {
playerFile.getParentFile().mkdirs();
copy(getResource("players.dat"), playerFile);
}
}
// YAML Copy Method
public static void copy(InputStream in, File file) {
try {
final OutputStream out = new FileOutputStream(file);
final byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (final Exception e) {
e.printStackTrace();
}
}
// YAML Load Method
public void loadYamls() {
try {
config.load(configFile);
classes.load(classesFile);
waypoints.load(waypointsFile);
players.load(playerFile);
} catch (final Exception e) {
e.printStackTrace();
}
}
public void reloadConfigFiles() throws FileNotFoundException, IOException, InvalidConfigurationException {
config.load(configFile);
classes.load(classesFile);
configUsePermissions = config.getBoolean("UsePermissions");
configFriendlyFire = config.getBoolean("FriendlyFire");
configStopHealthRegen = config.getBoolean("StopHealthRegen");
configInventoryType = config.getString("InventoryType").toLowerCase();
configReadyBlock = config.getInt("ReadyBlock");
configDebug = config.getBoolean("Debug");
classesDummyItem = classes.getInt("DummyItem");
for (final String className : classes.getConfigurationSection("Classes")
.getKeys(false)) {
BattleClasses.put(className,
classes.getString("Classes." + className + ".Items", null));
}
for (final String className : classes.getConfigurationSection("Classes")
.getKeys(false)) {
BattleArmor.put(className,
classes.getString("Classes." + className + ".Armor", null));
}
ClassList = classes.getConfigurationSection("Classes").getKeys(false);
}
// Waypoints Load Method
public static void loadWaypoints() {
try {
waypoints.load(waypointsFile);
} catch (final Exception e) {
e.printStackTrace();
}
}
// YAML Save Method
public void saveYamls() {
try {
config.save(configFile);
classes.save(classesFile);
waypoints.save(waypointsFile);
players.save(playerFile);
} catch (final IOException e) {
e.printStackTrace();
}
}
public static void saveYAML(ConfigFile file) {
try {
if (file.equals(ConfigFile.Main))
config.save(configFile);
if (file.equals(ConfigFile.Classes))
classes.save(classesFile);
if (file.equals(ConfigFile.Waypoints))
waypoints.save(waypointsFile);
if (file.equals(ConfigFile.Players))
players.save(playerFile);
} catch (final IOException e) {
e.printStackTrace();
}
}
public enum ConfigFile {
Main, Classes, Waypoints, Players
}
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if (commandLabel.equalsIgnoreCase("bn")) {
if (args.length < 1) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "Incorrect usage. Type '/bn help' to show the help menu.");
return true;
} else if (args[0].equalsIgnoreCase("set")) {
WaypointCommand cmd = new WaypointCommand(sender, args);
cmd.perform();
} else if (args.length == 1) {
if (args[0].equalsIgnoreCase("help")) {
if (hasPerm(Perm.ADMIN, sender)) {
sender.sendMessage(ChatColor.DARK_GRAY + " ---------- "
+ ChatColor.WHITE + "BattleNight Help Menu"
+ ChatColor.DARK_GRAY + " ---------- ");
sender.sendMessage(ChatColor.WHITE
+ " /bn help - Shows general help.");
sender.sendMessage(ChatColor.WHITE
+ " /bn waypoints - Shows set/unset waypoints.");
sender.sendMessage(ChatColor.WHITE
+ " /bn version - Shows the version of BattleNight in use.");
sender.sendMessage(ChatColor.WHITE
+ " /bn join - Join the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn leave - Leave the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn watch - Watch the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn kick [player] - Kick a player from the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn kickall - Kick all players in the Battle.");
sender.sendMessage(ChatColor.DARK_GRAY
+ " --------------------------------------- ");
} else if (hasPerm(Perm.USER, sender)) {
sender.sendMessage(ChatColor.DARK_GRAY + " ---------- "
+ ChatColor.WHITE + "BattleNight Help Menu"
+ ChatColor.DARK_GRAY + " ---------- ");
sender.sendMessage(ChatColor.WHITE
+ " /bn help - Shows general help.");
sender.sendMessage(ChatColor.WHITE
+ " /bn version - Shows the version of BattleNight in use.");
sender.sendMessage(ChatColor.WHITE
+ " /bn join - Join the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn leave - Leave the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn watch - Watch the Battle");
sender.sendMessage(ChatColor.DARK_GRAY
+ " --------------------------------------- ");
} else {
sender.sendMessage(BattleNight.BNTag + Track.NO_PERMISSION.msg);
}
}
else if (args[0].equalsIgnoreCase("waypoints") && hasPerm(Perm.ADMIN, sender)) {
sender.sendMessage(ChatColor.DARK_GRAY + " ---------- "
+ ChatColor.WHITE + "BattleNight Waypoints"
+ ChatColor.DARK_GRAY + " ---------- ");
sender.sendMessage(ChatColor.WHITE + " Setup points: "
+ numSetupPoints() + "/6");
if (pointSet(Waypoint.RED_LOUNGE)) {
sender.sendMessage(ChatColor.GREEN + " Red Lounge"
+ ChatColor.WHITE + " (/bn redlounge)");
} else {
sender.sendMessage(ChatColor.RED + " Red Lounge"
+ ChatColor.WHITE + " (/bn redlounge)");
}
if (pointSet(Waypoint.BLUE_LOUNGE)) {
sender.sendMessage(ChatColor.GREEN + " Blue Lounge"
+ ChatColor.WHITE + " (/bn bluelounge)");
} else {
sender.sendMessage(ChatColor.RED + " Blue Lounge"
+ ChatColor.WHITE + " (/bn bluelounge)");
}
if (pointSet(Waypoint.RED_SPAWN)) {
sender.sendMessage(ChatColor.GREEN + " Red Spawn"
+ ChatColor.WHITE + " (/bn redspawn)");
} else {
sender.sendMessage(ChatColor.RED + " Red Spawn"
+ ChatColor.WHITE + " (/bn redspawn)");
}
if (pointSet(Waypoint.BLUE_SPAWN)) {
sender.sendMessage(ChatColor.GREEN + " Blue Spawn"
+ ChatColor.WHITE + " (/bn bluespawn)");
} else {
sender.sendMessage(ChatColor.RED + " Blue Spawn"
+ ChatColor.WHITE + " (/bn bluespawn)");
}
if (pointSet(Waypoint.SPECTATOR)) {
sender.sendMessage(ChatColor.GREEN + " Spectator"
+ ChatColor.WHITE + " (/bn spectator)");
} else {
sender.sendMessage(ChatColor.RED + " Spectator"
+ ChatColor.WHITE + " (/bn spectator)");
}
if (pointSet(Waypoint.EXIT)) {
sender.sendMessage(ChatColor.GREEN + " Exit"
+ ChatColor.WHITE + " (/bn exit)");
} else {
sender.sendMessage(ChatColor.RED + " Exit"
+ ChatColor.WHITE + " (/bn exit)");
}
sender.sendMessage(ChatColor.DARK_GRAY
+ " --------------------------------------- ");
}
else if (args[0].equalsIgnoreCase("join") && hasPerm(Perm.USER, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
if (isSetup() && !battleInProgress && !BattleUsersTeam.containsKey(player.getName())) {
battle.addPlayer(player);
} else if (!isSetup()) {
tellPlayer(player, Track.WAYPOINTS_UNSET);
} else if (battleInProgress) {
tellPlayer(player, Track.BATTLE_IN_PROGRESS);
} else if (BattleUsersTeam.containsKey(player.getName())) {
tellPlayer(player, Track.ALREADY_IN_TEAM);
}
}
else if ((args[0].equalsIgnoreCase("watch")) && hasPerm(Perm.USER, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
addSpectator(player, "command");
} else if (args[0].equalsIgnoreCase("leave") && hasPerm(Perm.USER, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
if (BattleUsersTeam.containsKey(player.getName())) {
battle.removePlayer(player, false, "has left the Battle.", "You have left the Battle.");
} else if (BattleSpectators.containsKey(player.getName())) {
removeSpectator(player);
} else {
tellPlayer(player, Track.NOT_IN_TEAM.msg);
}
}
else if (args[0].equalsIgnoreCase("kick") && hasPerm(Perm.MOD, sender)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + Track.SPECIFY_PLAYER.msg);
}
else if ((args[0].equalsIgnoreCase("kickall") || args[0].equalsIgnoreCase("endgame")) && hasPerm(Perm.MOD, sender)) {
battle.end();
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + Track.BATTLE_ENDED.msg);
}
else if (args[0].equalsIgnoreCase("redlounge") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "redlounge");
tellPlayer(player, Track.RED_LOUNGE_SET);
}
else if (args[0].equalsIgnoreCase("redspawn") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "redspawn");
tellPlayer(player, Track.RED_SPAWN_SET);
}
else if (args[0].equalsIgnoreCase("bluelounge") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "bluelounge");
tellPlayer(player, Track.BLUE_LOUNGE_SET);
}
else if (args[0].equalsIgnoreCase("bluespawn") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "bluespawn");
tellPlayer(player, Track.BLUE_SPAWN_SET);
}
else if (args[0].equalsIgnoreCase("spectator") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "spectator");
tellPlayer(player, Track.SPECTATOR_SET);
}
else if (args[0].equalsIgnoreCase("exit") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "exit");
tellPlayer(player, Track.EXIT_SET);
}
else if (args[0].equalsIgnoreCase("version")) {
PluginDescriptionFile pdfFile = getDescription();
String[] msgs = {
BNTag + "This server is currently using Battlenight Version " + pdfFile.getVersion() + ".",
- "For more information about Battlenight and the features included in this version, please visit: ",
+ ChatColor.WHITE + "For more information about Battlenight and the features included in this version, please visit: ",
ChatColor.DARK_AQUA + pdfFile.getWebsite()
};
sender.sendMessage(msgs);
}
else if (args[0].equalsIgnoreCase("reload") && hasPerm(Perm.ADMIN, sender)) {
sender.sendMessage(BNTag + "Reloading config...");
try {
reloadConfigFiles();
sender.sendMessage(BNTag + ChatColor.GREEN + "Reloaded successfully.");
} catch (final Exception e) {
e.printStackTrace();
sender.sendMessage(BNTag + ChatColor.RED + "Reload failed.");
}
}
else {
sender.sendMessage(BNTag + ChatColor.RED + Track.INVALID_COMAND.msg);
}
}
if (args.length == 2) {
if (args[0].equalsIgnoreCase("kick") && hasPerm(Perm.MOD, sender)) {
Player badplayer = Bukkit.getPlayerExact(args[1]);
if (badplayer.isOnline()) {
if (BattleUsersTeam.containsKey(badplayer.getName())) {
battle.removePlayer(badplayer, false, "has been kicked from the current Battle.", "You have been kicked from the current Battle.");
} else {
sender.sendMessage(BNTag + ChatColor.RED + "Player: " + badplayer.getName() + " is not in the current Battle.");
}
} else {
sender.sendMessage(BNTag + ChatColor.RED + "Can't find user " + badplayer.getName() + ". No kick.");
}
}
}
if (args.length > 2) {
sender.sendMessage(BNTag + ChatColor.RED + Track.INVALID_COMAND.msg);
}
return true;
}
return false;
}
// Set Coords and put in waypoints.data
public void setCoords(Player player, String place) {
final Location location = player.getLocation();
loadWaypoints();
waypoints.set("coords." + place + ".world", location.getWorld().getName());
waypoints.set("coords." + place + ".x", location.getX());
waypoints.set("coords." + place + ".y", location.getY());
waypoints.set("coords." + place + ".z", location.getZ());
waypoints.set("coords." + place + ".yaw", location.getYaw());
waypoints.set("coords." + place + ".pitch", location.getPitch());
saveYAML(ConfigFile.Waypoints);
}
// Set Coords and put in waypoints.data
public static void setCoords(Waypoint waypoint, Location location) {
String place = waypoint.getName();
loadWaypoints();
waypoints.set("coords." + place + ".world", location.getWorld().getName());
waypoints.set("coords." + place + ".x", location.getX());
waypoints.set("coords." + place + ".y", location.getY());
waypoints.set("coords." + place + ".z", location.getZ());
waypoints.set("coords." + place + ".yaw", location.getYaw());
waypoints.set("coords." + place + ".pitch", location.getPitch());
saveYAML(ConfigFile.Waypoints);
}
// Get Coords from waypoints.data
public Location getCoords(String place) {
loadWaypoints();
final Double x = waypoints.getDouble("coords." + place + ".x", 0);
final Double y = waypoints.getDouble("coords." + place + ".y", 0);
final Double z = waypoints.getDouble("coords." + place + ".z", 0);
final String yawToParse = waypoints.getString("coords." + place + ".yaw");
float yaw = 0;
if (yawToParse != null) {
try {
yaw = Float.parseFloat(yawToParse);
} catch (final NumberFormatException nfe) {
// log it, do whatever you want, it's not a float. Maybe give it
// a default value
}
}
final String pitchToParse = waypoints.getString("coords." + place + ".pitch");
float pitch = 0;
if (pitchToParse != null) {
try {
pitch = Float.parseFloat(pitchToParse);
} catch (final NumberFormatException nfe) {
// log it, do whatever you want, it's not a float. Maybe give it
// a default value
}
}
final World world = Bukkit.getServer().getWorld(
waypoints.getString("coords." + place + ".world"));
return new Location(world, x, y, z, yaw, pitch);
}
public boolean pointSet(Waypoint waypoint) {
loadWaypoints();
try {
final Set<String> set = waypoints.getConfigurationSection("coords")
.getKeys(false);
final List<String> setpoints = new ArrayList<String>(set);
if (setpoints.contains(waypoint.getName())) {
return true;
} else {
return false;
}
} catch (final NullPointerException e) {
return false;
}
}
// Check if all Waypoints have been set.
public Boolean isSetup() {
loadWaypoints();
if (!waypoints.isSet("coords")) {
return false;
} else {
final Set<String> set = waypoints.getConfigurationSection("coords")
.getKeys(false);
final List<String> list = new ArrayList<String>(set);
if (list.size() == 6) {
return true;
} else {
return false;
}
}
}
public int numSetupPoints() {
loadWaypoints();
if (!waypoints.isSet("coords")) {
return 0;
} else {
final Set<String> set = waypoints.getConfigurationSection("coords")
.getKeys(false);
final List<String> list = new ArrayList<String>(set);
return list.size();
}
}
// Give Player Class Items
public void giveItems(Player player) {
final String playerClass = BattleUsersClass.get(player.getName());
final String rawItems = BattleClasses.get(playerClass);
final String ArmorList = BattleArmor.get(playerClass);
String[] items;
items = rawItems.split(",");
for (int i = 0; i < items.length; i++) {
final String item = items[i];
player.getInventory().setItem(i, parseItem(item));
if (player.getInventory().contains(classesDummyItem)) {
player.getInventory().remove(classesDummyItem);
}
}
// Set Armour
// Helmets
if (ArmorList.contains("298")) {
player.getInventory().setHelmet(new ItemStack(298, 1));
} else if (ArmorList.contains("302")) {
player.getInventory().setHelmet(new ItemStack(302, 1));
} else if (ArmorList.contains("306")) {
player.getInventory().setHelmet(new ItemStack(306, 1));
} else if (ArmorList.contains("310")) {
player.getInventory().setHelmet(new ItemStack(310, 1));
} else if (ArmorList.contains("314")) {
player.getInventory().setHelmet(new ItemStack(314, 1));
}
// Chestplates
if (ArmorList.contains("299")) {
player.getInventory().setChestplate(new ItemStack(299, 1));
} else if (ArmorList.contains("303")) {
player.getInventory().setChestplate(new ItemStack(303, 1));
} else if (ArmorList.contains("307")) {
player.getInventory().setChestplate(new ItemStack(307, 1));
} else if (ArmorList.contains("311")) {
player.getInventory().setChestplate(new ItemStack(311, 1));
} else if (ArmorList.contains("315")) {
player.getInventory().setChestplate(new ItemStack(315, 1));
}
// Leggings
if (ArmorList.contains("300")) {
player.getInventory().setLeggings(new ItemStack(300, 1));
} else if (ArmorList.contains("304")) {
player.getInventory().setLeggings(new ItemStack(304, 1));
} else if (ArmorList.contains("308")) {
player.getInventory().setLeggings(new ItemStack(308, 1));
} else if (ArmorList.contains("312")) {
player.getInventory().setLeggings(new ItemStack(312, 1));
} else if (ArmorList.contains("316")) {
player.getInventory().setLeggings(new ItemStack(316, 1));
}
// Boots
if (ArmorList.contains("301")) {
player.getInventory().setBoots(new ItemStack(301, 1));
} else if (ArmorList.contains("305")) {
player.getInventory().setBoots(new ItemStack(305, 1));
} else if (ArmorList.contains("309")) {
player.getInventory().setBoots(new ItemStack(309, 1));
} else if (ArmorList.contains("313")) {
player.getInventory().setBoots(new ItemStack(313, 1));
} else if (ArmorList.contains("317")) {
player.getInventory().setBoots(new ItemStack(317, 1));
}
}
// Clean Up All Signs People Have Used For Classes
public void cleanSigns() {
for (final Entry<String, Sign> entry : BattleSigns.entrySet()) {
if (entry.getValue() != null) {
final Sign currentSign = entry.getValue();
currentSign.setLine(2, "");
currentSign.setLine(3, "");
currentSign.update();
}
}
}
// Clean Up Signs Specific Player Has Used For Classes
public void cleanSigns(Player player) {
for (final Entry<String, Sign> entry : BattleSigns.entrySet()) {
if (entry.getValue() != null && player != null) {
final Sign currentSign = entry.getValue();
if (currentSign.getLine(2) == player.getName()) currentSign.setLine(2, "");
if (currentSign.getLine(3) == player.getName()) currentSign.setLine(3, "");
currentSign.update();
}
}
}
public boolean teamReady(Team team) {
int members = 0;
int membersReady = 0;
for (final Entry<String, Team> entry : BattleUsersTeam.entrySet()) {
if (Bukkit.getPlayer(entry.getKey()) != null) {
if (entry.getValue().equals(team)) {
members++;
if (BattleUsersClass.containsKey(entry.getKey())) membersReady++;
}
}
}
if (members == membersReady && members > 0) {
if (team.equals(Team.RED) || team.equals(Team.BLUE)) { return true; }
}
return false;
}
public void tellEveryone(String msg) {
for (final String name : BattleUsersTeam.keySet()) {
if (Bukkit.getPlayer(name) != null) Bukkit.getPlayer(name).sendMessage(BNTag + msg);
}
}
public void tellEveryone(Track track) {
for (final String name : BattleUsersTeam.keySet()) {
if (Bukkit.getPlayer(name) != null) Bukkit.getPlayer(name).sendMessage(BNTag + track.msg);
}
}
public void killFeed(String msg) {
final LinkedList<Player> told = new LinkedList<Player>();
for (final String name : BattleUsersTeam.keySet()) {
if (Bukkit.getPlayer(name) != null) {
final Player currentPlayer = Bukkit.getPlayer(name);
currentPlayer.sendMessage(BNTag + msg);
told.add(currentPlayer);
}
}
for (final String name : BattleSpectators.keySet()) {
if (Bukkit.getPlayer(name) != null) {
final Player currentPlayer = Bukkit.getPlayer(name);
if (!told.contains(currentPlayer)) {
currentPlayer.sendMessage(BNTag + msg);
told.add(currentPlayer);
}
}
}
told.clear();
}
public void tellEveryoneExcept(Player player, String msg) {
for (final String name : BattleUsersTeam.keySet()) {
if (Bukkit.getPlayer(name) != null) {
final Player currentPlayer = Bukkit.getPlayer(name);
if (currentPlayer != player) currentPlayer.sendMessage(BNTag + msg);
}
}
}
public void tellTeam(Team team, String msg) {
for (final String name : BattleUsersTeam.keySet()) {
if (Bukkit.getPlayer(name) != null) {
final Player currentPlayer = Bukkit.getPlayer(name);
if (BattleUsersTeam.get(name).equals(team)) currentPlayer.sendMessage(BNTag + msg);
}
}
}
public void tellTeam(Team team, Track track) {
for (final String name : BattleUsersTeam.keySet()) {
if (Bukkit.getPlayer(name) != null) {
final Player currentPlayer = Bukkit.getPlayer(name);
if (BattleUsersTeam.get(name).equals(team)) currentPlayer.sendMessage(BNTag + track.msg);
}
}
}
public static void tellPlayer(Player player, String msg) {
player.sendMessage(BNTag + msg);
}
public void tellPlayer(Player player, Track track) {
player.sendMessage(BNTag + track.msg);
}
public void teleportAllToSpawn() {
for (final String name : BattleUsersTeam.keySet()) {
if (Bukkit.getPlayer(name) != null) {
final Player currentPlayer = Bukkit.getPlayer(name);
if (BattleUsersTeam.get(name).equals(Team.RED)) {
goToWaypoint(currentPlayer, Waypoint.RED_SPAWN);
}
if (BattleUsersTeam.get(name).equals(Team.BLUE)) {
goToWaypoint(currentPlayer, Waypoint.BLUE_SPAWN);
}
}
}
}
public boolean hasEmptyInventory(Player player) {
final ItemStack[] invContents = player.getInventory().getContents();
final ItemStack[] armContents = player.getInventory().getArmorContents();
int invNullCounter = 0;
int armNullCounter = 0;
for (int i = 0; i < invContents.length; i++) {
if (invContents[i] == null) {
invNullCounter++;
}
}
for (int i = 0; i < armContents.length; i++) {
if (armContents[i].getType() == Material.AIR) {
armNullCounter++;
}
}
return (invNullCounter == invContents.length)
&& (armNullCounter == armContents.length);
}
public void goToWaypoint(Player player, Waypoint waypoint) {
final Location destination = getCoords(waypoint.getName());
final Chunk chunk = destination.getChunk();
if (!chunk.isLoaded()) {
chunk.load();
while (!chunk.isLoaded()) {
// Wait until loaded
}
}
BattleTelePass.put(player.getName(), "yes");
player.teleport(destination);
BattleTelePass.remove(player.getName());
}
public enum Perm {
ADMIN, MOD, USER
}
public boolean hasPerm(BattleNight.Perm perm, CommandSender sender) {
// Player check
if (!(sender instanceof Player)) {
return true;
}
Player player = (Player) sender;
if (perm.equals(Perm.ADMIN)) {
if ((configUsePermissions && player
.hasPermission("battlenight.admin"))
|| (!configUsePermissions && player.isOp())) {
return true;
} else if ((configUsePermissions && !player
.hasPermission("battlenight.admin"))
|| (!configUsePermissions && !player.isOp())) {
tellPlayer(player, Track.NO_PERMISSION);
return false;
} else {
tellPlayer(player, Track.CONFIG_UNSET);
return false;
}
}
if (perm.equals(Perm.MOD)) {
if ((configUsePermissions && player
.hasPermission("battlenight.moderator"))
|| (!configUsePermissions && player.isOp())) {
return true;
} else if ((configUsePermissions && !player
.hasPermission("battlenight.moderator"))
|| (!configUsePermissions && !player.isOp())) {
tellPlayer(player, Track.NO_PERMISSION);
return false;
} else {
tellPlayer(player, Track.CONFIG_UNSET);
return false;
}
} else if (perm.equals(Perm.USER)) {
if ((configUsePermissions && player
.hasPermission("battlenight.user"))
|| !configUsePermissions) {
return true;
} else if (configUsePermissions
&& !player.hasPermission("battlenight.user")) {
tellPlayer(player, Track.NO_PERMISSION);
return false;
} else {
tellPlayer(player, Track.CONFIG_UNSET);
return false;
}
} else {
return false;
}
}
public static ItemStack parseItem(String rawItem) {
if (rawItem == null || rawItem.equals(""))
return null;
final String[] part1 = rawItem.split("x");
final String[] part2 = part1[0].split(":");
final String item = part2[0];
if (part1.length == 1) {
if (part2.length == 1) {
return parseItemWithoutData(item, "1");
} else if (part2.length == 2) {
final String data = part2[1];
return parseItemWithData(item, data);
}
} else if (part1.length == 2) {
final String amount = part1[1];
if (part2.length == 1) {
return parseItemWithoutData(item, amount);
} else if (part2.length == 2) {
final String data = part2[1];
return parseItemWithData(item, data, amount);
}
}
return null;
}
private static ItemStack parseItemWithoutData(String item, String amount) {
final Material m = Material.getMaterial(Integer.parseInt(item));
int a = Integer.parseInt(amount);
if (a > m.getMaxStackSize()) {
log.warning("You attempted to set the item:" + m + " to have a greater stack size than possible.");
a = m.getMaxStackSize();
}
return new ItemStack(m, a);
}
private static ItemStack parseItemWithData(String item, String data) {
final int i = Integer.parseInt(item);
final short d = Short.parseShort(data);
return new ItemStack(i, 1, d);
}
private static ItemStack parseItemWithData(String item, String data,
String amount) {
final Material m = Material.getMaterial(Integer.parseInt(item));
final byte d = Byte.parseByte(data);
int a = Integer.parseInt(amount);
if (a > m.getMaxStackSize()) {
log.warning("You attempted to set the item:" + m + " to have a greater stack size than possible.");
a = m.getMaxStackSize();
}
return new ItemStack(m, a, d);
}
public void addSpectator(Player player, String type) {
if (type.equals("death")) {
BattleSpectators.put(player.getName(), "death");
tellPlayer(player, Track.WELCOME_SPECTATOR_DEATH);
} else {
if (isSetup() && battleInProgress) {
if (BattleUsersTeam.containsKey(player.getName())) {
battle.removePlayer(player, false, "has left the Battle.", "You have left the Battle.");
}
goToWaypoint(player, Waypoint.SPECTATOR);
BattleSpectators.put(player.getName(), "command");
tellPlayer(player, Track.WELCOME_SPECTATOR);
return;
} else if (!isSetup()) {
tellPlayer(player, Track.WAYPOINTS_UNSET);
return;
} else if (!battleInProgress) {
tellPlayer(player, Track.BATTLE_NOT_IN_PROGRESS);
return;
}
}
}
public void removeSpectator(Player player) {
goToWaypoint(player, Waypoint.EXIT);
BattleSpectators.remove(player.getName());
tellPlayer(player, Track.GOODBYE_SPECTATOR);
}
public void removeAllSpectators() {
for (final String pName : BattleSpectators.keySet()) {
if (Bukkit.getPlayer(pName) != null) {
final Player currentPlayer = Bukkit.getPlayer(pName);
goToWaypoint(currentPlayer, Waypoint.EXIT);
}
}
BattleSpectators.clear();
}
public boolean preparePlayer(Player p) {
if (config.getString("InventoryType").equalsIgnoreCase("prompt") && !hasEmptyInventory(p)) return false;
final String name = p.getName();
// Inventory
if (config.getString("InventoryType").equalsIgnoreCase("save")) {
config.set(name + ".data.inv.main", Arrays.asList(p.getInventory().getContents()));
config.set(name + ".data.inv.armor", Arrays.asList(p.getInventory().getArmorContents()));
}
// Health
config.set(name + ".data.health", p.getHealth());
// Hunger
config.set(name + ".data.hunger.foodlevel", p.getFoodLevel());
config.set(name + ".data.hunger.saturation", Float.toString(p.getSaturation()));
config.set(name + ".data.hunger.exhaustion", Float.toString(p.getExhaustion()));
// Experience
config.set(name + ".data.exp.level", p.getLevel());
config.set(name + ".data.exp.ammount", Float.toString(p.getExp()));
// GameMode
config.set(name + ".data.gamemode", p.getGameMode().getValue());
// Flying
config.set(name + ".data.flight.allowed", p.getAllowFlight());
config.set(name + ".data.flight.flying", p.isFlying());
// Sleep
config.set(name + ".data.sleepignored", p.isSleepingIgnored());
// Information
config.set(name + ".data.info.displayname", p.getDisplayName());
config.set(name + ".data.info.listname", p.getPlayerListName());
// Statistics
config.set(name + ".data.stats.tickslived", p.getTicksLived());
config.set(name + ".data.stats.nodamageticks", p.getNoDamageTicks());
// State
config.set(name + ".data.state.remainingair", p.getRemainingAir());
config.set(name + ".data.state.falldistance", Float.toString(p.getFallDistance()));
config.set(name + ".data.state.fireticks", p.getFireTicks());
saveYAML(ConfigFile.Players);
// Reset Player
reset(p, false);
return true;
}
public void restorePlayer(Player p) {
final String name = p.getName();
reset(p, true);
try {
// Inventory
if (config.getString("InventoryType").equalsIgnoreCase("save")) {
p.getInventory().setContents(config.getList(name + ".data.inv.main").toArray(new ItemStack[0]));
p.getInventory().setArmorContents(config.getList(name + ".data.inv.armor").toArray(new ItemStack[0]));
}
// Health
p.setHealth(config.getInt(name + ".data.health"));
// Hunger
p.setFoodLevel(config.getInt(name + ".data.hunger.foodlevel"));
p.setSaturation(Float.parseFloat(config.getString(name + ".data.hunger.saturation")));
p.setExhaustion(Float.parseFloat(config.getString(name + ".data.hunger.exhaustion")));
// Experience
p.setLevel(config.getInt(name + ".data.exp.level"));
p.setExp(Float.parseFloat(config.getString(name + ".data.exp.ammount")));
// GameMode
p.setGameMode(GameMode.getByValue(config.getInt(name + ".data.gamemode")));
// Flying
p.setAllowFlight(config.getBoolean(name + ".data.flight.allowed"));
p.setFlying(config.getBoolean(name + ".data.flight.flying"));
// Sleep
p.setSleepingIgnored(config.getBoolean(name + ".data.sleepignored"));
// Information
p.setDisplayName(config.getString(name + ".data.info.displayname"));
p.setPlayerListName(config.getString(name + ".data.info.listname"));
// Statistics
p.setTicksLived(config.getInt(name + ".data.stats.tickslived"));
p.setNoDamageTicks(config.getInt(name + ".data.stats.nodamageticks"));
} catch (final NullPointerException e) {
log.warning("Failed to restore data for player: '" + name + "'.");
}
}
public void reset(Player p, boolean light) {
final PlayerInventory inv = p.getInventory();
inv.clear();
inv.setArmorContents(new ItemStack[inv.getArmorContents().length]);
removePotionEffects(p);
if (!light) {
p.setHealth(p.getMaxHealth());
p.setFoodLevel(16);
p.setSaturation(1000);
p.setExhaustion(0);
p.setLevel(0);
p.setExp(0);
p.setGameMode(GameMode.SURVIVAL);
p.setAllowFlight(false);
p.setFlying(false);
p.setSleepingIgnored(true);
setNames(p);
p.setTicksLived(1);
p.setNoDamageTicks(0);
p.setRemainingAir(300);
p.setFallDistance(0.0f);
p.setFireTicks(-20);
}
}
public void setNames(Player player) {
final String name = player.getName();
final String pListName = ChatColor.GRAY + "[BN] " + name;
ChatColor teamColour = ChatColor.WHITE;
if (BattleUsersTeam.containsKey(name)) {
teamColour = BattleUsersTeam.get(name).equals(Team.RED) ? ChatColor.RED : ChatColor.BLUE;
}
player.setPlayerListName(pListName.length() < 16 ? pListName : pListName.substring(0, 16));
player.setDisplayName(ChatColor.GRAY + "[BN] " + teamColour + name + ChatColor.RESET);
try {
TagAPI.refreshPlayer(player);
} catch (final Exception e) {
}
}
private void removePotionEffects(Player p) {
for (final PotionEffect effect : p.getActivePotionEffects()) {
p.addPotionEffect(new PotionEffect(effect.getType(), 0, 0), true);
}
}
}
| true | true |
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if (commandLabel.equalsIgnoreCase("bn")) {
if (args.length < 1) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "Incorrect usage. Type '/bn help' to show the help menu.");
return true;
} else if (args[0].equalsIgnoreCase("set")) {
WaypointCommand cmd = new WaypointCommand(sender, args);
cmd.perform();
} else if (args.length == 1) {
if (args[0].equalsIgnoreCase("help")) {
if (hasPerm(Perm.ADMIN, sender)) {
sender.sendMessage(ChatColor.DARK_GRAY + " ---------- "
+ ChatColor.WHITE + "BattleNight Help Menu"
+ ChatColor.DARK_GRAY + " ---------- ");
sender.sendMessage(ChatColor.WHITE
+ " /bn help - Shows general help.");
sender.sendMessage(ChatColor.WHITE
+ " /bn waypoints - Shows set/unset waypoints.");
sender.sendMessage(ChatColor.WHITE
+ " /bn version - Shows the version of BattleNight in use.");
sender.sendMessage(ChatColor.WHITE
+ " /bn join - Join the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn leave - Leave the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn watch - Watch the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn kick [player] - Kick a player from the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn kickall - Kick all players in the Battle.");
sender.sendMessage(ChatColor.DARK_GRAY
+ " --------------------------------------- ");
} else if (hasPerm(Perm.USER, sender)) {
sender.sendMessage(ChatColor.DARK_GRAY + " ---------- "
+ ChatColor.WHITE + "BattleNight Help Menu"
+ ChatColor.DARK_GRAY + " ---------- ");
sender.sendMessage(ChatColor.WHITE
+ " /bn help - Shows general help.");
sender.sendMessage(ChatColor.WHITE
+ " /bn version - Shows the version of BattleNight in use.");
sender.sendMessage(ChatColor.WHITE
+ " /bn join - Join the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn leave - Leave the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn watch - Watch the Battle");
sender.sendMessage(ChatColor.DARK_GRAY
+ " --------------------------------------- ");
} else {
sender.sendMessage(BattleNight.BNTag + Track.NO_PERMISSION.msg);
}
}
else if (args[0].equalsIgnoreCase("waypoints") && hasPerm(Perm.ADMIN, sender)) {
sender.sendMessage(ChatColor.DARK_GRAY + " ---------- "
+ ChatColor.WHITE + "BattleNight Waypoints"
+ ChatColor.DARK_GRAY + " ---------- ");
sender.sendMessage(ChatColor.WHITE + " Setup points: "
+ numSetupPoints() + "/6");
if (pointSet(Waypoint.RED_LOUNGE)) {
sender.sendMessage(ChatColor.GREEN + " Red Lounge"
+ ChatColor.WHITE + " (/bn redlounge)");
} else {
sender.sendMessage(ChatColor.RED + " Red Lounge"
+ ChatColor.WHITE + " (/bn redlounge)");
}
if (pointSet(Waypoint.BLUE_LOUNGE)) {
sender.sendMessage(ChatColor.GREEN + " Blue Lounge"
+ ChatColor.WHITE + " (/bn bluelounge)");
} else {
sender.sendMessage(ChatColor.RED + " Blue Lounge"
+ ChatColor.WHITE + " (/bn bluelounge)");
}
if (pointSet(Waypoint.RED_SPAWN)) {
sender.sendMessage(ChatColor.GREEN + " Red Spawn"
+ ChatColor.WHITE + " (/bn redspawn)");
} else {
sender.sendMessage(ChatColor.RED + " Red Spawn"
+ ChatColor.WHITE + " (/bn redspawn)");
}
if (pointSet(Waypoint.BLUE_SPAWN)) {
sender.sendMessage(ChatColor.GREEN + " Blue Spawn"
+ ChatColor.WHITE + " (/bn bluespawn)");
} else {
sender.sendMessage(ChatColor.RED + " Blue Spawn"
+ ChatColor.WHITE + " (/bn bluespawn)");
}
if (pointSet(Waypoint.SPECTATOR)) {
sender.sendMessage(ChatColor.GREEN + " Spectator"
+ ChatColor.WHITE + " (/bn spectator)");
} else {
sender.sendMessage(ChatColor.RED + " Spectator"
+ ChatColor.WHITE + " (/bn spectator)");
}
if (pointSet(Waypoint.EXIT)) {
sender.sendMessage(ChatColor.GREEN + " Exit"
+ ChatColor.WHITE + " (/bn exit)");
} else {
sender.sendMessage(ChatColor.RED + " Exit"
+ ChatColor.WHITE + " (/bn exit)");
}
sender.sendMessage(ChatColor.DARK_GRAY
+ " --------------------------------------- ");
}
else if (args[0].equalsIgnoreCase("join") && hasPerm(Perm.USER, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
if (isSetup() && !battleInProgress && !BattleUsersTeam.containsKey(player.getName())) {
battle.addPlayer(player);
} else if (!isSetup()) {
tellPlayer(player, Track.WAYPOINTS_UNSET);
} else if (battleInProgress) {
tellPlayer(player, Track.BATTLE_IN_PROGRESS);
} else if (BattleUsersTeam.containsKey(player.getName())) {
tellPlayer(player, Track.ALREADY_IN_TEAM);
}
}
else if ((args[0].equalsIgnoreCase("watch")) && hasPerm(Perm.USER, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
addSpectator(player, "command");
} else if (args[0].equalsIgnoreCase("leave") && hasPerm(Perm.USER, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
if (BattleUsersTeam.containsKey(player.getName())) {
battle.removePlayer(player, false, "has left the Battle.", "You have left the Battle.");
} else if (BattleSpectators.containsKey(player.getName())) {
removeSpectator(player);
} else {
tellPlayer(player, Track.NOT_IN_TEAM.msg);
}
}
else if (args[0].equalsIgnoreCase("kick") && hasPerm(Perm.MOD, sender)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + Track.SPECIFY_PLAYER.msg);
}
else if ((args[0].equalsIgnoreCase("kickall") || args[0].equalsIgnoreCase("endgame")) && hasPerm(Perm.MOD, sender)) {
battle.end();
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + Track.BATTLE_ENDED.msg);
}
else if (args[0].equalsIgnoreCase("redlounge") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "redlounge");
tellPlayer(player, Track.RED_LOUNGE_SET);
}
else if (args[0].equalsIgnoreCase("redspawn") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "redspawn");
tellPlayer(player, Track.RED_SPAWN_SET);
}
else if (args[0].equalsIgnoreCase("bluelounge") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "bluelounge");
tellPlayer(player, Track.BLUE_LOUNGE_SET);
}
else if (args[0].equalsIgnoreCase("bluespawn") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "bluespawn");
tellPlayer(player, Track.BLUE_SPAWN_SET);
}
else if (args[0].equalsIgnoreCase("spectator") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "spectator");
tellPlayer(player, Track.SPECTATOR_SET);
}
else if (args[0].equalsIgnoreCase("exit") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "exit");
tellPlayer(player, Track.EXIT_SET);
}
else if (args[0].equalsIgnoreCase("version")) {
PluginDescriptionFile pdfFile = getDescription();
String[] msgs = {
BNTag + "This server is currently using Battlenight Version " + pdfFile.getVersion() + ".",
"For more information about Battlenight and the features included in this version, please visit: ",
ChatColor.DARK_AQUA + pdfFile.getWebsite()
};
sender.sendMessage(msgs);
}
else if (args[0].equalsIgnoreCase("reload") && hasPerm(Perm.ADMIN, sender)) {
sender.sendMessage(BNTag + "Reloading config...");
try {
reloadConfigFiles();
sender.sendMessage(BNTag + ChatColor.GREEN + "Reloaded successfully.");
} catch (final Exception e) {
e.printStackTrace();
sender.sendMessage(BNTag + ChatColor.RED + "Reload failed.");
}
}
else {
sender.sendMessage(BNTag + ChatColor.RED + Track.INVALID_COMAND.msg);
}
}
if (args.length == 2) {
if (args[0].equalsIgnoreCase("kick") && hasPerm(Perm.MOD, sender)) {
Player badplayer = Bukkit.getPlayerExact(args[1]);
if (badplayer.isOnline()) {
if (BattleUsersTeam.containsKey(badplayer.getName())) {
battle.removePlayer(badplayer, false, "has been kicked from the current Battle.", "You have been kicked from the current Battle.");
} else {
sender.sendMessage(BNTag + ChatColor.RED + "Player: " + badplayer.getName() + " is not in the current Battle.");
}
} else {
sender.sendMessage(BNTag + ChatColor.RED + "Can't find user " + badplayer.getName() + ". No kick.");
}
}
}
if (args.length > 2) {
sender.sendMessage(BNTag + ChatColor.RED + Track.INVALID_COMAND.msg);
}
return true;
}
return false;
}
|
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if (commandLabel.equalsIgnoreCase("bn")) {
if (args.length < 1) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "Incorrect usage. Type '/bn help' to show the help menu.");
return true;
} else if (args[0].equalsIgnoreCase("set")) {
WaypointCommand cmd = new WaypointCommand(sender, args);
cmd.perform();
} else if (args.length == 1) {
if (args[0].equalsIgnoreCase("help")) {
if (hasPerm(Perm.ADMIN, sender)) {
sender.sendMessage(ChatColor.DARK_GRAY + " ---------- "
+ ChatColor.WHITE + "BattleNight Help Menu"
+ ChatColor.DARK_GRAY + " ---------- ");
sender.sendMessage(ChatColor.WHITE
+ " /bn help - Shows general help.");
sender.sendMessage(ChatColor.WHITE
+ " /bn waypoints - Shows set/unset waypoints.");
sender.sendMessage(ChatColor.WHITE
+ " /bn version - Shows the version of BattleNight in use.");
sender.sendMessage(ChatColor.WHITE
+ " /bn join - Join the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn leave - Leave the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn watch - Watch the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn kick [player] - Kick a player from the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn kickall - Kick all players in the Battle.");
sender.sendMessage(ChatColor.DARK_GRAY
+ " --------------------------------------- ");
} else if (hasPerm(Perm.USER, sender)) {
sender.sendMessage(ChatColor.DARK_GRAY + " ---------- "
+ ChatColor.WHITE + "BattleNight Help Menu"
+ ChatColor.DARK_GRAY + " ---------- ");
sender.sendMessage(ChatColor.WHITE
+ " /bn help - Shows general help.");
sender.sendMessage(ChatColor.WHITE
+ " /bn version - Shows the version of BattleNight in use.");
sender.sendMessage(ChatColor.WHITE
+ " /bn join - Join the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn leave - Leave the Battle.");
sender.sendMessage(ChatColor.WHITE
+ " /bn watch - Watch the Battle");
sender.sendMessage(ChatColor.DARK_GRAY
+ " --------------------------------------- ");
} else {
sender.sendMessage(BattleNight.BNTag + Track.NO_PERMISSION.msg);
}
}
else if (args[0].equalsIgnoreCase("waypoints") && hasPerm(Perm.ADMIN, sender)) {
sender.sendMessage(ChatColor.DARK_GRAY + " ---------- "
+ ChatColor.WHITE + "BattleNight Waypoints"
+ ChatColor.DARK_GRAY + " ---------- ");
sender.sendMessage(ChatColor.WHITE + " Setup points: "
+ numSetupPoints() + "/6");
if (pointSet(Waypoint.RED_LOUNGE)) {
sender.sendMessage(ChatColor.GREEN + " Red Lounge"
+ ChatColor.WHITE + " (/bn redlounge)");
} else {
sender.sendMessage(ChatColor.RED + " Red Lounge"
+ ChatColor.WHITE + " (/bn redlounge)");
}
if (pointSet(Waypoint.BLUE_LOUNGE)) {
sender.sendMessage(ChatColor.GREEN + " Blue Lounge"
+ ChatColor.WHITE + " (/bn bluelounge)");
} else {
sender.sendMessage(ChatColor.RED + " Blue Lounge"
+ ChatColor.WHITE + " (/bn bluelounge)");
}
if (pointSet(Waypoint.RED_SPAWN)) {
sender.sendMessage(ChatColor.GREEN + " Red Spawn"
+ ChatColor.WHITE + " (/bn redspawn)");
} else {
sender.sendMessage(ChatColor.RED + " Red Spawn"
+ ChatColor.WHITE + " (/bn redspawn)");
}
if (pointSet(Waypoint.BLUE_SPAWN)) {
sender.sendMessage(ChatColor.GREEN + " Blue Spawn"
+ ChatColor.WHITE + " (/bn bluespawn)");
} else {
sender.sendMessage(ChatColor.RED + " Blue Spawn"
+ ChatColor.WHITE + " (/bn bluespawn)");
}
if (pointSet(Waypoint.SPECTATOR)) {
sender.sendMessage(ChatColor.GREEN + " Spectator"
+ ChatColor.WHITE + " (/bn spectator)");
} else {
sender.sendMessage(ChatColor.RED + " Spectator"
+ ChatColor.WHITE + " (/bn spectator)");
}
if (pointSet(Waypoint.EXIT)) {
sender.sendMessage(ChatColor.GREEN + " Exit"
+ ChatColor.WHITE + " (/bn exit)");
} else {
sender.sendMessage(ChatColor.RED + " Exit"
+ ChatColor.WHITE + " (/bn exit)");
}
sender.sendMessage(ChatColor.DARK_GRAY
+ " --------------------------------------- ");
}
else if (args[0].equalsIgnoreCase("join") && hasPerm(Perm.USER, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
if (isSetup() && !battleInProgress && !BattleUsersTeam.containsKey(player.getName())) {
battle.addPlayer(player);
} else if (!isSetup()) {
tellPlayer(player, Track.WAYPOINTS_UNSET);
} else if (battleInProgress) {
tellPlayer(player, Track.BATTLE_IN_PROGRESS);
} else if (BattleUsersTeam.containsKey(player.getName())) {
tellPlayer(player, Track.ALREADY_IN_TEAM);
}
}
else if ((args[0].equalsIgnoreCase("watch")) && hasPerm(Perm.USER, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
addSpectator(player, "command");
} else if (args[0].equalsIgnoreCase("leave") && hasPerm(Perm.USER, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
if (BattleUsersTeam.containsKey(player.getName())) {
battle.removePlayer(player, false, "has left the Battle.", "You have left the Battle.");
} else if (BattleSpectators.containsKey(player.getName())) {
removeSpectator(player);
} else {
tellPlayer(player, Track.NOT_IN_TEAM.msg);
}
}
else if (args[0].equalsIgnoreCase("kick") && hasPerm(Perm.MOD, sender)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + Track.SPECIFY_PLAYER.msg);
}
else if ((args[0].equalsIgnoreCase("kickall") || args[0].equalsIgnoreCase("endgame")) && hasPerm(Perm.MOD, sender)) {
battle.end();
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + Track.BATTLE_ENDED.msg);
}
else if (args[0].equalsIgnoreCase("redlounge") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "redlounge");
tellPlayer(player, Track.RED_LOUNGE_SET);
}
else if (args[0].equalsIgnoreCase("redspawn") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "redspawn");
tellPlayer(player, Track.RED_SPAWN_SET);
}
else if (args[0].equalsIgnoreCase("bluelounge") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "bluelounge");
tellPlayer(player, Track.BLUE_LOUNGE_SET);
}
else if (args[0].equalsIgnoreCase("bluespawn") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "bluespawn");
tellPlayer(player, Track.BLUE_SPAWN_SET);
}
else if (args[0].equalsIgnoreCase("spectator") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BattleNight.BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "spectator");
tellPlayer(player, Track.SPECTATOR_SET);
}
else if (args[0].equalsIgnoreCase("exit") && hasPerm(Perm.ADMIN, sender)) {
// Player check
if (!(sender instanceof Player)) {
sender.sendMessage(BNTag + ChatColor.RED + "This command can only be run by a Player.");
return true;
}
Player player = (Player) sender;
setCoords(player, "exit");
tellPlayer(player, Track.EXIT_SET);
}
else if (args[0].equalsIgnoreCase("version")) {
PluginDescriptionFile pdfFile = getDescription();
String[] msgs = {
BNTag + "This server is currently using Battlenight Version " + pdfFile.getVersion() + ".",
ChatColor.WHITE + "For more information about Battlenight and the features included in this version, please visit: ",
ChatColor.DARK_AQUA + pdfFile.getWebsite()
};
sender.sendMessage(msgs);
}
else if (args[0].equalsIgnoreCase("reload") && hasPerm(Perm.ADMIN, sender)) {
sender.sendMessage(BNTag + "Reloading config...");
try {
reloadConfigFiles();
sender.sendMessage(BNTag + ChatColor.GREEN + "Reloaded successfully.");
} catch (final Exception e) {
e.printStackTrace();
sender.sendMessage(BNTag + ChatColor.RED + "Reload failed.");
}
}
else {
sender.sendMessage(BNTag + ChatColor.RED + Track.INVALID_COMAND.msg);
}
}
if (args.length == 2) {
if (args[0].equalsIgnoreCase("kick") && hasPerm(Perm.MOD, sender)) {
Player badplayer = Bukkit.getPlayerExact(args[1]);
if (badplayer.isOnline()) {
if (BattleUsersTeam.containsKey(badplayer.getName())) {
battle.removePlayer(badplayer, false, "has been kicked from the current Battle.", "You have been kicked from the current Battle.");
} else {
sender.sendMessage(BNTag + ChatColor.RED + "Player: " + badplayer.getName() + " is not in the current Battle.");
}
} else {
sender.sendMessage(BNTag + ChatColor.RED + "Can't find user " + badplayer.getName() + ". No kick.");
}
}
}
if (args.length > 2) {
sender.sendMessage(BNTag + ChatColor.RED + Track.INVALID_COMAND.msg);
}
return true;
}
return false;
}
|
diff --git a/MonacaFramework/src/mobi/monaca/framework/nativeui/component/ToolbarBackgroundDrawable.java b/MonacaFramework/src/mobi/monaca/framework/nativeui/component/ToolbarBackgroundDrawable.java
index 28f3943..d30e043 100644
--- a/MonacaFramework/src/mobi/monaca/framework/nativeui/component/ToolbarBackgroundDrawable.java
+++ b/MonacaFramework/src/mobi/monaca/framework/nativeui/component/ToolbarBackgroundDrawable.java
@@ -1,113 +1,111 @@
package mobi.monaca.framework.nativeui.component;
import android.graphics.Canvas;
import mobi.monaca.framework.nativeui.NonScaleBitmapDrawable;
import mobi.monaca.framework.psedo.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.NinePatch;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
public class ToolbarBackgroundDrawable extends Drawable {
protected Drawable drawable;
protected int alpha = 255;
protected ColorFilter colorFilter = null;
protected Context context;
public ToolbarBackgroundDrawable(Context context) {
super();
this.drawable = context.getResources().getDrawable(R.drawable.monaca_toolbar_bg);
this.context = context;
}
@Override
public void draw(Canvas canvas) {
Rect rect = drawable.getBounds();
if (rect.width() <= 0 || rect.height() <= 0) {
return;
}
Bitmap bitmap = Bitmap.createBitmap(rect.width(), rect.height(), Bitmap.Config.ARGB_8888);
if (colorFilter != null) {
drawable.setColorFilter(colorFilter);
}
drawable.draw(new Canvas(bitmap));
- Drawable filteredDrawable = new NonScaleBitmapDrawable(bitmap);
- filteredDrawable.setAlpha(alpha);
- filteredDrawable.draw(canvas);
- filteredDrawable = null;
+ canvas.drawBitmap(bitmap, 0, 0, new Paint());
+ canvas.drawColor((alpha & 0xff) << 24, PorterDuff.Mode.DST_IN);
bitmap.recycle();
}
@Override
public void setBounds(Rect bounds) {
drawable.setBounds(bounds);
super.setBounds(bounds);
invalidateSelf();
}
@Override
public void setBounds(int left, int top, int width, int height) {
drawable.setBounds(left, top, width, height);
super.setBounds(left, top, width, height);
invalidateSelf();
}
@Override
public int getIntrinsicHeight() {
return drawable.getIntrinsicHeight();
}
@Override
public int getIntrinsicWidth() {
return drawable.getIntrinsicWidth();
}
@Override
public int getMinimumHeight() {
return drawable.getMinimumHeight();
}
@Override
public int getMinimumWidth() {
return drawable.getMinimumWidth();
}
@Override
public boolean getPadding(Rect padding) {
return drawable.getPadding(padding);
}
@Override
public void setAlpha(int alpha) {
this.alpha = 0xff & alpha;
invalidateSelf();
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
this.colorFilter = colorFilter;
invalidateSelf();
}
@Override
public int getOpacity() {
return drawable.getOpacity();
}
}
| true | true |
public void draw(Canvas canvas) {
Rect rect = drawable.getBounds();
if (rect.width() <= 0 || rect.height() <= 0) {
return;
}
Bitmap bitmap = Bitmap.createBitmap(rect.width(), rect.height(), Bitmap.Config.ARGB_8888);
if (colorFilter != null) {
drawable.setColorFilter(colorFilter);
}
drawable.draw(new Canvas(bitmap));
Drawable filteredDrawable = new NonScaleBitmapDrawable(bitmap);
filteredDrawable.setAlpha(alpha);
filteredDrawable.draw(canvas);
filteredDrawable = null;
bitmap.recycle();
}
|
public void draw(Canvas canvas) {
Rect rect = drawable.getBounds();
if (rect.width() <= 0 || rect.height() <= 0) {
return;
}
Bitmap bitmap = Bitmap.createBitmap(rect.width(), rect.height(), Bitmap.Config.ARGB_8888);
if (colorFilter != null) {
drawable.setColorFilter(colorFilter);
}
drawable.draw(new Canvas(bitmap));
canvas.drawBitmap(bitmap, 0, 0, new Paint());
canvas.drawColor((alpha & 0xff) << 24, PorterDuff.Mode.DST_IN);
bitmap.recycle();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.