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/core/src/main/java/org/freud/core/iterator/OneShotNonThreadSafeIterable.java b/core/src/main/java/org/freud/core/iterator/OneShotNonThreadSafeIterable.java
index 09d1f54..0f6ed9e 100644
--- a/core/src/main/java/org/freud/core/iterator/OneShotNonThreadSafeIterable.java
+++ b/core/src/main/java/org/freud/core/iterator/OneShotNonThreadSafeIterable.java
@@ -1,29 +1,29 @@
package org.freud.core.iterator;
import java.util.Iterator;
public abstract class OneShotNonThreadSafeIterable<T> implements Iterable<T>, Iterator<T> {
private boolean hasNext = true;
@Override
public final Iterator<T> iterator() {
return this;
}
@Override
public final boolean hasNext() {
if (!hasNext) {
- throw new IllegalStateException("This iterator can only be iterated through once");
+ throw new IllegalStateException("This iterable can only be iterated through once");
}
hasNext = calculateHasNext();
return hasNext;
}
protected abstract boolean calculateHasNext();
@Override
public final void remove() {
throw new UnsupportedOperationException();
}
}
| true | true | public final boolean hasNext() {
if (!hasNext) {
throw new IllegalStateException("This iterator can only be iterated through once");
}
hasNext = calculateHasNext();
return hasNext;
}
| public final boolean hasNext() {
if (!hasNext) {
throw new IllegalStateException("This iterable can only be iterated through once");
}
hasNext = calculateHasNext();
return hasNext;
}
|
diff --git a/src/main/ed/appserver/templates/djang10/tagHandlers/CallTagHandler.java b/src/main/ed/appserver/templates/djang10/tagHandlers/CallTagHandler.java
index ff9de474a..6880c285f 100644
--- a/src/main/ed/appserver/templates/djang10/tagHandlers/CallTagHandler.java
+++ b/src/main/ed/appserver/templates/djang10/tagHandlers/CallTagHandler.java
@@ -1,48 +1,48 @@
package ed.appserver.templates.djang10.tagHandlers;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ed.appserver.templates.djang10.Node;
import ed.appserver.templates.djang10.Parser;
import ed.appserver.templates.djang10.TemplateException;
import ed.appserver.templates.djang10.Parser.Token;
import ed.appserver.templates.djang10.generator.JSWriter;
import ed.js.JSFunction;
public class CallTagHandler implements TagHandler {
public static final String EVAL = "eval";
public Node compile(Parser parser, String command, Token token) throws TemplateException {
- Pattern pattern = Pattern.compile("^\\s*\\S+\\s+(\\S+)(?:\\s+(allowGlobal))?\\s*$");
+ Pattern pattern = Pattern.compile("^\\s*\\S+\\s+(.+?)(?:\\s+(allowGlobal))?\\s*$");
Matcher matcher = pattern.matcher(token.contents);
if(!matcher.find())
throw new TemplateException("Invlaid syntax");
String methodCall = matcher.group(1);
boolean allowGlobal = matcher.group(2) != null;
String compiledExpr = VariableTagHandler.compileExpression(methodCall);
return new CallNode(token, compiledExpr);
}
public Map<String, JSFunction> getHelpers() {
return new HashMap<String, JSFunction>();
}
private static class CallNode extends Node {
private final String compiledExpr;
public CallNode(Token token, String compiledExpr) {
super(token);
this.compiledExpr = compiledExpr;
}
@Override
public void getRenderJSFn(JSWriter preamble, JSWriter buffer) throws TemplateException {
buffer.append(startLine, compiledExpr + ";\n");
}
}
}
| true | true | public Node compile(Parser parser, String command, Token token) throws TemplateException {
Pattern pattern = Pattern.compile("^\\s*\\S+\\s+(\\S+)(?:\\s+(allowGlobal))?\\s*$");
Matcher matcher = pattern.matcher(token.contents);
if(!matcher.find())
throw new TemplateException("Invlaid syntax");
String methodCall = matcher.group(1);
boolean allowGlobal = matcher.group(2) != null;
String compiledExpr = VariableTagHandler.compileExpression(methodCall);
return new CallNode(token, compiledExpr);
}
| public Node compile(Parser parser, String command, Token token) throws TemplateException {
Pattern pattern = Pattern.compile("^\\s*\\S+\\s+(.+?)(?:\\s+(allowGlobal))?\\s*$");
Matcher matcher = pattern.matcher(token.contents);
if(!matcher.find())
throw new TemplateException("Invlaid syntax");
String methodCall = matcher.group(1);
boolean allowGlobal = matcher.group(2) != null;
String compiledExpr = VariableTagHandler.compileExpression(methodCall);
return new CallNode(token, compiledExpr);
}
|
diff --git a/src/java/org/apache/hadoop/hbase/zookeeper/HQuorumPeer.java b/src/java/org/apache/hadoop/hbase/zookeeper/HQuorumPeer.java
index 226e20f66..c7cc69b15 100644
--- a/src/java/org/apache/hadoop/hbase/zookeeper/HQuorumPeer.java
+++ b/src/java/org/apache/hadoop/hbase/zookeeper/HQuorumPeer.java
@@ -1,265 +1,265 @@
/**
* Copyright 2009 The Apache Software Foundation
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.zookeeper;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.net.DNS;
import org.apache.hadoop.util.StringUtils;
import org.apache.zookeeper.server.ServerConfig;
import org.apache.zookeeper.server.ZooKeeperServerMain;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.apache.zookeeper.server.quorum.QuorumPeerMain;
/**
* HBase's version of ZooKeeper's QuorumPeer. When HBase is set to manage
* ZooKeeper, this class is used to start up QuorumPeer instances. By doing
* things in here rather than directly calling to ZooKeeper, we have more
* control over the process. Currently, this class allows us to parse the
* zoo.cfg and inject variables from HBase's site.xml configuration in.
*/
public class HQuorumPeer implements HConstants {
private static final Log LOG = LogFactory.getLog(HQuorumPeer.class);
private static final String VARIABLE_START = "${";
private static final int VARIABLE_START_LENGTH = VARIABLE_START.length();
private static final String VARIABLE_END = "}";
private static final int VARIABLE_END_LENGTH = VARIABLE_END.length();
private static final String ZK_CFG_PROPERTY = "hbase.zookeeper.property.";
private static final int ZK_CFG_PROPERTY_SIZE = ZK_CFG_PROPERTY.length();
/**
* Parse ZooKeeper configuration from HBase XML config and run a QuorumPeer.
* @param args String[] of command line arguments. Not used.
*/
public static void main(String[] args) {
HBaseConfiguration conf = new HBaseConfiguration();
try {
Properties zkProperties = makeZKProps(conf);
writeMyID(zkProperties);
QuorumPeerConfig zkConfig = new QuorumPeerConfig();
zkConfig.parseProperties(zkProperties);
runZKServer(zkConfig);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
private static void runZKServer(QuorumPeerConfig zkConfig) throws UnknownHostException, IOException {
if (zkConfig.isDistributed()) {
QuorumPeerMain qp = new QuorumPeerMain();
qp.runFromConfig(zkConfig);
} else {
ZooKeeperServerMain zk = new ZooKeeperServerMain();
ServerConfig serverConfig = new ServerConfig();
serverConfig.readFrom(zkConfig);
zk.runFromConfig(serverConfig);
}
}
private static boolean addressIsLocalHost(String address) {
return address.equals("localhost") || address.equals("127.0.0.1");
}
private static boolean hostEquals(String addrA, String addrB) {
if (addrA.contains(".") && addrB.contains(".")) {
return addrA.equals(addrB);
}
String hostA = StringUtils.simpleHostname(addrA);
String hostB = StringUtils.simpleHostname(addrB);
return hostA.equals(hostB);
}
private static void writeMyID(Properties properties) throws UnknownHostException, IOException {
HBaseConfiguration conf = new HBaseConfiguration();
String myAddress = DNS.getDefaultHost(
conf.get("hbase.zookeeper.dns.interface","default"),
conf.get("hbase.zookeeper.dns.nameserver","default"));
long myId = -1;
for (Entry<Object, Object> entry : properties.entrySet()) {
String key = entry.getKey().toString().trim();
String value = entry.getValue().toString().trim();
if (key.startsWith("server.")) {
int dot = key.indexOf('.');
long id = Long.parseLong(key.substring(dot + 1));
String[] parts = value.split(":");
String address = parts[0];
if (addressIsLocalHost(address) || hostEquals(myAddress, address)) {
LOG.debug("found my address: " + myAddress + ", in list: " + address +
", setting myId to " + id);
myId = id;
break;
}
}
}
if (myId == -1) {
throw new IOException("Could not find my address: " + myAddress +
" in list of ZooKeeper quorum servers");
}
String dataDirStr = properties.get("dataDir").toString().trim();
File dataDir = new File(dataDirStr);
if (!dataDir.isDirectory()) {
if (!dataDir.mkdirs()) {
throw new IOException("Unable to create data dir " + dataDir);
}
}
File myIdFile = new File(dataDir, "myid");
PrintWriter w = new PrintWriter(myIdFile);
w.println(myId);
w.close();
}
/**
* Make a Properties object holding ZooKeeper config equivalent to zoo.cfg.
* If there is a zoo.cfg in the classpath, simply read it in. Otherwise parse
* the corresponding config options from the HBase XML configs and generate
* the appropriate ZooKeeper properties.
* @param conf HBaseConfiguration to read from.
* @return Properties holding mappings representing ZooKeeper zoo.cfg file.
*/
public static Properties makeZKProps(HBaseConfiguration conf) {
// First check if there is a zoo.cfg in the CLASSPATH. If so, simply read
// it and grab its configuration properties.
ClassLoader cl = HQuorumPeer.class.getClassLoader();
InputStream inputStream = cl.getResourceAsStream(ZOOKEEPER_CONFIG_NAME);
if (inputStream != null) {
try {
return parseZooCfg(conf, inputStream);
} catch (IOException e) {
LOG.warn("Cannot read " + ZOOKEEPER_CONFIG_NAME +
", loading from XML files", e);
}
}
// Otherwise, use the configuration options from HBase's XML files.
Properties zkProperties = new Properties();
// Directly map all of the hbase.zookeeper.property.KEY properties.
for (Entry<String, String> entry : conf) {
String key = entry.getKey();
if (key.startsWith(ZK_CFG_PROPERTY)) {
String zkKey = key.substring(ZK_CFG_PROPERTY_SIZE);
String value = entry.getValue();
// If the value has variables substitutions, need to do a get.
if (value.contains(VARIABLE_START)) {
value = conf.get(key);
}
zkProperties.put(zkKey, value);
}
}
// Create the server.X properties.
int peerPort = conf.getInt("hbase.zookeeper.peerport", 2888);
int leaderPort = conf.getInt("hbase.zookeeper.leaderport", 3888);
String[] serverHosts = conf.getStrings(ZOOKEEPER_QUORUM, "localhost");
for (int i = 0; i < serverHosts.length; ++i) {
String serverHost = serverHosts[i];
String address = serverHost + ":" + peerPort + ":" + leaderPort;
String key = "server." + i;
zkProperties.put(key, address);
}
return zkProperties;
}
/**
* Parse ZooKeeper's zoo.cfg, injecting HBase Configuration variables in.
* This method is used for testing so we can pass our own InputStream.
* @param conf HBaseConfiguration to use for injecting variables.
* @param inputStream InputStream to read from.
* @return Properties parsed from config stream with variables substituted.
* @throws IOException if anything goes wrong parsing config
*/
public static Properties parseZooCfg(HBaseConfiguration conf,
InputStream inputStream) throws IOException {
Properties properties = new Properties();
try {
properties.load(inputStream);
} catch (IOException e) {
String msg = "fail to read properties from " + ZOOKEEPER_CONFIG_NAME;
LOG.fatal(msg);
- throw new IOException(msg);
+ throw new IOException(msg, e);
}
for (Entry<Object, Object> entry : properties.entrySet()) {
String value = entry.getValue().toString().trim();
String key = entry.getKey().toString().trim();
StringBuilder newValue = new StringBuilder();
int varStart = value.indexOf(VARIABLE_START);
int varEnd = 0;
while (varStart != -1) {
varEnd = value.indexOf(VARIABLE_END, varStart);
if (varEnd == -1) {
String msg = "variable at " + varStart + " has no end marker";
LOG.fatal(msg);
throw new IOException(msg);
}
String variable = value.substring(varStart + VARIABLE_START_LENGTH, varEnd);
String substituteValue = System.getProperty(variable);
if (substituteValue == null) {
substituteValue = conf.get(variable);
}
if (substituteValue == null) {
String msg = "variable " + variable + " not set in system property "
+ "or hbase configs";
LOG.fatal(msg);
throw new IOException(msg);
}
newValue.append(substituteValue);
varEnd += VARIABLE_END_LENGTH;
varStart = value.indexOf(VARIABLE_START, varEnd);
}
// Special case for 'hbase.cluster.distributed' property being 'true'
if (key.startsWith("server.")) {
if(conf.get(CLUSTER_DISTRIBUTED).equals(CLUSTER_IS_DISTRIBUTED) &&
value.startsWith("localhost")) {
String msg = "The server in zoo.cfg cannot be set to localhost " +
"in a fully-distributed setup because it won't be reachable. " +
"See \"Getting Started\" for more information.";
LOG.fatal(msg);
throw new IOException(msg);
}
}
newValue.append(value.substring(varEnd));
properties.setProperty(key, newValue.toString());
}
return properties;
}
}
| true | true | public static Properties parseZooCfg(HBaseConfiguration conf,
InputStream inputStream) throws IOException {
Properties properties = new Properties();
try {
properties.load(inputStream);
} catch (IOException e) {
String msg = "fail to read properties from " + ZOOKEEPER_CONFIG_NAME;
LOG.fatal(msg);
throw new IOException(msg);
}
for (Entry<Object, Object> entry : properties.entrySet()) {
String value = entry.getValue().toString().trim();
String key = entry.getKey().toString().trim();
StringBuilder newValue = new StringBuilder();
int varStart = value.indexOf(VARIABLE_START);
int varEnd = 0;
while (varStart != -1) {
varEnd = value.indexOf(VARIABLE_END, varStart);
if (varEnd == -1) {
String msg = "variable at " + varStart + " has no end marker";
LOG.fatal(msg);
throw new IOException(msg);
}
String variable = value.substring(varStart + VARIABLE_START_LENGTH, varEnd);
String substituteValue = System.getProperty(variable);
if (substituteValue == null) {
substituteValue = conf.get(variable);
}
if (substituteValue == null) {
String msg = "variable " + variable + " not set in system property "
+ "or hbase configs";
LOG.fatal(msg);
throw new IOException(msg);
}
newValue.append(substituteValue);
varEnd += VARIABLE_END_LENGTH;
varStart = value.indexOf(VARIABLE_START, varEnd);
}
// Special case for 'hbase.cluster.distributed' property being 'true'
if (key.startsWith("server.")) {
if(conf.get(CLUSTER_DISTRIBUTED).equals(CLUSTER_IS_DISTRIBUTED) &&
value.startsWith("localhost")) {
String msg = "The server in zoo.cfg cannot be set to localhost " +
"in a fully-distributed setup because it won't be reachable. " +
"See \"Getting Started\" for more information.";
LOG.fatal(msg);
throw new IOException(msg);
}
}
newValue.append(value.substring(varEnd));
properties.setProperty(key, newValue.toString());
}
return properties;
}
| public static Properties parseZooCfg(HBaseConfiguration conf,
InputStream inputStream) throws IOException {
Properties properties = new Properties();
try {
properties.load(inputStream);
} catch (IOException e) {
String msg = "fail to read properties from " + ZOOKEEPER_CONFIG_NAME;
LOG.fatal(msg);
throw new IOException(msg, e);
}
for (Entry<Object, Object> entry : properties.entrySet()) {
String value = entry.getValue().toString().trim();
String key = entry.getKey().toString().trim();
StringBuilder newValue = new StringBuilder();
int varStart = value.indexOf(VARIABLE_START);
int varEnd = 0;
while (varStart != -1) {
varEnd = value.indexOf(VARIABLE_END, varStart);
if (varEnd == -1) {
String msg = "variable at " + varStart + " has no end marker";
LOG.fatal(msg);
throw new IOException(msg);
}
String variable = value.substring(varStart + VARIABLE_START_LENGTH, varEnd);
String substituteValue = System.getProperty(variable);
if (substituteValue == null) {
substituteValue = conf.get(variable);
}
if (substituteValue == null) {
String msg = "variable " + variable + " not set in system property "
+ "or hbase configs";
LOG.fatal(msg);
throw new IOException(msg);
}
newValue.append(substituteValue);
varEnd += VARIABLE_END_LENGTH;
varStart = value.indexOf(VARIABLE_START, varEnd);
}
// Special case for 'hbase.cluster.distributed' property being 'true'
if (key.startsWith("server.")) {
if(conf.get(CLUSTER_DISTRIBUTED).equals(CLUSTER_IS_DISTRIBUTED) &&
value.startsWith("localhost")) {
String msg = "The server in zoo.cfg cannot be set to localhost " +
"in a fully-distributed setup because it won't be reachable. " +
"See \"Getting Started\" for more information.";
LOG.fatal(msg);
throw new IOException(msg);
}
}
newValue.append(value.substring(varEnd));
properties.setProperty(key, newValue.toString());
}
return properties;
}
|
diff --git a/client/src/remuco/util/Tools.java b/client/src/remuco/util/Tools.java
index 4e1ba7b..c096f9d 100644
--- a/client/src/remuco/util/Tools.java
+++ b/client/src/remuco/util/Tools.java
@@ -1,223 +1,223 @@
/*
* Remuco - A remote control system for media players.
* Copyright (C) 2006-2009 Oben Sonne <[email protected]>
*
* This file is part of Remuco.
*
* Remuco is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Remuco 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 Remuco. If not, see <http://www.gnu.org/licenses/>.
*
*/
package remuco.util;
import java.util.Vector;
/**
* Miscellaneous J2ME specific utility constants and methods.
*
* @author Oben Sonne
*
*/
public final class Tools {
/**
* Compare two byte arrays.
*
* @param ba1
* (may be null)
* @param ba2
* (may be null)
* @return <code>true</code> if the arrays equal, <code>false</code>
* otherwise
*/
public static boolean compare(byte[] ba1, byte[] ba2) {
if (ba1 == ba2)
return true;
if (ba1 == null || ba2 == null)
return false;
if (ba1.length != ba2.length)
return false;
for (int i = 0; i < ba2.length; i++) {
if (ba1[i] != ba2[i]) {
return false;
}
}
return true;
}
/**
* Compare two integer arrays.
*
* @param ia1
* (may be null)
* @param ia2
* (may be null)
* @return <code>true</code> if the arrays equal, <code>false</code>
* otherwise
*/
public static boolean compare(int[] ia1, int[] ia2) {
if (ia1 == ia2)
return true;
if (ia1 == null || ia2 == null)
return false;
if (ia1.length != ia2.length)
return false;
for (int i = 0; i < ia1.length; i++) {
if (ia1[i] != ia2[i])
return false;
}
return true;
}
/**
* Compare two string arrays.
*
* @param sa1
* (may be null)
* @param sa2
* (may be null)
* @return <code>true</code> if the arrays equal, <code>false</code>
* otherwise
*/
public static boolean compare(String[] sa1, String[] sa2) {
if (sa1 == sa2)
return true;
if (sa1 == null || sa2 == null)
return false;
if (sa1.length != sa2.length)
return false;
for (int i = 0; i < sa1.length; i++) {
if (!sa1[i].equals(sa2[i]))
return false;
}
return true;
}
/**
* Compare two vectors.
*
* @param v1
* (may be null)
* @param v2
* (may be null)
* @return <code>true</code> if the vectors equal, <code>false</code>
* otherwise
*/
public static boolean compare(Vector v1, Vector v2) {
if (v1 == v2)
return true;
if (v1 == null || v2 == null)
return false;
if (v1.size() != v2.size())
return false;
for (int i = 0; i < v1.size(); i++) {
if (!v1.elementAt(i).equals(v2.elementAt(i)))
return false;
}
return true;
}
/** Format a time in seconds to something like 'mm:ss'. */
public static String formatTime(int seconds) {
final StringBuffer sb = new StringBuffer();
if (seconds < 0) {
return "";
}
final int s = seconds % 60;
sb.append((int) (seconds / 60)).append(":");
sb.append(s < 10 ? "0" : "").append(s);
return sb.toString();
}
/**
* Get the first index of an object within an object array. Object equality
* is checked by {@link Object#equals(Object)}.
*
* @param array
* @param element
* @return the index number or -1 if <i>element</i> is not contained within
* <i>array</i>
*/
public static int getIndex(Object array[], Object element) {
for (int i = 0; i < array.length; i++) {
if (element.equals(array[i])) {
return i;
}
}
return 1;
}
/**
* Sleep a while. {@link InterruptedException} gets caught but sleeping
* won't be continued.
*
* @param ms
*/
public static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
// e.printStackTrace();
}
}
/**
* Splits a string into a string array.
*
* @param s
* @param splitter
* @return
*/
public static String[] splitString(String s, char splitter, boolean trim) {
int first, last, sal;
first = s.indexOf(splitter);
sal = 1;
while (first >= 0) {
sal++;
first = s.indexOf(splitter, first + 1);
}
final String ret[] = new String[sal];
first = 0;
last = s.indexOf(splitter);
for (int i = 0; i < sal; i++) {
if ((last = s.indexOf(splitter, first)) < 0) {
last = s.length();
}
ret[i] = s.substring(first, last);
if (trim) {
- ret[i].trim();
+ ret[i] = ret[i].trim();
}
first = last + 1;
}
return ret;
}
}
| true | true | public static String[] splitString(String s, char splitter, boolean trim) {
int first, last, sal;
first = s.indexOf(splitter);
sal = 1;
while (first >= 0) {
sal++;
first = s.indexOf(splitter, first + 1);
}
final String ret[] = new String[sal];
first = 0;
last = s.indexOf(splitter);
for (int i = 0; i < sal; i++) {
if ((last = s.indexOf(splitter, first)) < 0) {
last = s.length();
}
ret[i] = s.substring(first, last);
if (trim) {
ret[i].trim();
}
first = last + 1;
}
return ret;
}
| public static String[] splitString(String s, char splitter, boolean trim) {
int first, last, sal;
first = s.indexOf(splitter);
sal = 1;
while (first >= 0) {
sal++;
first = s.indexOf(splitter, first + 1);
}
final String ret[] = new String[sal];
first = 0;
last = s.indexOf(splitter);
for (int i = 0; i < sal; i++) {
if ((last = s.indexOf(splitter, first)) < 0) {
last = s.length();
}
ret[i] = s.substring(first, last);
if (trim) {
ret[i] = ret[i].trim();
}
first = last + 1;
}
return ret;
}
|
diff --git a/patientview-parent/patientview/src/main/java/org/patientview/service/impl/PatientManagerImpl.java b/patientview-parent/patientview/src/main/java/org/patientview/service/impl/PatientManagerImpl.java
index d761ccbe..65b9da33 100644
--- a/patientview-parent/patientview/src/main/java/org/patientview/service/impl/PatientManagerImpl.java
+++ b/patientview-parent/patientview/src/main/java/org/patientview/service/impl/PatientManagerImpl.java
@@ -1,177 +1,177 @@
/*
* PatientView
*
* Copyright (c) Worth Solutions Limited 2004-2013
*
* This file is part of PatientView.
*
* PatientView is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
* PatientView 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 PatientView in a file
* titled COPYING. If not, see <http://www.gnu.org/licenses/>.
*
* @package PatientView
* @link http://www.patientview.org
* @author PatientView <[email protected]>
* @copyright Copyright (c) 2004-2013, Worth Solutions Limited
* @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
*/
package org.patientview.service.impl;
import org.patientview.model.Patient;
import org.patientview.patientview.PatientDetails;
import org.patientview.patientview.logging.AddLog;
import org.patientview.model.Unit;
import org.patientview.patientview.model.UserMapping;
import org.patientview.patientview.uktransplant.UktUtils;
import org.patientview.repository.PatientDao;
import org.patientview.service.DiagnosisManager;
import org.patientview.service.EdtaCodeManager;
import org.patientview.service.LetterManager;
import org.patientview.service.MedicineManager;
import org.patientview.service.PatientManager;
import org.patientview.service.SecurityUserManager;
import org.patientview.service.TestResultManager;
import org.patientview.service.UnitManager;
import org.patientview.service.UserManager;
import org.patientview.utils.LegacySpringUtils;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
@Service(value = "patientManager")
public class PatientManagerImpl implements PatientManager {
@Inject
private PatientDao patientDao;
@Inject
private SecurityUserManager securityUserManager;
@Inject
private UserManager userManager;
@Inject
private UnitManager unitManager;
@Inject
private EdtaCodeManager edtaCodeManager;
@Inject
private DiagnosisManager diagnosisManager;
@Inject
private TestResultManager testResultManager;
@Inject
private LetterManager letterManager;
@Inject
private MedicineManager medicineManager;
@Override
public Patient get(Long id) {
return patientDao.get(id);
}
@Override
public Patient get(String nhsno, String unitcode) {
return patientDao.get(nhsno, unitcode);
}
@Override
public void save(Patient patient) {
patientDao.save(patient);
}
@Override
public void delete(String nhsno, String unitcode) {
patientDao.delete(nhsno, unitcode);
}
@Override
public void removePatientFromSystem(String nhsno, String unitcode) {
// remove all the patiens content
testResultManager.deleteTestResults(nhsno, unitcode);
letterManager.delete(nhsno, unitcode);
medicineManager.delete(nhsno, unitcode);
diagnosisManager.deleteOtherDiagnoses(nhsno, unitcode);
// finally remove the patient
delete(nhsno, unitcode);
}
@Override
public List<Patient> get(String unitCode) {
return patientDao.get(unitCode);
}
@Override
public List getUnitPatientsWithTreatment(String unitcode, String nhsno, String name, boolean showgps) {
return patientDao.getUnitPatientsWithTreatmentDao(unitcode, nhsno, name, showgps,
securityUserManager.getLoggedInSpecialty());
}
@Override
public List getAllUnitPatientsWithTreatment(String nhsno, String name, boolean showgps) {
return patientDao.getAllUnitPatientsWithTreatmentDao(nhsno, name, showgps,
securityUserManager.getLoggedInSpecialty());
}
@Override
public List getUnitPatientsAllWithTreatmentDao(String unitcode) {
return patientDao.getUnitPatientsAllWithTreatmentDao(unitcode, securityUserManager.getLoggedInSpecialty());
}
@Override
public List<Patient> getUktPatients() {
return patientDao.getUktPatients();
}
@Override
public List<PatientDetails> getPatientDetails(String username) {
List<UserMapping> userMappings = userManager.getUserMappings(username);
List<PatientDetails> patientDetails = new ArrayList<PatientDetails>();
for (UserMapping userMapping : userMappings) {
String unitcode = userMapping.getUnitcode();
- if (!securityUserManager.userHasReadAccessToUnit(unitcode)) {
- continue;
- }
+ //todo so by the fact that in the past the original patient record will have a unitcode
+ //todo stamped with a mapping that is in the usermapping table when this approach should
+ //todo work. However the exists statement needs to be used on the Patient get method
Patient patient = get(userMapping.getNhsno(), unitcode);
Unit unit = unitManager.get(unitcode);
if (patient != null && unit != null) {
PatientDetails patientDetail = new PatientDetails();
patientDetail.setPatient(patient);
patientDetail.setUnit(unit);
patientDetail.setEdtaDiagnosis(edtaCodeManager.getEdtaCode(patient.getDiagnosis()));
patientDetail.setEdtaTreatment(edtaCodeManager.getEdtaCode(patient.getTreatment()));
patientDetail.setOtherDiagnoses(diagnosisManager.getOtherDiagnoses(patient.getNhsno(),
patient.getUnitcode()));
// TODO: dont really know bout this UktUtils ?
patientDetail.setUktStatus(UktUtils.retreiveUktStatus(userMapping.getNhsno()));
patientDetails.add(patientDetail);
AddLog.addLog(LegacySpringUtils.getSecurityUserManager().getLoggedInUsername(),
AddLog.PATIENT_VIEW, "", patient.getNhsno(),
patient.getUnitcode(), "");
}
}
return patientDetails;
}
}
| true | true | public List<PatientDetails> getPatientDetails(String username) {
List<UserMapping> userMappings = userManager.getUserMappings(username);
List<PatientDetails> patientDetails = new ArrayList<PatientDetails>();
for (UserMapping userMapping : userMappings) {
String unitcode = userMapping.getUnitcode();
if (!securityUserManager.userHasReadAccessToUnit(unitcode)) {
continue;
}
Patient patient = get(userMapping.getNhsno(), unitcode);
Unit unit = unitManager.get(unitcode);
if (patient != null && unit != null) {
PatientDetails patientDetail = new PatientDetails();
patientDetail.setPatient(patient);
patientDetail.setUnit(unit);
patientDetail.setEdtaDiagnosis(edtaCodeManager.getEdtaCode(patient.getDiagnosis()));
patientDetail.setEdtaTreatment(edtaCodeManager.getEdtaCode(patient.getTreatment()));
patientDetail.setOtherDiagnoses(diagnosisManager.getOtherDiagnoses(patient.getNhsno(),
patient.getUnitcode()));
// TODO: dont really know bout this UktUtils ?
patientDetail.setUktStatus(UktUtils.retreiveUktStatus(userMapping.getNhsno()));
patientDetails.add(patientDetail);
AddLog.addLog(LegacySpringUtils.getSecurityUserManager().getLoggedInUsername(),
AddLog.PATIENT_VIEW, "", patient.getNhsno(),
patient.getUnitcode(), "");
}
}
return patientDetails;
}
| public List<PatientDetails> getPatientDetails(String username) {
List<UserMapping> userMappings = userManager.getUserMappings(username);
List<PatientDetails> patientDetails = new ArrayList<PatientDetails>();
for (UserMapping userMapping : userMappings) {
String unitcode = userMapping.getUnitcode();
//todo so by the fact that in the past the original patient record will have a unitcode
//todo stamped with a mapping that is in the usermapping table when this approach should
//todo work. However the exists statement needs to be used on the Patient get method
Patient patient = get(userMapping.getNhsno(), unitcode);
Unit unit = unitManager.get(unitcode);
if (patient != null && unit != null) {
PatientDetails patientDetail = new PatientDetails();
patientDetail.setPatient(patient);
patientDetail.setUnit(unit);
patientDetail.setEdtaDiagnosis(edtaCodeManager.getEdtaCode(patient.getDiagnosis()));
patientDetail.setEdtaTreatment(edtaCodeManager.getEdtaCode(patient.getTreatment()));
patientDetail.setOtherDiagnoses(diagnosisManager.getOtherDiagnoses(patient.getNhsno(),
patient.getUnitcode()));
// TODO: dont really know bout this UktUtils ?
patientDetail.setUktStatus(UktUtils.retreiveUktStatus(userMapping.getNhsno()));
patientDetails.add(patientDetail);
AddLog.addLog(LegacySpringUtils.getSecurityUserManager().getLoggedInUsername(),
AddLog.PATIENT_VIEW, "", patient.getNhsno(),
patient.getUnitcode(), "");
}
}
return patientDetails;
}
|
diff --git a/jelly-tags/jsl/src/java/org/apache/commons/jelly/tags/jsl/ApplyTemplatesTag.java b/jelly-tags/jsl/src/java/org/apache/commons/jelly/tags/jsl/ApplyTemplatesTag.java
index f52a446c..7c56cda4 100644
--- a/jelly-tags/jsl/src/java/org/apache/commons/jelly/tags/jsl/ApplyTemplatesTag.java
+++ b/jelly-tags/jsl/src/java/org/apache/commons/jelly/tags/jsl/ApplyTemplatesTag.java
@@ -1,96 +1,96 @@
/*
* Copyright 2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.jelly.tags.jsl;
import org.apache.commons.jelly.JellyTagException;
import org.apache.commons.jelly.TagSupport;
import org.apache.commons.jelly.XMLOutput;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.rule.Stylesheet;
import org.jaxen.XPath;
/**
* Implements the apply templates function in the stylesheet, similar to the XSLT equivalent.
* a JSP include.
*
* @author <a href="mailto:[email protected]">James Strachan</a>
* @version $Revision: 1.8 $
*/
public class ApplyTemplatesTag extends TagSupport {
/** The Log to which logging calls will be made. */
private Log log = LogFactory.getLog(ApplyTemplatesTag.class);
/** Holds value of property mode. */
private String mode;
/** Holds the XPath object */
private XPath select;
public ApplyTemplatesTag() {
}
// Tag interface
//-------------------------------------------------------------------------
/** By default just evaluate the body */
public void doTag(XMLOutput output) throws JellyTagException {
StylesheetTag tag = (StylesheetTag) findAncestorWithClass( StylesheetTag.class );
if (tag == null) {
throw new JellyTagException(
"<applyTemplates> tag must be inside a <stylesheet> tag"
);
}
Stylesheet stylesheet = tag.getStylesheet();
XMLOutput oldOutput = tag.getStylesheetOutput();
tag.setStylesheetOutput(output);
Object source = tag.getXPathSource();
// for some reason, these DOM4J methods only throw Exception
try {
if ( select != null ) {
- stylesheet.applyTemplates( source, select );
+ stylesheet.applyTemplates( source, select, mode );
}
else {
- stylesheet.applyTemplates( source );
+ stylesheet.applyTemplates( source, mode );
}
}
catch (Exception e) {
throw new JellyTagException(e);
}
tag.setStylesheetOutput(oldOutput);
// #### should support MODE!!!
}
// Properties
//-------------------------------------------------------------------------
public void setSelect( XPath select ) {
this.select = select;
}
/** Sets the mode.
* @param mode New value of property mode.
*/
public void setMode(String mode) {
this.mode = mode;
}
}
| false | true | public void doTag(XMLOutput output) throws JellyTagException {
StylesheetTag tag = (StylesheetTag) findAncestorWithClass( StylesheetTag.class );
if (tag == null) {
throw new JellyTagException(
"<applyTemplates> tag must be inside a <stylesheet> tag"
);
}
Stylesheet stylesheet = tag.getStylesheet();
XMLOutput oldOutput = tag.getStylesheetOutput();
tag.setStylesheetOutput(output);
Object source = tag.getXPathSource();
// for some reason, these DOM4J methods only throw Exception
try {
if ( select != null ) {
stylesheet.applyTemplates( source, select );
}
else {
stylesheet.applyTemplates( source );
}
}
catch (Exception e) {
throw new JellyTagException(e);
}
tag.setStylesheetOutput(oldOutput);
// #### should support MODE!!!
}
| public void doTag(XMLOutput output) throws JellyTagException {
StylesheetTag tag = (StylesheetTag) findAncestorWithClass( StylesheetTag.class );
if (tag == null) {
throw new JellyTagException(
"<applyTemplates> tag must be inside a <stylesheet> tag"
);
}
Stylesheet stylesheet = tag.getStylesheet();
XMLOutput oldOutput = tag.getStylesheetOutput();
tag.setStylesheetOutput(output);
Object source = tag.getXPathSource();
// for some reason, these DOM4J methods only throw Exception
try {
if ( select != null ) {
stylesheet.applyTemplates( source, select, mode );
}
else {
stylesheet.applyTemplates( source, mode );
}
}
catch (Exception e) {
throw new JellyTagException(e);
}
tag.setStylesheetOutput(oldOutput);
// #### should support MODE!!!
}
|
diff --git a/src/org/smerty/cache/ImageCache.java b/src/org/smerty/cache/ImageCache.java
index 5ac4e8c..571f1bf 100644
--- a/src/org/smerty/cache/ImageCache.java
+++ b/src/org/smerty/cache/ImageCache.java
@@ -1,139 +1,121 @@
package org.smerty.cache;
import java.io.File;
import java.util.ArrayList;
import org.smerty.zooborns.ZooBorns;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.util.Log;
public class ImageCache {
private ZooBorns mContext;
public ArrayList<CachedImage> images;
private AsyncTask<ImageCache, Integer, ImageCache> task;
public ImageCache(ZooBorns c) {
super();
this.mContext = c;
this.images = new ArrayList<CachedImage>();
}
public boolean add(String url) {
return this.images.add(new CachedImage(url));
}
public void startDownloading() {
if (this.task == null) {
Log.d("startDownloading", "task was null, calling execute");
task = new DownloadFilesTask().execute(this);
} else {
Status s = this.task.getStatus();
if (s == Status.FINISHED) {
// todo: something
Log.d("startDownloading",
"task wasn't null, status finished, calling execute");
task = new DownloadFilesTask().execute(this);
} else if (s == Status.PENDING) {
// todo: something
Log.d("startDownloading", "task wasn't null, status pending");
} else if (s == Status.RUNNING) {
// todo: something
Log.d("startDownloading", "task wasn't null, status running");
} else {
Log.d("startDownloading", "task wasn't null, status unknown");
}
}
}
private class DownloadFilesTask extends
AsyncTask<ImageCache, Integer, ImageCache> {
ZooBorns that;
protected ImageCache doInBackground(ImageCache... imageCaches) {
ImageCache imgCache = imageCaches[0];
if (that == null) {
this.that = imgCache.mContext;
}
int doneCount = 0;
for (int n = 0; n < imgCache.images.size(); n++) {
if (imgCache.images.get(n).imageFileExists()) {
Log.d("DownloadFilesTask:doInBackground", "skipping, marking complete");
imgCache.images.get(n).thumbnail(that.columnWidth);
imgCache.images.get(n).setComplete(true);
imgCache.images.get(n).setFailed(false);
}
}
for (int n = 0; n < imgCache.images.size(); n++) {
Log.d("DownloadFilesTask:doInBackground", imgCache.images
.get(n).getUrl());
if (imgCache.images.get(n).isComplete()) {
continue;
}
if (imgCache.images.get(n).download()) {
imgCache.images.get(n).thumbnail(that.columnWidth);
imgCache.images.get(n).setComplete(true);
imgCache.images.get(n).setFailed(false);
Log.d("DownloadFilesTask:doInBackground", "success");
} else {
- Log.d("DownloadFilesTask:doInBackground", "1st failure");
- if (imgCache.images.get(n).download()) {
- imgCache.images.get(n).setComplete(true);
- imgCache.images.get(n).setFailed(false);
- Log.d("DownloadFilesTask:doInBackground", "success!");
- } else {
- Log
- .d("DownloadFilesTask:doInBackground",
- "2nd failure");
- if (imgCache.images.get(n).download()) {
- imgCache.images.get(n).setComplete(true);
- imgCache.images.get(n).setFailed(false);
- Log.d("DownloadFilesTask:doInBackground",
- "success!!");
- } else {
- Log.d("DownloadFilesTask:doInBackground",
- "3rd failure");
- imgCache.images.get(n).setFailed(true);
- imgCache.images
- .get(n)
- .setBitmapIcon(
- ((BitmapDrawable) that
- .getResources()
- .getDrawable(
- android.R.drawable.ic_menu_close_clear_cancel))
- .getBitmap());
- }
- }
+ Log.d("DownloadFilesTask:doInBackground", "failure");
+ imgCache.images.get(n).setFailed(true);
+ imgCache.images
+ .get(n)
+ .setBitmapIcon(
+ ((BitmapDrawable) that
+ .getResources()
+ .getDrawable(
+ android.R.drawable.ic_menu_close_clear_cancel))
+ .getBitmap());
}
publishProgress((int) ((doneCount++ / (float) imgCache.images
.size()) * 100));
}
publishProgress(100);
return imgCache;
}
protected void onProgressUpdate(Integer... progress) {
Log.d("onProgressUpdate", progress[0].toString());
that.imgAdapter.notifyDataSetChanged();
}
protected void onPostExecute(ImageCache result) {
Log.d("onPostExecute", that.getApplicationInfo().packageName);
}
}
}
| true | true | protected ImageCache doInBackground(ImageCache... imageCaches) {
ImageCache imgCache = imageCaches[0];
if (that == null) {
this.that = imgCache.mContext;
}
int doneCount = 0;
for (int n = 0; n < imgCache.images.size(); n++) {
if (imgCache.images.get(n).imageFileExists()) {
Log.d("DownloadFilesTask:doInBackground", "skipping, marking complete");
imgCache.images.get(n).thumbnail(that.columnWidth);
imgCache.images.get(n).setComplete(true);
imgCache.images.get(n).setFailed(false);
}
}
for (int n = 0; n < imgCache.images.size(); n++) {
Log.d("DownloadFilesTask:doInBackground", imgCache.images
.get(n).getUrl());
if (imgCache.images.get(n).isComplete()) {
continue;
}
if (imgCache.images.get(n).download()) {
imgCache.images.get(n).thumbnail(that.columnWidth);
imgCache.images.get(n).setComplete(true);
imgCache.images.get(n).setFailed(false);
Log.d("DownloadFilesTask:doInBackground", "success");
} else {
Log.d("DownloadFilesTask:doInBackground", "1st failure");
if (imgCache.images.get(n).download()) {
imgCache.images.get(n).setComplete(true);
imgCache.images.get(n).setFailed(false);
Log.d("DownloadFilesTask:doInBackground", "success!");
} else {
Log
.d("DownloadFilesTask:doInBackground",
"2nd failure");
if (imgCache.images.get(n).download()) {
imgCache.images.get(n).setComplete(true);
imgCache.images.get(n).setFailed(false);
Log.d("DownloadFilesTask:doInBackground",
"success!!");
} else {
Log.d("DownloadFilesTask:doInBackground",
"3rd failure");
imgCache.images.get(n).setFailed(true);
imgCache.images
.get(n)
.setBitmapIcon(
((BitmapDrawable) that
.getResources()
.getDrawable(
android.R.drawable.ic_menu_close_clear_cancel))
.getBitmap());
}
}
}
publishProgress((int) ((doneCount++ / (float) imgCache.images
.size()) * 100));
}
publishProgress(100);
return imgCache;
}
| protected ImageCache doInBackground(ImageCache... imageCaches) {
ImageCache imgCache = imageCaches[0];
if (that == null) {
this.that = imgCache.mContext;
}
int doneCount = 0;
for (int n = 0; n < imgCache.images.size(); n++) {
if (imgCache.images.get(n).imageFileExists()) {
Log.d("DownloadFilesTask:doInBackground", "skipping, marking complete");
imgCache.images.get(n).thumbnail(that.columnWidth);
imgCache.images.get(n).setComplete(true);
imgCache.images.get(n).setFailed(false);
}
}
for (int n = 0; n < imgCache.images.size(); n++) {
Log.d("DownloadFilesTask:doInBackground", imgCache.images
.get(n).getUrl());
if (imgCache.images.get(n).isComplete()) {
continue;
}
if (imgCache.images.get(n).download()) {
imgCache.images.get(n).thumbnail(that.columnWidth);
imgCache.images.get(n).setComplete(true);
imgCache.images.get(n).setFailed(false);
Log.d("DownloadFilesTask:doInBackground", "success");
} else {
Log.d("DownloadFilesTask:doInBackground", "failure");
imgCache.images.get(n).setFailed(true);
imgCache.images
.get(n)
.setBitmapIcon(
((BitmapDrawable) that
.getResources()
.getDrawable(
android.R.drawable.ic_menu_close_clear_cancel))
.getBitmap());
}
publishProgress((int) ((doneCount++ / (float) imgCache.images
.size()) * 100));
}
publishProgress(100);
return imgCache;
}
|
diff --git a/BetterBatteryStats/src/com/asksven/betterbatterystats/services/BbsDashClockExtension.java b/BetterBatteryStats/src/com/asksven/betterbatterystats/services/BbsDashClockExtension.java
index 3891bb90..0e455a4e 100644
--- a/BetterBatteryStats/src/com/asksven/betterbatterystats/services/BbsDashClockExtension.java
+++ b/BetterBatteryStats/src/com/asksven/betterbatterystats/services/BbsDashClockExtension.java
@@ -1,147 +1,147 @@
/*
* Copyright (C) 2011-2013 asksven
*
* 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.asksven.betterbatterystats.services;
import java.util.ArrayList;
import com.asksven.android.common.privateapiproxies.BatteryStatsProxy;
import com.asksven.android.common.privateapiproxies.Misc;
import com.asksven.android.common.privateapiproxies.StatElement;
import com.asksven.android.common.utils.DateUtils;
import com.asksven.betterbatterystats.LogSettings;
import com.asksven.betterbatterystats.PreferencesActivity;
import com.asksven.betterbatterystats.R;
import com.asksven.betterbatterystats.StatsActivity;
import com.asksven.betterbatterystats.data.Reference;
import com.asksven.betterbatterystats.data.ReferenceStore;
import com.asksven.betterbatterystats.data.StatsProvider;
import com.asksven.betterbatterystats.widgetproviders.SmallWidgetProvider;
import com.asksven.betterbatterystats.widgets.WidgetBattery;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
public class BbsDashClockExtension extends DashClockExtension
{
private static final String TAG = "BbsDashClockExtension";
public static final String PREF_NAME = "pref_name";
@Override
protected void onUpdateData(int reason)
{
// Get preference value.
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// we want to refresh out stats each time the screen goes on
setUpdateWhenScreenOn(true);
// collect some data
String refFrom = sharedPrefs.getString("dashclock_default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
long timeAwake = 0;
long timeSince = 0;
long drain = 0;
String strAwake = "";
String strDrain = "";
StatsProvider stats = StatsProvider.getInstance(this);
// make sure to flush cache
BatteryStatsProxy.getInstance(this).invalidate();
try
{
Reference toRef = StatsProvider.getInstance(this).getUncachedPartialReference(0);
Reference fromRef = ReferenceStore.getReferenceByName(refFrom, this);
ArrayList<StatElement> otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, toRef);
timeSince = stats.getSince(fromRef, toRef);
drain = stats.getBatteryLevelStat(fromRef, toRef);
if ( (otherStats == null) || ( otherStats.size() == 1) )
{
// the desired stat type is unavailable, pick the alternate one and go on with that one
- refFrom = sharedPrefs.getString("dashclock_fallback_stat_type", Reference.UNPLUGGED_REF_FILENAME);
+ refFrom = sharedPrefs.getString("dashclock_fallback_stat_type", Reference.BOOT_REF_FILENAME);
fromRef = ReferenceStore.getReferenceByName(refFrom, this);
otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, toRef);
}
if ( (otherStats != null) && ( otherStats.size() > 1) )
{
Misc timeAwakeStat = (Misc) stats.getElementByKey(otherStats, "Awake");
if (timeAwakeStat != null)
{
timeAwake = timeAwakeStat.getTimeOn();
}
else
{
timeAwake = 0;
}
}
}
catch (Exception e)
{
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
finally
{
if (LogSettings.DEBUG)
{
Log.d(TAG, "Awake: " + DateUtils.formatDuration(timeAwake));
Log.d(TAG, "Since: " + DateUtils.formatDuration(timeSince));
Log.d(TAG, "Drain: " + drain);
if (timeSince != 0)
{
Log.d(TAG, "Drain %/h: " + drain/timeSince);
}
else
{
Log.d(TAG, "Drain %/h: 0");
}
}
strAwake = DateUtils.formatDurationCompressed(timeAwake);
if (timeSince != 0)
{
float pct = drain / ((float)timeSince / 1000F / 60F / 60F);
strDrain = String.format("%.1f", pct) + "%/h";
}
else
{
strDrain = "0 %/h";
}
}
String refs = getString(R.string.label_since) + " " + Reference.getLabel(refFrom);
// Publish the extension data update.
publishUpdate(new ExtensionData().visible(true).icon(R.drawable.icon_notext).status(strDrain)
.expandedTitle(strAwake + " " + getString(R.string.label_awake_abbrev) + ", " + strDrain).expandedBody(refs)
.clickIntent(new Intent(this, StatsActivity.class)));
}
}
| true | true | protected void onUpdateData(int reason)
{
// Get preference value.
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// we want to refresh out stats each time the screen goes on
setUpdateWhenScreenOn(true);
// collect some data
String refFrom = sharedPrefs.getString("dashclock_default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
long timeAwake = 0;
long timeSince = 0;
long drain = 0;
String strAwake = "";
String strDrain = "";
StatsProvider stats = StatsProvider.getInstance(this);
// make sure to flush cache
BatteryStatsProxy.getInstance(this).invalidate();
try
{
Reference toRef = StatsProvider.getInstance(this).getUncachedPartialReference(0);
Reference fromRef = ReferenceStore.getReferenceByName(refFrom, this);
ArrayList<StatElement> otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, toRef);
timeSince = stats.getSince(fromRef, toRef);
drain = stats.getBatteryLevelStat(fromRef, toRef);
if ( (otherStats == null) || ( otherStats.size() == 1) )
{
// the desired stat type is unavailable, pick the alternate one and go on with that one
refFrom = sharedPrefs.getString("dashclock_fallback_stat_type", Reference.UNPLUGGED_REF_FILENAME);
fromRef = ReferenceStore.getReferenceByName(refFrom, this);
otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, toRef);
}
if ( (otherStats != null) && ( otherStats.size() > 1) )
{
Misc timeAwakeStat = (Misc) stats.getElementByKey(otherStats, "Awake");
if (timeAwakeStat != null)
{
timeAwake = timeAwakeStat.getTimeOn();
}
else
{
timeAwake = 0;
}
}
}
catch (Exception e)
{
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
finally
{
if (LogSettings.DEBUG)
{
Log.d(TAG, "Awake: " + DateUtils.formatDuration(timeAwake));
Log.d(TAG, "Since: " + DateUtils.formatDuration(timeSince));
Log.d(TAG, "Drain: " + drain);
if (timeSince != 0)
{
Log.d(TAG, "Drain %/h: " + drain/timeSince);
}
else
{
Log.d(TAG, "Drain %/h: 0");
}
}
strAwake = DateUtils.formatDurationCompressed(timeAwake);
if (timeSince != 0)
{
float pct = drain / ((float)timeSince / 1000F / 60F / 60F);
strDrain = String.format("%.1f", pct) + "%/h";
}
else
{
strDrain = "0 %/h";
}
}
String refs = getString(R.string.label_since) + " " + Reference.getLabel(refFrom);
// Publish the extension data update.
publishUpdate(new ExtensionData().visible(true).icon(R.drawable.icon_notext).status(strDrain)
.expandedTitle(strAwake + " " + getString(R.string.label_awake_abbrev) + ", " + strDrain).expandedBody(refs)
.clickIntent(new Intent(this, StatsActivity.class)));
}
| protected void onUpdateData(int reason)
{
// Get preference value.
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// we want to refresh out stats each time the screen goes on
setUpdateWhenScreenOn(true);
// collect some data
String refFrom = sharedPrefs.getString("dashclock_default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
long timeAwake = 0;
long timeSince = 0;
long drain = 0;
String strAwake = "";
String strDrain = "";
StatsProvider stats = StatsProvider.getInstance(this);
// make sure to flush cache
BatteryStatsProxy.getInstance(this).invalidate();
try
{
Reference toRef = StatsProvider.getInstance(this).getUncachedPartialReference(0);
Reference fromRef = ReferenceStore.getReferenceByName(refFrom, this);
ArrayList<StatElement> otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, toRef);
timeSince = stats.getSince(fromRef, toRef);
drain = stats.getBatteryLevelStat(fromRef, toRef);
if ( (otherStats == null) || ( otherStats.size() == 1) )
{
// the desired stat type is unavailable, pick the alternate one and go on with that one
refFrom = sharedPrefs.getString("dashclock_fallback_stat_type", Reference.BOOT_REF_FILENAME);
fromRef = ReferenceStore.getReferenceByName(refFrom, this);
otherStats = stats.getOtherUsageStatList(true, fromRef, false, true, toRef);
}
if ( (otherStats != null) && ( otherStats.size() > 1) )
{
Misc timeAwakeStat = (Misc) stats.getElementByKey(otherStats, "Awake");
if (timeAwakeStat != null)
{
timeAwake = timeAwakeStat.getTimeOn();
}
else
{
timeAwake = 0;
}
}
}
catch (Exception e)
{
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
finally
{
if (LogSettings.DEBUG)
{
Log.d(TAG, "Awake: " + DateUtils.formatDuration(timeAwake));
Log.d(TAG, "Since: " + DateUtils.formatDuration(timeSince));
Log.d(TAG, "Drain: " + drain);
if (timeSince != 0)
{
Log.d(TAG, "Drain %/h: " + drain/timeSince);
}
else
{
Log.d(TAG, "Drain %/h: 0");
}
}
strAwake = DateUtils.formatDurationCompressed(timeAwake);
if (timeSince != 0)
{
float pct = drain / ((float)timeSince / 1000F / 60F / 60F);
strDrain = String.format("%.1f", pct) + "%/h";
}
else
{
strDrain = "0 %/h";
}
}
String refs = getString(R.string.label_since) + " " + Reference.getLabel(refFrom);
// Publish the extension data update.
publishUpdate(new ExtensionData().visible(true).icon(R.drawable.icon_notext).status(strDrain)
.expandedTitle(strAwake + " " + getString(R.string.label_awake_abbrev) + ", " + strDrain).expandedBody(refs)
.clickIntent(new Intent(this, StatsActivity.class)));
}
|
diff --git a/crypto/src/org/bouncycastle/cms/CMSUtils.java b/crypto/src/org/bouncycastle/cms/CMSUtils.java
index 1dd9c221..811db5ec 100644
--- a/crypto/src/org/bouncycastle/cms/CMSUtils.java
+++ b/crypto/src/org/bouncycastle/cms/CMSUtils.java
@@ -1,167 +1,167 @@
package org.bouncycastle.cms;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.DEREncodable;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.x509.CertificateList;
import org.bouncycastle.asn1.x509.X509CertificateStructure;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.CRLException;
import java.security.cert.CertStore;
import java.security.cert.CertStoreException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509CRL;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
class CMSUtils
{
private static final Runtime RUNTIME = Runtime.getRuntime();
static int getMaximumMemory()
{
long maxMem = RUNTIME.maxMemory();
if (maxMem > Integer.MAX_VALUE)
{
return Integer.MAX_VALUE;
}
return (int)maxMem;
}
static ContentInfo readContentInfo(
byte[] input)
throws CMSException
{
// enforce limit checking as from a byte array
return readContentInfo(new ASN1InputStream(input));
}
static ContentInfo readContentInfo(
InputStream input)
throws CMSException
{
// enforce some limit checking
return readContentInfo(new ASN1InputStream(input, getMaximumMemory()));
}
static List getCertificatesFromStore(CertStore certStore)
throws CertStoreException, CMSException
{
List certs = new ArrayList();
try
{
for (Iterator it = certStore.getCertificates(null).iterator(); it.hasNext();)
{
X509Certificate c = (X509Certificate)it.next();
certs.add(X509CertificateStructure.getInstance(
ASN1Object.fromByteArray(c.getEncoded())));
}
return certs;
}
catch (IllegalArgumentException e)
{
- throw new CMSException("error processing crls", e);
+ throw new CMSException("error processing certs", e);
}
catch (IOException e)
{
throw new CMSException("error processing certs", e);
}
catch (CertificateEncodingException e)
{
throw new CMSException("error encoding certs", e);
}
}
static List getCRLsFromStore(CertStore certStore)
throws CertStoreException, CMSException
{
List crls = new ArrayList();
try
{
for (Iterator it = certStore.getCRLs(null).iterator(); it.hasNext();)
{
X509CRL c = (X509CRL)it.next();
crls.add(CertificateList.getInstance(ASN1Object.fromByteArray(c.getEncoded())));
}
return crls;
}
catch (IllegalArgumentException e)
{
throw new CMSException("error processing crls", e);
}
catch (IOException e)
{
throw new CMSException("error processing crls", e);
}
catch (CRLException e)
{
throw new CMSException("error encoding crls", e);
}
}
static ASN1Set createDerSetFromList(List derObjects)
{
ASN1EncodableVector v = new ASN1EncodableVector();
for (Iterator it = derObjects.iterator(); it.hasNext();)
{
v.add((DEREncodable)it.next());
}
return new DERSet(v);
}
private static ContentInfo readContentInfo(
ASN1InputStream in)
throws CMSException
{
try
{
return ContentInfo.getInstance(in.readObject());
}
catch (IOException e)
{
throw new CMSException("IOException reading content.", e);
}
catch (ClassCastException e)
{
throw new CMSException("Malformed content.", e);
}
catch (IllegalArgumentException e)
{
throw new CMSException("Malformed content.", e);
}
}
public static byte[] streamToByteArray(
InputStream in)
throws IOException
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
int ch;
while ((ch = in.read()) >= 0)
{
bOut.write(ch);
}
return bOut.toByteArray();
}
}
| true | true | static List getCertificatesFromStore(CertStore certStore)
throws CertStoreException, CMSException
{
List certs = new ArrayList();
try
{
for (Iterator it = certStore.getCertificates(null).iterator(); it.hasNext();)
{
X509Certificate c = (X509Certificate)it.next();
certs.add(X509CertificateStructure.getInstance(
ASN1Object.fromByteArray(c.getEncoded())));
}
return certs;
}
catch (IllegalArgumentException e)
{
throw new CMSException("error processing crls", e);
}
catch (IOException e)
{
throw new CMSException("error processing certs", e);
}
catch (CertificateEncodingException e)
{
throw new CMSException("error encoding certs", e);
}
}
| static List getCertificatesFromStore(CertStore certStore)
throws CertStoreException, CMSException
{
List certs = new ArrayList();
try
{
for (Iterator it = certStore.getCertificates(null).iterator(); it.hasNext();)
{
X509Certificate c = (X509Certificate)it.next();
certs.add(X509CertificateStructure.getInstance(
ASN1Object.fromByteArray(c.getEncoded())));
}
return certs;
}
catch (IllegalArgumentException e)
{
throw new CMSException("error processing certs", e);
}
catch (IOException e)
{
throw new CMSException("error processing certs", e);
}
catch (CertificateEncodingException e)
{
throw new CMSException("error encoding certs", e);
}
}
|
diff --git a/src/main/java/nz/org/nesi/goldwrap/impl/GoldWrapServiceImpl.java b/src/main/java/nz/org/nesi/goldwrap/impl/GoldWrapServiceImpl.java
index 220391a..206f9f8 100644
--- a/src/main/java/nz/org/nesi/goldwrap/impl/GoldWrapServiceImpl.java
+++ b/src/main/java/nz/org/nesi/goldwrap/impl/GoldWrapServiceImpl.java
@@ -1,663 +1,663 @@
package nz.org.nesi.goldwrap.impl;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.jws.WebService;
import javax.ws.rs.Path;
import nz.org.nesi.goldwrap.Config;
import nz.org.nesi.goldwrap.api.GoldWrapService;
import nz.org.nesi.goldwrap.domain.Allocation;
import nz.org.nesi.goldwrap.domain.ExternalCommand;
import nz.org.nesi.goldwrap.domain.Machine;
import nz.org.nesi.goldwrap.domain.Project;
import nz.org.nesi.goldwrap.domain.User;
import nz.org.nesi.goldwrap.errors.MachineFault;
import nz.org.nesi.goldwrap.errors.ProjectFault;
import nz.org.nesi.goldwrap.errors.ServiceException;
import nz.org.nesi.goldwrap.errors.UserFault;
import nz.org.nesi.goldwrap.util.GoldHelper;
import nz.org.nesi.goldwrap.utils.BeanHelpers;
import nz.org.nesi.goldwrap.utils.JSONHelpers;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
@WebService(endpointInterface = "nz.org.nesi.goldwrap.api.GoldWrapService", name = "GoldWrapService")
@Path("/goldwrap")
public class GoldWrapServiceImpl implements GoldWrapService {
public static Logger myLogger = LoggerFactory
.getLogger(GoldWrapServiceImpl.class);
private static ExternalCommand executeGoldCommand(String command) {
ExternalCommand gc = new ExternalCommand(command);
gc.execute();
gc.verify();
return gc;
}
private static ExternalCommand executeGoldCommand(List<String> command) {
ExternalCommand gc = new ExternalCommand(command);
gc.execute();
gc.verify();
return gc;
}
private static volatile boolean initialized = false;
public GoldWrapServiceImpl() {
initialize();
}
public synchronized void initialize() {
if (!initialized) {
try {
File configDir = Config.getConfigDir();
myLogger.debug("Running init commands...");
File initFile = new File(configDir, "init.config");
if (initFile.exists()) {
List<String> lines = null;
try {
lines = Files.readLines(initFile, Charsets.UTF_8);
} catch (IOException e1) {
throw new RuntimeException("Can't read file: "
+ initFile.toString());
}
for (String line : lines) {
line = line.trim();
if (StringUtils.isEmpty(line) || line.startsWith("#")) {
continue;
}
myLogger.debug("Executing: " + line);
ExternalCommand ec = executeGoldCommand(line);
myLogger.debug("StdOut:\n\n{}\n\n", Joiner.on("\n")
.join(ec.getStdOut()));
myLogger.debug("StdErr:\n\n{}\n\n", Joiner.on("\n")
.join(ec.getStdErr()));
}
}
myLogger.debug("Trying to initialize static values...");
File machinesFile = new File(configDir, "machines.json");
if (machinesFile.exists()) {
try {
List<Machine> machines = JSONHelpers.readJSONfile(
machinesFile, Machine.class);
for (Machine m : machines) {
Machine mInGold = null;
try {
mInGold = getMachine(m.getName());
myLogger.debug("Machine " + m.getName()
+ " in Gold, modifying it...");
modifyMachine(m.getName(), m);
} catch (MachineFault mf) {
myLogger.debug("Machine " + m.getName()
+ " not in Gold, creating it...");
createMachine(m);
}
}
} catch (Exception e) {
throw new RuntimeException("Can't parse json file: "
+ machinesFile.toString(), e);
}
}
} finally {
initialized = true;
}
}
}
public Project addUserToProject(String projName, String userId) {
return GoldHelper.addUserToProject(projName, userId);
}
private void checkProjectname(String projectname) {
if (StringUtils.isBlank(projectname)) {
throw new ServiceException("Can't execute operation.",
"Projectname blank or not specified.");
}
}
private void checkUsername(String username) {
if (StringUtils.isBlank(username)) {
throw new ServiceException("Can't execute operation.",
"Username blank or not specified.");
}
}
public void checkMachineName(String machineName) {
if (StringUtils.isBlank(machineName)) {
throw new ServiceException("Can't execute operation.",
"Machine name blank or not specified.");
}
}
public void createMachine(Machine mach) {
String machName = mach.getName();
mach.validate(true);
if (GoldHelper.machineExists(machName)) {
throw new MachineFault(mach, "Can't create machine " + machName,
"Machine name '" + machName + "' already exists in Gold.");
}
StringBuffer command = new StringBuffer("gmkmachine ");
String desc = mach.getDescription();
if (StringUtils.isNotBlank(desc)) {
command.append("-d '" + desc + "' ");
}
String arch = mach.getArch();
if (StringUtils.isNotBlank(arch)) {
command.append("--arch '" + arch + "' ");
}
String opsys = mach.getOpsys();
if (StringUtils.isNotBlank(opsys)) {
command.append("--opsys '" + opsys + "' ");
}
command.append(machName);
ExternalCommand ec = executeGoldCommand(command.toString());
if (!GoldHelper.machineExists(machName)) {
throw new MachineFault(mach, "Can't create machine.",
"Unknow reason");
}
}
public void createProject(Project proj) {
String projName = proj.getProjectId();
proj.validate(true);
if (GoldHelper.projectExists(projName)) {
throw new ProjectFault(proj, "Can't create project " + projName,
"Project name '" + projName + "' already exists in Gold.");
}
String principal = proj.getPrincipal();
if (StringUtils.isNotBlank(principal)) {
try {
User princ = getUser(principal);
} catch (Exception e) {
throw new ProjectFault(proj,
"Can't create project " + projName, "Principal '"
+ principal + "' does not exist in Gold.");
}
}
List<User> users = proj.getUsers();
if (users != null) {
users = Lists.newArrayList(users);
} else {
users = Lists.newArrayList();
}
for (User user : users) {
String userId = user.getUserId();
if (StringUtils.isBlank(userId)) {
throw new ProjectFault(proj,
"Can't create project " + projName,
"Userid not specified.");
}
// if (!GoldHelper.isRegistered(userId)) {
// throw new ProjectFault(proj,
// "Can't create project " + projName, "User '" + userId
// + "' does not exist in Gold yet.");
// }
}
List<String> command = Lists.newArrayList("gmkproject");
proj.setUsers(new ArrayList<User>());
proj.setAllocations(new ArrayList<Allocation>());
String desc = JSONHelpers.convertToJSONString(proj);
- desc = "'{\"projectId\":\"" + projName + "\"'}";
+ desc = "{\"projectId\":\"" + projName + "\"}";
command.add("-d");
command.add("'" + desc + "'");
// String users = Joiner.on(",").join(proj.getUsers());
//
// if (StringUtils.isNotBlank(users)) {
// command.append("-u '" + users + "' ");
// }
command.add("--createAccount=False");
if (proj.isFunded()) {
command.add("-X");
command.add("Funded=True");
} else {
command.add("-X");
command.add("Funded=False");
}
command.add(projName);
ExternalCommand ec = executeGoldCommand(command);
if (!GoldHelper.projectExists(projName)) {
throw new ProjectFault(proj, "Can't create project.",
"Unknow reason");
}
myLogger.debug("Creating account...");
String command2 = "gmkaccount ";
command2 = command2 + "-p " + projName + " ";
command2 = command2 + "-n " + "acc_" + projName;
ExternalCommand ec2 = executeGoldCommand(command2);
int exitCode = ec2.getExitCode();
if (exitCode != 0) {
try {
myLogger.debug("Trying to delete project {}...", projName);
deleteProject(projName);
} catch (Exception e) {
myLogger.debug("Deleting project failed: {}",
e.getLocalizedMessage());
}
throw new ProjectFault(proj, "Could not create project.",
"Could not create associated account for some reason.");
}
myLogger.debug("Parsing output to find out account number.");
try {
String stdout = ec2.getStdOut().get(0);
Iterable<String> tokens = Splitter.on(' ').split(stdout);
Integer accNr = Integer.parseInt(Iterables.getLast(tokens));
Project tempProj = new Project(projName);
tempProj.setAccountId(accNr);
// remove ANY user
myLogger.debug("Removeing ANY user from account {}", accNr);
String removeAnyCommand = "gchaccount --delUsers ANY " + accNr;
ExternalCommand removeCommand = executeGoldCommand(removeAnyCommand);
modifyProject(projName, tempProj);
} catch (Exception e) {
try {
myLogger.debug("Trying to delete project {}...", projName);
deleteProject(projName);
} catch (Exception e2) {
myLogger.debug("Deleting project failed: {}",
e2.getLocalizedMessage());
}
throw new ProjectFault(proj, "Could not create project.",
"Could not parse account nr for project.");
}
myLogger.debug("Account created. Now adding users...");
createOrModifyUsers(users);
addUsersToProject(projName, users);
}
private void createOrModifyUsers(List<User> users) {
for (User user : users) {
if (GoldHelper.isRegistered(user.getUserId())) {
myLogger.debug("Potentially modifying user " + user.getUserId());
modifyUser(user.getUserId(), user);
} else {
myLogger.debug("Creating user: " + user.getUserId());
createUser(user);
}
}
}
public void createUser(User user) {
user.validate(false);
String username = user.getUserId();
String phone = user.getPhone();
String email = user.getEmail();
String middlename = user.getMiddleName();
String fullname = user.getFirstName();
if (StringUtils.isNotBlank(middlename)) {
fullname = fullname + " " + middlename;
}
fullname = fullname + " " + user.getLastName();
String institution = user.getInstitution();
if (GoldHelper.isRegistered(username)) {
throw new UserFault("Can't create user.", "User " + username
+ " already in Gold database.", 409);
}
String desc = JSONHelpers.convertToJSONString(user);
String command = "gmkuser ";
if (StringUtils.isNotBlank(fullname)) {
command = command + "-n \"" + fullname + "\" ";
}
if (StringUtils.isNotBlank(email)) {
command = command + "-E " + email + " ";
}
if (StringUtils.isNotBlank(phone)) {
command = command + "-F " + phone + " ";
}
command = command + " -d '" + desc + "' " + username;
ExternalCommand ec = executeGoldCommand(command);
if (!GoldHelper.isRegistered(username)) {
throw new UserFault(user, "Can't create user.", "Unknown reason");
}
}
public void deleteProject(String projName) {
checkProjectname(projName);
if (!GoldHelper.projectExists(projName)) {
throw new ProjectFault("Can't delete project " + projName + ".",
"Project " + projName + " not in Gold database.", 404);
}
String command = "grmproject " + projName;
ExternalCommand ec = executeGoldCommand(command);
if (GoldHelper.projectExists(projName)) {
throw new ProjectFault(
"Could not delete project " + projName + ".",
"Unknown reason.", 500);
}
}
public void deleteUser(String username) {
if (StringUtils.isBlank(username)) {
throw new ServiceException("Can't delete user.",
"Username blank or not specified.");
}
if (!GoldHelper.isRegistered(username)) {
throw new UserFault("Can't delete user.", "User " + username
+ " not in Gold database.", 404);
}
String command = "grmuser " + username;
ExternalCommand ec = executeGoldCommand(command);
if (GoldHelper.isRegistered(username)) {
throw new UserFault("Could not delete user.", "Unknown reason.",
500);
}
}
public Machine getMachine(String machineName) {
checkMachineName(machineName);
return GoldHelper.getMachine(machineName);
}
public List<Machine> getMachines() {
return GoldHelper.getAllMachines();
}
public Project getProject(String projName) {
checkProjectname(projName);
return GoldHelper.getProject(projName);
}
public List<Project> getProjects() {
return GoldHelper.getAllProjects();
}
public List<Project> getProjectsForUser(String username) {
return GoldHelper.getProjectsForUser(username);
}
public User getUser(String username) {
checkUsername(username);
User u = GoldHelper.getUser(username);
return u;
}
public List<User> getUsers() {
return GoldHelper.getAllUsers();
}
public List<User> getUsersForProject(String projName) {
return GoldHelper.getUsersForProject(projName);
}
public boolean isRegistered(String user) {
return GoldHelper.isRegistered(user);
}
public Project modifyProject(String projName, Project project) {
checkProjectname(projName);
if (StringUtils.isNotBlank(project.getProjectId())
&& !projName.equals(project.getProjectId())) {
throw new ProjectFault(project, "Can't modify project.",
"Project name can't be changed.");
}
if (!GoldHelper.projectExists(projName)) {
throw new ProjectFault("Can't modify project.", "Project "
+ projName + " not in Gold database.", 404);
}
String principal = project.getPrincipal();
if (StringUtils.isNotBlank(principal)) {
try {
User princ = getUser(principal);
} catch (Exception e) {
throw new ProjectFault(project, "Can't create project "
+ projName, "Principal '" + principal
+ "' does not exist in Gold.");
}
}
List<User> users = project.getUsers();
if (users != null) {
users = Lists.newArrayList(users);
} else {
users = Lists.newArrayList();
}
for (User user : users) {
String userId = user.getUserId();
if (StringUtils.isBlank(userId)) {
throw new ProjectFault(project, "Can't modify project "
+ projName, "Userid not specified.");
}
}
project.validate(false);
Project goldProject = getProject(projName);
try {
BeanHelpers.merge(goldProject, project);
} catch (Exception e) {
e.printStackTrace();
throw new ProjectFault(project, "Can't modify project " + projName,
"Can't merge new properties: " + e.getLocalizedMessage());
}
// we don't want to store userdata in the description
goldProject.setUsers(new ArrayList<User>());
StringBuffer command = new StringBuffer("gchproject ");
String desc = JSONHelpers.convertToJSONString(goldProject);
command.append("-d '" + desc + "' ");
command.append(projName);
ExternalCommand ec = executeGoldCommand(command.toString());
// ensuring users are present
createOrModifyUsers(users);
addUsersToProject(projName, users);
Project p = getProject(projName);
return p;
}
public void addUsersToProject(String projectName, List<User> users) {
for (User user : users) {
addUserToProject(projectName, user.getUserId());
}
}
public Machine modifyMachine(String machName, Machine machine) {
checkMachineName(machName);
machine.validate(true);
Machine mach = null;
try {
mach = getMachine(machName);
} catch (Exception e) {
myLogger.debug("Can't load machine {}", machName, e);
}
if (mach == null) {
throw new MachineFault("Can't modify machine " + machName + ".",
"Machine " + machName + " not in Gold database", 404);
}
String newArch = machine.getArch();
String newOs = machine.getOpsys();
String newDesc = machine.getDescription();
StringBuffer command = new StringBuffer("gchmachine ");
if (StringUtils.isNotBlank(newDesc)) {
command.append("-d '" + newDesc + "' ");
}
if (StringUtils.isNotBlank(newArch)) {
command.append("--arch '" + newArch + "' ");
}
if (StringUtils.isNotBlank(newOs)) {
command.append("--opsys '" + newOs + "' ");
}
command.append(machName);
ExternalCommand ec = executeGoldCommand(command.toString());
return getMachine(machName);
}
public void modifyUser(String username, User user) {
if (StringUtils.isBlank(username)) {
throw new UserFault(user, "Can't modify user.",
"Username field can't be blank.");
}
if (StringUtils.isNotBlank(user.getUserId())
&& !username.equals(user.getUserId())) {
throw new UserFault(user, "Can't modify user.",
"Username can't be changed.");
}
if (!GoldHelper.isRegistered(username)) {
throw new UserFault("Can't modify user.", "User " + username
+ " not in Gold database.", 404);
}
User goldUser = getUser(username);
try {
BeanHelpers.merge(goldUser, user);
} catch (Exception e) {
throw new UserFault(goldUser, "Can't merge new user into old one.",
e.getLocalizedMessage());
}
goldUser.validate(false);
String middlename = goldUser.getMiddleName();
String fullname = goldUser.getFirstName();
if (StringUtils.isNotBlank(middlename)) {
fullname = fullname + " " + middlename;
}
fullname = fullname + " " + goldUser.getLastName();
String phone = goldUser.getPhone();
String institution = goldUser.getInstitution();
String email = goldUser.getEmail();
String desc = JSONHelpers.convertToJSONString(goldUser);
String command = "gchuser ";
if (StringUtils.isNotBlank(fullname)) {
command = command + "-n \"" + fullname + "\" ";
}
if (StringUtils.isNotBlank(email)) {
command = command + "-E " + email + " ";
}
if (StringUtils.isNotBlank(phone)) {
command = command + "-F " + phone + " ";
}
command = command + " -d '" + desc + "' " + username;
ExternalCommand ec = executeGoldCommand(command);
if (!GoldHelper.isRegistered(username)) {
throw new UserFault(goldUser, "Can't create user.",
"Unknown reason");
}
}
}
| true | true | public void createProject(Project proj) {
String projName = proj.getProjectId();
proj.validate(true);
if (GoldHelper.projectExists(projName)) {
throw new ProjectFault(proj, "Can't create project " + projName,
"Project name '" + projName + "' already exists in Gold.");
}
String principal = proj.getPrincipal();
if (StringUtils.isNotBlank(principal)) {
try {
User princ = getUser(principal);
} catch (Exception e) {
throw new ProjectFault(proj,
"Can't create project " + projName, "Principal '"
+ principal + "' does not exist in Gold.");
}
}
List<User> users = proj.getUsers();
if (users != null) {
users = Lists.newArrayList(users);
} else {
users = Lists.newArrayList();
}
for (User user : users) {
String userId = user.getUserId();
if (StringUtils.isBlank(userId)) {
throw new ProjectFault(proj,
"Can't create project " + projName,
"Userid not specified.");
}
// if (!GoldHelper.isRegistered(userId)) {
// throw new ProjectFault(proj,
// "Can't create project " + projName, "User '" + userId
// + "' does not exist in Gold yet.");
// }
}
List<String> command = Lists.newArrayList("gmkproject");
proj.setUsers(new ArrayList<User>());
proj.setAllocations(new ArrayList<Allocation>());
String desc = JSONHelpers.convertToJSONString(proj);
desc = "'{\"projectId\":\"" + projName + "\"'}";
command.add("-d");
command.add("'" + desc + "'");
// String users = Joiner.on(",").join(proj.getUsers());
//
// if (StringUtils.isNotBlank(users)) {
// command.append("-u '" + users + "' ");
// }
command.add("--createAccount=False");
if (proj.isFunded()) {
command.add("-X");
command.add("Funded=True");
} else {
command.add("-X");
command.add("Funded=False");
}
command.add(projName);
ExternalCommand ec = executeGoldCommand(command);
if (!GoldHelper.projectExists(projName)) {
throw new ProjectFault(proj, "Can't create project.",
"Unknow reason");
}
myLogger.debug("Creating account...");
String command2 = "gmkaccount ";
command2 = command2 + "-p " + projName + " ";
command2 = command2 + "-n " + "acc_" + projName;
ExternalCommand ec2 = executeGoldCommand(command2);
int exitCode = ec2.getExitCode();
if (exitCode != 0) {
try {
myLogger.debug("Trying to delete project {}...", projName);
deleteProject(projName);
} catch (Exception e) {
myLogger.debug("Deleting project failed: {}",
e.getLocalizedMessage());
}
throw new ProjectFault(proj, "Could not create project.",
"Could not create associated account for some reason.");
}
myLogger.debug("Parsing output to find out account number.");
try {
String stdout = ec2.getStdOut().get(0);
Iterable<String> tokens = Splitter.on(' ').split(stdout);
Integer accNr = Integer.parseInt(Iterables.getLast(tokens));
Project tempProj = new Project(projName);
tempProj.setAccountId(accNr);
// remove ANY user
myLogger.debug("Removeing ANY user from account {}", accNr);
String removeAnyCommand = "gchaccount --delUsers ANY " + accNr;
ExternalCommand removeCommand = executeGoldCommand(removeAnyCommand);
modifyProject(projName, tempProj);
} catch (Exception e) {
try {
myLogger.debug("Trying to delete project {}...", projName);
deleteProject(projName);
} catch (Exception e2) {
myLogger.debug("Deleting project failed: {}",
e2.getLocalizedMessage());
}
throw new ProjectFault(proj, "Could not create project.",
"Could not parse account nr for project.");
}
myLogger.debug("Account created. Now adding users...");
createOrModifyUsers(users);
addUsersToProject(projName, users);
}
| public void createProject(Project proj) {
String projName = proj.getProjectId();
proj.validate(true);
if (GoldHelper.projectExists(projName)) {
throw new ProjectFault(proj, "Can't create project " + projName,
"Project name '" + projName + "' already exists in Gold.");
}
String principal = proj.getPrincipal();
if (StringUtils.isNotBlank(principal)) {
try {
User princ = getUser(principal);
} catch (Exception e) {
throw new ProjectFault(proj,
"Can't create project " + projName, "Principal '"
+ principal + "' does not exist in Gold.");
}
}
List<User> users = proj.getUsers();
if (users != null) {
users = Lists.newArrayList(users);
} else {
users = Lists.newArrayList();
}
for (User user : users) {
String userId = user.getUserId();
if (StringUtils.isBlank(userId)) {
throw new ProjectFault(proj,
"Can't create project " + projName,
"Userid not specified.");
}
// if (!GoldHelper.isRegistered(userId)) {
// throw new ProjectFault(proj,
// "Can't create project " + projName, "User '" + userId
// + "' does not exist in Gold yet.");
// }
}
List<String> command = Lists.newArrayList("gmkproject");
proj.setUsers(new ArrayList<User>());
proj.setAllocations(new ArrayList<Allocation>());
String desc = JSONHelpers.convertToJSONString(proj);
desc = "{\"projectId\":\"" + projName + "\"}";
command.add("-d");
command.add("'" + desc + "'");
// String users = Joiner.on(",").join(proj.getUsers());
//
// if (StringUtils.isNotBlank(users)) {
// command.append("-u '" + users + "' ");
// }
command.add("--createAccount=False");
if (proj.isFunded()) {
command.add("-X");
command.add("Funded=True");
} else {
command.add("-X");
command.add("Funded=False");
}
command.add(projName);
ExternalCommand ec = executeGoldCommand(command);
if (!GoldHelper.projectExists(projName)) {
throw new ProjectFault(proj, "Can't create project.",
"Unknow reason");
}
myLogger.debug("Creating account...");
String command2 = "gmkaccount ";
command2 = command2 + "-p " + projName + " ";
command2 = command2 + "-n " + "acc_" + projName;
ExternalCommand ec2 = executeGoldCommand(command2);
int exitCode = ec2.getExitCode();
if (exitCode != 0) {
try {
myLogger.debug("Trying to delete project {}...", projName);
deleteProject(projName);
} catch (Exception e) {
myLogger.debug("Deleting project failed: {}",
e.getLocalizedMessage());
}
throw new ProjectFault(proj, "Could not create project.",
"Could not create associated account for some reason.");
}
myLogger.debug("Parsing output to find out account number.");
try {
String stdout = ec2.getStdOut().get(0);
Iterable<String> tokens = Splitter.on(' ').split(stdout);
Integer accNr = Integer.parseInt(Iterables.getLast(tokens));
Project tempProj = new Project(projName);
tempProj.setAccountId(accNr);
// remove ANY user
myLogger.debug("Removeing ANY user from account {}", accNr);
String removeAnyCommand = "gchaccount --delUsers ANY " + accNr;
ExternalCommand removeCommand = executeGoldCommand(removeAnyCommand);
modifyProject(projName, tempProj);
} catch (Exception e) {
try {
myLogger.debug("Trying to delete project {}...", projName);
deleteProject(projName);
} catch (Exception e2) {
myLogger.debug("Deleting project failed: {}",
e2.getLocalizedMessage());
}
throw new ProjectFault(proj, "Could not create project.",
"Could not parse account nr for project.");
}
myLogger.debug("Account created. Now adding users...");
createOrModifyUsers(users);
addUsersToProject(projName, users);
}
|
diff --git a/app/models/Code.java b/app/models/Code.java
index e682d9a..e442ebe 100755
--- a/app/models/Code.java
+++ b/app/models/Code.java
@@ -1,112 +1,114 @@
package models;
import com.google.gson.Gson;
import com.greenlaw110.rythm.Rythm;
import com.greenlaw110.rythm.RythmEngine;
import com.greenlaw110.rythm.extension.ICodeType;
import com.greenlaw110.rythm.sandbox.RythmSecurityManager;
import com.greenlaw110.rythm.sandbox.SandboxThreadFactory;
import com.greenlaw110.rythm.utils.JSONWrapper;
import com.greenlaw110.rythm.utils.S;
import play.mvc.Scope;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static common.Helper.eq;
/**
* User: freewind
* Date: 13-3-18
* Time: 下午6:07
*/
public class Code {
public String id;
public String desc;
public String params;
public List<CodeFile> files;
public boolean showInMenu;
public boolean isNew() {
return S.empty(id);
}
private static final Object lock = new Object();
private static final Map<String, RythmEngine> engines = new HashMap<String, RythmEngine>();
private static final String sandboxPassword = UUID.randomUUID().toString();
private static final RythmSecurityManager rsm = new RythmSecurityManager(null, sandboxPassword, null);
private static final SandboxThreadFactory stf = new SandboxThreadFactory(rsm, sandboxPassword, null);
private RythmEngine engine() {
String sessId = Scope.Session.current().getId();
synchronized (lock) {
RythmEngine e = engines.get(sessId);
if (null == e) {
Map<String, Object> conf = new HashMap<String, Object>();
conf.put("resource.loader", new InMemoryResourceLoader(sessId));
conf.put("default.code_type", ICodeType.DefImpl.HTML);
conf.put("engine.mode", Rythm.Mode.dev);
conf.put("sandbox.security_manager", rsm);
conf.put("sandbox.thread_factory", stf);
+ conf.put("log.source.java.enabled", false);
+ conf.put("log.source.template.enabled", false);
e = new RythmEngine(conf);
engines.put(sessId, e);
}
return e;
}
}
public String render() throws IOException {
CodeFile main = getMainCodeFile();
// FIXME? Is it correct to use a file? (which will make rythm use FileTemplateResource)
Map<String, Object> context = new HashMap();
context.put("session-id", Scope.Session.current().getId());
RythmEngine rythm = engine();
if (S.notEmpty(params)) {
return rythm.sandbox(context).render(main.getKey(), JSONWrapper.wrap(params));
} else {
return rythm.sandbox(context).render(main.getKey());
}
}
public String toJson() {
return new Gson().toJson(this);
}
public CodeFile getMainCodeFile() {
for (CodeFile file : files) {
if (file.isMain) {
return file;
}
}
return files.get(0);
}
public CodeFile findCodeFile(String path) {
// find by fullname first
for (CodeFile file : files) {
if (eq(file.filename, path)) {
return file;
}
}
// find by prefix
for (CodeFile file : files) {
if (file.filename.startsWith(path + ".")) {
return file;
}
}
return null;
}
public void save(String sessionId) {
for (CodeFile file : files) {
file.save(sessionId);
}
}
}
| true | true | private RythmEngine engine() {
String sessId = Scope.Session.current().getId();
synchronized (lock) {
RythmEngine e = engines.get(sessId);
if (null == e) {
Map<String, Object> conf = new HashMap<String, Object>();
conf.put("resource.loader", new InMemoryResourceLoader(sessId));
conf.put("default.code_type", ICodeType.DefImpl.HTML);
conf.put("engine.mode", Rythm.Mode.dev);
conf.put("sandbox.security_manager", rsm);
conf.put("sandbox.thread_factory", stf);
e = new RythmEngine(conf);
engines.put(sessId, e);
}
return e;
}
}
| private RythmEngine engine() {
String sessId = Scope.Session.current().getId();
synchronized (lock) {
RythmEngine e = engines.get(sessId);
if (null == e) {
Map<String, Object> conf = new HashMap<String, Object>();
conf.put("resource.loader", new InMemoryResourceLoader(sessId));
conf.put("default.code_type", ICodeType.DefImpl.HTML);
conf.put("engine.mode", Rythm.Mode.dev);
conf.put("sandbox.security_manager", rsm);
conf.put("sandbox.thread_factory", stf);
conf.put("log.source.java.enabled", false);
conf.put("log.source.template.enabled", false);
e = new RythmEngine(conf);
engines.put(sessId, e);
}
return e;
}
}
|
diff --git a/src/org/biojava/bio/molbio/RestrictionSiteFinder.java b/src/org/biojava/bio/molbio/RestrictionSiteFinder.java
index f08a2e60a..6bf375715 100644
--- a/src/org/biojava/bio/molbio/RestrictionSiteFinder.java
+++ b/src/org/biojava/bio/molbio/RestrictionSiteFinder.java
@@ -1,140 +1,144 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.molbio;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.biojava.bio.BioRuntimeException;
import org.biojava.bio.seq.Sequence;
import org.biojava.bio.seq.StrandedFeature;
import org.biojava.bio.seq.io.SymbolListCharSequence;
import org.biojava.bio.symbol.RangeLocation;
/**
* <code>RestrictionSiteFinder</code>s do the work of finding sites
* for one <code>RestrictionEnzyme</code> in a target
* <code>Sequence</code>. Instances are passed to a
* <code>ThreadPool</code> in order to perform several concurrent
* searches.
*
* @author Keith James
* @since 1.3
*/
class RestrictionSiteFinder implements Runnable
{
private Sequence target;
private boolean findAll;
private RestrictionEnzyme enzyme;
/**
* Creates a new <code>RestrictionSiteFinder</code>.
*
* @param enzyme a <code>RestrictionEnzyme</code> for which to
* find sites.
* @param findAll a <code>boolean</code> indicating whether all
* sites should be found, including those which have recognition
* sites within the sequence, but cut outside it.
* @param target a <code>Sequence</code> to search.
*/
RestrictionSiteFinder(RestrictionEnzyme enzyme,
boolean findAll,
Sequence target)
{
this.enzyme = enzyme;
this.findAll = findAll;
this.target = target;
}
/**
* <code>run</code> searches for restriction sites.
*/
public void run()
{
SymbolListCharSequence charSeq = new SymbolListCharSequence(target);
try
{
Pattern [] patterns = RestrictionEnzymeManager.getPatterns(enzyme);
int siteLen = enzyme.getRecognitionSite().length();
int seqLen = target.length();
int usOffset = 0;
int dsOffset = 0;
int [] dsCut = enzyme.getDownstreamCut();
dsOffset = Math.max(dsCut[0], dsCut[1]);
if (enzyme.getCutType() == RestrictionEnzyme.CUT_COMPOUND)
{
// In coordinate space of recognition site, so
// upstream coordinates are negative
int [] usCut = enzyme.getUpstreamCut();
usOffset = Math.min(usCut[0], usCut[1]);
}
RestrictionSite.Template t = new RestrictionSite.Template();
t.type = RestrictionMapper.SITE_FEATURE_TYPE;
t.source = RestrictionMapper.SITE_FEATURE_SOURCE;
t.strand = StrandedFeature.POSITIVE;
t.annotation = RestrictionEnzymeManager.getAnnotation(enzyme);
t.enzyme = enzyme;
Matcher m = patterns[0].matcher(charSeq);
while (m.find())
{
int idx = m.start() + 1;
// Cuts outside target sequence
if (! findAll && (idx + usOffset < 0 || idx + dsOffset > seqLen))
continue;
t.location = new RangeLocation(idx, idx + siteLen - 1);
- target.createFeature(t);
+ synchronized (target) {
+ target.createFeature(t);
+ }
}
// If not palindromic we have to search reverse strand too
if (! enzyme.isPalindromic())
{
t.strand = StrandedFeature.NEGATIVE;
m = patterns[1].matcher(charSeq);
while (m.find())
{
int idx = m.start() + 1;
// Cuts outside target sequence
if (! findAll && (idx + usOffset < 0 || idx + dsOffset > seqLen))
continue;
t.location = new RangeLocation(idx, idx + siteLen - 1);
- target.createFeature(t);
+ synchronized (target) {
+ target.createFeature(t);
+ }
}
}
}
catch (Exception e)
{
throw new BioRuntimeException("Failed to complete search for "
+ enzyme,e);
}
}
}
| false | true | public void run()
{
SymbolListCharSequence charSeq = new SymbolListCharSequence(target);
try
{
Pattern [] patterns = RestrictionEnzymeManager.getPatterns(enzyme);
int siteLen = enzyme.getRecognitionSite().length();
int seqLen = target.length();
int usOffset = 0;
int dsOffset = 0;
int [] dsCut = enzyme.getDownstreamCut();
dsOffset = Math.max(dsCut[0], dsCut[1]);
if (enzyme.getCutType() == RestrictionEnzyme.CUT_COMPOUND)
{
// In coordinate space of recognition site, so
// upstream coordinates are negative
int [] usCut = enzyme.getUpstreamCut();
usOffset = Math.min(usCut[0], usCut[1]);
}
RestrictionSite.Template t = new RestrictionSite.Template();
t.type = RestrictionMapper.SITE_FEATURE_TYPE;
t.source = RestrictionMapper.SITE_FEATURE_SOURCE;
t.strand = StrandedFeature.POSITIVE;
t.annotation = RestrictionEnzymeManager.getAnnotation(enzyme);
t.enzyme = enzyme;
Matcher m = patterns[0].matcher(charSeq);
while (m.find())
{
int idx = m.start() + 1;
// Cuts outside target sequence
if (! findAll && (idx + usOffset < 0 || idx + dsOffset > seqLen))
continue;
t.location = new RangeLocation(idx, idx + siteLen - 1);
target.createFeature(t);
}
// If not palindromic we have to search reverse strand too
if (! enzyme.isPalindromic())
{
t.strand = StrandedFeature.NEGATIVE;
m = patterns[1].matcher(charSeq);
while (m.find())
{
int idx = m.start() + 1;
// Cuts outside target sequence
if (! findAll && (idx + usOffset < 0 || idx + dsOffset > seqLen))
continue;
t.location = new RangeLocation(idx, idx + siteLen - 1);
target.createFeature(t);
}
}
}
catch (Exception e)
{
throw new BioRuntimeException("Failed to complete search for "
+ enzyme,e);
}
}
| public void run()
{
SymbolListCharSequence charSeq = new SymbolListCharSequence(target);
try
{
Pattern [] patterns = RestrictionEnzymeManager.getPatterns(enzyme);
int siteLen = enzyme.getRecognitionSite().length();
int seqLen = target.length();
int usOffset = 0;
int dsOffset = 0;
int [] dsCut = enzyme.getDownstreamCut();
dsOffset = Math.max(dsCut[0], dsCut[1]);
if (enzyme.getCutType() == RestrictionEnzyme.CUT_COMPOUND)
{
// In coordinate space of recognition site, so
// upstream coordinates are negative
int [] usCut = enzyme.getUpstreamCut();
usOffset = Math.min(usCut[0], usCut[1]);
}
RestrictionSite.Template t = new RestrictionSite.Template();
t.type = RestrictionMapper.SITE_FEATURE_TYPE;
t.source = RestrictionMapper.SITE_FEATURE_SOURCE;
t.strand = StrandedFeature.POSITIVE;
t.annotation = RestrictionEnzymeManager.getAnnotation(enzyme);
t.enzyme = enzyme;
Matcher m = patterns[0].matcher(charSeq);
while (m.find())
{
int idx = m.start() + 1;
// Cuts outside target sequence
if (! findAll && (idx + usOffset < 0 || idx + dsOffset > seqLen))
continue;
t.location = new RangeLocation(idx, idx + siteLen - 1);
synchronized (target) {
target.createFeature(t);
}
}
// If not palindromic we have to search reverse strand too
if (! enzyme.isPalindromic())
{
t.strand = StrandedFeature.NEGATIVE;
m = patterns[1].matcher(charSeq);
while (m.find())
{
int idx = m.start() + 1;
// Cuts outside target sequence
if (! findAll && (idx + usOffset < 0 || idx + dsOffset > seqLen))
continue;
t.location = new RangeLocation(idx, idx + siteLen - 1);
synchronized (target) {
target.createFeature(t);
}
}
}
}
catch (Exception e)
{
throw new BioRuntimeException("Failed to complete search for "
+ enzyme,e);
}
}
|
diff --git a/src/game/Game.java b/src/game/Game.java
index 09c0edd..bd411bb 100644
--- a/src/game/Game.java
+++ b/src/game/Game.java
@@ -1,128 +1,129 @@
package game;
import input.KeyboardListener;
import java.io.IOException;
import settings.Settings;
import actor.ActorSet;
import actor.Asteroid;
public class Game {
private static graphics.Renderer renderer;
private static input.KeyboardListener input;
private static Player player;
private static Map map;
private static ActorSet actors;
private static GameThread game;
//for HUD radar testing, will be removed later
static actor.Asteroid a;
public static void init() {
System.out.println(Runtime.getRuntime().availableProcessors() + " available cores detected");
try {
Settings.init();
} catch (IOException e) {
e.printStackTrace();
}
map = Map.load("example_1");
player = new Player();
actors = new ActorSet();
actors.addAll(map.actors);
player.respawn(actors, map.getSpawnPosition());
renderer = new graphics.Renderer(player.getCamera());
input = new KeyboardListener();
graphics.Model.loadModels();
- sound.Manager.initialize(player.getCamera());
+ // FIXME: When we pass player.getCamera() the sound doesn't match the player position for some reason?
+ sound.Manager.initialize(player.getShip());
game = new GameThread(actors);
// CL - We need to get input even if the game is paused,
// that way we can unpause the game.
game.addCallback(input);
game.addCallback(new Updateable() {
public void update() {
player.updateCamera();
}
});
game.addCallback(new Updateable() {
public void update() {
sound.Manager.processEvents();
}
});
}
//for HUD radar testing, will be removed later
public static Asteroid getAsteroid() {
return a;
}
public static void joinServer(String server) {
player = new Player();
map = Map.load("example_1");
network.ClientServerThread.joinServer(server, player);
//renderer = new graphics.Renderer();
input = new KeyboardListener();
graphics.Model.loadModels();
a.setPosition(new math.Vector3f(0.0f,0.0f,-10.0f));
//actor.Actor.addActor(a);
//new GameThread().start();
}
public static void start() {
game.start();
renderer.start();
}
public static KeyboardListener getInputHandler(){
return input;
}
public static Player getPlayer() {
return player;
}
public static boolean isPaused() {
return game.getGameState() == GameThread.STATE_PAUSED;
}
public static void quitToMenu() {
game.setGameState(GameThread.STATE_STOPPED);
}
public static void togglePause() {
if (isPaused())
game.setGameState(GameThread.STATE_RUNNING);
else
game.setGameState(GameThread.STATE_PAUSED);
}
public static void exit() {
System.exit(0);
}
public static Map getMap() {
return map;
}
public static void setMap(Map m) {
map = m;
}
public static void main (String []args) throws IOException {
Game.init();
Game.start();
}
public static graphics.Renderer getRenderer() {
return renderer;
}
public static ActorSet getActors() {
return actors;
}
}
| true | true | public static void init() {
System.out.println(Runtime.getRuntime().availableProcessors() + " available cores detected");
try {
Settings.init();
} catch (IOException e) {
e.printStackTrace();
}
map = Map.load("example_1");
player = new Player();
actors = new ActorSet();
actors.addAll(map.actors);
player.respawn(actors, map.getSpawnPosition());
renderer = new graphics.Renderer(player.getCamera());
input = new KeyboardListener();
graphics.Model.loadModels();
sound.Manager.initialize(player.getCamera());
game = new GameThread(actors);
// CL - We need to get input even if the game is paused,
// that way we can unpause the game.
game.addCallback(input);
game.addCallback(new Updateable() {
public void update() {
player.updateCamera();
}
});
game.addCallback(new Updateable() {
public void update() {
sound.Manager.processEvents();
}
});
}
| public static void init() {
System.out.println(Runtime.getRuntime().availableProcessors() + " available cores detected");
try {
Settings.init();
} catch (IOException e) {
e.printStackTrace();
}
map = Map.load("example_1");
player = new Player();
actors = new ActorSet();
actors.addAll(map.actors);
player.respawn(actors, map.getSpawnPosition());
renderer = new graphics.Renderer(player.getCamera());
input = new KeyboardListener();
graphics.Model.loadModels();
// FIXME: When we pass player.getCamera() the sound doesn't match the player position for some reason?
sound.Manager.initialize(player.getShip());
game = new GameThread(actors);
// CL - We need to get input even if the game is paused,
// that way we can unpause the game.
game.addCallback(input);
game.addCallback(new Updateable() {
public void update() {
player.updateCamera();
}
});
game.addCallback(new Updateable() {
public void update() {
sound.Manager.processEvents();
}
});
}
|
diff --git a/environments/servlet/core/src/main/java/org/jboss/weld/environment/servlet/Listener.java b/environments/servlet/core/src/main/java/org/jboss/weld/environment/servlet/Listener.java
index 4b2378f57..ac9c35488 100644
--- a/environments/servlet/core/src/main/java/org/jboss/weld/environment/servlet/Listener.java
+++ b/environments/servlet/core/src/main/java/org/jboss/weld/environment/servlet/Listener.java
@@ -1,217 +1,217 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.environment.servlet;
import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyFactory.ClassLoaderProvider;
import javax.el.ELContextListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.jsp.JspApplicationContext;
import javax.servlet.jsp.JspFactory;
import org.jboss.weld.bootstrap.api.Bootstrap;
import org.jboss.weld.bootstrap.api.Environments;
import org.jboss.weld.context.api.BeanStore;
import org.jboss.weld.context.api.helpers.ConcurrentHashMapBeanStore;
import org.jboss.weld.environment.jetty.JettyWeldInjector;
import org.jboss.weld.environment.servlet.deployment.ServletDeployment;
import org.jboss.weld.environment.servlet.services.ServletResourceInjectionServices;
import org.jboss.weld.environment.servlet.services.ServletServicesImpl;
import org.jboss.weld.environment.servlet.util.Reflections;
import org.jboss.weld.environment.tomcat.WeldForwardingAnnotationProcessor;
import org.jboss.weld.injection.spi.ResourceInjectionServices;
import org.jboss.weld.manager.api.WeldManager;
import org.jboss.weld.servlet.api.ServletListener;
import org.jboss.weld.servlet.api.ServletServices;
import org.jboss.weld.servlet.api.helpers.ForwardingServletListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Pete Muir
*/
public class Listener extends ForwardingServletListener
{
private static final Logger log = LoggerFactory.getLogger(Listener.class);
private static final String BOOTSTRAP_IMPL_CLASS_NAME = "org.jboss.weld.bootstrap.WeldBootstrap";
private static final String WELD_LISTENER_CLASS_NAME = "org.jboss.weld.servlet.WeldListener";
private static final String APPLICATION_BEAN_STORE_ATTRIBUTE_NAME = Listener.class.getName() + ".applicationBeanStore";
private static final String EXPRESSION_FACTORY_NAME = "org.jboss.weld.el.ExpressionFactory";
private static final String JETTY_REQUIRED_CLASS_NAME = "org.mortbay.jetty.servlet.ServletHandler";
public static final String INJECTOR_ATTRIBUTE_NAME = "org.jboss.weld.environment.jetty.JettyWeldInjector";
private final transient Bootstrap bootstrap;
private final transient ServletListener weldListener;
private WeldManager manager;
public Listener()
{
try
{
bootstrap = Reflections.newInstance(BOOTSTRAP_IMPL_CLASS_NAME);
}
catch (IllegalArgumentException e)
{
throw new IllegalStateException("Error loading Weld bootstrap, check that Weld is on the classpath", e);
}
try
{
weldListener = Reflections.newInstance(WELD_LISTENER_CLASS_NAME);
}
catch (IllegalArgumentException e)
{
throw new IllegalStateException("Error loading Weld listener, check that Weld is on the classpath", e);
}
}
@Override
public void contextDestroyed(ServletContextEvent sce)
{
bootstrap.shutdown();
try
{
Reflections.classForName("org.apache.AnnotationProcessor");
WeldForwardingAnnotationProcessor.restoreAnnotationProcessor(sce);
}
catch (IllegalArgumentException ignore) {}
try
{
Reflections.classForName(JETTY_REQUIRED_CLASS_NAME);
sce.getServletContext().removeAttribute(INJECTOR_ATTRIBUTE_NAME);
}
catch (IllegalArgumentException ignore) {}
super.contextDestroyed(sce);
}
@Override
public void contextInitialized(ServletContextEvent sce)
{
// Make Javassist always use the TCCL to load classes
ProxyFactory.classLoaderProvider = new ClassLoaderProvider()
{
public ClassLoader get(ProxyFactory pf)
{
return Thread.currentThread().getContextClassLoader();
}
};
BeanStore applicationBeanStore = new ConcurrentHashMapBeanStore();
sce.getServletContext().setAttribute(APPLICATION_BEAN_STORE_ATTRIBUTE_NAME, applicationBeanStore);
ServletDeployment deployment = new ServletDeployment(sce.getServletContext());
try
{
deployment.getWebAppBeanDeploymentArchive().getServices().add(
ResourceInjectionServices.class, new ServletResourceInjectionServices() {});
}
catch (NoClassDefFoundError e)
{
// Support GAE
log.warn("@Resource injection not available in simple beans");
}
deployment.getServices().add(ServletServices.class,
new ServletServicesImpl(deployment.getWebAppBeanDeploymentArchive()));
bootstrap.startContainer(Environments.SERVLET, deployment, applicationBeanStore).startInitialization();
manager = bootstrap.getManager(deployment.getWebAppBeanDeploymentArchive());
boolean tomcat = true;
try
{
Reflections.classForName("org.apache.AnnotationProcessor");
}
catch (IllegalArgumentException e)
{
tomcat = false;
}
if (tomcat)
{
try
{
WeldForwardingAnnotationProcessor.replaceAnnotationProcessor(sce, manager);
- log.info("Tomcat 6 detected, JSR-299 injection will be available in Servlets, Filters etc.");
+ log.info("Tomcat 6 detected, CDI injection will be available in Servlets and Filters. Injection into Listeners is not supported");
}
catch (Exception e)
{
- log.error("Unable to replace Tomcat AnnotationProcessor. JSR-299 injection will not be available in Servlets, Filters etc.", e);
+ log.error("Unable to replace Tomcat AnnotationProcessor. CDI injection will not be available in Servlets, Filters, or Listeners", e);
}
}
boolean jetty = true;
try
{
Reflections.classForName(JETTY_REQUIRED_CLASS_NAME);
}
catch (IllegalArgumentException e)
{
jetty = false;
}
if (jetty)
{
// Try pushing a Jetty Injector into the servlet context
try
{
Class<?> clazz = Reflections.classForName(JettyWeldInjector.class.getName());
Object injector = clazz.getConstructor(WeldManager.class).newInstance(manager);
sce.getServletContext().setAttribute(INJECTOR_ATTRIBUTE_NAME, injector);
- log.info("Jetty detected, JSR-299 injection will be available in Servlets, Filters etc.");
+ log.info("Jetty detected, JSR-299 injection will be available in Servlets and Filters. Injection into Listeners is not supported.");
}
catch (Exception e)
{
- log.error("Unable to create JettyWeldInjector. JSR-299 injection will not be available in Servlets, Filters etc.", e);
+ log.error("Unable to create JettyWeldInjector. CDI injection will not be available in Servlets, Filters or Listeners", e);
}
}
if (!tomcat && !jetty) {
- log.info("No supported servlet container detected, JSR-299 injection will NOT be available in Servlets, Filters etc.");
+ log.info("No supported servlet container detected, CDI injection will NOT be available in Servlets, Filtersor or Listeners");
}
// Push the manager into the servlet context so we can access in JSF
if (JspFactory.getDefaultFactory() != null)
{
JspApplicationContext jspApplicationContext = JspFactory.getDefaultFactory().getJspApplicationContext(sce.getServletContext());
// Register the ELResolver with JSP
jspApplicationContext.addELResolver(manager.getELResolver());
// Register ELContextListener with JSP
jspApplicationContext.addELContextListener(Reflections.<ELContextListener>
newInstance("org.jboss.weld.el.WeldELContextListener"));
// Push the wrapped expression factory into the servlet context so that Tomcat or Jetty can hook it in using a container code
sce.getServletContext().setAttribute(EXPRESSION_FACTORY_NAME,
manager.wrapExpressionFactory(jspApplicationContext.getExpressionFactory()));
}
bootstrap.deployBeans().validateBeans().endInitialization();
super.contextInitialized(sce);
}
@Override
protected ServletListener delegate()
{
return weldListener;
}
}
| false | true | public void contextInitialized(ServletContextEvent sce)
{
// Make Javassist always use the TCCL to load classes
ProxyFactory.classLoaderProvider = new ClassLoaderProvider()
{
public ClassLoader get(ProxyFactory pf)
{
return Thread.currentThread().getContextClassLoader();
}
};
BeanStore applicationBeanStore = new ConcurrentHashMapBeanStore();
sce.getServletContext().setAttribute(APPLICATION_BEAN_STORE_ATTRIBUTE_NAME, applicationBeanStore);
ServletDeployment deployment = new ServletDeployment(sce.getServletContext());
try
{
deployment.getWebAppBeanDeploymentArchive().getServices().add(
ResourceInjectionServices.class, new ServletResourceInjectionServices() {});
}
catch (NoClassDefFoundError e)
{
// Support GAE
log.warn("@Resource injection not available in simple beans");
}
deployment.getServices().add(ServletServices.class,
new ServletServicesImpl(deployment.getWebAppBeanDeploymentArchive()));
bootstrap.startContainer(Environments.SERVLET, deployment, applicationBeanStore).startInitialization();
manager = bootstrap.getManager(deployment.getWebAppBeanDeploymentArchive());
boolean tomcat = true;
try
{
Reflections.classForName("org.apache.AnnotationProcessor");
}
catch (IllegalArgumentException e)
{
tomcat = false;
}
if (tomcat)
{
try
{
WeldForwardingAnnotationProcessor.replaceAnnotationProcessor(sce, manager);
log.info("Tomcat 6 detected, JSR-299 injection will be available in Servlets, Filters etc.");
}
catch (Exception e)
{
log.error("Unable to replace Tomcat AnnotationProcessor. JSR-299 injection will not be available in Servlets, Filters etc.", e);
}
}
boolean jetty = true;
try
{
Reflections.classForName(JETTY_REQUIRED_CLASS_NAME);
}
catch (IllegalArgumentException e)
{
jetty = false;
}
if (jetty)
{
// Try pushing a Jetty Injector into the servlet context
try
{
Class<?> clazz = Reflections.classForName(JettyWeldInjector.class.getName());
Object injector = clazz.getConstructor(WeldManager.class).newInstance(manager);
sce.getServletContext().setAttribute(INJECTOR_ATTRIBUTE_NAME, injector);
log.info("Jetty detected, JSR-299 injection will be available in Servlets, Filters etc.");
}
catch (Exception e)
{
log.error("Unable to create JettyWeldInjector. JSR-299 injection will not be available in Servlets, Filters etc.", e);
}
}
if (!tomcat && !jetty) {
log.info("No supported servlet container detected, JSR-299 injection will NOT be available in Servlets, Filters etc.");
}
// Push the manager into the servlet context so we can access in JSF
if (JspFactory.getDefaultFactory() != null)
{
JspApplicationContext jspApplicationContext = JspFactory.getDefaultFactory().getJspApplicationContext(sce.getServletContext());
// Register the ELResolver with JSP
jspApplicationContext.addELResolver(manager.getELResolver());
// Register ELContextListener with JSP
jspApplicationContext.addELContextListener(Reflections.<ELContextListener>
newInstance("org.jboss.weld.el.WeldELContextListener"));
// Push the wrapped expression factory into the servlet context so that Tomcat or Jetty can hook it in using a container code
sce.getServletContext().setAttribute(EXPRESSION_FACTORY_NAME,
manager.wrapExpressionFactory(jspApplicationContext.getExpressionFactory()));
}
bootstrap.deployBeans().validateBeans().endInitialization();
super.contextInitialized(sce);
}
| public void contextInitialized(ServletContextEvent sce)
{
// Make Javassist always use the TCCL to load classes
ProxyFactory.classLoaderProvider = new ClassLoaderProvider()
{
public ClassLoader get(ProxyFactory pf)
{
return Thread.currentThread().getContextClassLoader();
}
};
BeanStore applicationBeanStore = new ConcurrentHashMapBeanStore();
sce.getServletContext().setAttribute(APPLICATION_BEAN_STORE_ATTRIBUTE_NAME, applicationBeanStore);
ServletDeployment deployment = new ServletDeployment(sce.getServletContext());
try
{
deployment.getWebAppBeanDeploymentArchive().getServices().add(
ResourceInjectionServices.class, new ServletResourceInjectionServices() {});
}
catch (NoClassDefFoundError e)
{
// Support GAE
log.warn("@Resource injection not available in simple beans");
}
deployment.getServices().add(ServletServices.class,
new ServletServicesImpl(deployment.getWebAppBeanDeploymentArchive()));
bootstrap.startContainer(Environments.SERVLET, deployment, applicationBeanStore).startInitialization();
manager = bootstrap.getManager(deployment.getWebAppBeanDeploymentArchive());
boolean tomcat = true;
try
{
Reflections.classForName("org.apache.AnnotationProcessor");
}
catch (IllegalArgumentException e)
{
tomcat = false;
}
if (tomcat)
{
try
{
WeldForwardingAnnotationProcessor.replaceAnnotationProcessor(sce, manager);
log.info("Tomcat 6 detected, CDI injection will be available in Servlets and Filters. Injection into Listeners is not supported");
}
catch (Exception e)
{
log.error("Unable to replace Tomcat AnnotationProcessor. CDI injection will not be available in Servlets, Filters, or Listeners", e);
}
}
boolean jetty = true;
try
{
Reflections.classForName(JETTY_REQUIRED_CLASS_NAME);
}
catch (IllegalArgumentException e)
{
jetty = false;
}
if (jetty)
{
// Try pushing a Jetty Injector into the servlet context
try
{
Class<?> clazz = Reflections.classForName(JettyWeldInjector.class.getName());
Object injector = clazz.getConstructor(WeldManager.class).newInstance(manager);
sce.getServletContext().setAttribute(INJECTOR_ATTRIBUTE_NAME, injector);
log.info("Jetty detected, JSR-299 injection will be available in Servlets and Filters. Injection into Listeners is not supported.");
}
catch (Exception e)
{
log.error("Unable to create JettyWeldInjector. CDI injection will not be available in Servlets, Filters or Listeners", e);
}
}
if (!tomcat && !jetty) {
log.info("No supported servlet container detected, CDI injection will NOT be available in Servlets, Filtersor or Listeners");
}
// Push the manager into the servlet context so we can access in JSF
if (JspFactory.getDefaultFactory() != null)
{
JspApplicationContext jspApplicationContext = JspFactory.getDefaultFactory().getJspApplicationContext(sce.getServletContext());
// Register the ELResolver with JSP
jspApplicationContext.addELResolver(manager.getELResolver());
// Register ELContextListener with JSP
jspApplicationContext.addELContextListener(Reflections.<ELContextListener>
newInstance("org.jboss.weld.el.WeldELContextListener"));
// Push the wrapped expression factory into the servlet context so that Tomcat or Jetty can hook it in using a container code
sce.getServletContext().setAttribute(EXPRESSION_FACTORY_NAME,
manager.wrapExpressionFactory(jspApplicationContext.getExpressionFactory()));
}
bootstrap.deployBeans().validateBeans().endInitialization();
super.contextInitialized(sce);
}
|
diff --git a/db/src/main/java/com/psddev/dari/db/StateValueUtils.java b/db/src/main/java/com/psddev/dari/db/StateValueUtils.java
index 4730c65d..27ff5ed8 100644
--- a/db/src/main/java/com/psddev/dari/db/StateValueUtils.java
+++ b/db/src/main/java/com/psddev/dari/db/StateValueUtils.java
@@ -1,613 +1,613 @@
package com.psddev.dari.db;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.ObjectMap;
import com.psddev.dari.util.StringUtils;
import com.psddev.dari.util.StorageItem;
/** State value utility methods. */
abstract class StateValueUtils {
/** Key for the embedded object's unique ID. */
public static final String ID_KEY = "_id";
/** Key for the embedded object's type. */
public static final String TYPE_KEY = "_type";
/**
* Key for the reference to the object that should replace the
* embedded object map.
*/
public static final String REFERENCE_KEY = "_ref";
/**
* Thread local map used for detecting circular references in
* {@link #resolveReferences}.
*/
private static final ThreadLocal<Map<UUID, Object>> CIRCULAR_REFERENCES = new ThreadLocal<Map<UUID, Object>>();
/** Converts the given {@code object} into an ID if it's a reference. */
public static UUID toIdIfReference(Object object) {
return object instanceof Map ?
ObjectUtils.to(UUID.class, ((Map<?, ?>) object).get(REFERENCE_KEY)) :
null;
}
public static Object toObjectIfReference(Database database, Object object) {
if (object instanceof Map) {
Map<?, ?> objectMap = (Map<?, ?>) object;
UUID id = ObjectUtils.to(UUID.class, objectMap.get(REFERENCE_KEY));
if (id != null) {
UUID typeId = ObjectUtils.to(UUID.class, objectMap.get(TYPE_KEY));
ObjectType type = database.getEnvironment().getTypeById(typeId);
if (type == null || type.isAbstract()) {
return database.readFirst(Query.from(Object.class).where("_id = ?", id));
}
Object reference = type.createObject(id);
State referenceState = State.getInstance(reference);
referenceState.setStatus(StateStatus.REFERENCE_ONLY);
referenceState.setResolveToReferenceOnly(true);
return reference;
}
}
return null;
}
/** Resolves all object references within the given {@code items}. */
public static Map<UUID, Object> resolveReferences(Database database, Object parent, Iterable<?> items, String field) {
State parentState = State.getInstance(parent);
if (parentState != null && parentState.isResolveToReferenceOnly()) {
Map<UUID, Object> references = new HashMap<UUID, Object>();
for (Object item : items) {
Object itemReference = toObjectIfReference(database, item);
if (itemReference != null) {
references.put(State.getInstance(itemReference).getId(), itemReference);
}
}
return references;
}
if (parent instanceof Modification) {
for (Object item : parentState.getObjects()) {
if (!(item instanceof Modification)) {
parent = item;
break;
}
}
if (parent instanceof Modification) {
parent = null;
}
}
boolean isFirst = false;
try {
Map<UUID, Object> circularReferences = CIRCULAR_REFERENCES.get();
if (circularReferences == null) {
isFirst = true;
circularReferences = new HashMap<UUID, Object>();
CIRCULAR_REFERENCES.set(circularReferences);
}
if (parentState != null) {
circularReferences.put(parentState.getId(), parent);
}
// Find IDs that have not been resolved yet.
Map<UUID, Object> references = new HashMap<UUID, Object>();
Set<UUID> unresolvedIds = new HashSet<UUID>();
Set<UUID> unresolvedTypeIds = new HashSet<UUID>();
for (Object item : items) {
UUID id = toIdIfReference(item);
if (id != null) {
if (circularReferences.containsKey(id)) {
references.put(id, circularReferences.get(id));
} else if (parentState != null && parentState.getExtras().containsKey(State.SUB_DATA_STATE_EXTRA_PREFIX + id)) {
references.put(id, parentState.getExtras().get(State.SUB_DATA_STATE_EXTRA_PREFIX + id));
} else {
unresolvedIds.add(id);
unresolvedTypeIds.add(ObjectUtils.to(UUID.class, ((Map<?, ?>) item).get(TYPE_KEY)));
}
}
}
// Fetch unresolved objects and cache them.
if (!unresolvedIds.isEmpty()) {
Query<?> query = Query.
from(Object.class).
where("_id = ?", unresolvedIds).
using(database).
option(State.REFERENCE_RESOLVING_QUERY_OPTION, parent).
option(State.REFERENCE_FIELD_QUERY_OPTION, field).
option(State.UNRESOLVED_TYPE_IDS_QUERY_OPTION, unresolvedTypeIds);
if (parentState != null) {
if (!parentState.isResolveUsingCache()) {
query.setCache(false);
}
if (parentState.isResolveUsingMaster()) {
query.setMaster(true);
}
}
for (Object object : query.selectAll()) {
UUID id = State.getInstance(object).getId();
unresolvedIds.remove(id);
circularReferences.put(id, object);
references.put(id, object);
}
for (UUID id : unresolvedIds) {
circularReferences.put(id, null);
}
}
for (Iterator<Map.Entry<UUID, Object>> i = references.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<UUID, Object> entry = i.next();
Object object = entry.getValue();
if ((parentState == null ||
!parentState.isResolveInvisible()) &&
object != null &&
- !ObjectUtils.isBlank(State.getInstance(object).get("dari.visibilities"))) {
+ !ObjectUtils.isBlank(State.getInstance(object).getRawValue("dari.visibilities"))) {
entry.setValue(null);
}
}
return references;
} finally {
if (isFirst) {
CIRCULAR_REFERENCES.remove();
}
}
}
public static Map<UUID, Object> resolveReferences(Database database, Object parent, Iterable<?> items) {
return resolveReferences(database, parent, items, null);
}
/**
* Converts the given {@code value} to an instance of the type that
* matches the given {@code field} and {@code type} and is most
* commonly used in Java.
*/
public static Object toJavaValue(
Database database,
Object object,
ObjectField field,
String type,
Object value) {
if (value == null && (field == null || ! field.isMetric())) {
return null;
}
UUID valueId = toIdIfReference(value);
if (valueId != null) {
Map<UUID, Object> references = resolveReferences(database, object, Collections.singleton(value));
value = references.get(valueId);
if (value == null) {
return null;
}
}
if (field == null || type == null) {
return value;
}
int slashAt = type.indexOf('/');
String firstType;
String subType;
if (slashAt > -1) {
firstType = type.substring(0, slashAt);
subType = type.substring(slashAt + 1);
} else {
firstType = type;
subType = null;
}
Converter converter = CONVERTERS.get(firstType);
if (converter == null) {
return value;
}
try {
return converter.toJavaValue(database, object, field, subType, value);
} catch (Exception error) {
if (object != null) {
State state = State.getInstance(object);
String name = field.getInternalName();
state.put("dari.trash." + name, value);
state.put("dari.trashError." + name, error.getClass().getName());
state.put("dari.trashErrorMessage." + name, error.getMessage());
}
return null;
}
}
/**
* Interface that defines how to convert between various
* representations of a state value.
*/
private interface Converter {
Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value)
throws Exception;
}
private static final Map<String, Converter> CONVERTERS; static {
Map<String, Converter> m = new HashMap<String, Converter>();
m.put(ObjectField.DATE_TYPE, new Converter() {
@Override
public Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value) {
if (value instanceof Date) {
return value;
} else if (value instanceof Number) {
return new Date(((Number) value).longValue());
} else {
return ObjectUtils.to(Date.class, value);
}
}
});
m.put(ObjectField.FILE_TYPE, new Converter() {
@Override
public Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value) {
if (value instanceof StorageItem) {
return value;
} else if (value instanceof String) {
return StorageItem.Static.createUrl((String) value);
} else if (value instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) value;
StorageItem item = StorageItem.Static.createIn(ObjectUtils.to(String.class, map.get("storage")));
new ObjectMap(item).putAll(map);
return item;
} else {
throw new IllegalArgumentException();
}
}
});
m.put(ObjectField.LIST_TYPE, new Converter() {
@Override
public Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value) {
if (value instanceof StateValueList) {
return value;
} else {
Iterable<?> iterable = ObjectUtils.to(Iterable.class, value);
return new StateValueList(database, object, field, subType, iterable);
}
}
});
m.put(ObjectField.LOCATION_TYPE, new Converter() {
@Override
public Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value) {
if (value instanceof Location) {
return value;
} else if (value instanceof Map) {
Map<?, ?> map = (Map<?, ?>) value;
Double x = ObjectUtils.to(Double.class, map.get("x"));
Double y = ObjectUtils.to(Double.class, map.get("y"));
if (x != null && y != null) {
return new Location(x, y);
}
}
throw new IllegalArgumentException();
}
});
m.put(ObjectField.REGION_TYPE, new Converter() {
@Override
public Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value) {
if (value instanceof Region) {
return value;
} else if (value instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) value;
Region region = Region.parseGeoJson(map);
Region.parseCircles(region, (List<List<Double>>) map.get("circles"));
return region;
}
throw new IllegalArgumentException();
}
});
m.put(ObjectField.MAP_TYPE, new Converter() {
@Override
public Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value) {
if (value instanceof StateValueMap) {
return value;
} else if (value instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) value;
return new StateValueMap(database, object, field, subType, map);
} else {
throw new IllegalArgumentException();
}
}
});
m.put(ObjectField.METRIC_TYPE, new Converter() {
@Override
public Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value) {
if (value instanceof Metric) {
return value;
} else {
Metric metric = new Metric(State.getInstance(object), field);
return metric;
}
}
});
m.put(ObjectField.RECORD_TYPE, new Converter() {
@Override
public Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value) {
if (value instanceof Recordable) {
return value;
} else if (value instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> valueMap = (Map<String, Object>) value;
Object typeId = valueMap.get(TYPE_KEY);
if (typeId != null) {
State objectState = State.getInstance(object);
DatabaseEnvironment environment = objectState.getDatabase().getEnvironment();
ObjectType valueType = environment.getTypeById(ObjectUtils.to(UUID.class, typeId));
if (valueType == null) {
valueType = environment.getTypeByName(ObjectUtils.to(String.class, typeId));
}
if (valueType != null) {
value = valueType.createObject(ObjectUtils.to(UUID.class, valueMap.get(ID_KEY)));
State valueState = State.getInstance(value);
valueState.setDatabase(database);
valueState.setResolveToReferenceOnly(objectState.isResolveToReferenceOnly());
valueState.setResolveInvisible(objectState.isResolveInvisible());
valueState.putAll(valueMap);
return value;
}
}
} else {
UUID id = ObjectUtils.to(UUID.class, value);
if (id != null) {
return Query.findById(Object.class, id);
}
}
throw new IllegalArgumentException();
}
});
m.put(ObjectField.REFERENTIAL_TEXT_TYPE, new Converter() {
@Override
public Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value) {
if (value instanceof ReferentialText) {
return value;
} else {
ReferentialText text = new ReferentialText();
if (value instanceof Iterable) {
for (Object item : (Iterable<?>) value) {
text.add(item);
}
} else {
text.add(value.toString());
}
return text;
}
}
});
m.put(ObjectField.SET_TYPE, new Converter() {
@Override
public Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value) {
if (value instanceof StateValueSet) {
return value;
} else {
Iterable<?> iterable = ObjectUtils.to(Iterable.class, value);
return new StateValueSet(database, object, field, subType, iterable);
}
}
});
m.put(ObjectField.TEXT_TYPE, new Converter() {
@Override
public Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value) {
if (value instanceof byte[]) {
value = new String((byte[]) value, StringUtils.UTF_8);
}
String enumClassName = field.getJavaEnumClassName();
Class<?> enumClass = ObjectUtils.getClassByName(enumClassName);
if (enumClass != null && Enum.class.isAssignableFrom(enumClass)) {
return ObjectUtils.to(enumClass, value);
}
return value.toString();
}
});
m.put(ObjectField.URI_TYPE, new Converter() {
@Override
public Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value)
throws URISyntaxException {
if (value instanceof URI) {
return value;
} else {
return new URI(value.toString());
}
}
});
m.put(ObjectField.URL_TYPE, new Converter() {
@Override
public Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value)
throws MalformedURLException {
if (value instanceof URL) {
return value;
} else {
return new URL(value.toString());
}
}
});
m.put(ObjectField.UUID_TYPE, new Converter() {
@Override
public Object toJavaValue(
Database database,
Object object,
ObjectField field,
String subType,
Object value) {
if (value instanceof UUID) {
return value;
} else {
UUID uuid = ObjectUtils.to(UUID.class, value);
if (uuid != null) {
return uuid;
}
}
throw new IllegalArgumentException();
}
});
CONVERTERS = m;
}
}
| true | true | public static Map<UUID, Object> resolveReferences(Database database, Object parent, Iterable<?> items, String field) {
State parentState = State.getInstance(parent);
if (parentState != null && parentState.isResolveToReferenceOnly()) {
Map<UUID, Object> references = new HashMap<UUID, Object>();
for (Object item : items) {
Object itemReference = toObjectIfReference(database, item);
if (itemReference != null) {
references.put(State.getInstance(itemReference).getId(), itemReference);
}
}
return references;
}
if (parent instanceof Modification) {
for (Object item : parentState.getObjects()) {
if (!(item instanceof Modification)) {
parent = item;
break;
}
}
if (parent instanceof Modification) {
parent = null;
}
}
boolean isFirst = false;
try {
Map<UUID, Object> circularReferences = CIRCULAR_REFERENCES.get();
if (circularReferences == null) {
isFirst = true;
circularReferences = new HashMap<UUID, Object>();
CIRCULAR_REFERENCES.set(circularReferences);
}
if (parentState != null) {
circularReferences.put(parentState.getId(), parent);
}
// Find IDs that have not been resolved yet.
Map<UUID, Object> references = new HashMap<UUID, Object>();
Set<UUID> unresolvedIds = new HashSet<UUID>();
Set<UUID> unresolvedTypeIds = new HashSet<UUID>();
for (Object item : items) {
UUID id = toIdIfReference(item);
if (id != null) {
if (circularReferences.containsKey(id)) {
references.put(id, circularReferences.get(id));
} else if (parentState != null && parentState.getExtras().containsKey(State.SUB_DATA_STATE_EXTRA_PREFIX + id)) {
references.put(id, parentState.getExtras().get(State.SUB_DATA_STATE_EXTRA_PREFIX + id));
} else {
unresolvedIds.add(id);
unresolvedTypeIds.add(ObjectUtils.to(UUID.class, ((Map<?, ?>) item).get(TYPE_KEY)));
}
}
}
// Fetch unresolved objects and cache them.
if (!unresolvedIds.isEmpty()) {
Query<?> query = Query.
from(Object.class).
where("_id = ?", unresolvedIds).
using(database).
option(State.REFERENCE_RESOLVING_QUERY_OPTION, parent).
option(State.REFERENCE_FIELD_QUERY_OPTION, field).
option(State.UNRESOLVED_TYPE_IDS_QUERY_OPTION, unresolvedTypeIds);
if (parentState != null) {
if (!parentState.isResolveUsingCache()) {
query.setCache(false);
}
if (parentState.isResolveUsingMaster()) {
query.setMaster(true);
}
}
for (Object object : query.selectAll()) {
UUID id = State.getInstance(object).getId();
unresolvedIds.remove(id);
circularReferences.put(id, object);
references.put(id, object);
}
for (UUID id : unresolvedIds) {
circularReferences.put(id, null);
}
}
for (Iterator<Map.Entry<UUID, Object>> i = references.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<UUID, Object> entry = i.next();
Object object = entry.getValue();
if ((parentState == null ||
!parentState.isResolveInvisible()) &&
object != null &&
!ObjectUtils.isBlank(State.getInstance(object).get("dari.visibilities"))) {
entry.setValue(null);
}
}
return references;
} finally {
if (isFirst) {
CIRCULAR_REFERENCES.remove();
}
}
}
| public static Map<UUID, Object> resolveReferences(Database database, Object parent, Iterable<?> items, String field) {
State parentState = State.getInstance(parent);
if (parentState != null && parentState.isResolveToReferenceOnly()) {
Map<UUID, Object> references = new HashMap<UUID, Object>();
for (Object item : items) {
Object itemReference = toObjectIfReference(database, item);
if (itemReference != null) {
references.put(State.getInstance(itemReference).getId(), itemReference);
}
}
return references;
}
if (parent instanceof Modification) {
for (Object item : parentState.getObjects()) {
if (!(item instanceof Modification)) {
parent = item;
break;
}
}
if (parent instanceof Modification) {
parent = null;
}
}
boolean isFirst = false;
try {
Map<UUID, Object> circularReferences = CIRCULAR_REFERENCES.get();
if (circularReferences == null) {
isFirst = true;
circularReferences = new HashMap<UUID, Object>();
CIRCULAR_REFERENCES.set(circularReferences);
}
if (parentState != null) {
circularReferences.put(parentState.getId(), parent);
}
// Find IDs that have not been resolved yet.
Map<UUID, Object> references = new HashMap<UUID, Object>();
Set<UUID> unresolvedIds = new HashSet<UUID>();
Set<UUID> unresolvedTypeIds = new HashSet<UUID>();
for (Object item : items) {
UUID id = toIdIfReference(item);
if (id != null) {
if (circularReferences.containsKey(id)) {
references.put(id, circularReferences.get(id));
} else if (parentState != null && parentState.getExtras().containsKey(State.SUB_DATA_STATE_EXTRA_PREFIX + id)) {
references.put(id, parentState.getExtras().get(State.SUB_DATA_STATE_EXTRA_PREFIX + id));
} else {
unresolvedIds.add(id);
unresolvedTypeIds.add(ObjectUtils.to(UUID.class, ((Map<?, ?>) item).get(TYPE_KEY)));
}
}
}
// Fetch unresolved objects and cache them.
if (!unresolvedIds.isEmpty()) {
Query<?> query = Query.
from(Object.class).
where("_id = ?", unresolvedIds).
using(database).
option(State.REFERENCE_RESOLVING_QUERY_OPTION, parent).
option(State.REFERENCE_FIELD_QUERY_OPTION, field).
option(State.UNRESOLVED_TYPE_IDS_QUERY_OPTION, unresolvedTypeIds);
if (parentState != null) {
if (!parentState.isResolveUsingCache()) {
query.setCache(false);
}
if (parentState.isResolveUsingMaster()) {
query.setMaster(true);
}
}
for (Object object : query.selectAll()) {
UUID id = State.getInstance(object).getId();
unresolvedIds.remove(id);
circularReferences.put(id, object);
references.put(id, object);
}
for (UUID id : unresolvedIds) {
circularReferences.put(id, null);
}
}
for (Iterator<Map.Entry<UUID, Object>> i = references.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<UUID, Object> entry = i.next();
Object object = entry.getValue();
if ((parentState == null ||
!parentState.isResolveInvisible()) &&
object != null &&
!ObjectUtils.isBlank(State.getInstance(object).getRawValue("dari.visibilities"))) {
entry.setValue(null);
}
}
return references;
} finally {
if (isFirst) {
CIRCULAR_REFERENCES.remove();
}
}
}
|
diff --git a/src/libbitster/Manager.java b/src/libbitster/Manager.java
index af6c93a..c4925b0 100644
--- a/src/libbitster/Manager.java
+++ b/src/libbitster/Manager.java
@@ -1,609 +1,609 @@
package libbitster;
import java.io.File;
import java.io.IOException;
import java.nio.channels.*;
import java.nio.ByteBuffer;
import java.util.*;
import java.net.*;
/**
* Coordinates actions of all the {@link Actor}s and manages
* the application's operation.
* @author Martin Miralles-Cordal
* @author Russell Frank
* @author Theodore Surgent
*/
public class Manager extends Actor implements Communicator {
private Broker optimisticUnchoke = null;
private ArrayList<Broker> preferred; // preferred peers
private int uploadSlots = 4;
private final int blockSize = 16384;
private String state;
// the contents of the metainfo file
private TorrentInfo metainfo;
// destination file
private File dest;
// communicates with tracker
private Deputy deputy;
// Actually select()s on sockets
private Overlord overlord;
// Peer ID
private final ByteBuffer peerId;
// Listens for incoming peer connections
private ServerSocketChannel listen;
// current list of peers
private ArrayList<Map<String, Object>> peers;
private LinkedList<Broker> brokers; // broker objects for peer communication
private ArrayList<Piece> pieces;
private Object[] piecesByAvailability;
private BitSet received;
private HashMap<String, Broker> peersByAddress;
// torrent info
private int downloaded, left;
private UserInterface ui;
private Funnel funnel;
// true if the torrent was already done when we started.
// This is for suppressing "completed" messages when we're already seeding.
boolean startedSeeding = false;
/**
* Instantiates the Manager and its Deputy, sending a memo containing the
* tracker's announce URL.
* @param metainfo A {@link TorrentInfo} object containing information about
* a torrent.
* @param dest The file to save the download as
*/
public Manager(TorrentInfo metainfo, File dest, UserInterface ui)
{
super();
state = "booting";
Log.info("Manager init");
preferred = new ArrayList<Broker>();
this.metainfo = metainfo;
this.dest = dest;
this.downloaded = 0;
this.ui = ui;
this.setLeft(metainfo.file_length);
overlord = new Overlord();
brokers = new LinkedList<Broker>();
pieces = new ArrayList<Piece>();
received = new BitSet(metainfo.piece_hashes.length);
try {
funnel = new Funnel(metainfo, dest, this);
} catch (IOException e1) {
System.err.println("Error creating funnel");
System.exit(1);
}
funnel.start();
// generate peer ID if we haven't already
this.peerId = generatePeerID();
peersByAddress = new HashMap<String, Broker>();
Log.info("Our peer id: " + Util.buff2str(peerId));
int i, total = metainfo.file_length;
for (i = 0; i < metainfo.piece_hashes.length; i++) {
pieces.add(new Piece(
metainfo.piece_hashes[i].array(),
i,
blockSize,
// If the last piece is truncated (which it probably is) total will
// be less than piece_length and will be the last piece's length.
Math.min(metainfo.piece_length, total)
));
total -= metainfo.piece_length;
}
Util.setTimeout(30000, new Memo("optimisticUnchoke", null, this));
Util.setTimeout(60000, new Memo("status", null, this));
}
private void initialize() {
if(left == 0) {
this.startedSeeding = true;
}
// We have all the piece objects, now populate our RPF array
piecesByAvailability = pieces.toArray();
// listen for connections, try ports 6881-6889, quite if all taken
for(int i = 6881; i < 6890; ++i)
{
try {
listen = ServerSocketChannel.open();
listen.socket().bind(new InetSocketAddress("0.0.0.0", i));
listen.configureBlocking(false);
break;
}
catch (IOException e) {
if(i == 6890)
{
Log.warning("could not open a socket for listening");
shutdown();
}
}
}
overlord.register(listen, this);
state = "downloading";
Janitor.getInstance().register(this);
ui.addManager(this);
deputy = new Deputy(metainfo, listen.socket().getLocalPort(), this);
deputy.start();
}
@SuppressWarnings("unchecked")
protected void receive (Memo memo) {
/*
* Messages received from our Deputy.
*/
if(memo.getSender() == deputy) {
// Peer list received from Deputy.
if(memo.getType().equals("peers"))
{
Log.info("Received peer list");
peers = (ArrayList<Map<String, Object>>) memo.getPayload();
if (peers.isEmpty()) Log.warning("Peer list empty!");
Message bitfield = Message.createBitfield(received, metainfo.piece_hashes.length);
for(int i = 0; i < peers.size(); i++)
{
// find the right peer for part one
Map<String,Object> currPeer = peers.get(i);
String ip = (String) currPeer.get("ip");
String address = ip + ":" + currPeer.get("port");
if ((ip.equals("128.6.5.130") || ip.equals("128.6.5.131"))
&& peersByAddress.get(address) == null)
{
try {
InetAddress inetip = InetAddress.getByName(ip);
// set up a broker
Broker b = new Broker(
inetip,
(Integer) currPeer.get("port"),
this,
bitfield
);
brokers.add(b);
peersByAddress.put(b.address(), b);
}
catch (UnknownHostException e) {
// Malformed ip, just ignore it
}
}
}
}
// Part 2: Deputy is done telling the tracker we're shutting down
else if (memo.getType().equals("done")) {
funnel.post(new Memo("halt", null, this));
}
}
/*
* Messages received from our Brokers.
*/
else if (memo.getSender() instanceof Broker) {
// Received from Brokers when they get a block.
if (memo.getType().equals("block")) {
Message msg = (Message) memo.getPayload();
Piece p = pieces.get(msg.getIndex());
if (p.addBlock(msg.getBegin(), msg.getBlock())) {
downloaded += msg.getBlockLength();
left -= msg.getBlockLength();
}
if (p.finished()) {
Log.info("Posting piece " + p.getNumber() + " to funnel");
funnel.post(new Memo("piece", p, this));
received.set(p.getNumber());
}
Broker b = (Broker) memo.getSender();
//Log.info("Got block of piece " + p.getNumber() + " from " + Util.buff2str(b.peerId()) + " who has speed " + b.speed);
// request more shit
//request((Broker)memo.getSender());
}
else if (memo.getType().equals("stateChanged")) {
if (state.equals("seeding")) return;
Broker b = (Broker) memo.getSender();
// determine if we want to interact with this peer
// If we don't have all upload slots filled and we are interested
if (preferred.size() < uploadSlots && !b.choked() && b.interested()) {
// Add them to the preferred set and return
Log.info("Not enough upload slots filled so immediately communicating with " + Util.buff2str(b.peerId()));
preferred.add(b);
return;
}
// If it's a choke message or the peer has disconnected and peer is
// preferred
if (preferred.contains(b) && (b.choked() || b.state().equals("error"))) {
// Find a new peer to fill the upload slot and fill it
preferred.remove(b);
for (Broker n : brokers) {
if (
!preferred.contains(n) && !n.choked() && n.interested() &&
n != optimisticUnchoke
) {
preferred.add(n);
return;
}
}
}
}
// sent when a Broker gets a bitfield message
else if(memo.getType().equals("bitfield")) {
BitSet field = (BitSet) memo.getPayload();
for(int i = 0; i < field.length(); i++) {
if(field.get(i)) {
Piece p = pieces.get(i);
p.incAvailable();
}
}
Arrays.sort(piecesByAvailability);
// Git dem peecazzz
//request((Broker)memo.getSender());
}
// sent when a Broker gets a have message
else if(memo.getType().equals("have-message")) {
int piece = (Integer) memo.getPayload();
Piece p = pieces.get(piece);
p.incAvailable();
Arrays.sort(piecesByAvailability);
//request((Broker)memo.getSender());
}
// Received from Brokers when a block has been requested
else if (memo.getType().equals("request")) {
Message msg = (Message) memo.getPayload();
funnel.post(new Memo("block", memo.getPayload(), memo.getSender()));
this.addUploaded(msg.getBlockLength());
}
// Received from Brokers when they can't requested a block from a peer
// anymore, ie when choked or when the connection is dropped.
else if (memo.getType().equals("blockFail")) {
Message m = (Message) memo.getPayload();
Piece p = pieces.get(m.getIndex());
p.blockFail(m.getBegin());
}
}
/*
* Messages sent from the Funnel.
*/
else if (memo.getSender() == funnel) {
if (memo.getType().equals("pieces")) {
ArrayList<Piece> ps = (ArrayList<Piece>) memo.getPayload();
for(int i = 0, l = ps.size(); i < l; ++i) {
Piece p = ps.get(i);
int length = p.getData().length;
downloaded += length;
left -= length;
pieces.set(p.getNumber(), p);
received.set(p.getNumber());
}
Log.info("Resuming, " + left + " left to download.");
initialize();
}
// Received from Funnel when we successfully verify and store some piece.
// We forward the message off to each Broker so they can inform peers.
else if (memo.getType().equals("have")) {
for (Broker b : brokers)
b.post(new Memo("have", memo.getPayload(), this));
}
// Part 3: Received from Funnel when we're ready to shut down.
else if (memo.getType().equals("done") && memo.getSender().equals(funnel)) {
shutdown();
Janitor.getInstance().post(new Memo("done", null, this));
}
}
else if (memo.getSender() instanceof Janitor) {
// Part 1: halt message from Janitor
if (memo.getType().equals("halt"))
{
state = "shutdown";
try { listen.close(); } catch (IOException e) { e.printStackTrace(); }
deputy.post(new Memo("halt", null, this));
}
}
else if (memo.getType().equals("optimisticUnchoke")) {
if (state.equals("seeding")) return;
Log.info("Running optimistic unchoke code");
// Check status of previous optimistic unchoke, if there was one.
if (optimisticUnchoke!= null) {
Iterator <Broker> i = preferred.iterator();
while (i.hasNext()) {
Broker item = i.next();
// If he's doing better than someone in our current preferred set..
if (optimisticUnchoke.speed > item.speed) {
// Promote him to a preferred peer.
i.remove();
item.post(new Memo("choke", null, this));
Log.info("Promoting our optimistic unchoke " + Util.buff2str(optimisticUnchoke.peerId()));
- brokers.add(optimisticUnchoke);
+ preferred.add(optimisticUnchoke);
break;
}
}
}
// Choose a new optimistic unchoke.
for (Broker b : brokers) {
if (!preferred.contains(b) && b.interested() && !b.choked()) {
optimisticUnchoke = b;
Log.info("Chose a new optimistic unchoke: " + Util.buff2str(optimisticUnchoke.peerId()));
b.post(new Memo("unchoke", null, this));
break;
}
}
}
else if (memo.getType().equals("status")) {
for (Broker b : preferred) {
Log.info("preferred: " + b);
}
}
}
private void request(Broker b) {
if (b.interested() && b.numQueued() < 5 && left > 0) {
// We are interested in the peer, we have less than 5 requests
// queued on the peer, and we have more shit to download. We should
// queue up a request on the peer.
Piece p = next(b.bitfield());
if (p != null) {
int index = p.next();
b.post(new Memo("request", Message.createRequest(
p.getNumber(), index * blockSize, p.sizeOf(index)
), this));
}
}
}
protected void idle () {
// actually select() on sockets and do network io
overlord.communicate(100);
try { Thread.sleep(50); } catch (InterruptedException e) {}
if (state.equals("downloading") || state.equals("seeding")) {
Iterator<Broker> i = brokers.iterator();
Broker b;
while (i.hasNext()) {
b = i.next();
request(b);
b.tick();
if (b.state().equals("error")) {
i.remove();
// Updating our availability
BitSet field = b.bitfield();
if(field != null) {
for(int j = 0; j < field.length(); j++) {
if(!field.get(j)) {
Piece p = pieces.get(j);
p.decAvailable();
}
}
}
peersByAddress.put(b.address(), null);
}
}
}
if (state.equals("seeding")) {
Iterator <Broker> j = preferred.iterator();
while (j.hasNext()) {
Broker item = j.next();
if (!item.interesting() || item.state().equals("error")) {
j.remove();
}
}
// unchoke interested peers
//Log.debug("Seeding, unchoking interested peers. Preferred size: " + preferred.size());
Iterator <Broker> i = brokers.iterator();
while (i.hasNext()) {
if (preferred.size() > uploadSlots) break;
Broker item = i.next();
if (item.interesting()) {
item.post(new Memo("unchoke", null, this));
preferred.add(item);
}
}
}
if (left == 0 && !state.equals("shutdown") && !state.equals("seeding")) {
Log.info("Download complete");
state = "seeding";
funnel.post(new Memo("save", null, this));
if(!startedSeeding) {
deputy.post(new Memo("done", null, this));
}
ui.post(new Memo("done", null, this));
}
}
public boolean onAcceptable () {
try {
Message bitfield = Message.createBitfield(received, metainfo.piece_hashes.length);
SocketChannel newConnection = listen.accept();
newConnection.configureBlocking(false);
if (newConnection != null) {
brokers.add(new Broker(newConnection, this, bitfield));
}
} catch (IOException e) {
// connection failed, ignore
}
return true;
}
public boolean onReadable () { return false; }
public boolean onWritable () { return false; }
public boolean onConnectable () { return false; }
/**
* Generates a 20 character {@code byte} array for use as a
* peer ID
* @return A randomly generated peer ID
*/
private ByteBuffer generatePeerID()
{
byte[] id = new byte[20];
// generating random peer ID. BTS- + 16 alphanums = 20 characters
Random r = new Random(System.currentTimeMillis());
id[0] = 'B';
id[1] = 'T';
id[2] = 'S';
id[3] = '-';
for(int i = 4; i < 20; i++)
{
int rand = r.nextInt(36);
if(rand < 10)
id[i] = (byte) ('0' + rand);
else
{
rand -= 10;
id[i] = (byte) ('A' + rand);
}
}
return ByteBuffer.wrap(id);
}
/** Returns true if the given bitset is interesting to us. Run by Brokers. */
public boolean isInteresting (BitSet peer) {
Iterator<Piece> i = pieces.iterator();
Piece p;
while (i.hasNext()) {
p = i.next();
if (!p.finished() && peer.get(p.getNumber())) return true;
}
return false;
}
/**
* Get the next piece we need to download. Uses rarest-piece-first.
*/
private Piece next (BitSet b) {
// list of rarest pieces. We return a random value in this.
Piece[] rarestPieces = new Piece[5];
int rpi = 0;
for(int i = 0; i < piecesByAvailability.length; i++) {
Piece p = (Piece) piecesByAvailability[i];
if (b.get(p.getNumber()) && !p.requested()) {
rarestPieces[rpi++] = p;
}
if(rpi == 5) {
break;
}
}
if(rpi > 0) {
Random r = new Random();
return rarestPieces[r.nextInt(rpi)];
}
else {
return null;
}
}
/** Add a peer to our internal list of peer ids */
public boolean addPeer (String address, Broker b) {
if (peersByAddress.get(address) != null) return false;
peersByAddress.put(address, b);
return true;
}
public int getDownloaded() {
return downloaded;
}
public int getUploaded() {
return BitsterInfo.getInstance().getUploadData(getInfoHash());
}
public void addUploaded(int uploaded) {
BitsterInfo.getInstance().setUploadData(getInfoHash(), getUploaded() + uploaded);
}
public int getLeft() {
return left;
}
private void setLeft(int left) {
this.left = left;
}
public ByteBuffer getPeerId () {
return peerId;
}
public ByteBuffer getInfoHash () {
return metainfo.info_hash;
}
public String getState () { return state; }
public Overlord getOverlord () { return overlord; }
public String getFileName() { return dest.getName(); }
}
| true | true | protected void receive (Memo memo) {
/*
* Messages received from our Deputy.
*/
if(memo.getSender() == deputy) {
// Peer list received from Deputy.
if(memo.getType().equals("peers"))
{
Log.info("Received peer list");
peers = (ArrayList<Map<String, Object>>) memo.getPayload();
if (peers.isEmpty()) Log.warning("Peer list empty!");
Message bitfield = Message.createBitfield(received, metainfo.piece_hashes.length);
for(int i = 0; i < peers.size(); i++)
{
// find the right peer for part one
Map<String,Object> currPeer = peers.get(i);
String ip = (String) currPeer.get("ip");
String address = ip + ":" + currPeer.get("port");
if ((ip.equals("128.6.5.130") || ip.equals("128.6.5.131"))
&& peersByAddress.get(address) == null)
{
try {
InetAddress inetip = InetAddress.getByName(ip);
// set up a broker
Broker b = new Broker(
inetip,
(Integer) currPeer.get("port"),
this,
bitfield
);
brokers.add(b);
peersByAddress.put(b.address(), b);
}
catch (UnknownHostException e) {
// Malformed ip, just ignore it
}
}
}
}
// Part 2: Deputy is done telling the tracker we're shutting down
else if (memo.getType().equals("done")) {
funnel.post(new Memo("halt", null, this));
}
}
/*
* Messages received from our Brokers.
*/
else if (memo.getSender() instanceof Broker) {
// Received from Brokers when they get a block.
if (memo.getType().equals("block")) {
Message msg = (Message) memo.getPayload();
Piece p = pieces.get(msg.getIndex());
if (p.addBlock(msg.getBegin(), msg.getBlock())) {
downloaded += msg.getBlockLength();
left -= msg.getBlockLength();
}
if (p.finished()) {
Log.info("Posting piece " + p.getNumber() + " to funnel");
funnel.post(new Memo("piece", p, this));
received.set(p.getNumber());
}
Broker b = (Broker) memo.getSender();
//Log.info("Got block of piece " + p.getNumber() + " from " + Util.buff2str(b.peerId()) + " who has speed " + b.speed);
// request more shit
//request((Broker)memo.getSender());
}
else if (memo.getType().equals("stateChanged")) {
if (state.equals("seeding")) return;
Broker b = (Broker) memo.getSender();
// determine if we want to interact with this peer
// If we don't have all upload slots filled and we are interested
if (preferred.size() < uploadSlots && !b.choked() && b.interested()) {
// Add them to the preferred set and return
Log.info("Not enough upload slots filled so immediately communicating with " + Util.buff2str(b.peerId()));
preferred.add(b);
return;
}
// If it's a choke message or the peer has disconnected and peer is
// preferred
if (preferred.contains(b) && (b.choked() || b.state().equals("error"))) {
// Find a new peer to fill the upload slot and fill it
preferred.remove(b);
for (Broker n : brokers) {
if (
!preferred.contains(n) && !n.choked() && n.interested() &&
n != optimisticUnchoke
) {
preferred.add(n);
return;
}
}
}
}
// sent when a Broker gets a bitfield message
else if(memo.getType().equals("bitfield")) {
BitSet field = (BitSet) memo.getPayload();
for(int i = 0; i < field.length(); i++) {
if(field.get(i)) {
Piece p = pieces.get(i);
p.incAvailable();
}
}
Arrays.sort(piecesByAvailability);
// Git dem peecazzz
//request((Broker)memo.getSender());
}
// sent when a Broker gets a have message
else if(memo.getType().equals("have-message")) {
int piece = (Integer) memo.getPayload();
Piece p = pieces.get(piece);
p.incAvailable();
Arrays.sort(piecesByAvailability);
//request((Broker)memo.getSender());
}
// Received from Brokers when a block has been requested
else if (memo.getType().equals("request")) {
Message msg = (Message) memo.getPayload();
funnel.post(new Memo("block", memo.getPayload(), memo.getSender()));
this.addUploaded(msg.getBlockLength());
}
// Received from Brokers when they can't requested a block from a peer
// anymore, ie when choked or when the connection is dropped.
else if (memo.getType().equals("blockFail")) {
Message m = (Message) memo.getPayload();
Piece p = pieces.get(m.getIndex());
p.blockFail(m.getBegin());
}
}
/*
* Messages sent from the Funnel.
*/
else if (memo.getSender() == funnel) {
if (memo.getType().equals("pieces")) {
ArrayList<Piece> ps = (ArrayList<Piece>) memo.getPayload();
for(int i = 0, l = ps.size(); i < l; ++i) {
Piece p = ps.get(i);
int length = p.getData().length;
downloaded += length;
left -= length;
pieces.set(p.getNumber(), p);
received.set(p.getNumber());
}
Log.info("Resuming, " + left + " left to download.");
initialize();
}
// Received from Funnel when we successfully verify and store some piece.
// We forward the message off to each Broker so they can inform peers.
else if (memo.getType().equals("have")) {
for (Broker b : brokers)
b.post(new Memo("have", memo.getPayload(), this));
}
// Part 3: Received from Funnel when we're ready to shut down.
else if (memo.getType().equals("done") && memo.getSender().equals(funnel)) {
shutdown();
Janitor.getInstance().post(new Memo("done", null, this));
}
}
else if (memo.getSender() instanceof Janitor) {
// Part 1: halt message from Janitor
if (memo.getType().equals("halt"))
{
state = "shutdown";
try { listen.close(); } catch (IOException e) { e.printStackTrace(); }
deputy.post(new Memo("halt", null, this));
}
}
else if (memo.getType().equals("optimisticUnchoke")) {
if (state.equals("seeding")) return;
Log.info("Running optimistic unchoke code");
// Check status of previous optimistic unchoke, if there was one.
if (optimisticUnchoke!= null) {
Iterator <Broker> i = preferred.iterator();
while (i.hasNext()) {
Broker item = i.next();
// If he's doing better than someone in our current preferred set..
if (optimisticUnchoke.speed > item.speed) {
// Promote him to a preferred peer.
i.remove();
item.post(new Memo("choke", null, this));
Log.info("Promoting our optimistic unchoke " + Util.buff2str(optimisticUnchoke.peerId()));
brokers.add(optimisticUnchoke);
break;
}
}
}
// Choose a new optimistic unchoke.
for (Broker b : brokers) {
if (!preferred.contains(b) && b.interested() && !b.choked()) {
optimisticUnchoke = b;
Log.info("Chose a new optimistic unchoke: " + Util.buff2str(optimisticUnchoke.peerId()));
b.post(new Memo("unchoke", null, this));
break;
}
}
}
else if (memo.getType().equals("status")) {
for (Broker b : preferred) {
Log.info("preferred: " + b);
}
}
}
| protected void receive (Memo memo) {
/*
* Messages received from our Deputy.
*/
if(memo.getSender() == deputy) {
// Peer list received from Deputy.
if(memo.getType().equals("peers"))
{
Log.info("Received peer list");
peers = (ArrayList<Map<String, Object>>) memo.getPayload();
if (peers.isEmpty()) Log.warning("Peer list empty!");
Message bitfield = Message.createBitfield(received, metainfo.piece_hashes.length);
for(int i = 0; i < peers.size(); i++)
{
// find the right peer for part one
Map<String,Object> currPeer = peers.get(i);
String ip = (String) currPeer.get("ip");
String address = ip + ":" + currPeer.get("port");
if ((ip.equals("128.6.5.130") || ip.equals("128.6.5.131"))
&& peersByAddress.get(address) == null)
{
try {
InetAddress inetip = InetAddress.getByName(ip);
// set up a broker
Broker b = new Broker(
inetip,
(Integer) currPeer.get("port"),
this,
bitfield
);
brokers.add(b);
peersByAddress.put(b.address(), b);
}
catch (UnknownHostException e) {
// Malformed ip, just ignore it
}
}
}
}
// Part 2: Deputy is done telling the tracker we're shutting down
else if (memo.getType().equals("done")) {
funnel.post(new Memo("halt", null, this));
}
}
/*
* Messages received from our Brokers.
*/
else if (memo.getSender() instanceof Broker) {
// Received from Brokers when they get a block.
if (memo.getType().equals("block")) {
Message msg = (Message) memo.getPayload();
Piece p = pieces.get(msg.getIndex());
if (p.addBlock(msg.getBegin(), msg.getBlock())) {
downloaded += msg.getBlockLength();
left -= msg.getBlockLength();
}
if (p.finished()) {
Log.info("Posting piece " + p.getNumber() + " to funnel");
funnel.post(new Memo("piece", p, this));
received.set(p.getNumber());
}
Broker b = (Broker) memo.getSender();
//Log.info("Got block of piece " + p.getNumber() + " from " + Util.buff2str(b.peerId()) + " who has speed " + b.speed);
// request more shit
//request((Broker)memo.getSender());
}
else if (memo.getType().equals("stateChanged")) {
if (state.equals("seeding")) return;
Broker b = (Broker) memo.getSender();
// determine if we want to interact with this peer
// If we don't have all upload slots filled and we are interested
if (preferred.size() < uploadSlots && !b.choked() && b.interested()) {
// Add them to the preferred set and return
Log.info("Not enough upload slots filled so immediately communicating with " + Util.buff2str(b.peerId()));
preferred.add(b);
return;
}
// If it's a choke message or the peer has disconnected and peer is
// preferred
if (preferred.contains(b) && (b.choked() || b.state().equals("error"))) {
// Find a new peer to fill the upload slot and fill it
preferred.remove(b);
for (Broker n : brokers) {
if (
!preferred.contains(n) && !n.choked() && n.interested() &&
n != optimisticUnchoke
) {
preferred.add(n);
return;
}
}
}
}
// sent when a Broker gets a bitfield message
else if(memo.getType().equals("bitfield")) {
BitSet field = (BitSet) memo.getPayload();
for(int i = 0; i < field.length(); i++) {
if(field.get(i)) {
Piece p = pieces.get(i);
p.incAvailable();
}
}
Arrays.sort(piecesByAvailability);
// Git dem peecazzz
//request((Broker)memo.getSender());
}
// sent when a Broker gets a have message
else if(memo.getType().equals("have-message")) {
int piece = (Integer) memo.getPayload();
Piece p = pieces.get(piece);
p.incAvailable();
Arrays.sort(piecesByAvailability);
//request((Broker)memo.getSender());
}
// Received from Brokers when a block has been requested
else if (memo.getType().equals("request")) {
Message msg = (Message) memo.getPayload();
funnel.post(new Memo("block", memo.getPayload(), memo.getSender()));
this.addUploaded(msg.getBlockLength());
}
// Received from Brokers when they can't requested a block from a peer
// anymore, ie when choked or when the connection is dropped.
else if (memo.getType().equals("blockFail")) {
Message m = (Message) memo.getPayload();
Piece p = pieces.get(m.getIndex());
p.blockFail(m.getBegin());
}
}
/*
* Messages sent from the Funnel.
*/
else if (memo.getSender() == funnel) {
if (memo.getType().equals("pieces")) {
ArrayList<Piece> ps = (ArrayList<Piece>) memo.getPayload();
for(int i = 0, l = ps.size(); i < l; ++i) {
Piece p = ps.get(i);
int length = p.getData().length;
downloaded += length;
left -= length;
pieces.set(p.getNumber(), p);
received.set(p.getNumber());
}
Log.info("Resuming, " + left + " left to download.");
initialize();
}
// Received from Funnel when we successfully verify and store some piece.
// We forward the message off to each Broker so they can inform peers.
else if (memo.getType().equals("have")) {
for (Broker b : brokers)
b.post(new Memo("have", memo.getPayload(), this));
}
// Part 3: Received from Funnel when we're ready to shut down.
else if (memo.getType().equals("done") && memo.getSender().equals(funnel)) {
shutdown();
Janitor.getInstance().post(new Memo("done", null, this));
}
}
else if (memo.getSender() instanceof Janitor) {
// Part 1: halt message from Janitor
if (memo.getType().equals("halt"))
{
state = "shutdown";
try { listen.close(); } catch (IOException e) { e.printStackTrace(); }
deputy.post(new Memo("halt", null, this));
}
}
else if (memo.getType().equals("optimisticUnchoke")) {
if (state.equals("seeding")) return;
Log.info("Running optimistic unchoke code");
// Check status of previous optimistic unchoke, if there was one.
if (optimisticUnchoke!= null) {
Iterator <Broker> i = preferred.iterator();
while (i.hasNext()) {
Broker item = i.next();
// If he's doing better than someone in our current preferred set..
if (optimisticUnchoke.speed > item.speed) {
// Promote him to a preferred peer.
i.remove();
item.post(new Memo("choke", null, this));
Log.info("Promoting our optimistic unchoke " + Util.buff2str(optimisticUnchoke.peerId()));
preferred.add(optimisticUnchoke);
break;
}
}
}
// Choose a new optimistic unchoke.
for (Broker b : brokers) {
if (!preferred.contains(b) && b.interested() && !b.choked()) {
optimisticUnchoke = b;
Log.info("Chose a new optimistic unchoke: " + Util.buff2str(optimisticUnchoke.peerId()));
b.post(new Memo("unchoke", null, this));
break;
}
}
}
else if (memo.getType().equals("status")) {
for (Broker b : preferred) {
Log.info("preferred: " + b);
}
}
}
|
diff --git a/plugins/org.eclipse.m2m.atl.engine.vm/src/org/eclipse/m2m/atl/engine/vm/nativelib/SOTSExpression2.java b/plugins/org.eclipse.m2m.atl.engine.vm/src/org/eclipse/m2m/atl/engine/vm/nativelib/SOTSExpression2.java
index 9196ccda..fa0bc8dc 100644
--- a/plugins/org.eclipse.m2m.atl.engine.vm/src/org/eclipse/m2m/atl/engine/vm/nativelib/SOTSExpression2.java
+++ b/plugins/org.eclipse.m2m.atl.engine.vm/src/org/eclipse/m2m/atl/engine/vm/nativelib/SOTSExpression2.java
@@ -1,421 +1,422 @@
package org.eclipse.m2m.atl.engine.vm.nativelib;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Iterator;
import org.eclipse.m2m.atl.engine.vm.ASMExecEnv;
import org.eclipse.m2m.atl.engine.vm.Operation;
import org.eclipse.m2m.atl.engine.vm.StackFrame;
/**
* Simple query language evaluator.
* This is used in the present version of the compiler.
*
* Recognized grammar:
* <code>
* exp ::= (simpleExp '+' exp) | simpleExp | INT | STRING | ('(' exp ')')
* simpleExp ::= '$' varName:IDENT ('.' propName:IDENT ('(' ')')? ('[' ("ISA" '(' mname:IDENT '!' mename:IDENT ')') | (propName:IDENT '=' value:exp) | (index:exp) ']')*)* (',' default:exp)?;
* IDENT ::= [A-Za-z_][A-Za-z0-9_]*;
* VALUE ::= STRING | INT;
* STRING ::= '[^']';
* INT ::= [0-9]+;
* SKIP ::= ' ' | '\t' | '\n' | '\r';
* </code>
* @author Fr�d�ric Jouault
*/
public class SOTSExpression2 {
private static final boolean debug = false;
public SOTSExpression2(String exp) {
this.exp = exp;
in = new StringReader(exp);
}
public ASMOclAny exec(StackFrame frame, ASMTuple args) throws IOException {
if(debug) System.out.println("Trying to execute " + exp);
ASMOclAny ret = exp(frame, args);
if(debug) System.out.println("\treturn value = " + ret);
return ret;
}
private ASMOclAny exp(StackFrame frame, ASMTuple args) throws IOException {
ASMOclAny ret = null;
Token t = null;
t = next();
if(t.type == Token.LPAREN) {
ret = exp(frame, args);
match(Token.RPAREN);
return ret;
} else if((t.type == Token.STRING) || (t.type == Token.INT)) {
ret = convValue(t);
} else {
unread(t);
ret = simpleExp(frame, args);
}
t = next();
if(t.type == Token.PLUS) {
ASMOclAny right = exp(frame, args);
if(right == null) {
ret = null;
} else if(ret instanceof ASMInteger) {
ret = ASMInteger.operatorPlus(frame, (ASMInteger)ret, (ASMInteger)right);
} else if(ret instanceof ASMString) {
if(right instanceof ASMString) {
ret = ASMString.operatorPlus(frame, (ASMString)ret, (ASMString)right);
} else {
ret = ASMString.operatorPlus(frame, (ASMString)ret, new ASMString(right.toString()));
}
} else {
System.out.println("ERROR: could not add type " + ASMOclAny.oclType(frame, ret) + ".");
}
} else {
unread(t);
}
return ret;
}
private ASMOclAny simpleExp(StackFrame frame, ASMTuple args) throws IOException {
Token t = null;
ASMOclAny ret = null;
t = match(Token.IDENT);
ret = args.get(frame, t.value);
boolean done = false;
do {
if(debug)
System.out.println("\tcontext = " + ret + ((ret != null) ? " : " + ASMOclAny.oclType(frame, ret) : ""));
t = next();
ASMModelElement ame = null;
ASMSequence col = null;
ASMOclAny value = null;
switch(t.type) {
case Token.EOF:
done = true;
break;
case Token.DOT:
t = next();
if((t.type != Token.IDENT) && (t.type != Token.STRING))
error(t);
ret = toCollection(ret);
col = new ASMSequence();
Token n = next();
if(n.type == Token.LPAREN) {
match(Token.RPAREN);
for(Iterator i = ((ASMSequence)ret).iterator() ; i.hasNext() ; ) {
ASMOclAny o = (ASMOclAny)i.next();
Operation oper = ((ASMExecEnv)frame.getExecEnv()).getOperation(o.getType(), t.value);
if(oper != null) {
ASMOclAny v = oper.exec(frame.enterFrame(oper, Arrays.asList(new Object[] {o})));
col.add(v);
} else {
frame.printStackTrace("ERROR: could not find operation " + t.value + " on " + o.getType() + " having supertypes: " + o.getType().getSupertypes());
}
}
} else {
unread(n);
for(Iterator i = ((ASMSequence)ret).iterator() ; i.hasNext() ; ) {
ame = (ASMModelElement)i.next();
if(t.type == Token.IDENT) {
ASMOclAny v = ame.get(frame, t.value);
if(!(v instanceof ASMOclUndefined))
col.add(v);
} else
col.add(new ASMString(t.value));
}
}
ret = ASMSequence.flatten(frame, col);
break;
case Token.COMA:
// t = next();
// if(!(t.type == Token.INT) && !(t.type == Token.STRING)) {
// error(t);
// }
if((ret == null) || ((ret instanceof ASMSequence) && (ASMSequence.size(frame, (ASMSequence)ret).getSymbol() == 0))) {
value = exp(frame, args);
ret = value;
}
break;
case Token.LSQUARE:
t = next();
ret = toCollection(ret);
col = new ASMSequence();
if(t.type == Token.ISA) {
match(Token.LPAREN);
String mname = match(Token.IDENT).value;
match(Token.EXCL);
String mename = match(Token.IDENT).value;
match(Token.RPAREN);
String expectedTypeName = mname + "!" + mename;
for(Iterator i = ((ASMSequence)ret).iterator() ; i.hasNext() ; ) {
ame = (ASMModelElement)i.next();
String typeName = ASMOclAny.oclType(frame, ame).toString();
if(typeName.equals(expectedTypeName)) {
col.add(ame);
}
}
ret = col;
} else if(t.type == Token.INT) {
unread(t);
-// int val = ((ASMInteger)exp(frame, args)).getSymbol();
+// int val =
+ ((ASMInteger)exp(frame, args)).getSymbol();
if(ASMSequence.size(frame, (ASMSequence)ret).getSymbol() > 0)
ret = (ASMOclAny)((ASMSequence)ret).iterator().next(); // TODO: index rather than first
else
ret = null;
} else {
if(t.type != Token.IDENT)
error(t);
String propName = t.value;
match(Token.EQ);
// t = next();
// if(!(t.type == Token.INT) && !(t.type == Token.STRING)) {
// error(t);
// }
// ASMOclAny value = convValue(t);
value = exp(frame, args);
for(Iterator i = ((ASMCollection)ret).iterator() ; i.hasNext() ; ) {
ame = (ASMModelElement)i.next();
if(ame.get(frame, propName).equals(value)) {
col.add(ame);
}
}
ret = col;
}
match(Token.RSQUARE);
break;
default:
unread(t);
done = true;
break;
}
} while(!done);
if(debug) System.out.println("\tpartial return value = " + ret);
return ret;
}
private ASMOclAny toCollection(ASMOclAny value) {
ASMSequence ret = null;
if(value instanceof ASMSequence) {
ret = (ASMSequence)value;
} else {
ASMOclAny elem = value;
ret = new ASMSequence();
if(elem != null)
ret.add(elem);
}
return ret;
}
private ASMOclAny convValue(Token value) {
ASMOclAny ret = null;
if(value.type == Token.INT) {
ret = new ASMInteger(java.lang.Integer.parseInt(value.value));
} else {
ret = new ASMString(value.value);
}
return ret;
}
private void error(Token t) {
System.out.println("ERROR: unexpected " + t);
new Exception().printStackTrace();
}
private Token match(int type) throws IOException {
Token ret = next();
if(ret.type != type)
error(ret);
return ret;
}
private void unread(Token t) {
readAhead = t;
}
private Token next() throws IOException {
Token ret = null;
String value = "";
if(readAhead != null) {
Token tmp = readAhead;
readAhead = null;
return tmp;
}
int c = in.read();
switch(c) {
case ' ': case '\t': case '\n': case '\r':
do {
in.mark(1);
c = in.read();
} while(
(c == ' ') || (c == '\t') ||
(c == '\n') || (c == '\r')
);
in.reset();
ret = next();
break;
case -1:
ret = new Token(Token.EOF, "<EOF>");
break;
case '.':
ret = new Token(Token.DOT, ".");
break;
case ',':
ret = new Token(Token.COMA, ",");
break;
case '!':
ret = new Token(Token.EXCL, "!");
break;
case '=':
ret = new Token(Token.EQ, "=");
break;
case '+':
ret = new Token(Token.PLUS, "+");
break;
case '[':
ret = new Token(Token.LSQUARE, "[");
break;
case ']':
ret = new Token(Token.RSQUARE, "]");
break;
case '(':
ret = new Token(Token.LPAREN, "(");
break;
case ')':
ret = new Token(Token.RPAREN, ")");
break;
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9':
do {
value += (char)c;
in.mark(1);
c = in.read();
} while((c >= '0') && (c <= '9'));
in.reset();
ret = new Token(Token.INT, value);
break;
case '\'':
while((c = in.read()) != '\'') {
value += (char)c;
}
ret = new Token(Token.STRING, value);
break;
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Z': case '_':
case 'a': case 'b': case 'c': case 'd':
case 'e': case 'f': case 'g': case 'h':
case 'i': case 'j': case 'k': case 'l':
case 'm': case 'n': case 'o': case 'p':
case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x':
case 'z':
do {
value += (char)c;
in.mark(1);
c = in.read();
} while(
((c >= '0') && (c <= '9')) ||
((c >= 'A') && (c <= 'Z')) ||
((c >= 'a') && (c <= 'z')) ||
(c == '_')
);
in.reset();
if(value.equals("ISA")) {
ret = new Token(Token.ISA, value);
} else {
ret = new Token(Token.IDENT, value);
}
break;
case '$':
ret = next(); // ignore '$'
break;
default:
System.out.println("ERROR: unexpected char \'" + (char)c + "\'.");
ret = next(); // trying to recover
break;
}
return ret;
}
private static String tokenNames[] = {
"EOF",
"DOT",
"COMA",
"EXCL",
"EQ",
"PLUS",
"LSQUARE",
"RSQUARE",
"LPAREN",
"RPAREN",
"INT",
"STRING",
"IDENT",
"ISA"
};
private class Token {
public static final int EOF = 0;
public static final int DOT = 1;
public static final int COMA = 2;
public static final int EXCL = 3;
public static final int EQ = 4;
public static final int PLUS = 5;
public static final int LSQUARE = 6;
public static final int RSQUARE = 7;
public static final int LPAREN = 8;
public static final int RPAREN = 9;
public static final int INT = 10;
public static final int STRING = 11;
public static final int IDENT = 12;
public static final int ISA = 13;
public Token(int type, String value) {
this.type = type;
this.value = value;
}
public String toString() {
return tokenNames[type] + ":" + value;
}
public int type;
public String value;
}
private String exp;
private Reader in;
private Token readAhead = null;
}
| true | true | private ASMOclAny simpleExp(StackFrame frame, ASMTuple args) throws IOException {
Token t = null;
ASMOclAny ret = null;
t = match(Token.IDENT);
ret = args.get(frame, t.value);
boolean done = false;
do {
if(debug)
System.out.println("\tcontext = " + ret + ((ret != null) ? " : " + ASMOclAny.oclType(frame, ret) : ""));
t = next();
ASMModelElement ame = null;
ASMSequence col = null;
ASMOclAny value = null;
switch(t.type) {
case Token.EOF:
done = true;
break;
case Token.DOT:
t = next();
if((t.type != Token.IDENT) && (t.type != Token.STRING))
error(t);
ret = toCollection(ret);
col = new ASMSequence();
Token n = next();
if(n.type == Token.LPAREN) {
match(Token.RPAREN);
for(Iterator i = ((ASMSequence)ret).iterator() ; i.hasNext() ; ) {
ASMOclAny o = (ASMOclAny)i.next();
Operation oper = ((ASMExecEnv)frame.getExecEnv()).getOperation(o.getType(), t.value);
if(oper != null) {
ASMOclAny v = oper.exec(frame.enterFrame(oper, Arrays.asList(new Object[] {o})));
col.add(v);
} else {
frame.printStackTrace("ERROR: could not find operation " + t.value + " on " + o.getType() + " having supertypes: " + o.getType().getSupertypes());
}
}
} else {
unread(n);
for(Iterator i = ((ASMSequence)ret).iterator() ; i.hasNext() ; ) {
ame = (ASMModelElement)i.next();
if(t.type == Token.IDENT) {
ASMOclAny v = ame.get(frame, t.value);
if(!(v instanceof ASMOclUndefined))
col.add(v);
} else
col.add(new ASMString(t.value));
}
}
ret = ASMSequence.flatten(frame, col);
break;
case Token.COMA:
// t = next();
// if(!(t.type == Token.INT) && !(t.type == Token.STRING)) {
// error(t);
// }
if((ret == null) || ((ret instanceof ASMSequence) && (ASMSequence.size(frame, (ASMSequence)ret).getSymbol() == 0))) {
value = exp(frame, args);
ret = value;
}
break;
case Token.LSQUARE:
t = next();
ret = toCollection(ret);
col = new ASMSequence();
if(t.type == Token.ISA) {
match(Token.LPAREN);
String mname = match(Token.IDENT).value;
match(Token.EXCL);
String mename = match(Token.IDENT).value;
match(Token.RPAREN);
String expectedTypeName = mname + "!" + mename;
for(Iterator i = ((ASMSequence)ret).iterator() ; i.hasNext() ; ) {
ame = (ASMModelElement)i.next();
String typeName = ASMOclAny.oclType(frame, ame).toString();
if(typeName.equals(expectedTypeName)) {
col.add(ame);
}
}
ret = col;
} else if(t.type == Token.INT) {
unread(t);
// int val = ((ASMInteger)exp(frame, args)).getSymbol();
if(ASMSequence.size(frame, (ASMSequence)ret).getSymbol() > 0)
ret = (ASMOclAny)((ASMSequence)ret).iterator().next(); // TODO: index rather than first
else
ret = null;
} else {
if(t.type != Token.IDENT)
error(t);
String propName = t.value;
match(Token.EQ);
// t = next();
// if(!(t.type == Token.INT) && !(t.type == Token.STRING)) {
// error(t);
// }
// ASMOclAny value = convValue(t);
value = exp(frame, args);
for(Iterator i = ((ASMCollection)ret).iterator() ; i.hasNext() ; ) {
ame = (ASMModelElement)i.next();
if(ame.get(frame, propName).equals(value)) {
col.add(ame);
}
}
ret = col;
}
match(Token.RSQUARE);
break;
default:
unread(t);
done = true;
break;
}
} while(!done);
if(debug) System.out.println("\tpartial return value = " + ret);
return ret;
}
| private ASMOclAny simpleExp(StackFrame frame, ASMTuple args) throws IOException {
Token t = null;
ASMOclAny ret = null;
t = match(Token.IDENT);
ret = args.get(frame, t.value);
boolean done = false;
do {
if(debug)
System.out.println("\tcontext = " + ret + ((ret != null) ? " : " + ASMOclAny.oclType(frame, ret) : ""));
t = next();
ASMModelElement ame = null;
ASMSequence col = null;
ASMOclAny value = null;
switch(t.type) {
case Token.EOF:
done = true;
break;
case Token.DOT:
t = next();
if((t.type != Token.IDENT) && (t.type != Token.STRING))
error(t);
ret = toCollection(ret);
col = new ASMSequence();
Token n = next();
if(n.type == Token.LPAREN) {
match(Token.RPAREN);
for(Iterator i = ((ASMSequence)ret).iterator() ; i.hasNext() ; ) {
ASMOclAny o = (ASMOclAny)i.next();
Operation oper = ((ASMExecEnv)frame.getExecEnv()).getOperation(o.getType(), t.value);
if(oper != null) {
ASMOclAny v = oper.exec(frame.enterFrame(oper, Arrays.asList(new Object[] {o})));
col.add(v);
} else {
frame.printStackTrace("ERROR: could not find operation " + t.value + " on " + o.getType() + " having supertypes: " + o.getType().getSupertypes());
}
}
} else {
unread(n);
for(Iterator i = ((ASMSequence)ret).iterator() ; i.hasNext() ; ) {
ame = (ASMModelElement)i.next();
if(t.type == Token.IDENT) {
ASMOclAny v = ame.get(frame, t.value);
if(!(v instanceof ASMOclUndefined))
col.add(v);
} else
col.add(new ASMString(t.value));
}
}
ret = ASMSequence.flatten(frame, col);
break;
case Token.COMA:
// t = next();
// if(!(t.type == Token.INT) && !(t.type == Token.STRING)) {
// error(t);
// }
if((ret == null) || ((ret instanceof ASMSequence) && (ASMSequence.size(frame, (ASMSequence)ret).getSymbol() == 0))) {
value = exp(frame, args);
ret = value;
}
break;
case Token.LSQUARE:
t = next();
ret = toCollection(ret);
col = new ASMSequence();
if(t.type == Token.ISA) {
match(Token.LPAREN);
String mname = match(Token.IDENT).value;
match(Token.EXCL);
String mename = match(Token.IDENT).value;
match(Token.RPAREN);
String expectedTypeName = mname + "!" + mename;
for(Iterator i = ((ASMSequence)ret).iterator() ; i.hasNext() ; ) {
ame = (ASMModelElement)i.next();
String typeName = ASMOclAny.oclType(frame, ame).toString();
if(typeName.equals(expectedTypeName)) {
col.add(ame);
}
}
ret = col;
} else if(t.type == Token.INT) {
unread(t);
// int val =
((ASMInteger)exp(frame, args)).getSymbol();
if(ASMSequence.size(frame, (ASMSequence)ret).getSymbol() > 0)
ret = (ASMOclAny)((ASMSequence)ret).iterator().next(); // TODO: index rather than first
else
ret = null;
} else {
if(t.type != Token.IDENT)
error(t);
String propName = t.value;
match(Token.EQ);
// t = next();
// if(!(t.type == Token.INT) && !(t.type == Token.STRING)) {
// error(t);
// }
// ASMOclAny value = convValue(t);
value = exp(frame, args);
for(Iterator i = ((ASMCollection)ret).iterator() ; i.hasNext() ; ) {
ame = (ASMModelElement)i.next();
if(ame.get(frame, propName).equals(value)) {
col.add(ame);
}
}
ret = col;
}
match(Token.RSQUARE);
break;
default:
unread(t);
done = true;
break;
}
} while(!done);
if(debug) System.out.println("\tpartial return value = " + ret);
return ret;
}
|
diff --git a/src/org/concord/datagraph/state/OTDataGraphableController.java b/src/org/concord/datagraph/state/OTDataGraphableController.java
index b7891cc..9ef52e2 100644
--- a/src/org/concord/datagraph/state/OTDataGraphableController.java
+++ b/src/org/concord/datagraph/state/OTDataGraphableController.java
@@ -1,310 +1,310 @@
/*
* Copyright (C) 2004 The Concord Consortium, Inc.,
* 10 Concord Crossing, Concord, MA 01742
*
* Web Site: http://www.concord.org
* Email: [email protected]
*
* 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
*
* END LICENSE */
/*
* Created on Mar 21, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.concord.datagraph.state;
import java.awt.Color;
import org.concord.data.state.OTDataProducer;
import org.concord.data.state.OTDataStore;
import org.concord.data.stream.ProducerDataStore;
import org.concord.datagraph.engine.ControllableDataGraphable;
import org.concord.datagraph.engine.ControllableDataGraphableDrawing;
import org.concord.datagraph.engine.DataGraphable;
import org.concord.framework.data.stream.DataListener;
import org.concord.framework.data.stream.DataProducer;
import org.concord.framework.data.stream.DataStore;
import org.concord.framework.data.stream.DataStoreEvent;
import org.concord.framework.data.stream.DataStoreListener;
import org.concord.framework.data.stream.DataStreamEvent;
import org.concord.framework.otrunk.OTObjectService;
import org.concord.graph.util.state.OTGraphableController;
/**
* @author scott
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class OTDataGraphableController extends OTGraphableController
{
public static Class [] realObjectClasses = {
DataGraphable.class, ControllableDataGraphable.class,
ControllableDataGraphableDrawing.class
};
public static Class otObjectClass = OTDataGraphable.class;
DataStoreListener dataStoreListener = new DataStoreListener(){
public void dataAdded(DataStoreEvent evt){}
public void dataChanged(DataStoreEvent evt){}
public void dataChannelDescChanged(DataStoreEvent evt)
{
// TODO we should verify that this is coming from
// the producer, if the description is coming
// from somewhere else then it isn't clear what
// should happen to the producer.
}
public void dataRemoved(DataStoreEvent evt)
{
DataStore dataStore = (DataStore)evt.getSource();
OTDataGraphable model = (OTDataGraphable)otObject;
DataProducer dataProducer = getDataProducer(model);
if(dataProducer != null && dataStore.getTotalNumSamples() == 0){
if(dataStore instanceof ProducerDataStore){
ProducerDataStore pDataStore = (ProducerDataStore) dataStore;
pDataStore.setDataProducer(dataProducer);
}
}
}
};
DataListener dataProducerListener = new DataListener(){
boolean started = false;
public void dataReceived(DataStreamEvent dataEvent)
{
if(started){
return;
}
started = true;
// Check if this dataProducer has already been added to the
// datastore, if not then add it.
// This will modify the list of dataListeners in the dataStore
// while it is iterating over it. It seems like this will
// work ok though
// This will happen whenever data arrives so we should
// remove ourselves from the list but we can't safely do that
// while in the method. So we have the boolean above instead.
OTDataGraphable model = (OTDataGraphable)otObject;
DataProducer modelDataProducer = getDataProducer(model);
DataStore dataStore = getDataStore(model);
if(dataStore instanceof ProducerDataStore){
ProducerDataStore pDataStore = (ProducerDataStore) dataStore;
DataProducer oldDataProducer = pDataStore.getDataProducer();
if(oldDataProducer != modelDataProducer){
pDataStore.setDataProducer(modelDataProducer);
}
}
}
public void dataStreamEvent(DataStreamEvent dataEvent){}
};
public void loadRealObject(Object realObject)
{
OTDataGraphable model = (OTDataGraphable)otObject;
DataGraphable dg = (DataGraphable)realObject;
dg.setColor(new Color(model.getColor()));
dg.setShowCrossPoint(model.getDrawMarks());
dg.setLabel(model.getName());
dg.setUseVirtualChannels(true);
dg.setLocked(model.getLocked());
dg.setConnectPoints(model.getConnectPoints());
DataProducer producer = getDataProducer(model);
DataStore dataStore = getDataStore(model);
if (model.getControllable() && producer != null){
// This is a schema type error
// we should give more information about tracking it down
throw new RuntimeException("Can't control a graphable with a data producer");
}
if(dataStore == null) {
// If the dataStore is null then we create a new
// one to store the data so it can retrieved
// later. If the data needs to be referenced
- // within the content then it should be explictly
+ // within the content then it should be explicitly
// defined in the content.
try {
OTObjectService objService = model.getOTObjectService();
OTDataStore otDataStore = (OTDataStore) objService.createObject(OTDataStore.class);
model.setDataStore(otDataStore);
dataStore = getDataStore(model);
} catch (Exception e) {
// we can't handle this
throw new RuntimeException(e);
}
}
// now we can safely assume dataStore != null
// however we should not set the producer onto the datastore
// if there is data in the data store, this could possibly
// mess up the data that is in the data store, because the data
// description of the data in the data store might be different
// from the data description in the producer.
// instead we need to listen to the dataStore and dataproducer
// and when the datastore is cleared, or the producer is started
// then we set the producer on the datastore.
// cleared, or the start
if (producer != null){
if(dataStore.getTotalNumSamples() == 0){
if(dataStore instanceof ProducerDataStore){
ProducerDataStore pDataStore = (ProducerDataStore) dataStore;
pDataStore.setDataProducer(producer);
}
}
// listen to the dataStore so if the data is cleared at some
// point then we will reset the producer
// we should be careful not to add a listener twice
dataStore.addDataStoreListener(dataStoreListener);
producer.addDataListener(dataProducerListener);
}
dg.setDataStore(dataStore);
dg.setChannelX(model.getXColumn());
dg.setChannelY(model.getYColumn());
if (model.isResourceSet("lineWidth")){
dg.setLineWidth(model.getLineWidth());
}
}
/**
* @see org.concord.framework.otrunk.OTController#saveObject(java.lang.Object)
*/
public void saveRealObject(Object realObject)
{
OTDataGraphable model = (OTDataGraphable)otObject;
DataGraphable dg = (DataGraphable)realObject;
Color c = dg.getColor();
if(c != null){
model.setColor(c.getRGB() & 0x00FFFFFF);
}
model.setConnectPoints(dg.isConnectPoints());
model.setDrawMarks(dg.isShowCrossPoint());
model.setXColumn(dg.getChannelX());
model.setYColumn(dg.getChannelY());
model.setName(dg.getLabel());
model.setLineWidth(dg.getLineWidth());
// This might not be quite right, lets cross our fingers
// that it doesn't screw anything else up
DataStore ds = dg.getDataStore();
OTDataStore otDataStore = (OTDataStore) controllerService.getOTObject(ds);
// the otDataStore could be null here, if the dataStore doesn't have an otObject.
// lets print a warning for now
if(otDataStore == null){
System.err.println("Warning trying to save a datastore which doesn't have an otObject");
System.err.println(" " + ds);
}
model.setDataStore(otDataStore);
// This is needed for some reason by the OTDrawingToolView
// Apparently it is to set the realObject class.
if(dg instanceof ControllableDataGraphableDrawing) {
model.setDrawing(true);
}
// FIXME we ought to be saving the dataproducer here, but there isn't
// a clear way to figure out which dataproducer to save.
// so for now we won't save any of them.
}
/**
* @see org.concord.framework.otrunk.OTController#getRealObjectClass()
*/
public Class getRealObjectClass()
{
OTDataGraphable model = (OTDataGraphable)otObject;
if (model.getDrawing()){
return ControllableDataGraphableDrawing.class;
}
else if (model.getControllable()){
return ControllableDataGraphable.class;
}
else {
return DataGraphable.class;
}
}
/* (non-Javadoc)
* @see org.concord.framework.otrunk.DefaultOTController#dispose()
*/
public void dispose(Object realObject)
{
OTDataGraphable model = (OTDataGraphable)otObject;
DataProducer producer = getDataProducer(model);
DataStore dataStore = getDataStore(model);
// listen to the dataStore so if the data is cleared at some
// point then we will reset the producer
// we should be careful not to add a listener twice
dataStore.removeDataStoreListener(dataStoreListener);
if(producer != null){
producer.removeDataListener(dataProducerListener);
}
// our realObject should be a DataGraphable
DataGraphable dataGraphable = (DataGraphable) realObject;
// set the data store to null, so our graphable stops
// listening to the datastore. Otherwise the datastore will
// keep a reference to the graphable, which might in turn keep
// references to other objects...
dataGraphable.setDataStore(null);
// TODO Auto-generated method stub
super.dispose(realObject);
}
DataProducer getDataProducer(OTDataGraphable model)
{
OTDataProducer otDataProducer = model.getDataProducer();
return (DataProducer) controllerService.getRealObject(otDataProducer);
}
DataStore getDataStore(OTDataGraphable model)
{
return (DataStore) controllerService.getRealObject(model.getDataStore());
}
}
| true | true | public void loadRealObject(Object realObject)
{
OTDataGraphable model = (OTDataGraphable)otObject;
DataGraphable dg = (DataGraphable)realObject;
dg.setColor(new Color(model.getColor()));
dg.setShowCrossPoint(model.getDrawMarks());
dg.setLabel(model.getName());
dg.setUseVirtualChannels(true);
dg.setLocked(model.getLocked());
dg.setConnectPoints(model.getConnectPoints());
DataProducer producer = getDataProducer(model);
DataStore dataStore = getDataStore(model);
if (model.getControllable() && producer != null){
// This is a schema type error
// we should give more information about tracking it down
throw new RuntimeException("Can't control a graphable with a data producer");
}
if(dataStore == null) {
// If the dataStore is null then we create a new
// one to store the data so it can retrieved
// later. If the data needs to be referenced
// within the content then it should be explictly
// defined in the content.
try {
OTObjectService objService = model.getOTObjectService();
OTDataStore otDataStore = (OTDataStore) objService.createObject(OTDataStore.class);
model.setDataStore(otDataStore);
dataStore = getDataStore(model);
} catch (Exception e) {
// we can't handle this
throw new RuntimeException(e);
}
}
// now we can safely assume dataStore != null
// however we should not set the producer onto the datastore
// if there is data in the data store, this could possibly
// mess up the data that is in the data store, because the data
// description of the data in the data store might be different
// from the data description in the producer.
// instead we need to listen to the dataStore and dataproducer
// and when the datastore is cleared, or the producer is started
// then we set the producer on the datastore.
// cleared, or the start
if (producer != null){
if(dataStore.getTotalNumSamples() == 0){
if(dataStore instanceof ProducerDataStore){
ProducerDataStore pDataStore = (ProducerDataStore) dataStore;
pDataStore.setDataProducer(producer);
}
}
// listen to the dataStore so if the data is cleared at some
// point then we will reset the producer
// we should be careful not to add a listener twice
dataStore.addDataStoreListener(dataStoreListener);
producer.addDataListener(dataProducerListener);
}
dg.setDataStore(dataStore);
dg.setChannelX(model.getXColumn());
dg.setChannelY(model.getYColumn());
if (model.isResourceSet("lineWidth")){
dg.setLineWidth(model.getLineWidth());
}
}
| public void loadRealObject(Object realObject)
{
OTDataGraphable model = (OTDataGraphable)otObject;
DataGraphable dg = (DataGraphable)realObject;
dg.setColor(new Color(model.getColor()));
dg.setShowCrossPoint(model.getDrawMarks());
dg.setLabel(model.getName());
dg.setUseVirtualChannels(true);
dg.setLocked(model.getLocked());
dg.setConnectPoints(model.getConnectPoints());
DataProducer producer = getDataProducer(model);
DataStore dataStore = getDataStore(model);
if (model.getControllable() && producer != null){
// This is a schema type error
// we should give more information about tracking it down
throw new RuntimeException("Can't control a graphable with a data producer");
}
if(dataStore == null) {
// If the dataStore is null then we create a new
// one to store the data so it can retrieved
// later. If the data needs to be referenced
// within the content then it should be explicitly
// defined in the content.
try {
OTObjectService objService = model.getOTObjectService();
OTDataStore otDataStore = (OTDataStore) objService.createObject(OTDataStore.class);
model.setDataStore(otDataStore);
dataStore = getDataStore(model);
} catch (Exception e) {
// we can't handle this
throw new RuntimeException(e);
}
}
// now we can safely assume dataStore != null
// however we should not set the producer onto the datastore
// if there is data in the data store, this could possibly
// mess up the data that is in the data store, because the data
// description of the data in the data store might be different
// from the data description in the producer.
// instead we need to listen to the dataStore and dataproducer
// and when the datastore is cleared, or the producer is started
// then we set the producer on the datastore.
// cleared, or the start
if (producer != null){
if(dataStore.getTotalNumSamples() == 0){
if(dataStore instanceof ProducerDataStore){
ProducerDataStore pDataStore = (ProducerDataStore) dataStore;
pDataStore.setDataProducer(producer);
}
}
// listen to the dataStore so if the data is cleared at some
// point then we will reset the producer
// we should be careful not to add a listener twice
dataStore.addDataStoreListener(dataStoreListener);
producer.addDataListener(dataProducerListener);
}
dg.setDataStore(dataStore);
dg.setChannelX(model.getXColumn());
dg.setChannelY(model.getYColumn());
if (model.isResourceSet("lineWidth")){
dg.setLineWidth(model.getLineWidth());
}
}
|
diff --git a/unittests/com/jgaap/distances/MeanDistanceTest.java b/unittests/com/jgaap/distances/MeanDistanceTest.java
index 0a3fe67..c3e7254 100644
--- a/unittests/com/jgaap/distances/MeanDistanceTest.java
+++ b/unittests/com/jgaap/distances/MeanDistanceTest.java
@@ -1,68 +1,68 @@
/*
* JGAAP -- a graphical program for stylometric authorship attribution
* Copyright (C) 2009,2011 by Patrick Juola
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
*
*/
package com.jgaap.distances;
import static org.junit.Assert.*;
import java.util.Vector;
import org.junit.Test;
import com.jgaap.generics.Event;
import com.jgaap.generics.EventSet;
import com.jgaap.generics.NumericEventSet;
/**
* @author michael
*
*/
public class MeanDistanceTest {
/**
* Test method for {@link com.jgaap.distances.MeanDistance#distance(com.jgaap.generics.EventSet, com.jgaap.generics.EventSet)}.
*/
@Test
public void testDistance() {
EventSet es1 = new NumericEventSet();
EventSet es2 = new NumericEventSet();
Vector<Event> test1 = new Vector<Event>();
test1.add(new Event("1.0"));
test1.add(new Event("2.0"));
test1.add(new Event("3.0"));
test1.add(new Event("4.0"));
test1.add(new Event("5.0"));
es1.addEvents(test1);
es2.addEvents(test1);
assertTrue(new MeanDistance().distance(es1, es2) == 0);
Vector<Event> test2 = new Vector<Event>();
test2.add(new Event("1.0"));
test2.add(new Event("2.0"));
test2.add(new Event("3.0"));
- es2 = new EventSet();
+ es2 = new NumericEventSet();
es2.addEvents(test2);
double result = new MeanDistance().distance(es1, es2);
assertTrue(DistanceTestHelper.inRange(result, 1.0, 0.0000000001));
}
}
| true | true | public void testDistance() {
EventSet es1 = new NumericEventSet();
EventSet es2 = new NumericEventSet();
Vector<Event> test1 = new Vector<Event>();
test1.add(new Event("1.0"));
test1.add(new Event("2.0"));
test1.add(new Event("3.0"));
test1.add(new Event("4.0"));
test1.add(new Event("5.0"));
es1.addEvents(test1);
es2.addEvents(test1);
assertTrue(new MeanDistance().distance(es1, es2) == 0);
Vector<Event> test2 = new Vector<Event>();
test2.add(new Event("1.0"));
test2.add(new Event("2.0"));
test2.add(new Event("3.0"));
es2 = new EventSet();
es2.addEvents(test2);
double result = new MeanDistance().distance(es1, es2);
assertTrue(DistanceTestHelper.inRange(result, 1.0, 0.0000000001));
}
| public void testDistance() {
EventSet es1 = new NumericEventSet();
EventSet es2 = new NumericEventSet();
Vector<Event> test1 = new Vector<Event>();
test1.add(new Event("1.0"));
test1.add(new Event("2.0"));
test1.add(new Event("3.0"));
test1.add(new Event("4.0"));
test1.add(new Event("5.0"));
es1.addEvents(test1);
es2.addEvents(test1);
assertTrue(new MeanDistance().distance(es1, es2) == 0);
Vector<Event> test2 = new Vector<Event>();
test2.add(new Event("1.0"));
test2.add(new Event("2.0"));
test2.add(new Event("3.0"));
es2 = new NumericEventSet();
es2.addEvents(test2);
double result = new MeanDistance().distance(es1, es2);
assertTrue(DistanceTestHelper.inRange(result, 1.0, 0.0000000001));
}
|
diff --git a/src/plugins/KeyUtils/KeyExplorerUtils.java b/src/plugins/KeyUtils/KeyExplorerUtils.java
index b9b45e2..287e3cf 100644
--- a/src/plugins/KeyUtils/KeyExplorerUtils.java
+++ b/src/plugins/KeyUtils/KeyExplorerUtils.java
@@ -1,498 +1,498 @@
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package plugins.KeyUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;
import com.db4o.ObjectContainer;
import freenet.client.ArchiveContext;
import freenet.client.ClientMetadata;
import freenet.client.FetchContext;
import freenet.client.FetchException;
import freenet.client.FetchResult;
import freenet.client.FetchWaiter;
import freenet.client.HighLevelSimpleClient;
import freenet.client.Metadata;
import freenet.client.MetadataParseException;
import freenet.client.InsertContext.CompatibilityMode;
import freenet.client.async.ClientContext;
import freenet.client.async.ClientGetState;
import freenet.client.async.ClientGetWorkerThread;
import freenet.client.async.ClientGetter;
import freenet.client.async.ManifestElement;
import freenet.client.async.GetCompletionCallback;
import freenet.client.async.KeyListenerConstructionException;
import freenet.client.async.SnoopBucket;
import freenet.client.async.SplitFileFetcher;
import freenet.client.async.StreamGenerator;
import freenet.client.filter.UnsafeContentTypeException;
import freenet.crypt.HashResult;
import freenet.keys.FreenetURI;
import freenet.node.RequestClient;
import freenet.node.RequestStarter;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.Logger;
import freenet.support.OOMHandler;
import freenet.support.api.Bucket;
import freenet.support.api.BucketFactory;
import freenet.support.compress.CompressionOutputSizeException;
import freenet.support.compress.Compressor;
import freenet.support.compress.DecompressorThreadManager;
import freenet.support.compress.Compressor.COMPRESSOR_TYPE;
import freenet.support.io.BucketTools;
import freenet.support.io.Closer;
public class KeyExplorerUtils {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(KeyExplorerUtils.class);
}
private static class SnoopGetter implements SnoopBucket {
private GetResult result;
private final BucketFactory _bf;
SnoopGetter (BucketFactory bf) {
_bf = bf;
}
@Override
public boolean snoopBucket(Bucket data, boolean isMetadata,
ObjectContainer container, ClientContext context) {
Bucket temp;
try {
temp = _bf.makeBucket(data.size());
BucketTools.copy(data, temp);
} catch (IOException e) {
Logger.error(this, "Bucket error, disk full?", e);
return true;
}
result = new GetResult(temp, isMetadata);
return true;
}
}
public static Metadata simpleManifestGet(PluginRespirator pr, FreenetURI uri) throws MetadataParseException, FetchException, IOException {
GetResult res = simpleGet(pr, uri);
if (!res.isMetaData()) {
throw new MetadataParseException("uri did not point to metadata " + uri);
}
return Metadata.construct(res.getData());
}
public static GetResult simpleGet(PluginRespirator pr, FreenetURI uri) throws FetchException {
SnoopGetter snooper = new SnoopGetter(pr.getNode().clientCore.tempBucketFactory);
FetchContext context = pr.getHLSimpleClient().getFetchContext();
FetchWaiter fw = new FetchWaiter();
ClientGetter get = new ClientGetter(fw, uri, context, RequestStarter.INTERACTIVE_PRIORITY_CLASS, (RequestClient)pr.getHLSimpleClient(), null, null, null);
get.setBucketSnoop(snooper);
try {
get.start(null, pr.getNode().clientCore.clientContext);
fw.waitForCompletion();
} catch (FetchException e) {
if (snooper.result == null) {
// really an error
Logger.error(KeyExplorerUtils.class, "pfehler", e);
throw e;
}
}
return snooper.result;
}
public static FetchResult splitGet(PluginRespirator pr, Metadata metadata) throws FetchException, MetadataParseException,
KeyListenerConstructionException {
if (!metadata.isSplitfile()) {
throw new MetadataParseException("uri did not point to splitfile");
}
final FetchWaiter fw = new FetchWaiter();
final FetchContext ctx = pr.getHLSimpleClient().getFetchContext();
GetCompletionCallback cb = new GetCompletionCallback() {
@Override
public void onBlockSetFinished(ClientGetState state, ObjectContainer container, ClientContext context) {
}
@Override
public void onExpectedMIME(String mime, ObjectContainer container, ClientContext context) {
}
@Override
public void onExpectedSize(long size, ObjectContainer container, ClientContext context) {
}
@Override
public void onFailure(FetchException e, ClientGetState state, ObjectContainer container, ClientContext context) {
fw.onFailure(e, null, container);
}
@Override
public void onFinalizedMetadata(ObjectContainer container) {
}
@Override
public void onTransition(ClientGetState oldState, ClientGetState newState, ObjectContainer container) {
}
@Override
public void onExpectedTopSize(long size, long compressed,
int blocksReq, int blocksTotal, ObjectContainer container,
ClientContext context) {
}
@Override
public void onHashes(HashResult[] hashes,
ObjectContainer container, ClientContext context) {
}
@Override
public void onSplitfileCompatibilityMode(CompatibilityMode min,
CompatibilityMode max, byte[] customSplitfileKey,
boolean compressed, boolean bottomLayer,
boolean definitiveAnyway, ObjectContainer container,
ClientContext context) {
}
@Override
public void onSuccess(StreamGenerator streamGenerator,
ClientMetadata clientMetadata,
List<? extends Compressor> decompressors,
ClientGetState state, ObjectContainer container,
ClientContext context) {
PipedOutputStream dataOutput = new PipedOutputStream();
PipedInputStream dataInput = new PipedInputStream();
OutputStream output = null;
DecompressorThreadManager decompressorManager = null;
ClientGetWorkerThread worker = null;
Bucket finalResult = null;
FetchResult result = null;
// FIXME use the two max lengths separately.
long maxLen = Math.max(ctx.maxTempLength, ctx.maxOutputLength);
try {
finalResult = context.getBucketFactory(false).makeBucket(maxLen);
dataOutput .connect(dataInput);
result = new FetchResult(clientMetadata, finalResult);
// Decompress
if(decompressors != null) {
if(logMINOR) Logger.minor(this, "Decompressing...");
decompressorManager = new DecompressorThreadManager(dataInput, decompressors, maxLen);
dataInput = decompressorManager.execute();
}
output = finalResult.getOutputStream();
- worker = new ClientGetWorkerThread(dataInput, output, null, null, null, false, ctx.charset, ctx.prefetchHook, ctx.tagReplacer);
+ worker = new ClientGetWorkerThread(dataInput, output, null, null, null, false, ctx.charset, ctx.prefetchHook, ctx.tagReplacer, null);
worker.start();
try {
streamGenerator.writeTo(dataOutput, container, context);
} catch(IOException e) {
//Check if the worker thread caught an exception
worker.getError();
//If not, throw the original error
throw e;
}
if(logMINOR) Logger.minor(this, "Size of written data: "+result.asBucket().size());
if(decompressorManager != null) {
if(logMINOR) Logger.minor(this, "Waiting for decompression to finalize");
decompressorManager.waitFinished();
}
if(logMINOR) Logger.minor(this, "Waiting for hashing, filtration, and writing to finish");
worker.waitFinished();
if(worker.getClientMetadata() != null) {
clientMetadata = worker.getClientMetadata();
result = new FetchResult(clientMetadata, finalResult);
}
dataOutput.close();
dataInput.close();
output.close();
} catch (OutOfMemoryError e) {
OOMHandler.handleOOM(e);
System.err.println("Failing above attempted fetch...");
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(UnsafeContentTypeException e) {
Logger.error(this, "Impossible, this piece of code does not filter", e);
onFailure(new FetchException(e.getFetchErrorCode(), e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(URISyntaxException e) {
//Impossible
Logger.error(this, "URISyntaxException converting a FreenetURI to a URI!: "+e, e);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state/*Not really the state's fault*/, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(CompressionOutputSizeException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.TOO_BIG, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(IOException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.BUCKET_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(FetchException e) {
Logger.error(this, "Caught "+e, e);
onFailure(e, state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(Throwable t) {
Logger.error(this, "Caught "+t, t);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, t), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} finally {
Closer.close(dataInput);
Closer.close(dataOutput);
Closer.close(output);
}
fw.onSuccess(result, null, container);
}
};
List<COMPRESSOR_TYPE> decompressors = new LinkedList<COMPRESSOR_TYPE>();
boolean deleteFetchContext = false;
ClientMetadata clientMetadata = null;
ArchiveContext actx = null;
int recursionLevel = 0;
Bucket returnBucket = null;
long token = 0;
if (metadata.isCompressed()) {
COMPRESSOR_TYPE codec = metadata.getCompressionCodec();
decompressors.add(codec);
}
VerySimpleGetter vsg = new VerySimpleGetter((short) 1, null, (RequestClient) pr.getHLSimpleClient());
SplitFileFetcher sf = new SplitFileFetcher(metadata, cb, vsg, ctx, deleteFetchContext, true, decompressors, clientMetadata, actx, recursionLevel, token,
false, (short) 0, null, pr.getNode().clientCore.clientContext);
// VerySimpleGetter vsg = new VerySimpleGetter((short) 1, uri,
// (RequestClient) pr.getHLSimpleClient());
// VerySimpleGet vs = new VerySimpleGet(ck, 0,
// pr.getHLSimpleClient().getFetchContext(), vsg);
sf.schedule(null, pr.getNode().clientCore.clientContext);
// fw.waitForCompletion();
return fw.waitForCompletion();
}
public static Metadata splitManifestGet(PluginRespirator pr, Metadata metadata) throws MetadataParseException, IOException, FetchException, KeyListenerConstructionException {
FetchResult res = splitGet(pr, metadata);
return Metadata.construct(res.asBucket());
}
public static Metadata zipManifestGet(PluginRespirator pr, FreenetURI uri) throws FetchException, MetadataParseException, IOException {
HighLevelSimpleClient hlsc = pr.getHLSimpleClient();
FetchContext fctx = hlsc.getFetchContext();
fctx.returnZIPManifests = true;
FetchWaiter fw = new FetchWaiter();
hlsc.fetch(uri, -1, (RequestClient) hlsc, fw, fctx);
FetchResult fr = fw.waitForCompletion();
ZipInputStream zis = new ZipInputStream(fr.asBucket().getInputStream());
ZipEntry entry;
ByteArrayOutputStream bos;
while (true) {
entry = zis.getNextEntry();
if (entry == null)
break;
if (entry.isDirectory())
continue;
String name = entry.getName();
if (".metadata".equals(name)) {
byte[] buf = new byte[32768];
bos = new ByteArrayOutputStream();
// Read the element
int readBytes;
while ((readBytes = zis.read(buf)) > 0) {
bos.write(buf, 0, readBytes);
}
bos.close();
return Metadata.construct(bos.toByteArray());
}
}
throw new FetchException(200, "impossible? no metadata in archive " + uri);
}
public static Metadata tarManifestGet(PluginRespirator pr, Metadata md, String metaName) throws FetchException, MetadataParseException, IOException {
FetchResult fr;
try {
fr = splitGet(pr, md);
} catch (KeyListenerConstructionException e) {
throw new FetchException(FetchException.INTERNAL_ERROR, e);
}
return internalTarManifestGet(fr.asBucket(), metaName);
}
public static Metadata tarManifestGet(PluginRespirator pr, FreenetURI uri, String metaName) throws FetchException, MetadataParseException, IOException {
HighLevelSimpleClient hlsc = pr.getHLSimpleClient();
FetchContext fctx = hlsc.getFetchContext();
fctx.returnZIPManifests = true;
FetchWaiter fw = new FetchWaiter();
hlsc.fetch(uri, -1, (RequestClient) hlsc, fw, fctx);
FetchResult fr = fw.waitForCompletion();
return internalTarManifestGet(fr.asBucket(), metaName);
}
public static Metadata internalTarManifestGet(Bucket data, String metaName) throws IOException, MetadataParseException, FetchException {
TarInputStream zis = new TarInputStream(data.getInputStream());
TarEntry entry;
ByteArrayOutputStream bos;
while (true) {
entry = zis.getNextEntry();
if (entry == null)
break;
if (entry.isDirectory())
continue;
String name = entry.getName();
if (metaName.equals(name)) {
byte[] buf = new byte[32768];
bos = new ByteArrayOutputStream();
// Read the element
int readBytes;
while ((readBytes = zis.read(buf)) > 0) {
bos.write(buf, 0, readBytes);
}
bos.close();
return Metadata.construct(bos.toByteArray());
}
}
throw new FetchException(200, "impossible? no metadata in archive ");
}
public static HashMap<String, Object> parseMetadata(Metadata oldMetadata, FreenetURI oldUri) throws MalformedURLException {
return parseMetadata(oldMetadata.getDocuments(), oldUri, "");
}
private static HashMap<String, Object> parseMetadata(HashMap<String, Metadata> oldMetadata, FreenetURI oldUri, String prefix) throws MalformedURLException {
HashMap<String, Object> newMetadata = new HashMap<String, Object>();
for(Entry<String, Metadata> entry:oldMetadata.entrySet()) {
Metadata md = entry.getValue();
String name = entry.getKey();
if (md.isArchiveInternalRedirect()) {
String fname = prefix + name;
FreenetURI newUri = new FreenetURI(oldUri.toString(false, false) + "/"+ fname);
//System.err.println("NewURI: "+newUri.toString(false, false));
newMetadata.put(name, new ManifestElement(name, newUri, null));
} else if (md.isSingleFileRedirect()) {
newMetadata.put(name, new ManifestElement(name, md.getSingleTarget(), null));
} else if (md.isSplitfile()) {
newMetadata.put(name, new ManifestElement(name, md.getSingleTarget(), null));
} else {
newMetadata.put(name, parseMetadata(md.getDocuments(), oldUri, prefix + name + "/"));
}
}
return newMetadata;
}
private byte[] doDownload(PluginRespirator pluginRespirator, List<String> errors, String key) {
if (errors.size() > 0) {
return null;
}
if (key == null || (key.trim().length() == 0)) {
errors.add("Are you jokingly? Empty URI");
return null;
}
try {
//FreenetURI furi = sanitizeURI(errors, key);
FreenetURI furi = new FreenetURI(key);
GetResult getresult = simpleGet(pluginRespirator, furi);
if (getresult.isMetaData()) {
return unrollMetadata(pluginRespirator, errors, Metadata.construct(getresult.getData()));
} else {
return BucketTools.toByteArray(getresult.getData());
}
} catch (MalformedURLException e) {
errors.add(e.getMessage());
e.printStackTrace();
} catch (MetadataParseException e) {
errors.add(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
errors.add(e.getMessage());
e.printStackTrace();
} catch (FetchException e) {
errors.add(e.getMessage());
e.printStackTrace();
} catch (KeyListenerConstructionException e) {
errors.add(e.getMessage());
e.printStackTrace();
}
return null;
}
public static byte[] unrollMetadata(PluginRespirator pluginRespirator, List<String> errors, Metadata md) throws MalformedURLException, IOException, FetchException, MetadataParseException, KeyListenerConstructionException {
if (!md.isSplitfile()) {
errors.add("Unsupported Metadata: Not a Splitfile");
return null;
}
byte[] result = null;
result = BucketTools.toByteArray(splitGet(pluginRespirator, md).asBucket());
return result;
}
}
| true | true | public static FetchResult splitGet(PluginRespirator pr, Metadata metadata) throws FetchException, MetadataParseException,
KeyListenerConstructionException {
if (!metadata.isSplitfile()) {
throw new MetadataParseException("uri did not point to splitfile");
}
final FetchWaiter fw = new FetchWaiter();
final FetchContext ctx = pr.getHLSimpleClient().getFetchContext();
GetCompletionCallback cb = new GetCompletionCallback() {
@Override
public void onBlockSetFinished(ClientGetState state, ObjectContainer container, ClientContext context) {
}
@Override
public void onExpectedMIME(String mime, ObjectContainer container, ClientContext context) {
}
@Override
public void onExpectedSize(long size, ObjectContainer container, ClientContext context) {
}
@Override
public void onFailure(FetchException e, ClientGetState state, ObjectContainer container, ClientContext context) {
fw.onFailure(e, null, container);
}
@Override
public void onFinalizedMetadata(ObjectContainer container) {
}
@Override
public void onTransition(ClientGetState oldState, ClientGetState newState, ObjectContainer container) {
}
@Override
public void onExpectedTopSize(long size, long compressed,
int blocksReq, int blocksTotal, ObjectContainer container,
ClientContext context) {
}
@Override
public void onHashes(HashResult[] hashes,
ObjectContainer container, ClientContext context) {
}
@Override
public void onSplitfileCompatibilityMode(CompatibilityMode min,
CompatibilityMode max, byte[] customSplitfileKey,
boolean compressed, boolean bottomLayer,
boolean definitiveAnyway, ObjectContainer container,
ClientContext context) {
}
@Override
public void onSuccess(StreamGenerator streamGenerator,
ClientMetadata clientMetadata,
List<? extends Compressor> decompressors,
ClientGetState state, ObjectContainer container,
ClientContext context) {
PipedOutputStream dataOutput = new PipedOutputStream();
PipedInputStream dataInput = new PipedInputStream();
OutputStream output = null;
DecompressorThreadManager decompressorManager = null;
ClientGetWorkerThread worker = null;
Bucket finalResult = null;
FetchResult result = null;
// FIXME use the two max lengths separately.
long maxLen = Math.max(ctx.maxTempLength, ctx.maxOutputLength);
try {
finalResult = context.getBucketFactory(false).makeBucket(maxLen);
dataOutput .connect(dataInput);
result = new FetchResult(clientMetadata, finalResult);
// Decompress
if(decompressors != null) {
if(logMINOR) Logger.minor(this, "Decompressing...");
decompressorManager = new DecompressorThreadManager(dataInput, decompressors, maxLen);
dataInput = decompressorManager.execute();
}
output = finalResult.getOutputStream();
worker = new ClientGetWorkerThread(dataInput, output, null, null, null, false, ctx.charset, ctx.prefetchHook, ctx.tagReplacer);
worker.start();
try {
streamGenerator.writeTo(dataOutput, container, context);
} catch(IOException e) {
//Check if the worker thread caught an exception
worker.getError();
//If not, throw the original error
throw e;
}
if(logMINOR) Logger.minor(this, "Size of written data: "+result.asBucket().size());
if(decompressorManager != null) {
if(logMINOR) Logger.minor(this, "Waiting for decompression to finalize");
decompressorManager.waitFinished();
}
if(logMINOR) Logger.minor(this, "Waiting for hashing, filtration, and writing to finish");
worker.waitFinished();
if(worker.getClientMetadata() != null) {
clientMetadata = worker.getClientMetadata();
result = new FetchResult(clientMetadata, finalResult);
}
dataOutput.close();
dataInput.close();
output.close();
} catch (OutOfMemoryError e) {
OOMHandler.handleOOM(e);
System.err.println("Failing above attempted fetch...");
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(UnsafeContentTypeException e) {
Logger.error(this, "Impossible, this piece of code does not filter", e);
onFailure(new FetchException(e.getFetchErrorCode(), e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(URISyntaxException e) {
//Impossible
Logger.error(this, "URISyntaxException converting a FreenetURI to a URI!: "+e, e);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state/*Not really the state's fault*/, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(CompressionOutputSizeException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.TOO_BIG, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(IOException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.BUCKET_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(FetchException e) {
Logger.error(this, "Caught "+e, e);
onFailure(e, state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(Throwable t) {
Logger.error(this, "Caught "+t, t);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, t), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} finally {
Closer.close(dataInput);
Closer.close(dataOutput);
Closer.close(output);
}
fw.onSuccess(result, null, container);
}
};
List<COMPRESSOR_TYPE> decompressors = new LinkedList<COMPRESSOR_TYPE>();
boolean deleteFetchContext = false;
ClientMetadata clientMetadata = null;
ArchiveContext actx = null;
int recursionLevel = 0;
Bucket returnBucket = null;
long token = 0;
if (metadata.isCompressed()) {
COMPRESSOR_TYPE codec = metadata.getCompressionCodec();
decompressors.add(codec);
}
VerySimpleGetter vsg = new VerySimpleGetter((short) 1, null, (RequestClient) pr.getHLSimpleClient());
SplitFileFetcher sf = new SplitFileFetcher(metadata, cb, vsg, ctx, deleteFetchContext, true, decompressors, clientMetadata, actx, recursionLevel, token,
false, (short) 0, null, pr.getNode().clientCore.clientContext);
// VerySimpleGetter vsg = new VerySimpleGetter((short) 1, uri,
// (RequestClient) pr.getHLSimpleClient());
// VerySimpleGet vs = new VerySimpleGet(ck, 0,
// pr.getHLSimpleClient().getFetchContext(), vsg);
sf.schedule(null, pr.getNode().clientCore.clientContext);
// fw.waitForCompletion();
return fw.waitForCompletion();
}
| public static FetchResult splitGet(PluginRespirator pr, Metadata metadata) throws FetchException, MetadataParseException,
KeyListenerConstructionException {
if (!metadata.isSplitfile()) {
throw new MetadataParseException("uri did not point to splitfile");
}
final FetchWaiter fw = new FetchWaiter();
final FetchContext ctx = pr.getHLSimpleClient().getFetchContext();
GetCompletionCallback cb = new GetCompletionCallback() {
@Override
public void onBlockSetFinished(ClientGetState state, ObjectContainer container, ClientContext context) {
}
@Override
public void onExpectedMIME(String mime, ObjectContainer container, ClientContext context) {
}
@Override
public void onExpectedSize(long size, ObjectContainer container, ClientContext context) {
}
@Override
public void onFailure(FetchException e, ClientGetState state, ObjectContainer container, ClientContext context) {
fw.onFailure(e, null, container);
}
@Override
public void onFinalizedMetadata(ObjectContainer container) {
}
@Override
public void onTransition(ClientGetState oldState, ClientGetState newState, ObjectContainer container) {
}
@Override
public void onExpectedTopSize(long size, long compressed,
int blocksReq, int blocksTotal, ObjectContainer container,
ClientContext context) {
}
@Override
public void onHashes(HashResult[] hashes,
ObjectContainer container, ClientContext context) {
}
@Override
public void onSplitfileCompatibilityMode(CompatibilityMode min,
CompatibilityMode max, byte[] customSplitfileKey,
boolean compressed, boolean bottomLayer,
boolean definitiveAnyway, ObjectContainer container,
ClientContext context) {
}
@Override
public void onSuccess(StreamGenerator streamGenerator,
ClientMetadata clientMetadata,
List<? extends Compressor> decompressors,
ClientGetState state, ObjectContainer container,
ClientContext context) {
PipedOutputStream dataOutput = new PipedOutputStream();
PipedInputStream dataInput = new PipedInputStream();
OutputStream output = null;
DecompressorThreadManager decompressorManager = null;
ClientGetWorkerThread worker = null;
Bucket finalResult = null;
FetchResult result = null;
// FIXME use the two max lengths separately.
long maxLen = Math.max(ctx.maxTempLength, ctx.maxOutputLength);
try {
finalResult = context.getBucketFactory(false).makeBucket(maxLen);
dataOutput .connect(dataInput);
result = new FetchResult(clientMetadata, finalResult);
// Decompress
if(decompressors != null) {
if(logMINOR) Logger.minor(this, "Decompressing...");
decompressorManager = new DecompressorThreadManager(dataInput, decompressors, maxLen);
dataInput = decompressorManager.execute();
}
output = finalResult.getOutputStream();
worker = new ClientGetWorkerThread(dataInput, output, null, null, null, false, ctx.charset, ctx.prefetchHook, ctx.tagReplacer, null);
worker.start();
try {
streamGenerator.writeTo(dataOutput, container, context);
} catch(IOException e) {
//Check if the worker thread caught an exception
worker.getError();
//If not, throw the original error
throw e;
}
if(logMINOR) Logger.minor(this, "Size of written data: "+result.asBucket().size());
if(decompressorManager != null) {
if(logMINOR) Logger.minor(this, "Waiting for decompression to finalize");
decompressorManager.waitFinished();
}
if(logMINOR) Logger.minor(this, "Waiting for hashing, filtration, and writing to finish");
worker.waitFinished();
if(worker.getClientMetadata() != null) {
clientMetadata = worker.getClientMetadata();
result = new FetchResult(clientMetadata, finalResult);
}
dataOutput.close();
dataInput.close();
output.close();
} catch (OutOfMemoryError e) {
OOMHandler.handleOOM(e);
System.err.println("Failing above attempted fetch...");
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(UnsafeContentTypeException e) {
Logger.error(this, "Impossible, this piece of code does not filter", e);
onFailure(new FetchException(e.getFetchErrorCode(), e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(URISyntaxException e) {
//Impossible
Logger.error(this, "URISyntaxException converting a FreenetURI to a URI!: "+e, e);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state/*Not really the state's fault*/, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(CompressionOutputSizeException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.TOO_BIG, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(IOException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.BUCKET_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(FetchException e) {
Logger.error(this, "Caught "+e, e);
onFailure(e, state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(Throwable t) {
Logger.error(this, "Caught "+t, t);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, t), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} finally {
Closer.close(dataInput);
Closer.close(dataOutput);
Closer.close(output);
}
fw.onSuccess(result, null, container);
}
};
List<COMPRESSOR_TYPE> decompressors = new LinkedList<COMPRESSOR_TYPE>();
boolean deleteFetchContext = false;
ClientMetadata clientMetadata = null;
ArchiveContext actx = null;
int recursionLevel = 0;
Bucket returnBucket = null;
long token = 0;
if (metadata.isCompressed()) {
COMPRESSOR_TYPE codec = metadata.getCompressionCodec();
decompressors.add(codec);
}
VerySimpleGetter vsg = new VerySimpleGetter((short) 1, null, (RequestClient) pr.getHLSimpleClient());
SplitFileFetcher sf = new SplitFileFetcher(metadata, cb, vsg, ctx, deleteFetchContext, true, decompressors, clientMetadata, actx, recursionLevel, token,
false, (short) 0, null, pr.getNode().clientCore.clientContext);
// VerySimpleGetter vsg = new VerySimpleGetter((short) 1, uri,
// (RequestClient) pr.getHLSimpleClient());
// VerySimpleGet vs = new VerySimpleGet(ck, 0,
// pr.getHLSimpleClient().getFetchContext(), vsg);
sf.schedule(null, pr.getNode().clientCore.clientContext);
// fw.waitForCompletion();
return fw.waitForCompletion();
}
|
diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/EmptyPropertyState.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/EmptyPropertyState.java
index 43cc84ae9d..1360200c1a 100644
--- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/EmptyPropertyState.java
+++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/EmptyPropertyState.java
@@ -1,147 +1,148 @@
/*
* 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.jackrabbit.oak.plugins.memory;
import java.util.Collections;
import javax.annotation.Nonnull;
import javax.jcr.PropertyType;
import com.google.common.collect.Iterables;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Type;
import static org.apache.jackrabbit.oak.api.Type.BINARIES;
import static org.apache.jackrabbit.oak.api.Type.STRING;
import static org.apache.jackrabbit.oak.api.Type.STRINGS;
abstract class EmptyPropertyState implements PropertyState {
private final String name;
protected EmptyPropertyState(String name) {
this.name = name;
}
@Nonnull
@Override
public String getName() {
return name;
}
@Override
public boolean isArray() {
return true;
}
@SuppressWarnings("unchecked")
@Nonnull
@Override
public <T> T getValue(Type<T> type) {
if (type.isArray()) {
return (T) Collections.emptyList();
}
else {
throw new IllegalStateException("Not a single valued property");
}
}
@Nonnull
@Override
public <T> T getValue(Type<T> type, int index) {
throw new IndexOutOfBoundsException(String.valueOf(index));
}
@Override
public long size() {
throw new IllegalStateException("Not a single valued property");
}
@Override
public long size(int index) {
throw new IndexOutOfBoundsException(String.valueOf(index));
}
@Override
public int count() {
return 0;
}
//------------------------------------------------------------< Object >--
/**
* Checks whether the given object is equal to this one. Two property
* states are considered equal if their names and types match and
* their string representation of their values are equal.
* Subclasses may override this method with a more efficient
* equality check if one is available.
*
* @param other target of the comparison
* @return {@code true} if the objects are equal, {@code false} otherwise
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
else if (other instanceof PropertyState) {
PropertyState that = (PropertyState) other;
if (!getName().equals(that.getName())) {
return false;
}
if (!getType().equals(that.getType())) {
return false;
}
if (getType().tag() == PropertyType.BINARY) {
- return getValue(BINARIES).equals(that.getValue(BINARIES));
+ return Iterables.elementsEqual(
+ getValue(BINARIES), that.getValue(BINARIES));
}
else {
return Iterables.elementsEqual(
getValue(STRINGS), that.getValue(STRINGS));
}
}
else {
return false;
}
}
/**
* Returns a hash code that's compatible with how the
* {@link #equals(Object)} method is implemented. The current
* implementation simply returns the hash code of the property name
* since {@link PropertyState} instances are not intended for use as
* hash keys.
*
* @return hash code
*/
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
if (isArray()) {
return getName() + '=' + getValue(STRINGS);
}
else {
return getName() + '=' + getValue(STRING);
}
}
}
| true | true | public boolean equals(Object other) {
if (this == other) {
return true;
}
else if (other instanceof PropertyState) {
PropertyState that = (PropertyState) other;
if (!getName().equals(that.getName())) {
return false;
}
if (!getType().equals(that.getType())) {
return false;
}
if (getType().tag() == PropertyType.BINARY) {
return getValue(BINARIES).equals(that.getValue(BINARIES));
}
else {
return Iterables.elementsEqual(
getValue(STRINGS), that.getValue(STRINGS));
}
}
else {
return false;
}
}
| public boolean equals(Object other) {
if (this == other) {
return true;
}
else if (other instanceof PropertyState) {
PropertyState that = (PropertyState) other;
if (!getName().equals(that.getName())) {
return false;
}
if (!getType().equals(that.getType())) {
return false;
}
if (getType().tag() == PropertyType.BINARY) {
return Iterables.elementsEqual(
getValue(BINARIES), that.getValue(BINARIES));
}
else {
return Iterables.elementsEqual(
getValue(STRINGS), that.getValue(STRINGS));
}
}
else {
return false;
}
}
|
diff --git a/trunk/src/main/java/net/wimpi/modbus/net/TCPMasterConnection.java b/trunk/src/main/java/net/wimpi/modbus/net/TCPMasterConnection.java
index 0199731..9459821 100755
--- a/trunk/src/main/java/net/wimpi/modbus/net/TCPMasterConnection.java
+++ b/trunk/src/main/java/net/wimpi/modbus/net/TCPMasterConnection.java
@@ -1,189 +1,188 @@
/***
* Copyright 2002-2010 jamod development team
*
* 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 net.wimpi.modbus.net;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.io.ModbusTCPTransport;
import net.wimpi.modbus.io.ModbusTransport;
/**
* Class that implements a TCPMasterConnection.
*
* @author Dieter Wimberger
* @version @version@ (@date@)
*/
public class TCPMasterConnection {
//instance attributes
private Socket m_Socket;
private int m_Timeout = Modbus.DEFAULT_TIMEOUT;
private boolean m_Connected;
private InetAddress m_Address;
private int m_Port = Modbus.DEFAULT_PORT;
//private int m_Retries = Modbus.DEFAULT_RETRIES;
private ModbusTCPTransport m_ModbusTransport;
/**
* Constructs a <tt>TCPMasterConnection</tt> instance
* with a given destination address.
*
* @param adr the destination <tt>InetAddress</tt>.
*/
public TCPMasterConnection(InetAddress adr) {
m_Address = adr;
}//constructor
/**
* Opens this <tt>TCPMasterConnection</tt>.
*
* @throws Exception if there is a network failure.
*/
public synchronized void connect()
throws Exception {
if(!m_Connected) {
if(Modbus.debug) System.out.println("connect()");
- m_Socket = new Socket(m_Address, m_Port);
- m_Socket = new Socket();
- java.net.InetSocketAddress sockaddr = new java.net.InetSocketAddress( m_Address, m_Port );
- m_Socket.connect( sockaddr, m_Timeout );
+ m_Socket = new Socket();
+ java.net.InetSocketAddress sockaddr = new java.net.InetSocketAddress( m_Address, m_Port );
+ m_Socket.connect( sockaddr, m_Timeout );
setTimeout(m_Timeout);
prepareTransport();
m_Connected = true;
}
}//connect
/**
* Closes this <tt>TCPMasterConnection</tt>.
*/
public void close() {
if(m_Connected) {
try {
m_ModbusTransport.close();
} catch (IOException ex) {
if(Modbus.debug) System.out.println("close()");
}
m_Connected = false;
}
}//close
/**
* Returns the <tt>ModbusTransport</tt> associated with this
* <tt>TCPMasterConnection</tt>.
*
* @return the connection's <tt>ModbusTransport</tt>.
*/
public ModbusTransport getModbusTransport() {
return m_ModbusTransport;
}//getModbusTransport
/**
* Prepares the associated <tt>ModbusTransport</tt> of this
* <tt>TCPMasterConnection</tt> for use.
*
* @throws IOException if an I/O related error occurs.
*/
private void prepareTransport() throws IOException {
if (m_ModbusTransport == null) {
m_ModbusTransport = new ModbusTCPTransport(m_Socket);
} else {
m_ModbusTransport.setSocket(m_Socket);
}
}//prepareIO
/**
* Returns the timeout for this <tt>TCPMasterConnection</tt>.
*
* @return the timeout as <tt>int</tt>.
*/
public int getTimeout() {
return m_Timeout;
}//getReceiveTimeout
/**
* Sets the timeout for this <tt>TCPMasterConnection</tt>.
*
* @param timeout the timeout as <tt>int</tt>.
*/
public void setTimeout(int timeout) {
m_Timeout = timeout;
if(m_Socket != null) {
try {
m_Socket.setSoTimeout(m_Timeout);
} catch (IOException ex) {
//handle?
}
}
}//setReceiveTimeout
/**
* Returns the destination port of this
* <tt>TCPMasterConnection</tt>.
*
* @return the port number as <tt>int</tt>.
*/
public int getPort() {
return m_Port;
}//getPort
/**
* Sets the destination port of this
* <tt>TCPMasterConnection</tt>.
* The default is defined as <tt>Modbus.DEFAULT_PORT</tt>.
*
* @param port the port number as <tt>int</tt>.
*/
public void setPort(int port) {
m_Port = port;
}//setPort
/**
* Returns the destination <tt>InetAddress</tt> of this
* <tt>TCPMasterConnection</tt>.
*
* @return the destination address as <tt>InetAddress</tt>.
*/
public InetAddress getAddress() {
return m_Address;
}//getAddress
/**
* Sets the destination <tt>InetAddress</tt> of this
* <tt>TCPMasterConnection</tt>.
*
* @param adr the destination address as <tt>InetAddress</tt>.
*/
public void setAddress(InetAddress adr) {
m_Address = adr;
}//setAddress
/**
* Tests if this <tt>TCPMasterConnection</tt> is connected.
*
* @return <tt>true</tt> if connected, <tt>false</tt> otherwise.
*/
public boolean isConnected() {
return m_Connected;
}//isConnected
}//class TCPMasterConnection
| true | true | public synchronized void connect()
throws Exception {
if(!m_Connected) {
if(Modbus.debug) System.out.println("connect()");
m_Socket = new Socket(m_Address, m_Port);
m_Socket = new Socket();
java.net.InetSocketAddress sockaddr = new java.net.InetSocketAddress( m_Address, m_Port );
m_Socket.connect( sockaddr, m_Timeout );
setTimeout(m_Timeout);
prepareTransport();
m_Connected = true;
}
}//connect
| public synchronized void connect()
throws Exception {
if(!m_Connected) {
if(Modbus.debug) System.out.println("connect()");
m_Socket = new Socket();
java.net.InetSocketAddress sockaddr = new java.net.InetSocketAddress( m_Address, m_Port );
m_Socket.connect( sockaddr, m_Timeout );
setTimeout(m_Timeout);
prepareTransport();
m_Connected = true;
}
}//connect
|
diff --git a/src/java/com/android/internal/telephony/PhoneProxy.java b/src/java/com/android/internal/telephony/PhoneProxy.java
index e972bb2..cb9629f 100644
--- a/src/java/com/android/internal/telephony/PhoneProxy.java
+++ b/src/java/com/android/internal/telephony/PhoneProxy.java
@@ -1,1189 +1,1198 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony;
import android.app.ActivityManagerNative;
import android.content.Context;
import android.content.Intent;
import android.net.LinkCapabilities;
import android.net.LinkProperties;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.Message;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.telephony.CellInfo;
import android.telephony.CellLocation;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.Rlog;
import com.android.internal.telephony.test.SimulatedRadioControl;
import com.android.internal.telephony.uicc.IccCardProxy;
import com.android.internal.telephony.uicc.IsimRecords;
import com.android.internal.telephony.uicc.UsimServiceTable;
import com.android.internal.telephony.CallManager;
import java.util.List;
public class PhoneProxy extends Handler implements Phone {
public final static Object lockForRadioTechnologyChange = new Object();
private Phone mActivePhone;
private CommandsInterface mCommandsInterface;
private IccSmsInterfaceManagerProxy mIccSmsInterfaceManagerProxy;
private IccPhoneBookInterfaceManagerProxy mIccPhoneBookInterfaceManagerProxy;
private PhoneSubInfoProxy mPhoneSubInfoProxy;
private IccCardProxy mIccCardProxy;
private boolean mResetModemOnRadioTechnologyChange = false;
private int mRilVersion;
private boolean mRilV7NeedsCDMALTEPhone = SystemProperties.getBoolean(
"telephony.rilV7NeedCDMALTEPhone", false);
private static final int EVENT_VOICE_RADIO_TECH_CHANGED = 1;
private static final int EVENT_RADIO_ON = 2;
private static final int EVENT_REQUEST_VOICE_RADIO_TECH_DONE = 3;
private static final int EVENT_RIL_CONNECTED = 4;
private static final String LOG_TAG = "PhoneProxy";
//***** Class Methods
public PhoneProxy(PhoneBase phone) {
mActivePhone = phone;
mResetModemOnRadioTechnologyChange = SystemProperties.getBoolean(
TelephonyProperties.PROPERTY_RESET_ON_RADIO_TECH_CHANGE, false);
mIccSmsInterfaceManagerProxy = new IccSmsInterfaceManagerProxy(
phone.getContext(),
phone.getIccSmsInterfaceManager());
mIccPhoneBookInterfaceManagerProxy = new IccPhoneBookInterfaceManagerProxy(
phone.getIccPhoneBookInterfaceManager());
mPhoneSubInfoProxy = new PhoneSubInfoProxy(phone.getPhoneSubInfo());
mCommandsInterface = ((PhoneBase)mActivePhone).mCi;
mCommandsInterface.registerForRilConnected(this, EVENT_RIL_CONNECTED, null);
mCommandsInterface.registerForOn(this, EVENT_RADIO_ON, null);
mCommandsInterface.registerForVoiceRadioTechChanged(
this, EVENT_VOICE_RADIO_TECH_CHANGED, null);
mIccCardProxy = new IccCardProxy(phone.getContext(), mCommandsInterface);
if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_GSM) {
// For the purpose of IccCardProxy we only care about the technology family
mIccCardProxy.setVoiceRadioTech(ServiceState.RIL_RADIO_TECHNOLOGY_UMTS);
} else if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
mIccCardProxy.setVoiceRadioTech(ServiceState.RIL_RADIO_TECHNOLOGY_1xRTT);
}
}
@Override
public void handleMessage(Message msg) {
AsyncResult ar = (AsyncResult) msg.obj;
switch(msg.what) {
case EVENT_RADIO_ON:
/* Proactively query voice radio technologies */
mCommandsInterface.getVoiceRadioTechnology(
obtainMessage(EVENT_REQUEST_VOICE_RADIO_TECH_DONE));
break;
case EVENT_RIL_CONNECTED:
if (ar.exception == null && ar.result != null) {
mRilVersion = (Integer) ar.result;
} else {
logd("Unexpected exception on EVENT_RIL_CONNECTED");
mRilVersion = -1;
}
break;
case EVENT_VOICE_RADIO_TECH_CHANGED:
case EVENT_REQUEST_VOICE_RADIO_TECH_DONE:
if (ar.exception == null) {
if ((ar.result != null) && (((int[]) ar.result).length != 0)) {
int newVoiceTech = ((int[]) ar.result)[0];
updatePhoneObject(newVoiceTech);
} else {
loge("Voice Radio Technology event " + msg.what + " has no tech!");
}
} else {
loge("Voice Radio Technology event " + msg.what + " exception!" + ar.exception);
}
break;
default:
loge("Error! This handler was not registered for this message type. Message: "
+ msg.what);
break;
}
super.handleMessage(msg);
}
private static void logd(String msg) {
Rlog.d(LOG_TAG, "[PhoneProxy] " + msg);
}
private void loge(String msg) {
Rlog.e(LOG_TAG, "[PhoneProxy] " + msg);
}
private void updatePhoneObject(int newVoiceRadioTech) {
if (mActivePhone != null) {
if((mRilVersion == 6 && getLteOnCdmaMode() == PhoneConstants.LTE_ON_CDMA_TRUE) ||
mRilV7NeedsCDMALTEPhone) {
/*
* On v6 RIL, when LTE_ON_CDMA is TRUE, always create CDMALTEPhone
- * irrespective of the voice radio tech reported.
+ * irrespective of the voice radio tech reported. Handle instance
+ * where device may be global phone, reporting as cdma device. Don't update
+ * voice tech in that scenario.
*/
- if (mActivePhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
+ if ((ServiceState.isCdma(newVoiceRadioTech) &&
+ mActivePhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
logd("LTE ON CDMA property is set. Use CDMA Phone" +
" newVoiceRadioTech = " + newVoiceRadioTech +
" Active Phone = " + mActivePhone.getPhoneName());
// IccCardProxy needs to be kept in sync
mIccCardProxy.setVoiceRadioTech(newVoiceRadioTech);
return;
+ } else if ((ServiceState.isGsm(newVoiceRadioTech) &&
+ mActivePhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
+ logd("LTE ON CDMA property is set. Already CDMA Phone" +
+ " newVoiceRadioTech = " + newVoiceRadioTech +
+ " Active Phone = " + mActivePhone.getPhoneName());
+ return;
} else {
logd("LTE ON CDMA property is set. Switch to CDMALTEPhone" +
" newVoiceRadioTech = " + newVoiceRadioTech +
" Active Phone = " + mActivePhone.getPhoneName());
newVoiceRadioTech = ServiceState.RIL_RADIO_TECHNOLOGY_1xRTT;
}
} else {
if ((ServiceState.isCdma(newVoiceRadioTech) &&
mActivePhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) ||
(ServiceState.isGsm(newVoiceRadioTech) &&
mActivePhone.getPhoneType() == PhoneConstants.PHONE_TYPE_GSM)) {
// Nothing changed. Keep phone as it is.
logd("Ignoring voice radio technology changed message." +
" newVoiceRadioTech = " + newVoiceRadioTech +
" Active Phone = " + mActivePhone.getPhoneName());
// IccCardProxy needs to be kept in sync
mIccCardProxy.setVoiceRadioTech(newVoiceRadioTech);
return;
}
}
}
if (newVoiceRadioTech == ServiceState.RIL_RADIO_TECHNOLOGY_UNKNOWN) {
// We need some voice phone object to be active always, so never
// delete the phone without anything to replace it with!
logd("Ignoring voice radio technology changed message. newVoiceRadioTech = Unknown."
+ " Active Phone = " + mActivePhone.getPhoneName());
// IccCardProxy, though, needs to know even if radio tech is unknown
mIccCardProxy.setVoiceRadioTech(newVoiceRadioTech);
return;
}
boolean oldPowerState = false; // old power state to off
if (mResetModemOnRadioTechnologyChange) {
if (mCommandsInterface.getRadioState().isOn()) {
oldPowerState = true;
logd("Setting Radio Power to Off");
mCommandsInterface.setRadioPower(false, null);
}
}
deleteAndCreatePhone(newVoiceRadioTech);
if (mResetModemOnRadioTechnologyChange && oldPowerState) { // restore power state
logd("Resetting Radio");
mCommandsInterface.setRadioPower(oldPowerState, null);
}
// Set the new interfaces in the proxy's
mIccSmsInterfaceManagerProxy.setmIccSmsInterfaceManager(
mActivePhone.getIccSmsInterfaceManager());
mIccPhoneBookInterfaceManagerProxy.setmIccPhoneBookInterfaceManager(mActivePhone
.getIccPhoneBookInterfaceManager());
mPhoneSubInfoProxy.setmPhoneSubInfo(mActivePhone.getPhoneSubInfo());
mCommandsInterface = ((PhoneBase)mActivePhone).mCi;
mIccCardProxy.setVoiceRadioTech(newVoiceRadioTech);
// Send an Intent to the PhoneApp that we had a radio technology change
Intent intent = new Intent(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
intent.putExtra(PhoneConstants.PHONE_NAME_KEY, mActivePhone.getPhoneName());
ActivityManagerNative.broadcastStickyIntent(intent, null, UserHandle.USER_ALL);
}
private void deleteAndCreatePhone(int newVoiceRadioTech) {
String outgoingPhoneName = "Unknown";
Phone oldPhone = mActivePhone;
if (oldPhone != null) {
outgoingPhoneName = ((PhoneBase) oldPhone).getPhoneName();
}
logd("Switching Voice Phone : " + outgoingPhoneName + " >>> "
+ (ServiceState.isGsm(newVoiceRadioTech) ? "GSM" : "CDMA"));
if (oldPhone != null) {
CallManager.getInstance().unregisterPhone(oldPhone);
logd("Disposing old phone..");
oldPhone.dispose();
}
// Give the garbage collector a hint to start the garbage collection
// asap NOTE this has been disabled since radio technology change could
// happen during e.g. a multimedia playing and could slow the system.
// Tests needs to be done to see the effects of the GC call here when
// system is busy.
// System.gc();
if (ServiceState.isCdma(newVoiceRadioTech)) {
mActivePhone = PhoneFactory.getCdmaPhone();
} else if (ServiceState.isGsm(newVoiceRadioTech)) {
mActivePhone = PhoneFactory.getGsmPhone();
}
if (oldPhone != null) {
oldPhone.removeReferences();
}
if(mActivePhone != null) {
CallManager.getInstance().registerPhone(mActivePhone);
}
oldPhone = null;
}
@Override
public ServiceState getServiceState() {
return mActivePhone.getServiceState();
}
@Override
public CellLocation getCellLocation() {
return mActivePhone.getCellLocation();
}
/**
* @return all available cell information or null if none.
*/
@Override
public List<CellInfo> getAllCellInfo() {
return mActivePhone.getAllCellInfo();
}
/**
* {@inheritDoc}
*/
@Override
public void setCellInfoListRate(int rateInMillis) {
mActivePhone.setCellInfoListRate(rateInMillis);
}
@Override
public PhoneConstants.DataState getDataConnectionState() {
return mActivePhone.getDataConnectionState(PhoneConstants.APN_TYPE_DEFAULT);
}
@Override
public PhoneConstants.DataState getDataConnectionState(String apnType) {
return mActivePhone.getDataConnectionState(apnType);
}
@Override
public DataActivityState getDataActivityState() {
return mActivePhone.getDataActivityState();
}
@Override
public Context getContext() {
return mActivePhone.getContext();
}
@Override
public void disableDnsCheck(boolean b) {
mActivePhone.disableDnsCheck(b);
}
@Override
public boolean isDnsCheckDisabled() {
return mActivePhone.isDnsCheckDisabled();
}
@Override
public PhoneConstants.State getState() {
return mActivePhone.getState();
}
@Override
public String getPhoneName() {
return mActivePhone.getPhoneName();
}
@Override
public int getPhoneType() {
return mActivePhone.getPhoneType();
}
@Override
public String[] getActiveApnTypes() {
return mActivePhone.getActiveApnTypes();
}
@Override
public String getActiveApnHost(String apnType) {
return mActivePhone.getActiveApnHost(apnType);
}
@Override
public LinkProperties getLinkProperties(String apnType) {
return mActivePhone.getLinkProperties(apnType);
}
@Override
public LinkCapabilities getLinkCapabilities(String apnType) {
return mActivePhone.getLinkCapabilities(apnType);
}
@Override
public SignalStrength getSignalStrength() {
return mActivePhone.getSignalStrength();
}
@Override
public void registerForUnknownConnection(Handler h, int what, Object obj) {
mActivePhone.registerForUnknownConnection(h, what, obj);
}
@Override
public void unregisterForUnknownConnection(Handler h) {
mActivePhone.unregisterForUnknownConnection(h);
}
@Override
public void registerForPreciseCallStateChanged(Handler h, int what, Object obj) {
mActivePhone.registerForPreciseCallStateChanged(h, what, obj);
}
@Override
public void unregisterForPreciseCallStateChanged(Handler h) {
mActivePhone.unregisterForPreciseCallStateChanged(h);
}
@Override
public void registerForNewRingingConnection(Handler h, int what, Object obj) {
mActivePhone.registerForNewRingingConnection(h, what, obj);
}
@Override
public void unregisterForNewRingingConnection(Handler h) {
mActivePhone.unregisterForNewRingingConnection(h);
}
@Override
public void registerForIncomingRing(Handler h, int what, Object obj) {
mActivePhone.registerForIncomingRing(h, what, obj);
}
@Override
public void unregisterForIncomingRing(Handler h) {
mActivePhone.unregisterForIncomingRing(h);
}
@Override
public void registerForDisconnect(Handler h, int what, Object obj) {
mActivePhone.registerForDisconnect(h, what, obj);
}
@Override
public void unregisterForDisconnect(Handler h) {
mActivePhone.unregisterForDisconnect(h);
}
@Override
public void registerForMmiInitiate(Handler h, int what, Object obj) {
mActivePhone.registerForMmiInitiate(h, what, obj);
}
@Override
public void unregisterForMmiInitiate(Handler h) {
mActivePhone.unregisterForMmiInitiate(h);
}
@Override
public void registerForMmiComplete(Handler h, int what, Object obj) {
mActivePhone.registerForMmiComplete(h, what, obj);
}
@Override
public void unregisterForMmiComplete(Handler h) {
mActivePhone.unregisterForMmiComplete(h);
}
@Override
public List<? extends MmiCode> getPendingMmiCodes() {
return mActivePhone.getPendingMmiCodes();
}
@Override
public void sendUssdResponse(String ussdMessge) {
mActivePhone.sendUssdResponse(ussdMessge);
}
@Override
public void registerForServiceStateChanged(Handler h, int what, Object obj) {
mActivePhone.registerForServiceStateChanged(h, what, obj);
}
@Override
public void unregisterForServiceStateChanged(Handler h) {
mActivePhone.unregisterForServiceStateChanged(h);
}
@Override
public void registerForSuppServiceNotification(Handler h, int what, Object obj) {
mActivePhone.registerForSuppServiceNotification(h, what, obj);
}
@Override
public void unregisterForSuppServiceNotification(Handler h) {
mActivePhone.unregisterForSuppServiceNotification(h);
}
@Override
public void registerForSuppServiceFailed(Handler h, int what, Object obj) {
mActivePhone.registerForSuppServiceFailed(h, what, obj);
}
@Override
public void unregisterForSuppServiceFailed(Handler h) {
mActivePhone.unregisterForSuppServiceFailed(h);
}
@Override
public void registerForInCallVoicePrivacyOn(Handler h, int what, Object obj){
mActivePhone.registerForInCallVoicePrivacyOn(h,what,obj);
}
@Override
public void unregisterForInCallVoicePrivacyOn(Handler h){
mActivePhone.unregisterForInCallVoicePrivacyOn(h);
}
@Override
public void registerForInCallVoicePrivacyOff(Handler h, int what, Object obj){
mActivePhone.registerForInCallVoicePrivacyOff(h,what,obj);
}
@Override
public void unregisterForInCallVoicePrivacyOff(Handler h){
mActivePhone.unregisterForInCallVoicePrivacyOff(h);
}
@Override
public void registerForCdmaOtaStatusChange(Handler h, int what, Object obj) {
mActivePhone.registerForCdmaOtaStatusChange(h,what,obj);
}
@Override
public void unregisterForCdmaOtaStatusChange(Handler h) {
mActivePhone.unregisterForCdmaOtaStatusChange(h);
}
@Override
public void registerForSubscriptionInfoReady(Handler h, int what, Object obj) {
mActivePhone.registerForSubscriptionInfoReady(h, what, obj);
}
@Override
public void unregisterForSubscriptionInfoReady(Handler h) {
mActivePhone.unregisterForSubscriptionInfoReady(h);
}
@Override
public void registerForEcmTimerReset(Handler h, int what, Object obj) {
mActivePhone.registerForEcmTimerReset(h,what,obj);
}
@Override
public void unregisterForEcmTimerReset(Handler h) {
mActivePhone.unregisterForEcmTimerReset(h);
}
@Override
public void registerForRingbackTone(Handler h, int what, Object obj) {
mActivePhone.registerForRingbackTone(h,what,obj);
}
@Override
public void unregisterForRingbackTone(Handler h) {
mActivePhone.unregisterForRingbackTone(h);
}
@Override
public void registerForResendIncallMute(Handler h, int what, Object obj) {
mActivePhone.registerForResendIncallMute(h,what,obj);
}
@Override
public void unregisterForResendIncallMute(Handler h) {
mActivePhone.unregisterForResendIncallMute(h);
}
@Override
public boolean getIccRecordsLoaded() {
return mIccCardProxy.getIccRecordsLoaded();
}
@Override
public IccCard getIccCard() {
return mIccCardProxy;
}
@Override
public void acceptCall() throws CallStateException {
mActivePhone.acceptCall();
}
@Override
public void rejectCall() throws CallStateException {
mActivePhone.rejectCall();
}
@Override
public void switchHoldingAndActive() throws CallStateException {
mActivePhone.switchHoldingAndActive();
}
@Override
public boolean canConference() {
return mActivePhone.canConference();
}
@Override
public void conference() throws CallStateException {
mActivePhone.conference();
}
@Override
public void enableEnhancedVoicePrivacy(boolean enable, Message onComplete) {
mActivePhone.enableEnhancedVoicePrivacy(enable, onComplete);
}
@Override
public void getEnhancedVoicePrivacy(Message onComplete) {
mActivePhone.getEnhancedVoicePrivacy(onComplete);
}
@Override
public boolean canTransfer() {
return mActivePhone.canTransfer();
}
@Override
public void explicitCallTransfer() throws CallStateException {
mActivePhone.explicitCallTransfer();
}
@Override
public void clearDisconnected() {
mActivePhone.clearDisconnected();
}
@Override
public Call getForegroundCall() {
return mActivePhone.getForegroundCall();
}
@Override
public Call getBackgroundCall() {
return mActivePhone.getBackgroundCall();
}
@Override
public Call getRingingCall() {
return mActivePhone.getRingingCall();
}
@Override
public Connection dial(String dialString) throws CallStateException {
return mActivePhone.dial(dialString);
}
@Override
public Connection dial(String dialString, UUSInfo uusInfo) throws CallStateException {
return mActivePhone.dial(dialString, uusInfo);
}
@Override
public boolean handlePinMmi(String dialString) {
return mActivePhone.handlePinMmi(dialString);
}
@Override
public boolean handleInCallMmiCommands(String command) throws CallStateException {
return mActivePhone.handleInCallMmiCommands(command);
}
@Override
public void sendDtmf(char c) {
mActivePhone.sendDtmf(c);
}
@Override
public void startDtmf(char c) {
mActivePhone.startDtmf(c);
}
@Override
public void stopDtmf() {
mActivePhone.stopDtmf();
}
@Override
public void setRadioPower(boolean power) {
mActivePhone.setRadioPower(power);
}
@Override
public boolean getMessageWaitingIndicator() {
return mActivePhone.getMessageWaitingIndicator();
}
@Override
public boolean getCallForwardingIndicator() {
return mActivePhone.getCallForwardingIndicator();
}
@Override
public String getLine1Number() {
return mActivePhone.getLine1Number();
}
@Override
public String getCdmaMin() {
return mActivePhone.getCdmaMin();
}
@Override
public boolean isMinInfoReady() {
return mActivePhone.isMinInfoReady();
}
@Override
public String getCdmaPrlVersion() {
return mActivePhone.getCdmaPrlVersion();
}
@Override
public String getLine1AlphaTag() {
return mActivePhone.getLine1AlphaTag();
}
@Override
public void setLine1Number(String alphaTag, String number, Message onComplete) {
mActivePhone.setLine1Number(alphaTag, number, onComplete);
}
@Override
public String getVoiceMailNumber() {
return mActivePhone.getVoiceMailNumber();
}
/** @hide */
@Override
public int getVoiceMessageCount(){
return mActivePhone.getVoiceMessageCount();
}
@Override
public String getVoiceMailAlphaTag() {
return mActivePhone.getVoiceMailAlphaTag();
}
@Override
public void setVoiceMailNumber(String alphaTag,String voiceMailNumber,
Message onComplete) {
mActivePhone.setVoiceMailNumber(alphaTag, voiceMailNumber, onComplete);
}
@Override
public void getCallForwardingOption(int commandInterfaceCFReason,
Message onComplete) {
mActivePhone.getCallForwardingOption(commandInterfaceCFReason,
onComplete);
}
@Override
public void setCallForwardingOption(int commandInterfaceCFReason,
int commandInterfaceCFAction, String dialingNumber,
int timerSeconds, Message onComplete) {
mActivePhone.setCallForwardingOption(commandInterfaceCFReason,
commandInterfaceCFAction, dialingNumber, timerSeconds, onComplete);
}
@Override
public void getOutgoingCallerIdDisplay(Message onComplete) {
mActivePhone.getOutgoingCallerIdDisplay(onComplete);
}
@Override
public void setOutgoingCallerIdDisplay(int commandInterfaceCLIRMode,
Message onComplete) {
mActivePhone.setOutgoingCallerIdDisplay(commandInterfaceCLIRMode,
onComplete);
}
@Override
public void getCallWaiting(Message onComplete) {
mActivePhone.getCallWaiting(onComplete);
}
@Override
public void setCallWaiting(boolean enable, Message onComplete) {
mActivePhone.setCallWaiting(enable, onComplete);
}
@Override
public void getAvailableNetworks(Message response) {
mActivePhone.getAvailableNetworks(response);
}
@Override
public void setNetworkSelectionModeAutomatic(Message response) {
mActivePhone.setNetworkSelectionModeAutomatic(response);
}
@Override
public void selectNetworkManually(OperatorInfo network, Message response) {
mActivePhone.selectNetworkManually(network, response);
}
@Override
public void setPreferredNetworkType(int networkType, Message response) {
mActivePhone.setPreferredNetworkType(networkType, response);
}
@Override
public void getPreferredNetworkType(Message response) {
mActivePhone.getPreferredNetworkType(response);
}
@Override
public void getNeighboringCids(Message response) {
mActivePhone.getNeighboringCids(response);
}
@Override
public void setOnPostDialCharacter(Handler h, int what, Object obj) {
mActivePhone.setOnPostDialCharacter(h, what, obj);
}
@Override
public void setMute(boolean muted) {
mActivePhone.setMute(muted);
}
@Override
public boolean getMute() {
return mActivePhone.getMute();
}
@Override
public void setEchoSuppressionEnabled(boolean enabled) {
mActivePhone.setEchoSuppressionEnabled(enabled);
}
@Override
public void invokeOemRilRequestRaw(byte[] data, Message response) {
mActivePhone.invokeOemRilRequestRaw(data, response);
}
@Override
public void invokeOemRilRequestStrings(String[] strings, Message response) {
mActivePhone.invokeOemRilRequestStrings(strings, response);
}
@Override
public void getDataCallList(Message response) {
mActivePhone.getDataCallList(response);
}
@Override
public void updateServiceLocation() {
mActivePhone.updateServiceLocation();
}
@Override
public void enableLocationUpdates() {
mActivePhone.enableLocationUpdates();
}
@Override
public void disableLocationUpdates() {
mActivePhone.disableLocationUpdates();
}
@Override
public void setUnitTestMode(boolean f) {
mActivePhone.setUnitTestMode(f);
}
@Override
public boolean getUnitTestMode() {
return mActivePhone.getUnitTestMode();
}
@Override
public void setBandMode(int bandMode, Message response) {
mActivePhone.setBandMode(bandMode, response);
}
@Override
public void queryAvailableBandMode(Message response) {
mActivePhone.queryAvailableBandMode(response);
}
@Override
public boolean getDataRoamingEnabled() {
return mActivePhone.getDataRoamingEnabled();
}
@Override
public void setDataRoamingEnabled(boolean enable) {
mActivePhone.setDataRoamingEnabled(enable);
}
@Override
public void queryCdmaRoamingPreference(Message response) {
mActivePhone.queryCdmaRoamingPreference(response);
}
@Override
public void setCdmaRoamingPreference(int cdmaRoamingType, Message response) {
mActivePhone.setCdmaRoamingPreference(cdmaRoamingType, response);
}
@Override
public void setCdmaSubscription(int cdmaSubscriptionType, Message response) {
mActivePhone.setCdmaSubscription(cdmaSubscriptionType, response);
}
@Override
public SimulatedRadioControl getSimulatedRadioControl() {
return mActivePhone.getSimulatedRadioControl();
}
@Override
public int enableApnType(String type) {
return mActivePhone.enableApnType(type);
}
@Override
public int disableApnType(String type) {
return mActivePhone.disableApnType(type);
}
@Override
public boolean isDataConnectivityPossible() {
return mActivePhone.isDataConnectivityPossible(PhoneConstants.APN_TYPE_DEFAULT);
}
@Override
public boolean isDataConnectivityPossible(String apnType) {
return mActivePhone.isDataConnectivityPossible(apnType);
}
@Override
public String getDeviceId() {
return mActivePhone.getDeviceId();
}
@Override
public String getDeviceSvn() {
return mActivePhone.getDeviceSvn();
}
@Override
public String getSubscriberId() {
return mActivePhone.getSubscriberId();
}
@Override
public String getGroupIdLevel1() {
return mActivePhone.getGroupIdLevel1();
}
@Override
public String getIccSerialNumber() {
return mActivePhone.getIccSerialNumber();
}
@Override
public String getEsn() {
return mActivePhone.getEsn();
}
@Override
public String getMeid() {
return mActivePhone.getMeid();
}
@Override
public String getMsisdn() {
return mActivePhone.getMsisdn();
}
@Override
public String getImei() {
return mActivePhone.getImei();
}
@Override
public PhoneSubInfo getPhoneSubInfo(){
return mActivePhone.getPhoneSubInfo();
}
@Override
public IccSmsInterfaceManager getIccSmsInterfaceManager(){
return mActivePhone.getIccSmsInterfaceManager();
}
@Override
public IccPhoneBookInterfaceManager getIccPhoneBookInterfaceManager(){
return mActivePhone.getIccPhoneBookInterfaceManager();
}
@Override
public void setTTYMode(int ttyMode, Message onComplete) {
mActivePhone.setTTYMode(ttyMode, onComplete);
}
@Override
public void queryTTYMode(Message onComplete) {
mActivePhone.queryTTYMode(onComplete);
}
@Override
public void activateCellBroadcastSms(int activate, Message response) {
mActivePhone.activateCellBroadcastSms(activate, response);
}
@Override
public void getCellBroadcastSmsConfig(Message response) {
mActivePhone.getCellBroadcastSmsConfig(response);
}
@Override
public void setCellBroadcastSmsConfig(int[] configValuesArray, Message response) {
mActivePhone.setCellBroadcastSmsConfig(configValuesArray, response);
}
@Override
public void notifyDataActivity() {
mActivePhone.notifyDataActivity();
}
@Override
public void getSmscAddress(Message result) {
mActivePhone.getSmscAddress(result);
}
@Override
public void setSmscAddress(String address, Message result) {
mActivePhone.setSmscAddress(address, result);
}
@Override
public int getCdmaEriIconIndex() {
return mActivePhone.getCdmaEriIconIndex();
}
@Override
public String getCdmaEriText() {
return mActivePhone.getCdmaEriText();
}
@Override
public int getCdmaEriIconMode() {
return mActivePhone.getCdmaEriIconMode();
}
public Phone getActivePhone() {
return mActivePhone;
}
@Override
public void sendBurstDtmf(String dtmfString, int on, int off, Message onComplete){
mActivePhone.sendBurstDtmf(dtmfString, on, off, onComplete);
}
@Override
public void exitEmergencyCallbackMode(){
mActivePhone.exitEmergencyCallbackMode();
}
@Override
public boolean needsOtaServiceProvisioning(){
return mActivePhone.needsOtaServiceProvisioning();
}
@Override
public boolean isOtaSpNumber(String dialStr){
return mActivePhone.isOtaSpNumber(dialStr);
}
@Override
public void registerForCallWaiting(Handler h, int what, Object obj){
mActivePhone.registerForCallWaiting(h,what,obj);
}
@Override
public void unregisterForCallWaiting(Handler h){
mActivePhone.unregisterForCallWaiting(h);
}
@Override
public void registerForSignalInfo(Handler h, int what, Object obj) {
mActivePhone.registerForSignalInfo(h,what,obj);
}
@Override
public void unregisterForSignalInfo(Handler h) {
mActivePhone.unregisterForSignalInfo(h);
}
@Override
public void registerForDisplayInfo(Handler h, int what, Object obj) {
mActivePhone.registerForDisplayInfo(h,what,obj);
}
@Override
public void unregisterForDisplayInfo(Handler h) {
mActivePhone.unregisterForDisplayInfo(h);
}
@Override
public void registerForNumberInfo(Handler h, int what, Object obj) {
mActivePhone.registerForNumberInfo(h, what, obj);
}
@Override
public void unregisterForNumberInfo(Handler h) {
mActivePhone.unregisterForNumberInfo(h);
}
@Override
public void registerForRedirectedNumberInfo(Handler h, int what, Object obj) {
mActivePhone.registerForRedirectedNumberInfo(h, what, obj);
}
@Override
public void unregisterForRedirectedNumberInfo(Handler h) {
mActivePhone.unregisterForRedirectedNumberInfo(h);
}
@Override
public void registerForLineControlInfo(Handler h, int what, Object obj) {
mActivePhone.registerForLineControlInfo( h, what, obj);
}
@Override
public void unregisterForLineControlInfo(Handler h) {
mActivePhone.unregisterForLineControlInfo(h);
}
@Override
public void registerFoT53ClirlInfo(Handler h, int what, Object obj) {
mActivePhone.registerFoT53ClirlInfo(h, what, obj);
}
@Override
public void unregisterForT53ClirInfo(Handler h) {
mActivePhone.unregisterForT53ClirInfo(h);
}
@Override
public void registerForT53AudioControlInfo(Handler h, int what, Object obj) {
mActivePhone.registerForT53AudioControlInfo( h, what, obj);
}
@Override
public void unregisterForT53AudioControlInfo(Handler h) {
mActivePhone.unregisterForT53AudioControlInfo(h);
}
@Override
public void setOnEcbModeExitResponse(Handler h, int what, Object obj){
mActivePhone.setOnEcbModeExitResponse(h,what,obj);
}
@Override
public void unsetOnEcbModeExitResponse(Handler h){
mActivePhone.unsetOnEcbModeExitResponse(h);
}
@Override
public boolean isCspPlmnEnabled() {
return mActivePhone.isCspPlmnEnabled();
}
@Override
public IsimRecords getIsimRecords() {
return mActivePhone.getIsimRecords();
}
@Override
public void requestIsimAuthentication(String nonce, Message response) {
mActivePhone.requestIsimAuthentication(nonce, response);
}
/**
* {@inheritDoc}
*/
@Override
public int getLteOnCdmaMode() {
return mActivePhone.getLteOnCdmaMode();
}
/**
* {@hide}
*/
@Override
public int getLteOnGsmMode() {
return mActivePhone.getLteOnGsmMode();
}
@Override
public void setVoiceMessageWaiting(int line, int countWaiting) {
mActivePhone.setVoiceMessageWaiting(line, countWaiting);
}
@Override
public UsimServiceTable getUsimServiceTable() {
return mActivePhone.getUsimServiceTable();
}
@Override
public void dispose() {
mCommandsInterface.unregisterForOn(this);
mCommandsInterface.unregisterForVoiceRadioTechChanged(this);
mCommandsInterface.unregisterForRilConnected(this);
}
@Override
public void removeReferences() {
mActivePhone = null;
mCommandsInterface = null;
}
}
| false | true | private void updatePhoneObject(int newVoiceRadioTech) {
if (mActivePhone != null) {
if((mRilVersion == 6 && getLteOnCdmaMode() == PhoneConstants.LTE_ON_CDMA_TRUE) ||
mRilV7NeedsCDMALTEPhone) {
/*
* On v6 RIL, when LTE_ON_CDMA is TRUE, always create CDMALTEPhone
* irrespective of the voice radio tech reported.
*/
if (mActivePhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
logd("LTE ON CDMA property is set. Use CDMA Phone" +
" newVoiceRadioTech = " + newVoiceRadioTech +
" Active Phone = " + mActivePhone.getPhoneName());
// IccCardProxy needs to be kept in sync
mIccCardProxy.setVoiceRadioTech(newVoiceRadioTech);
return;
} else {
logd("LTE ON CDMA property is set. Switch to CDMALTEPhone" +
" newVoiceRadioTech = " + newVoiceRadioTech +
" Active Phone = " + mActivePhone.getPhoneName());
newVoiceRadioTech = ServiceState.RIL_RADIO_TECHNOLOGY_1xRTT;
}
} else {
if ((ServiceState.isCdma(newVoiceRadioTech) &&
mActivePhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) ||
(ServiceState.isGsm(newVoiceRadioTech) &&
mActivePhone.getPhoneType() == PhoneConstants.PHONE_TYPE_GSM)) {
// Nothing changed. Keep phone as it is.
logd("Ignoring voice radio technology changed message." +
" newVoiceRadioTech = " + newVoiceRadioTech +
" Active Phone = " + mActivePhone.getPhoneName());
// IccCardProxy needs to be kept in sync
mIccCardProxy.setVoiceRadioTech(newVoiceRadioTech);
return;
}
}
}
if (newVoiceRadioTech == ServiceState.RIL_RADIO_TECHNOLOGY_UNKNOWN) {
// We need some voice phone object to be active always, so never
// delete the phone without anything to replace it with!
logd("Ignoring voice radio technology changed message. newVoiceRadioTech = Unknown."
+ " Active Phone = " + mActivePhone.getPhoneName());
// IccCardProxy, though, needs to know even if radio tech is unknown
mIccCardProxy.setVoiceRadioTech(newVoiceRadioTech);
return;
}
boolean oldPowerState = false; // old power state to off
if (mResetModemOnRadioTechnologyChange) {
if (mCommandsInterface.getRadioState().isOn()) {
oldPowerState = true;
logd("Setting Radio Power to Off");
mCommandsInterface.setRadioPower(false, null);
}
}
deleteAndCreatePhone(newVoiceRadioTech);
if (mResetModemOnRadioTechnologyChange && oldPowerState) { // restore power state
logd("Resetting Radio");
mCommandsInterface.setRadioPower(oldPowerState, null);
}
// Set the new interfaces in the proxy's
mIccSmsInterfaceManagerProxy.setmIccSmsInterfaceManager(
mActivePhone.getIccSmsInterfaceManager());
mIccPhoneBookInterfaceManagerProxy.setmIccPhoneBookInterfaceManager(mActivePhone
.getIccPhoneBookInterfaceManager());
mPhoneSubInfoProxy.setmPhoneSubInfo(mActivePhone.getPhoneSubInfo());
mCommandsInterface = ((PhoneBase)mActivePhone).mCi;
mIccCardProxy.setVoiceRadioTech(newVoiceRadioTech);
// Send an Intent to the PhoneApp that we had a radio technology change
Intent intent = new Intent(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
intent.putExtra(PhoneConstants.PHONE_NAME_KEY, mActivePhone.getPhoneName());
ActivityManagerNative.broadcastStickyIntent(intent, null, UserHandle.USER_ALL);
}
| private void updatePhoneObject(int newVoiceRadioTech) {
if (mActivePhone != null) {
if((mRilVersion == 6 && getLteOnCdmaMode() == PhoneConstants.LTE_ON_CDMA_TRUE) ||
mRilV7NeedsCDMALTEPhone) {
/*
* On v6 RIL, when LTE_ON_CDMA is TRUE, always create CDMALTEPhone
* irrespective of the voice radio tech reported. Handle instance
* where device may be global phone, reporting as cdma device. Don't update
* voice tech in that scenario.
*/
if ((ServiceState.isCdma(newVoiceRadioTech) &&
mActivePhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
logd("LTE ON CDMA property is set. Use CDMA Phone" +
" newVoiceRadioTech = " + newVoiceRadioTech +
" Active Phone = " + mActivePhone.getPhoneName());
// IccCardProxy needs to be kept in sync
mIccCardProxy.setVoiceRadioTech(newVoiceRadioTech);
return;
} else if ((ServiceState.isGsm(newVoiceRadioTech) &&
mActivePhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
logd("LTE ON CDMA property is set. Already CDMA Phone" +
" newVoiceRadioTech = " + newVoiceRadioTech +
" Active Phone = " + mActivePhone.getPhoneName());
return;
} else {
logd("LTE ON CDMA property is set. Switch to CDMALTEPhone" +
" newVoiceRadioTech = " + newVoiceRadioTech +
" Active Phone = " + mActivePhone.getPhoneName());
newVoiceRadioTech = ServiceState.RIL_RADIO_TECHNOLOGY_1xRTT;
}
} else {
if ((ServiceState.isCdma(newVoiceRadioTech) &&
mActivePhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) ||
(ServiceState.isGsm(newVoiceRadioTech) &&
mActivePhone.getPhoneType() == PhoneConstants.PHONE_TYPE_GSM)) {
// Nothing changed. Keep phone as it is.
logd("Ignoring voice radio technology changed message." +
" newVoiceRadioTech = " + newVoiceRadioTech +
" Active Phone = " + mActivePhone.getPhoneName());
// IccCardProxy needs to be kept in sync
mIccCardProxy.setVoiceRadioTech(newVoiceRadioTech);
return;
}
}
}
if (newVoiceRadioTech == ServiceState.RIL_RADIO_TECHNOLOGY_UNKNOWN) {
// We need some voice phone object to be active always, so never
// delete the phone without anything to replace it with!
logd("Ignoring voice radio technology changed message. newVoiceRadioTech = Unknown."
+ " Active Phone = " + mActivePhone.getPhoneName());
// IccCardProxy, though, needs to know even if radio tech is unknown
mIccCardProxy.setVoiceRadioTech(newVoiceRadioTech);
return;
}
boolean oldPowerState = false; // old power state to off
if (mResetModemOnRadioTechnologyChange) {
if (mCommandsInterface.getRadioState().isOn()) {
oldPowerState = true;
logd("Setting Radio Power to Off");
mCommandsInterface.setRadioPower(false, null);
}
}
deleteAndCreatePhone(newVoiceRadioTech);
if (mResetModemOnRadioTechnologyChange && oldPowerState) { // restore power state
logd("Resetting Radio");
mCommandsInterface.setRadioPower(oldPowerState, null);
}
// Set the new interfaces in the proxy's
mIccSmsInterfaceManagerProxy.setmIccSmsInterfaceManager(
mActivePhone.getIccSmsInterfaceManager());
mIccPhoneBookInterfaceManagerProxy.setmIccPhoneBookInterfaceManager(mActivePhone
.getIccPhoneBookInterfaceManager());
mPhoneSubInfoProxy.setmPhoneSubInfo(mActivePhone.getPhoneSubInfo());
mCommandsInterface = ((PhoneBase)mActivePhone).mCi;
mIccCardProxy.setVoiceRadioTech(newVoiceRadioTech);
// Send an Intent to the PhoneApp that we had a radio technology change
Intent intent = new Intent(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
intent.putExtra(PhoneConstants.PHONE_NAME_KEY, mActivePhone.getPhoneName());
ActivityManagerNative.broadcastStickyIntent(intent, null, UserHandle.USER_ALL);
}
|
diff --git a/src/org/jruby/RubyString.java b/src/org/jruby/RubyString.java
index af05bdfb1..7f06712e8 100644
--- a/src/org/jruby/RubyString.java
+++ b/src/org/jruby/RubyString.java
@@ -1,3369 +1,3369 @@
/*
**** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common 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://www.eclipse.org/legal/cpl-v10.html
*
* 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) 2001 Alan Moore <[email protected]>
* Copyright (C) 2001-2002 Benoit Cerrina <[email protected]>
* Copyright (C) 2001-2004 Jan Arne Petersen <[email protected]>
* Copyright (C) 2002-2004 Anders Bengtsson <[email protected]>
* Copyright (C) 2002-2006 Thomas E Enebo <[email protected]>
* Copyright (C) 2004 Stefan Matthias Aust <[email protected]>
* Copyright (C) 2004 David Corbin <[email protected]>
* Copyright (C) 2005 Tim Azzopardi <[email protected]>
* Copyright (C) 2006 Miguel Covarrubias <[email protected]>
* Copyright (C) 2006 Ola Bini <[email protected]>
* Copyright (C) 2007 Nick Sieger <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.util.Locale;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallbackFactory;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.ByteList;
import org.jruby.util.KCode;
import org.jruby.util.Pack;
import org.jruby.util.Sprintf;
import org.joni.encoding.Encoding;
import org.joni.Regex;
import org.joni.Region;
/**
*
* @author jpetersen
*/
public class RubyString extends RubyObject {
// string doesn't have it's own ByteList (values)
private static final int SHARED_BUFFER_STR_F = 1 << 9;
// string has it's own ByteList, but it's pointing to a shared buffer (byte[])
private static final int SHARED_BYTELIST_STR_F = 1 << 10;
// string has either ByteList or buffer shared
private static final int SHARED_STR_F = SHARED_BUFFER_STR_F | SHARED_BYTELIST_STR_F;
private ByteList value;
private static ObjectAllocator STRING_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
RubyString newString = runtime.newString("");
newString.setMetaClass(klass);
return newString;
}
};
public static RubyClass createStringClass(Ruby runtime) {
RubyClass stringClass = runtime.defineClass("String", runtime.getObject(), STRING_ALLOCATOR);
runtime.setString(stringClass);
stringClass.index = ClassIndex.STRING;
stringClass.kindOf = new RubyModule.KindOf() {
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyString;
}
};
CallbackFactory callbackFactory = runtime.callbackFactory(RubyString.class);
stringClass.includeModule(runtime.getComparable());
stringClass.includeModule(runtime.getEnumerable());
stringClass.defineAnnotatedMethods(RubyString.class);
stringClass.dispatcher = callbackFactory.createDispatcher(stringClass);
return stringClass;
}
/** short circuit for String key comparison
*
*/
public final boolean eql(IRubyObject other) {
return other instanceof RubyString && value.equal(((RubyString)other).value);
}
private RubyString(Ruby runtime, RubyClass rubyClass, CharSequence value) {
super(runtime, rubyClass);
assert value != null;
this.value = new ByteList(ByteList.plain(value),false);
}
private RubyString(Ruby runtime, RubyClass rubyClass, byte[] value) {
super(runtime, rubyClass);
assert value != null;
this.value = new ByteList(value);
}
private RubyString(Ruby runtime, RubyClass rubyClass, ByteList value) {
super(runtime, rubyClass);
assert value != null;
this.value = value;
}
private RubyString(Ruby runtime, RubyClass rubyClass, ByteList value, boolean objectSpace) {
super(runtime, rubyClass, objectSpace);
assert value != null;
this.value = value;
}
public int getNativeTypeIndex() {
return ClassIndex.STRING;
}
public Class getJavaClass() {
return String.class;
}
public RubyString convertToString() {
return this;
}
public String toString() {
return value.toString();
}
/** rb_str_dup
*
*/
public final RubyString strDup() {
return strDup(getMetaClass());
}
private final RubyString strDup(RubyClass clazz) {
flags |= SHARED_BYTELIST_STR_F;
RubyString dup = new RubyString(getRuntime(), clazz, value);
dup.flags |= SHARED_BYTELIST_STR_F;
dup.infectBy(this);
return dup;
}
public final RubyString makeShared(int index, int len) {
if (len == 0) return newEmptyString(getRuntime(), getMetaClass());
if ((flags & SHARED_STR_F) == 0) flags |= SHARED_BUFFER_STR_F;
RubyString shared = new RubyString(getRuntime(), getMetaClass(), value.makeShared(index, len));
shared.flags |= SHARED_BUFFER_STR_F;
shared.infectBy(this);
return shared;
}
private final void modifyCheck() {
// TODO: tmp lock here!
testFrozen("string");
if (!isTaint() && getRuntime().getSafeLevel() >= 4) {
throw getRuntime().newSecurityError("Insecure: can't modify string");
}
}
private final void modifyCheck(byte[] b, int len) {
if (value.bytes != b || value.realSize != len) throw getRuntime().newRuntimeError("string modified");
}
private final void frozenCheck() {
if (isFrozen()) throw getRuntime().newRuntimeError("string frozen");
}
/** rb_str_modify
*
*/
public final void modify() {
modifyCheck();
if ((flags & SHARED_STR_F) != 0) {
if ((flags & SHARED_BYTELIST_STR_F) != 0) {
value = value.dup();
} else if ((flags & SHARED_BUFFER_STR_F) != 0) {
value.unshare();
}
flags &= ~SHARED_STR_F;
}
value.invalidate();
}
public final void modify(int length) {
modifyCheck();
if ((flags & SHARED_STR_F) != 0) {
if ((flags & SHARED_BYTELIST_STR_F) != 0) {
value = value.dup(length);
} else if ((flags & SHARED_BUFFER_STR_F) != 0) {
value.unshare(length);
}
flags &= ~SHARED_STR_F;
} else {
value = value.dup(length);
}
value.invalidate();
}
private final void view(ByteList bytes) {
modifyCheck();
value = bytes;
flags &= ~SHARED_STR_F;
}
private final void view(byte[]bytes) {
modifyCheck();
value.replace(bytes);
flags &= ~SHARED_STR_F;
value.invalidate();
}
private final void view(int index, int len) {
modifyCheck();
if ((flags & SHARED_STR_F) != 0) {
if ((flags & SHARED_BYTELIST_STR_F) != 0) {
// if len == 0 then shared empty
value = value.makeShared(index, len);
flags &= ~SHARED_BYTELIST_STR_F;
flags |= SHARED_BUFFER_STR_F;
} else if ((flags & SHARED_BUFFER_STR_F) != 0) {
value.view(index, len);
}
} else {
value.view(index, len);
// FIXME this below is temporary, but its much safer for COW (it prevents not shared Strings with begin != 0)
// this allows now e.g.: ByteList#set not to be begin aware
flags |= SHARED_BUFFER_STR_F;
}
value.invalidate();
}
public static String bytesToString(byte[] bytes, int beg, int len) {
return new String(ByteList.plain(bytes, beg, len));
}
public static String byteListToString(ByteList bytes) {
return bytesToString(bytes.unsafeBytes(), bytes.begin(), bytes.length());
}
public static String bytesToString(byte[] bytes) {
return bytesToString(bytes, 0, bytes.length);
}
public static byte[] stringToBytes(String string) {
return ByteList.plain(string);
}
public static boolean isDigit(int c) {
return c >= '0' && c <= '9';
}
public static boolean isUpper(int c) {
return c >= 'A' && c <= 'Z';
}
public static boolean isLower(int c) {
return c >= 'a' && c <= 'z';
}
public static boolean isLetter(int c) {
return isUpper(c) || isLower(c);
}
public static boolean isAlnum(int c) {
return isUpper(c) || isLower(c) || isDigit(c);
}
public static boolean isPrint(int c) {
return c >= 0x20 && c <= 0x7E;
}
public RubyString asString() {
return this;
}
public IRubyObject checkStringType() {
return this;
}
@JRubyMethod(name = {"to_s", "to_str"})
public IRubyObject to_s() {
if (getMetaClass().getRealClass() != getRuntime().getString()) {
return strDup(getRuntime().getString());
}
return this;
}
/* rb_str_cmp_m */
@JRubyMethod(name = "<=>", required = 1)
public IRubyObject op_cmp(IRubyObject other) {
if (other instanceof RubyString) {
return getRuntime().newFixnum(op_cmp((RubyString)other));
}
return getRuntime().getNil();
}
/**
*
*/
@JRubyMethod(name = "==", required = 1)
public IRubyObject op_equal(IRubyObject other) {
if (this == other) return getRuntime().getTrue();
if (!(other instanceof RubyString)) {
if (!other.respondsTo("to_str")) return getRuntime().getFalse();
Ruby runtime = getRuntime();
return other.callMethod(runtime.getCurrentContext(), MethodIndex.EQUALEQUAL, "==", this).isTrue() ? runtime.getTrue() : runtime.getFalse();
}
return value.equal(((RubyString)other).value) ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = "+", required = 1)
public IRubyObject op_plus(IRubyObject other) {
RubyString str = RubyString.stringValue(other);
ByteList newValue = new ByteList(value.length() + str.value.length());
newValue.append(value);
newValue.append(str.value);
return newString(getRuntime(), newValue).infectBy(other).infectBy(this);
}
@JRubyMethod(name = "*", required = 1)
public IRubyObject op_mul(IRubyObject other) {
RubyInteger otherInteger = (RubyInteger) other.convertToInteger();
long len = otherInteger.getLongValue();
if (len < 0) throw getRuntime().newArgumentError("negative argument");
// we limit to int because ByteBuffer can only allocate int sizes
if (len > 0 && Integer.MAX_VALUE / len < value.length()) {
throw getRuntime().newArgumentError("argument too big");
}
ByteList newBytes = new ByteList(value.length() * (int)len);
for (int i = 0; i < len; i++) {
newBytes.append(value);
}
RubyString newString = newString(getRuntime(), newBytes);
newString.setTaint(isTaint());
return newString;
}
@JRubyMethod(name = "%", required = 1)
public IRubyObject op_format(IRubyObject arg) {
// FIXME: Should we make this work with platform's locale, or continue hardcoding US?
return getRuntime().newString((ByteList)Sprintf.sprintf(Locale.US, value, arg));
}
@JRubyMethod(name = "hash")
public RubyFixnum hash() {
return getRuntime().newFixnum(value.hashCode());
}
public int hashCode() {
return value.hashCode();
}
public boolean equals(Object other) {
if (this == other) return true;
if (other instanceof RubyString) {
RubyString string = (RubyString) other;
if (string.value.equal(value)) return true;
}
return false;
}
/** rb_obj_as_string
*
*/
public static RubyString objAsString(IRubyObject obj) {
if (obj instanceof RubyString) return (RubyString) obj;
IRubyObject str = obj.callMethod(obj.getRuntime().getCurrentContext(), MethodIndex.TO_S, "to_s");
if (!(str instanceof RubyString)) return (RubyString) obj.anyToString();
if (obj.isTaint()) str.setTaint(true);
return (RubyString) str;
}
/** rb_str_cmp
*
*/
public int op_cmp(RubyString other) {
return value.cmp(other.value);
}
/** rb_to_id
*
*/
public String asInternedString() {
// TODO: callers that don't need interned string should be modified
// to call toString, there are just a handful of places this happens.
// this must be interned here - call #toString for non-interned value
return toString().intern();
}
/** Create a new String which uses the same Ruby runtime and the same
* class like this String.
*
* This method should be used to satisfy RCR #38.
*
*/
public RubyString newString(CharSequence s) {
return new RubyString(getRuntime(), getType(), s);
}
/** Create a new String which uses the same Ruby runtime and the same
* class like this String.
*
* This method should be used to satisfy RCR #38.
*
*/
public RubyString newString(ByteList s) {
return new RubyString(getRuntime(), getMetaClass(), s);
}
// Methods of the String class (rb_str_*):
/** rb_str_new2
*
*/
public static RubyString newString(Ruby runtime, CharSequence str) {
return new RubyString(runtime, runtime.getString(), str);
}
public static RubyString newEmptyString(Ruby runtime) {
return newEmptyString(runtime, runtime.getString());
}
public static RubyString newEmptyString(Ruby runtime, RubyClass metaClass) {
RubyString empty = new RubyString(runtime, metaClass, ByteList.EMPTY_BYTELIST);
empty.flags |= SHARED_BYTELIST_STR_F;
return empty;
}
public static RubyString newUnicodeString(Ruby runtime, String str) {
try {
return new RubyString(runtime, runtime.getString(), new ByteList(str.getBytes("UTF8"), false));
} catch (UnsupportedEncodingException uee) {
return new RubyString(runtime, runtime.getString(), str);
}
}
public static RubyString newString(Ruby runtime, RubyClass clazz, CharSequence str) {
return new RubyString(runtime, clazz, str);
}
public static RubyString newString(Ruby runtime, byte[] bytes) {
return new RubyString(runtime, runtime.getString(), bytes);
}
public static RubyString newString(Ruby runtime, ByteList bytes) {
return new RubyString(runtime, runtime.getString(), bytes);
}
public static RubyString newStringLight(Ruby runtime, ByteList bytes) {
return new RubyString(runtime, runtime.getString(), bytes, false);
}
public static RubyString newStringShared(Ruby runtime, RubyString orig) {
orig.flags |= SHARED_BYTELIST_STR_F;
RubyString str = new RubyString(runtime, runtime.getString(), orig.value);
str.flags |= SHARED_BYTELIST_STR_F;
return str;
}
public static RubyString newStringShared(Ruby runtime, ByteList bytes) {
return newStringShared(runtime, runtime.getString(), bytes);
}
public static RubyString newStringShared(Ruby runtime, RubyClass clazz, ByteList bytes) {
RubyString str = new RubyString(runtime, clazz, bytes);
str.flags |= SHARED_BYTELIST_STR_F;
return str;
}
public static RubyString newString(Ruby runtime, byte[] bytes, int start, int length) {
byte[] bytes2 = new byte[length];
System.arraycopy(bytes, start, bytes2, 0, length);
return new RubyString(runtime, runtime.getString(), new ByteList(bytes2, false));
}
public IRubyObject doClone(){
return newString(getRuntime(), value.dup());
}
// FIXME: cat methods should be more aware of sharing to prevent unnecessary reallocations in certain situations
public RubyString cat(byte[] str) {
modify();
value.append(str);
return this;
}
public RubyString cat(byte[] str, int beg, int len) {
modify();
value.append(str, beg, len);
return this;
}
public RubyString cat(ByteList str) {
modify();
value.append(str);
return this;
}
public RubyString cat(byte ch) {
modify();
value.append(ch);
return this;
}
/** rb_str_replace_m
*
*/
@JRubyMethod(name = {"replace", "initialize_copy"}, required = 1)
public RubyString replace(IRubyObject other) {
modifyCheck();
if (this == other) return this;
RubyString otherStr = stringValue(other);
flags |= SHARED_BYTELIST_STR_F;
otherStr.flags |= SHARED_BYTELIST_STR_F;
value = otherStr.value;
infectBy(other);
return this;
}
@JRubyMethod(name = "reverse")
public RubyString reverse() {
if (value.length() <= 1) return strDup();
ByteList buf = new ByteList(value.length()+2);
buf.realSize = value.length();
int src = value.length() - 1;
int dst = 0;
while (src >= 0) buf.set(dst++, value.get(src--));
RubyString rev = new RubyString(getRuntime(), getMetaClass(), buf);
rev.infectBy(this);
return rev;
}
@JRubyMethod(name = "reverse!")
public RubyString reverse_bang() {
if (value.length() > 1) {
modify();
for (int i = 0; i < (value.length() / 2); i++) {
byte b = (byte) value.get(i);
value.set(i, value.get(value.length() - i - 1));
value.set(value.length() - i - 1, b);
}
}
return this;
}
/** rb_str_s_new
*
*/
public static RubyString newInstance(IRubyObject recv, IRubyObject[] args, Block block) {
RubyString newString = newString(recv.getRuntime(), "");
newString.setMetaClass((RubyClass) recv);
newString.callInit(args, block);
return newString;
}
@JRubyMethod(name = "initialize", optional = 1, frame = true)
public IRubyObject initialize(IRubyObject[] args, Block unusedBlock) {
if (Arity.checkArgumentCount(getRuntime(), args, 0, 1) == 1) replace(args[0]);
return this;
}
@JRubyMethod(name = "casecmp", required = 1)
public IRubyObject casecmp(IRubyObject other) {
int compare = value.caseInsensitiveCmp(stringValue(other).value);
return RubyFixnum.newFixnum(getRuntime(), compare);
}
/** rb_str_match
*
*/
@JRubyMethod(name = "=~", required = 1)
public IRubyObject op_match(IRubyObject other) {
if (other instanceof RubyRegexp) return ((RubyRegexp) other).op_match(this);
if (other instanceof RubyString) {
throw getRuntime().newTypeError("type mismatch: String given");
}
return other.callMethod(getRuntime().getCurrentContext(), "=~", this);
}
/** rb_str_match2
*
*/
@JRubyMethod(name = "~")
public IRubyObject op_match2() {
return RubyRegexp.newRegexp(this, 0, null).op_match2();
}
/**
* String#match(pattern)
*
* rb_str_match_m
*
* @param pattern Regexp or String
*/
@JRubyMethod(name = "match", required = 1)
public IRubyObject match(IRubyObject pattern) {
return get_pat(pattern,false).callMethod(getRuntime().getCurrentContext(),"match",this);
}
private IRubyObject get_pat(IRubyObject pat, boolean quote) {
IRubyObject val;
if(pat instanceof RubyRegexp) {
return pat;
} else if(pat instanceof RubyString) {
} else {
val = pat.checkStringType();
if(val.isNil()) {
if(!(pat instanceof RubyRegexp)) {
throw getRuntime().newTypeError("wrong argument type " + pat.getMetaClass().getName() + " (expected Regexp)");
}
}
pat = val;
}
if(quote) {
pat = RubyRegexp.quote(pat,(KCode)null);
}
return RubyRegexp.newRegexp(pat,0,null);
}
/** rb_str_capitalize
*
*/
@JRubyMethod(name = "capitalize")
public IRubyObject capitalize() {
RubyString str = strDup();
str.capitalize_bang();
return str;
}
/** rb_str_capitalize_bang
*
*/
@JRubyMethod(name = "capitalize!")
public IRubyObject capitalize_bang() {
if (value.realSize == 0) return getRuntime().getNil();
modify();
int s = value.begin;
int send = s + value.realSize;
byte[]buf = value.bytes;
boolean modify = false;
char c = (char)(buf[s] & 0xff);
if (Character.isLetter(c) && Character.isLowerCase(c)) {
buf[s] = (byte)Character.toUpperCase(c);
modify = true;
}
while (++s < send) {
c = (char)(buf[s] & 0xff);
if (Character.isLetter(c) && Character.isUpperCase(c)) {
buf[s] = (byte)Character.toLowerCase(c);
modify = true;
}
}
if (modify) return this;
return getRuntime().getNil();
}
@JRubyMethod(name = ">=", required = 1)
public IRubyObject op_ge(IRubyObject other) {
if (other instanceof RubyString) {
return getRuntime().newBoolean(op_cmp((RubyString) other) >= 0);
}
return RubyComparable.op_ge(this, other);
}
@JRubyMethod(name = ">", required = 1)
public IRubyObject op_gt(IRubyObject other) {
if (other instanceof RubyString) {
return getRuntime().newBoolean(op_cmp((RubyString) other) > 0);
}
return RubyComparable.op_gt(this, other);
}
@JRubyMethod(name = "<=", required = 1)
public IRubyObject op_le(IRubyObject other) {
if (other instanceof RubyString) {
return getRuntime().newBoolean(op_cmp((RubyString) other) <= 0);
}
return RubyComparable.op_le(this, other);
}
@JRubyMethod(name = "<", required = 1)
public IRubyObject op_lt(IRubyObject other) {
if (other instanceof RubyString) {
return getRuntime().newBoolean(op_cmp((RubyString) other) < 0);
}
return RubyComparable.op_lt(this, other);
}
@JRubyMethod(name = "eql?", required = 1)
public IRubyObject eql_p(IRubyObject other) {
if (!(other instanceof RubyString)) return getRuntime().getFalse();
RubyString otherString = (RubyString)other;
return value.equal(otherString.value) ? getRuntime().getTrue() : getRuntime().getFalse();
}
/** rb_str_upcase
*
*/
@JRubyMethod(name = "upcase")
public RubyString upcase() {
RubyString str = strDup();
str.upcase_bang();
return str;
}
/** rb_str_upcase_bang
*
*/
@JRubyMethod(name = "upcase!")
public IRubyObject upcase_bang() {
if (value.realSize == 0) return getRuntime().getNil();
modify();
int s = value.begin;
int send = s + value.realSize;
byte []buf = value.bytes;
boolean modify = false;
while (s < send) {
char c = (char)(buf[s] & 0xff);
if (c >= 'a' && c<= 'z') {
buf[s] = (byte)(c-32);
modify = true;
}
s++;
}
if (modify) return this;
return getRuntime().getNil();
}
/** rb_str_downcase
*
*/
@JRubyMethod(name = "downcase")
public RubyString downcase() {
RubyString str = strDup();
str.downcase_bang();
return str;
}
/** rb_str_downcase_bang
*
*/
@JRubyMethod(name = "downcase!")
public IRubyObject downcase_bang() {
if (value.realSize == 0) return getRuntime().getNil();
modify();
int s = value.begin;
int send = s + value.realSize;
byte []buf = value.bytes;
boolean modify = false;
while (s < send) {
char c = (char)(buf[s] & 0xff);
if (c >= 'A' && c <= 'Z') {
buf[s] = (byte)(c+32);
modify = true;
}
s++;
}
if (modify) return this;
return getRuntime().getNil();
}
/** rb_str_swapcase
*
*/
@JRubyMethod(name = "swapcase")
public RubyString swapcase() {
RubyString str = strDup();
str.swapcase_bang();
return str;
}
/** rb_str_swapcase_bang
*
*/
@JRubyMethod(name = "swapcase!")
public IRubyObject swapcase_bang() {
if (value.realSize == 0) return getRuntime().getNil();
modify();
int s = value.begin;
int send = s + value.realSize;
byte[]buf = value.bytes;
boolean modify = false;
while (s < send) {
char c = (char)(buf[s] & 0xff);
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
buf[s] = (byte)Character.toLowerCase(c);
modify = true;
} else {
buf[s] = (byte)Character.toUpperCase(c);
modify = true;
}
}
s++;
}
if (modify) return this;
return getRuntime().getNil();
}
/** rb_str_dump
*
*/
@JRubyMethod(name = "dump")
public IRubyObject dump() {
return inspect();
}
@JRubyMethod(name = "insert", required = 2)
public IRubyObject insert(IRubyObject indexArg, IRubyObject stringArg) {
int index = (int) indexArg.convertToInteger().getLongValue();
if (index < 0) index += value.length() + 1;
if (index < 0 || index > value.length()) {
throw getRuntime().newIndexError("index " + index + " out of range");
}
modify();
ByteList insert = ((RubyString)stringArg.convertToString()).value;
value.unsafeReplace(index, 0, insert);
return this;
}
/** rb_str_inspect
*
*/
@JRubyMethod(name = "inspect")
public IRubyObject inspect() {
final int length = value.length();
Ruby runtime = getRuntime();
ByteList sb = new ByteList(length + 2 + length / 100);
sb.append('\"');
// FIXME: This may not be unicode-safe
for (int i = 0; i < length; i++) {
int c = value.get(i) & 0xFF;
if (isAlnum(c)) {
sb.append((char)c);
} else if (runtime.getKCode() == KCode.UTF8 && c == 0xEF) {
// don't escape encoded UTF8 characters, leave them as bytes
// append byte order mark plus two character bytes
sb.append((char)c);
sb.append((char)(value.get(++i) & 0xFF));
sb.append((char)(value.get(++i) & 0xFF));
} else if (c == '\"' || c == '\\') {
sb.append('\\').append((char)c);
} else if (c == '#' && isEVStr(i, length)) {
sb.append('\\').append((char)c);
} else if (isPrint(c)) {
sb.append((char)c);
} else if (c == '\n') {
sb.append('\\').append('n');
} else if (c == '\r') {
sb.append('\\').append('r');
} else if (c == '\t') {
sb.append('\\').append('t');
} else if (c == '\f') {
sb.append('\\').append('f');
} else if (c == '\u000B') {
sb.append('\\').append('v');
} else if (c == '\u0007') {
sb.append('\\').append('a');
} else if (c == '\u001B') {
sb.append('\\').append('e');
} else {
sb.append(ByteList.plain(Sprintf.sprintf(runtime,"\\%.3o",c)));
}
}
sb.append('\"');
return getRuntime().newString(sb);
}
private boolean isEVStr(int i, int length) {
if (i+1 >= length) return false;
int c = value.get(i+1) & 0xFF;
return c == '$' || c == '@' || c == '{';
}
/** rb_str_length
*
*/
@JRubyMethod(name = {"length", "size"})
public RubyFixnum length() {
return getRuntime().newFixnum(value.length());
}
/** rb_str_empty
*
*/
@JRubyMethod(name = "empty?")
public RubyBoolean empty_p() {
return isEmpty() ? getRuntime().getTrue() : getRuntime().getFalse();
}
private boolean isEmpty() {
return value.length() == 0;
}
/** rb_str_append
*
*/
public RubyString append(IRubyObject other) {
infectBy(other);
return cat(stringValue(other).value);
}
/** rb_str_concat
*
*/
@JRubyMethod(name = {"concat", "<<"}, required = 1)
public RubyString concat(IRubyObject other) {
if (other instanceof RubyFixnum) {
long value = ((RubyFixnum) other).getLongValue();
if (value >= 0 && value < 256) return cat((byte) value);
}
return append(other);
}
/** rb_str_crypt
*
*/
@JRubyMethod(name = "crypt", required = 1)
public RubyString crypt(IRubyObject other) {
ByteList salt = stringValue(other).getByteList();
if (salt.realSize < 2) {
throw getRuntime().newArgumentError("salt too short(need >=2 bytes)");
}
salt = salt.makeShared(0, 2);
return RubyString.newStringShared(getRuntime(),getMetaClass(), JavaCrypt.crypt(salt, this.getByteList()));
}
public static class JavaCrypt {
private static java.util.Random r_gen = new java.util.Random();
private static final int ITERATIONS = 16;
private static final int con_salt[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
0x0A, 0x0B, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12,
0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A,
0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22,
0x23, 0x24, 0x25, 0x20, 0x21, 0x22, 0x23, 0x24,
0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C,
0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34,
0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C,
0x3D, 0x3E, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00,
};
private static final boolean shifts2[] = {
false, false, true, true, true, true, true, true,
false, true, true, true, true, true, true, false };
private static final int skb[][] = {
{
/* for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
0x00000000, 0x00000010, 0x20000000, 0x20000010,
0x00010000, 0x00010010, 0x20010000, 0x20010010,
0x00000800, 0x00000810, 0x20000800, 0x20000810,
0x00010800, 0x00010810, 0x20010800, 0x20010810,
0x00000020, 0x00000030, 0x20000020, 0x20000030,
0x00010020, 0x00010030, 0x20010020, 0x20010030,
0x00000820, 0x00000830, 0x20000820, 0x20000830,
0x00010820, 0x00010830, 0x20010820, 0x20010830,
0x00080000, 0x00080010, 0x20080000, 0x20080010,
0x00090000, 0x00090010, 0x20090000, 0x20090010,
0x00080800, 0x00080810, 0x20080800, 0x20080810,
0x00090800, 0x00090810, 0x20090800, 0x20090810,
0x00080020, 0x00080030, 0x20080020, 0x20080030,
0x00090020, 0x00090030, 0x20090020, 0x20090030,
0x00080820, 0x00080830, 0x20080820, 0x20080830,
0x00090820, 0x00090830, 0x20090820, 0x20090830,
},{
/* for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 */
0x00000000, 0x02000000, 0x00002000, 0x02002000,
0x00200000, 0x02200000, 0x00202000, 0x02202000,
0x00000004, 0x02000004, 0x00002004, 0x02002004,
0x00200004, 0x02200004, 0x00202004, 0x02202004,
0x00000400, 0x02000400, 0x00002400, 0x02002400,
0x00200400, 0x02200400, 0x00202400, 0x02202400,
0x00000404, 0x02000404, 0x00002404, 0x02002404,
0x00200404, 0x02200404, 0x00202404, 0x02202404,
0x10000000, 0x12000000, 0x10002000, 0x12002000,
0x10200000, 0x12200000, 0x10202000, 0x12202000,
0x10000004, 0x12000004, 0x10002004, 0x12002004,
0x10200004, 0x12200004, 0x10202004, 0x12202004,
0x10000400, 0x12000400, 0x10002400, 0x12002400,
0x10200400, 0x12200400, 0x10202400, 0x12202400,
0x10000404, 0x12000404, 0x10002404, 0x12002404,
0x10200404, 0x12200404, 0x10202404, 0x12202404,
},{
/* for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 */
0x00000000, 0x00000001, 0x00040000, 0x00040001,
0x01000000, 0x01000001, 0x01040000, 0x01040001,
0x00000002, 0x00000003, 0x00040002, 0x00040003,
0x01000002, 0x01000003, 0x01040002, 0x01040003,
0x00000200, 0x00000201, 0x00040200, 0x00040201,
0x01000200, 0x01000201, 0x01040200, 0x01040201,
0x00000202, 0x00000203, 0x00040202, 0x00040203,
0x01000202, 0x01000203, 0x01040202, 0x01040203,
0x08000000, 0x08000001, 0x08040000, 0x08040001,
0x09000000, 0x09000001, 0x09040000, 0x09040001,
0x08000002, 0x08000003, 0x08040002, 0x08040003,
0x09000002, 0x09000003, 0x09040002, 0x09040003,
0x08000200, 0x08000201, 0x08040200, 0x08040201,
0x09000200, 0x09000201, 0x09040200, 0x09040201,
0x08000202, 0x08000203, 0x08040202, 0x08040203,
0x09000202, 0x09000203, 0x09040202, 0x09040203,
},{
/* for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 */
0x00000000, 0x00100000, 0x00000100, 0x00100100,
0x00000008, 0x00100008, 0x00000108, 0x00100108,
0x00001000, 0x00101000, 0x00001100, 0x00101100,
0x00001008, 0x00101008, 0x00001108, 0x00101108,
0x04000000, 0x04100000, 0x04000100, 0x04100100,
0x04000008, 0x04100008, 0x04000108, 0x04100108,
0x04001000, 0x04101000, 0x04001100, 0x04101100,
0x04001008, 0x04101008, 0x04001108, 0x04101108,
0x00020000, 0x00120000, 0x00020100, 0x00120100,
0x00020008, 0x00120008, 0x00020108, 0x00120108,
0x00021000, 0x00121000, 0x00021100, 0x00121100,
0x00021008, 0x00121008, 0x00021108, 0x00121108,
0x04020000, 0x04120000, 0x04020100, 0x04120100,
0x04020008, 0x04120008, 0x04020108, 0x04120108,
0x04021000, 0x04121000, 0x04021100, 0x04121100,
0x04021008, 0x04121008, 0x04021108, 0x04121108,
},{
/* for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
0x00000000, 0x10000000, 0x00010000, 0x10010000,
0x00000004, 0x10000004, 0x00010004, 0x10010004,
0x20000000, 0x30000000, 0x20010000, 0x30010000,
0x20000004, 0x30000004, 0x20010004, 0x30010004,
0x00100000, 0x10100000, 0x00110000, 0x10110000,
0x00100004, 0x10100004, 0x00110004, 0x10110004,
0x20100000, 0x30100000, 0x20110000, 0x30110000,
0x20100004, 0x30100004, 0x20110004, 0x30110004,
0x00001000, 0x10001000, 0x00011000, 0x10011000,
0x00001004, 0x10001004, 0x00011004, 0x10011004,
0x20001000, 0x30001000, 0x20011000, 0x30011000,
0x20001004, 0x30001004, 0x20011004, 0x30011004,
0x00101000, 0x10101000, 0x00111000, 0x10111000,
0x00101004, 0x10101004, 0x00111004, 0x10111004,
0x20101000, 0x30101000, 0x20111000, 0x30111000,
0x20101004, 0x30101004, 0x20111004, 0x30111004,
},{
/* for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 */
0x00000000, 0x08000000, 0x00000008, 0x08000008,
0x00000400, 0x08000400, 0x00000408, 0x08000408,
0x00020000, 0x08020000, 0x00020008, 0x08020008,
0x00020400, 0x08020400, 0x00020408, 0x08020408,
0x00000001, 0x08000001, 0x00000009, 0x08000009,
0x00000401, 0x08000401, 0x00000409, 0x08000409,
0x00020001, 0x08020001, 0x00020009, 0x08020009,
0x00020401, 0x08020401, 0x00020409, 0x08020409,
0x02000000, 0x0A000000, 0x02000008, 0x0A000008,
0x02000400, 0x0A000400, 0x02000408, 0x0A000408,
0x02020000, 0x0A020000, 0x02020008, 0x0A020008,
0x02020400, 0x0A020400, 0x02020408, 0x0A020408,
0x02000001, 0x0A000001, 0x02000009, 0x0A000009,
0x02000401, 0x0A000401, 0x02000409, 0x0A000409,
0x02020001, 0x0A020001, 0x02020009, 0x0A020009,
0x02020401, 0x0A020401, 0x02020409, 0x0A020409,
},{
/* for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 */
0x00000000, 0x00000100, 0x00080000, 0x00080100,
0x01000000, 0x01000100, 0x01080000, 0x01080100,
0x00000010, 0x00000110, 0x00080010, 0x00080110,
0x01000010, 0x01000110, 0x01080010, 0x01080110,
0x00200000, 0x00200100, 0x00280000, 0x00280100,
0x01200000, 0x01200100, 0x01280000, 0x01280100,
0x00200010, 0x00200110, 0x00280010, 0x00280110,
0x01200010, 0x01200110, 0x01280010, 0x01280110,
0x00000200, 0x00000300, 0x00080200, 0x00080300,
0x01000200, 0x01000300, 0x01080200, 0x01080300,
0x00000210, 0x00000310, 0x00080210, 0x00080310,
0x01000210, 0x01000310, 0x01080210, 0x01080310,
0x00200200, 0x00200300, 0x00280200, 0x00280300,
0x01200200, 0x01200300, 0x01280200, 0x01280300,
0x00200210, 0x00200310, 0x00280210, 0x00280310,
0x01200210, 0x01200310, 0x01280210, 0x01280310,
},{
/* for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 */
0x00000000, 0x04000000, 0x00040000, 0x04040000,
0x00000002, 0x04000002, 0x00040002, 0x04040002,
0x00002000, 0x04002000, 0x00042000, 0x04042000,
0x00002002, 0x04002002, 0x00042002, 0x04042002,
0x00000020, 0x04000020, 0x00040020, 0x04040020,
0x00000022, 0x04000022, 0x00040022, 0x04040022,
0x00002020, 0x04002020, 0x00042020, 0x04042020,
0x00002022, 0x04002022, 0x00042022, 0x04042022,
0x00000800, 0x04000800, 0x00040800, 0x04040800,
0x00000802, 0x04000802, 0x00040802, 0x04040802,
0x00002800, 0x04002800, 0x00042800, 0x04042800,
0x00002802, 0x04002802, 0x00042802, 0x04042802,
0x00000820, 0x04000820, 0x00040820, 0x04040820,
0x00000822, 0x04000822, 0x00040822, 0x04040822,
0x00002820, 0x04002820, 0x00042820, 0x04042820,
0x00002822, 0x04002822, 0x00042822, 0x04042822,
}
};
private static final int SPtrans[][] = {
{
/* nibble 0 */
0x00820200, 0x00020000, 0x80800000, 0x80820200,
0x00800000, 0x80020200, 0x80020000, 0x80800000,
0x80020200, 0x00820200, 0x00820000, 0x80000200,
0x80800200, 0x00800000, 0x00000000, 0x80020000,
0x00020000, 0x80000000, 0x00800200, 0x00020200,
0x80820200, 0x00820000, 0x80000200, 0x00800200,
0x80000000, 0x00000200, 0x00020200, 0x80820000,
0x00000200, 0x80800200, 0x80820000, 0x00000000,
0x00000000, 0x80820200, 0x00800200, 0x80020000,
0x00820200, 0x00020000, 0x80000200, 0x00800200,
0x80820000, 0x00000200, 0x00020200, 0x80800000,
0x80020200, 0x80000000, 0x80800000, 0x00820000,
0x80820200, 0x00020200, 0x00820000, 0x80800200,
0x00800000, 0x80000200, 0x80020000, 0x00000000,
0x00020000, 0x00800000, 0x80800200, 0x00820200,
0x80000000, 0x80820000, 0x00000200, 0x80020200,
},{
/* nibble 1 */
0x10042004, 0x00000000, 0x00042000, 0x10040000,
0x10000004, 0x00002004, 0x10002000, 0x00042000,
0x00002000, 0x10040004, 0x00000004, 0x10002000,
0x00040004, 0x10042000, 0x10040000, 0x00000004,
0x00040000, 0x10002004, 0x10040004, 0x00002000,
0x00042004, 0x10000000, 0x00000000, 0x00040004,
0x10002004, 0x00042004, 0x10042000, 0x10000004,
0x10000000, 0x00040000, 0x00002004, 0x10042004,
0x00040004, 0x10042000, 0x10002000, 0x00042004,
0x10042004, 0x00040004, 0x10000004, 0x00000000,
0x10000000, 0x00002004, 0x00040000, 0x10040004,
0x00002000, 0x10000000, 0x00042004, 0x10002004,
0x10042000, 0x00002000, 0x00000000, 0x10000004,
0x00000004, 0x10042004, 0x00042000, 0x10040000,
0x10040004, 0x00040000, 0x00002004, 0x10002000,
0x10002004, 0x00000004, 0x10040000, 0x00042000,
},{
/* nibble 2 */
0x41000000, 0x01010040, 0x00000040, 0x41000040,
0x40010000, 0x01000000, 0x41000040, 0x00010040,
0x01000040, 0x00010000, 0x01010000, 0x40000000,
0x41010040, 0x40000040, 0x40000000, 0x41010000,
0x00000000, 0x40010000, 0x01010040, 0x00000040,
0x40000040, 0x41010040, 0x00010000, 0x41000000,
0x41010000, 0x01000040, 0x40010040, 0x01010000,
0x00010040, 0x00000000, 0x01000000, 0x40010040,
0x01010040, 0x00000040, 0x40000000, 0x00010000,
0x40000040, 0x40010000, 0x01010000, 0x41000040,
0x00000000, 0x01010040, 0x00010040, 0x41010000,
0x40010000, 0x01000000, 0x41010040, 0x40000000,
0x40010040, 0x41000000, 0x01000000, 0x41010040,
0x00010000, 0x01000040, 0x41000040, 0x00010040,
0x01000040, 0x00000000, 0x41010000, 0x40000040,
0x41000000, 0x40010040, 0x00000040, 0x01010000,
},{
/* nibble 3 */
0x00100402, 0x04000400, 0x00000002, 0x04100402,
0x00000000, 0x04100000, 0x04000402, 0x00100002,
0x04100400, 0x04000002, 0x04000000, 0x00000402,
0x04000002, 0x00100402, 0x00100000, 0x04000000,
0x04100002, 0x00100400, 0x00000400, 0x00000002,
0x00100400, 0x04000402, 0x04100000, 0x00000400,
0x00000402, 0x00000000, 0x00100002, 0x04100400,
0x04000400, 0x04100002, 0x04100402, 0x00100000,
0x04100002, 0x00000402, 0x00100000, 0x04000002,
0x00100400, 0x04000400, 0x00000002, 0x04100000,
0x04000402, 0x00000000, 0x00000400, 0x00100002,
0x00000000, 0x04100002, 0x04100400, 0x00000400,
0x04000000, 0x04100402, 0x00100402, 0x00100000,
0x04100402, 0x00000002, 0x04000400, 0x00100402,
0x00100002, 0x00100400, 0x04100000, 0x04000402,
0x00000402, 0x04000000, 0x04000002, 0x04100400,
},{
/* nibble 4 */
0x02000000, 0x00004000, 0x00000100, 0x02004108,
0x02004008, 0x02000100, 0x00004108, 0x02004000,
0x00004000, 0x00000008, 0x02000008, 0x00004100,
0x02000108, 0x02004008, 0x02004100, 0x00000000,
0x00004100, 0x02000000, 0x00004008, 0x00000108,
0x02000100, 0x00004108, 0x00000000, 0x02000008,
0x00000008, 0x02000108, 0x02004108, 0x00004008,
0x02004000, 0x00000100, 0x00000108, 0x02004100,
0x02004100, 0x02000108, 0x00004008, 0x02004000,
0x00004000, 0x00000008, 0x02000008, 0x02000100,
0x02000000, 0x00004100, 0x02004108, 0x00000000,
0x00004108, 0x02000000, 0x00000100, 0x00004008,
0x02000108, 0x00000100, 0x00000000, 0x02004108,
0x02004008, 0x02004100, 0x00000108, 0x00004000,
0x00004100, 0x02004008, 0x02000100, 0x00000108,
0x00000008, 0x00004108, 0x02004000, 0x02000008,
},{
/* nibble 5 */
0x20000010, 0x00080010, 0x00000000, 0x20080800,
0x00080010, 0x00000800, 0x20000810, 0x00080000,
0x00000810, 0x20080810, 0x00080800, 0x20000000,
0x20000800, 0x20000010, 0x20080000, 0x00080810,
0x00080000, 0x20000810, 0x20080010, 0x00000000,
0x00000800, 0x00000010, 0x20080800, 0x20080010,
0x20080810, 0x20080000, 0x20000000, 0x00000810,
0x00000010, 0x00080800, 0x00080810, 0x20000800,
0x00000810, 0x20000000, 0x20000800, 0x00080810,
0x20080800, 0x00080010, 0x00000000, 0x20000800,
0x20000000, 0x00000800, 0x20080010, 0x00080000,
0x00080010, 0x20080810, 0x00080800, 0x00000010,
0x20080810, 0x00080800, 0x00080000, 0x20000810,
0x20000010, 0x20080000, 0x00080810, 0x00000000,
0x00000800, 0x20000010, 0x20000810, 0x20080800,
0x20080000, 0x00000810, 0x00000010, 0x20080010,
},{
/* nibble 6 */
0x00001000, 0x00000080, 0x00400080, 0x00400001,
0x00401081, 0x00001001, 0x00001080, 0x00000000,
0x00400000, 0x00400081, 0x00000081, 0x00401000,
0x00000001, 0x00401080, 0x00401000, 0x00000081,
0x00400081, 0x00001000, 0x00001001, 0x00401081,
0x00000000, 0x00400080, 0x00400001, 0x00001080,
0x00401001, 0x00001081, 0x00401080, 0x00000001,
0x00001081, 0x00401001, 0x00000080, 0x00400000,
0x00001081, 0x00401000, 0x00401001, 0x00000081,
0x00001000, 0x00000080, 0x00400000, 0x00401001,
0x00400081, 0x00001081, 0x00001080, 0x00000000,
0x00000080, 0x00400001, 0x00000001, 0x00400080,
0x00000000, 0x00400081, 0x00400080, 0x00001080,
0x00000081, 0x00001000, 0x00401081, 0x00400000,
0x00401080, 0x00000001, 0x00001001, 0x00401081,
0x00400001, 0x00401080, 0x00401000, 0x00001001,
},{
/* nibble 7 */
0x08200020, 0x08208000, 0x00008020, 0x00000000,
0x08008000, 0x00200020, 0x08200000, 0x08208020,
0x00000020, 0x08000000, 0x00208000, 0x00008020,
0x00208020, 0x08008020, 0x08000020, 0x08200000,
0x00008000, 0x00208020, 0x00200020, 0x08008000,
0x08208020, 0x08000020, 0x00000000, 0x00208000,
0x08000000, 0x00200000, 0x08008020, 0x08200020,
0x00200000, 0x00008000, 0x08208000, 0x00000020,
0x00200000, 0x00008000, 0x08000020, 0x08208020,
0x00008020, 0x08000000, 0x00000000, 0x00208000,
0x08200020, 0x08008020, 0x08008000, 0x00200020,
0x08208000, 0x00000020, 0x00200020, 0x08008000,
0x08208020, 0x00200000, 0x08200000, 0x08000020,
0x00208000, 0x00008020, 0x08008020, 0x08200000,
0x00000020, 0x08208000, 0x00208020, 0x00000000,
0x08000000, 0x08200020, 0x00008000, 0x00208020
}
};
private static final int cov_2char[] = {
0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44,
0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C,
0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54,
0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62,
0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A,
0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72,
0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
};
private static final int byteToUnsigned(byte b) {
return b & 0xFF;
}
private static int fourBytesToInt(byte b[], int offset) {
int value;
value = byteToUnsigned(b[offset++]);
value |= (byteToUnsigned(b[offset++]) << 8);
value |= (byteToUnsigned(b[offset++]) << 16);
value |= (byteToUnsigned(b[offset++]) << 24);
return(value);
}
private static final void intToFourBytes(int iValue, byte b[], int offset) {
b[offset++] = (byte)((iValue) & 0xff);
b[offset++] = (byte)((iValue >>> 8 ) & 0xff);
b[offset++] = (byte)((iValue >>> 16) & 0xff);
b[offset++] = (byte)((iValue >>> 24) & 0xff);
}
private static final void PERM_OP(int a, int b, int n, int m, int results[]) {
int t;
t = ((a >>> n) ^ b) & m;
a ^= t << n;
b ^= t;
results[0] = a;
results[1] = b;
}
private static final int HPERM_OP(int a, int n, int m) {
int t;
t = ((a << (16 - n)) ^ a) & m;
a = a ^ t ^ (t >>> (16 - n));
return a;
}
private static int [] des_set_key(byte key[]) {
int schedule[] = new int[ITERATIONS * 2];
int c = fourBytesToInt(key, 0);
int d = fourBytesToInt(key, 4);
int results[] = new int[2];
PERM_OP(d, c, 4, 0x0f0f0f0f, results);
d = results[0]; c = results[1];
c = HPERM_OP(c, -2, 0xcccc0000);
d = HPERM_OP(d, -2, 0xcccc0000);
PERM_OP(d, c, 1, 0x55555555, results);
d = results[0]; c = results[1];
PERM_OP(c, d, 8, 0x00ff00ff, results);
c = results[0]; d = results[1];
PERM_OP(d, c, 1, 0x55555555, results);
d = results[0]; c = results[1];
d = (((d & 0x000000ff) << 16) | (d & 0x0000ff00) |
((d & 0x00ff0000) >>> 16) | ((c & 0xf0000000) >>> 4));
c &= 0x0fffffff;
int s, t;
int j = 0;
for(int i = 0; i < ITERATIONS; i ++) {
if(shifts2[i]) {
c = (c >>> 2) | (c << 26);
d = (d >>> 2) | (d << 26);
} else {
c = (c >>> 1) | (c << 27);
d = (d >>> 1) | (d << 27);
}
c &= 0x0fffffff;
d &= 0x0fffffff;
s = skb[0][ (c ) & 0x3f ]|
skb[1][((c >>> 6) & 0x03) | ((c >>> 7) & 0x3c)]|
skb[2][((c >>> 13) & 0x0f) | ((c >>> 14) & 0x30)]|
skb[3][((c >>> 20) & 0x01) | ((c >>> 21) & 0x06) |
((c >>> 22) & 0x38)];
t = skb[4][ (d ) & 0x3f ]|
skb[5][((d >>> 7) & 0x03) | ((d >>> 8) & 0x3c)]|
skb[6][ (d >>>15) & 0x3f ]|
skb[7][((d >>>21) & 0x0f) | ((d >>> 22) & 0x30)];
schedule[j++] = ((t << 16) | (s & 0x0000ffff)) & 0xffffffff;
s = ((s >>> 16) | (t & 0xffff0000));
s = (s << 4) | (s >>> 28);
schedule[j++] = s & 0xffffffff;
}
return(schedule);
}
private static final int D_ENCRYPT(int L, int R, int S, int E0, int E1, int s[]) {
int t, u, v;
v = R ^ (R >>> 16);
u = v & E0;
v = v & E1;
u = (u ^ (u << 16)) ^ R ^ s[S];
t = (v ^ (v << 16)) ^ R ^ s[S + 1];
t = (t >>> 4) | (t << 28);
L ^= SPtrans[1][(t ) & 0x3f] |
SPtrans[3][(t >>> 8) & 0x3f] |
SPtrans[5][(t >>> 16) & 0x3f] |
SPtrans[7][(t >>> 24) & 0x3f] |
SPtrans[0][(u ) & 0x3f] |
SPtrans[2][(u >>> 8) & 0x3f] |
SPtrans[4][(u >>> 16) & 0x3f] |
SPtrans[6][(u >>> 24) & 0x3f];
return(L);
}
private static final int [] body(int schedule[], int Eswap0, int Eswap1) {
int left = 0;
int right = 0;
int t = 0;
for(int j = 0; j < 25; j ++) {
for(int i = 0; i < ITERATIONS * 2; i += 4) {
left = D_ENCRYPT(left, right, i, Eswap0, Eswap1, schedule);
right = D_ENCRYPT(right, left, i + 2, Eswap0, Eswap1, schedule);
}
t = left;
left = right;
right = t;
}
t = right;
right = (left >>> 1) | (left << 31);
left = (t >>> 1) | (t << 31);
left &= 0xffffffff;
right &= 0xffffffff;
int results[] = new int[2];
PERM_OP(right, left, 1, 0x55555555, results);
right = results[0]; left = results[1];
PERM_OP(left, right, 8, 0x00ff00ff, results);
left = results[0]; right = results[1];
PERM_OP(right, left, 2, 0x33333333, results);
right = results[0]; left = results[1];
PERM_OP(left, right, 16, 0x0000ffff, results);
left = results[0]; right = results[1];
PERM_OP(right, left, 4, 0x0f0f0f0f, results);
right = results[0]; left = results[1];
int out[] = new int[2];
out[0] = left; out[1] = right;
return(out);
}
public static final ByteList crypt(ByteList salt, ByteList original) {
ByteList buffer = new ByteList(new byte[]{' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '},false);
byte charZero = salt.bytes[salt.begin];
byte charOne = salt.bytes[salt.begin+1];
buffer.set(0,charZero);
buffer.set(1,charOne);
int Eswap0 = con_salt[(int)(charZero&0xFF)];
int Eswap1 = con_salt[(int)(charOne&0xFF)] << 4;
byte key[] = new byte[8];
for(int i = 0; i < key.length; i ++) {
key[i] = (byte)0;
}
for(int i = 0; i < key.length && i < original.length(); i ++) {
int iChar = (int)(original.bytes[original.begin+i]&0xFF);
key[i] = (byte)(iChar << 1);
}
int schedule[] = des_set_key(key);
int out[] = body(schedule, Eswap0, Eswap1);
byte b[] = new byte[9];
intToFourBytes(out[0], b, 0);
intToFourBytes(out[1], b, 4);
b[8] = 0;
for(int i = 2, y = 0, u = 0x80; i < 13; i ++) {
for(int j = 0, c = 0; j < 6; j ++) {
c <<= 1;
if(((int)b[y] & u) != 0)
c |= 1;
u >>>= 1;
if(u == 0) {
y++;
u = 0x80;
}
buffer.set(i, cov_2char[c]);
}
}
return buffer;
}
}
/* RubyString aka rb_string_value */
public static RubyString stringValue(IRubyObject object) {
return (RubyString) (object instanceof RubyString ? object :
object.convertToString());
}
/** rb_str_sub
*
*/
@JRubyMethod(name = "sub", required = 1, optional = 1)
public IRubyObject sub(IRubyObject[] args, Block block) {
RubyString str = strDup();
str.sub_bang(args, block);
return str;
}
/** rb_str_sub_bang
*
*/
@JRubyMethod(name = "sub!", required = 1, optional = 1)
public IRubyObject sub_bang(IRubyObject[] args, Block block) {
IRubyObject match;
RubyString repl = null;;
RubyRegexp pat;
Region regs;
boolean iter = false;
boolean tainted = false;
int plen;
if(args.length == 1 && block.isGiven()) {
iter = true;
} else if(args.length == 2) {
repl = args[1].convertToString();
if(repl.isTaint()) {
tainted = true;
}
} else {
throw getRuntime().newArgumentError("wrong number of arguments (" + args.length + " for 2)");
}
pat = (RubyRegexp)get_pat(args[0], true);
if(pat.search(this, 0, false) >= 0) {
match = getRuntime().getCurrentContext().getCurrentFrame().getBackRef();
regs = ((RubyMatchData)match).regs;
if(iter) {
// for modifyCheck
byte [] sb = value.bytes;
int slen = value.realSize;
((RubyMatchData)match).use();
repl = objAsString(block.yield(getRuntime().getCurrentContext(),RubyRegexp.nth_match(0,match)));
modifyCheck(sb,slen);
frozenCheck();
getRuntime().getCurrentContext().getCurrentFrame().setBackRef(match);
} else {
repl = pat.regsub(repl, this, regs);
}
modify();
if(repl.isTaint()) {
tainted = true;
}
this.value.unsafeReplace(this.value.begin + regs.beg[0], regs.end[0]-regs.beg[0], repl.value.bytes, repl.value.begin, repl.value.realSize);
if(tainted) {
setTaint(true);
}
return this;
}
return getRuntime().getNil();
}
/** rb_str_gsub
*
*/
@JRubyMethod(name = "gsub", required = 1, optional = 1, frame = true)
public IRubyObject gsub(IRubyObject[] args, Block block) {
return gsub(args, block, false);
}
/** rb_str_gsub_bang
*
*/
@JRubyMethod(name = "gsub!", required = 1, optional = 1, frame = true)
public IRubyObject gsub_bang(IRubyObject[] args, Block block) {
return gsub(args, block, true);
}
private final IRubyObject gsub(IRubyObject[] args, Block block, boolean bang) {
boolean iter = false;
IRubyObject repl;
Ruby runtime = getRuntime();
boolean tainted = false;
if (args.length == 1 && block.isGiven()) {
iter = true;
repl = runtime.getNil();
} else if (args.length == 2) {
repl = args[1].convertToString();
tainted = repl.isTaint();
} else {
throw runtime.newArgumentError("wrong number of arguments (" + args.length + "for 2)");
}
RubyRegexp pattern = getPat(args[0], true);
Region regs = null;
int begs = pattern.search(this, 0, false);
if(begs < 0) {
if(bang) {
return getRuntime().getNil(); /* no match, no substitution */
}
return strDup();
}
int blen = value.realSize + 30;
ByteList dest = new ByteList(blen);
dest.realSize = blen;
int buf = 0, bp = 0;
int cp = value.begin;
// for modifyCheck
byte [] sb = value.bytes;
int slen = value.realSize;
RubyString val;
ThreadContext context = runtime.getCurrentContext();
int offset = 0;
// tmp lock
RubyMatchData md = null;
while (begs>=0) {
md = (RubyMatchData)getRuntime().getCurrentContext().getCurrentFrame().getBackRef();
regs = ((RubyMatchData)md).regs;
if (iter) {
md.use();
context.getPreviousFrame().setBackRef(md);
// FIXME: I don't like this setting into the frame directly, but it's necessary since blocks dupe the
block.getFrame().setBackRef(md);
val = objAsString(block.yield(context, RubyRegexp.nth_match(0, md)));
modifyCheck(sb, slen);
if (bang) frozenCheck();
// rb_raise(rb_eRuntimeError, "block should not cheat");
} else {
val = pattern.regsub((RubyString)repl, this, regs);
}
if (val.isTaint()) tainted = true;
ByteList vbuf = val.value;
int beg = regs.beg[0];
int len = (bp - buf) + (beg - offset) + vbuf.realSize + 3;
if (blen < len) {
while (blen < len) blen <<= 1;
len = bp - buf;
dest.realloc(blen);
dest.realSize = blen;
bp = buf + len;
}
len = beg - offset;
System.arraycopy(value.bytes, cp, dest.bytes, bp, len);
bp += len;
System.arraycopy(vbuf.bytes, vbuf.begin, dest.bytes, bp, vbuf.realSize);
bp += vbuf.realSize;
int endZ = regs.end[0];
offset = endZ;
if (regs.beg[0] == regs.end[0]) {
if (value.realSize <= endZ) break;
len = 1;
System.arraycopy(value.bytes, value.begin + endZ, dest.bytes, bp, len);
bp += len;
offset = endZ + len;
}
cp = value.begin + offset;
if (offset > value.realSize) break;
begs = pattern.search(this, offset, false);
}
if (value.realSize > offset) {
int len = bp - buf;
if (blen - len < value.realSize - offset) {
blen = len + value.realSize - offset;
dest.realloc(blen);
bp = buf + len;
}
System.arraycopy(value.bytes, cp, dest.bytes, bp, value.realSize - offset);
bp += value.realSize - offset;
}
// match unlock
// tmp unlock;
dest.realSize = bp - buf;
if (bang) {
view(dest);
if (tainted) setTaint(true);
return this;
} else {
RubyString destStr = new RubyString(runtime, getMetaClass(), dest);
destStr.infectBy(this);
if (tainted) destStr.setTaint(true);
return destStr;
}
}
/** rb_str_index_m
*
*/
@JRubyMethod(name = "index", required = 1, optional = 1)
public IRubyObject index(IRubyObject[] args) {
int pos;
boolean offset = false;
if(Arity.checkArgumentCount(getRuntime(), args, 1, 2) == 2) {
pos = RubyNumeric.fix2int(args[1]);
} else {
pos = 0;
}
if(pos < 0) {
pos += value.length();
if(pos < 0) {
if(args[0] instanceof RubyRegexp) {
getRuntime().getCurrentContext().getPreviousFrame().setBackRef(getRuntime().getNil());
}
return getRuntime().getNil();
}
}
if (args[0] instanceof RubyRegexp) {
RubyRegexp sub = (RubyRegexp)args[0];
pos = sub.adjust_startpos(this, pos, false);
pos = sub.search(this, pos, false);
} else if (args[0] instanceof RubyFixnum) {
char c = (char) ((RubyFixnum) args[0]).getLongValue();
pos = value.indexOf(c, pos);
} else {
IRubyObject tmp = args[0].checkStringType();
if (tmp.isNil()) throw getRuntime().newTypeError("type mismatch: " + args[0].getMetaClass().getName() + " given");
ByteList sub = ((RubyString) tmp).value;
if (sub.length() > value.length()) return getRuntime().getNil();
// the empty string is always found at the beginning of a string (or at the end when rindex)
if (sub.realSize == 0) {
if(pos<value.realSize) {
return getRuntime().newFixnum(pos);
} else {
return getRuntime().getNil();
}
}
pos = value.indexOf(sub, pos);
}
return pos == -1 ? getRuntime().getNil() : getRuntime().newFixnum(pos);
}
/** rb_str_rindex_m
*
*/
@JRubyMethod(name = "rindex", required = 1, optional = 1)
public IRubyObject rindex(IRubyObject[] args) {
int pos;
boolean offset = false;
if(Arity.checkArgumentCount(getRuntime(), args, 1, 2) == 2) {
pos = RubyNumeric.fix2int(args[1]);
if(pos < 0) {
pos += value.length();
if(pos < 0) {
if(args[0] instanceof RubyRegexp) {
getRuntime().getCurrentContext().getPreviousFrame().setBackRef(getRuntime().getNil());
}
return getRuntime().getNil();
}
}
if(pos > this.value.realSize) {
pos = this.value.realSize;
}
} else {
pos = this.value.realSize;
}
if (args[0] instanceof RubyRegexp) {
RubyRegexp sub = (RubyRegexp)args[0];
if(sub.getByteListSource().realSize > 0) {
pos = sub.adjust_startpos(this, pos, true);
pos = sub.search(this, pos, true);
}
if(pos >= 0) {
return getRuntime().newFixnum(pos);
}
} else if (args[0] instanceof RubyFixnum) {
char c = (char) ((RubyFixnum) args[0]).getLongValue();
pos = value.lastIndexOf(c, pos);
} else {
IRubyObject tmp = args[0].checkStringType();
if (tmp.isNil()) throw getRuntime().newTypeError("type mismatch: " + args[0].getMetaClass().getName() + " given");
ByteList sub = ((RubyString) tmp).value;
if (sub.length() > value.length()) return getRuntime().getNil();
// the empty string is always found at the beginning of a string (or at the end when rindex)
if (sub.realSize == 0) return getRuntime().newFixnum(pos);
pos = value.lastIndexOf(sub, pos);
}
return pos == -1 ? getRuntime().getNil() : getRuntime().newFixnum(pos);
}
/* rb_str_substr */
public IRubyObject substr(int beg, int len) {
int length = value.length();
if (len < 0 || beg > length) return getRuntime().getNil();
if (beg < 0) {
beg += length;
if (beg < 0) return getRuntime().getNil();
}
int end = Math.min(length, beg + len);
return makeShared(beg, end - beg);
}
/* rb_str_replace */
public IRubyObject replace(int beg, int len, RubyString replaceWith) {
if (beg + len >= value.length()) len = value.length() - beg;
modify();
value.unsafeReplace(beg,len,replaceWith.value);
return infectBy(replaceWith);
}
/** rb_str_aref, rb_str_aref_m
*
*/
@JRubyMethod(name = {"[]", "slice"}, required = 1, optional = 1)
public IRubyObject op_aref(IRubyObject[] args) {
if (Arity.checkArgumentCount(getRuntime(), args, 1, 2) == 2) {
if (args[0] instanceof RubyRegexp) {
if(((RubyRegexp)args[0]).search(this,0,false) >= 0) {
return RubyRegexp.nth_match(RubyNumeric.fix2int(args[1]), getRuntime().getCurrentContext().getCurrentFrame().getBackRef());
}
return getRuntime().getNil();
}
return substr(RubyNumeric.fix2int(args[0]), RubyNumeric.fix2int(args[1]));
}
if (args[0] instanceof RubyRegexp) {
if(((RubyRegexp)args[0]).search(this,0,false) >= 0) {
return RubyRegexp.nth_match(0, getRuntime().getCurrentContext().getCurrentFrame().getBackRef());
}
return getRuntime().getNil();
} else if (args[0] instanceof RubyString) {
return value.indexOf(stringValue(args[0]).value) != -1 ?
args[0] : getRuntime().getNil();
} else if (args[0] instanceof RubyRange) {
long[] begLen = ((RubyRange) args[0]).begLen(value.length(), 0);
return begLen == null ? getRuntime().getNil() :
substr((int) begLen[0], (int) begLen[1]);
}
int idx = (int) args[0].convertToInteger().getLongValue();
if (idx < 0) idx += value.length();
if (idx < 0 || idx >= value.length()) return getRuntime().getNil();
return getRuntime().newFixnum(value.get(idx) & 0xFF);
}
/**
* rb_str_subpat_set
*
*/
private void subpatSet(RubyRegexp regexp, int nth, IRubyObject repl) {
RubyMatchData match;
int start, end, len;
if(regexp.search(this, 0, false) < 0) {
throw getRuntime().newIndexError("regexp not matched");
}
match = (RubyMatchData)getRuntime().getCurrentContext().getCurrentFrame().getBackRef();
if(nth >= match.regs.numRegs) {
throw getRuntime().newIndexError("index " + nth + " out of regexp");
}
if(nth < 0) {
if(-nth >= match.regs.numRegs) {
throw getRuntime().newIndexError("index " + nth + " out of regexp");
}
nth += match.regs.numRegs;
}
start = match.regs.beg[nth];
if(start == -1) {
throw getRuntime().newIndexError("regexp group " + nth + " not matched");
}
end = match.regs.end[nth];
len = end - start;
replace(start, len, stringValue(repl));
}
/** rb_str_aset, rb_str_aset_m
*
*/
@JRubyMethod(name = "[]=", required = 2, optional = 1)
public IRubyObject op_aset(IRubyObject[] args) {
int strLen = value.length();
if (Arity.checkArgumentCount(getRuntime(), args, 2, 3) == 3) {
if (args[0] instanceof RubyFixnum) {
RubyString repl = stringValue(args[2]);
int beg = RubyNumeric.fix2int(args[0]);
int len = RubyNumeric.fix2int(args[1]);
if (len < 0) throw getRuntime().newIndexError("negative length");
if (beg < 0) beg += strLen;
if (beg < 0 || (beg > 0 && beg > strLen)) {
throw getRuntime().newIndexError("string index out of bounds");
}
if (beg + len > strLen) len = strLen - beg;
replace(beg, len, repl);
return repl;
}
if (args[0] instanceof RubyRegexp) {
RubyString repl = stringValue(args[2]);
int nth = RubyNumeric.fix2int(args[1]);
subpatSet((RubyRegexp) args[0], nth, repl);
return repl;
}
}
if (args[0] instanceof RubyFixnum || args[0].respondsTo("to_int")) { // FIXME: RubyNumeric or RubyInteger instead?
int idx = 0;
// FIXME: second instanceof check adds overhead?
if (!(args[0] instanceof RubyFixnum)) {
// FIXME: ok to cast?
idx = (int)args[0].convertToInteger().getLongValue();
} else {
idx = RubyNumeric.fix2int(args[0]); // num2int?
}
if (idx < 0) idx += value.length();
if (idx < 0 || idx >= value.length()) {
throw getRuntime().newIndexError("string index out of bounds");
}
if (args[1] instanceof RubyFixnum) {
modify();
value.set(idx, (byte) RubyNumeric.fix2int(args[1]));
} else {
replace(idx, 1, stringValue(args[1]));
}
return args[1];
}
if (args[0] instanceof RubyRegexp) {
RubyString repl = stringValue(args[1]);
subpatSet((RubyRegexp) args[0], 0, repl);
return repl;
}
if (args[0] instanceof RubyString) {
RubyString orig = stringValue(args[0]);
int beg = value.indexOf(orig.value);
if (beg != -1) {
replace(beg, orig.value.length(), stringValue(args[1]));
}
return args[1];
}
if (args[0] instanceof RubyRange) {
long[] idxs = ((RubyRange) args[0]).getBeginLength(value.length(), true, true);
replace((int) idxs[0], (int) idxs[1], stringValue(args[1]));
return args[1];
}
throw getRuntime().newTypeError("wrong argument type");
}
/** rb_str_slice_bang
*
*/
@JRubyMethod(name = "slice!", required = 1, optional = 1)
public IRubyObject slice_bang(IRubyObject[] args) {
int argc = Arity.checkArgumentCount(getRuntime(), args, 1, 2);
IRubyObject[] newArgs = new IRubyObject[argc + 1];
newArgs[0] = args[0];
if (argc > 1) newArgs[1] = args[1];
newArgs[argc] = newString("");
IRubyObject result = op_aref(args);
if (result.isNil()) return result;
op_aset(newArgs);
return result;
}
@JRubyMethod(name = {"succ", "next"})
public IRubyObject succ() {
return strDup().succ_bang();
}
@JRubyMethod(name = {"succ!", "next!"})
public IRubyObject succ_bang() {
if (value.length() == 0) return this;
modify();
boolean alnumSeen = false;
int pos = -1;
int c = 0;
int n = 0;
for (int i = value.length() - 1; i >= 0; i--) {
c = value.get(i) & 0xFF;
if (isAlnum(c)) {
alnumSeen = true;
if ((isDigit(c) && c < '9') || (isLower(c) && c < 'z') || (isUpper(c) && c < 'Z')) {
value.set(i, (byte)(c + 1));
pos = -1;
break;
}
pos = i;
n = isDigit(c) ? '1' : (isLower(c) ? 'a' : 'A');
value.set(i, (byte)(isDigit(c) ? '0' : (isLower(c) ? 'a' : 'A')));
}
}
if (!alnumSeen) {
for (int i = value.length() - 1; i >= 0; i--) {
c = value.get(i) & 0xFF;
if (c < 0xff) {
value.set(i, (byte)(c + 1));
pos = -1;
break;
}
pos = i;
n = '\u0001';
value.set(i, 0);
}
}
if (pos > -1) {
// This represents left most digit in a set of incremented
// values? Therefore leftmost numeric must be '1' and not '0'
// 999 -> 1000, not 999 -> 0000. whereas chars should be
// zzz -> aaaa and non-alnum byte values should be "\377" -> "\001\000"
value.prepend((byte) n);
}
return this;
}
/** rb_str_upto_m
*
*/
@JRubyMethod(name = "upto", required = 1, frame = true)
public IRubyObject upto(IRubyObject str, Block block) {
return upto(str, false, block);
}
/* rb_str_upto */
public IRubyObject upto(IRubyObject str, boolean excl, Block block) {
// alias 'this' to 'beg' for ease of comparison with MRI
RubyString beg = this;
RubyString end = stringValue(str);
int n = beg.op_cmp(end);
if (n > 0 || (excl && n == 0)) return beg;
RubyString afterEnd = stringValue(end.succ());
RubyString current = beg;
ThreadContext context = getRuntime().getCurrentContext();
while (!current.equals(afterEnd)) {
block.yield(context, current);
if (!excl && current.equals(end)) break;
current = (RubyString) current.succ();
if (excl && current.equals(end)) break;
if (current.length().getLongValue() > end.length().getLongValue()) break;
}
return beg;
}
/** rb_str_include
*
*/
@JRubyMethod(name = "include?", required = 1)
public RubyBoolean include_p(IRubyObject obj) {
if (obj instanceof RubyFixnum) {
int c = RubyNumeric.fix2int(obj);
for (int i = 0; i < value.length(); i++) {
if (value.get(i) == (byte)c) {
return getRuntime().getTrue();
}
}
return getRuntime().getFalse();
}
ByteList str = stringValue(obj).value;
return getRuntime().newBoolean(value.indexOf(str) != -1);
}
/** rb_str_to_i
*
*/
@JRubyMethod(name = "to_i", optional = 1)
public IRubyObject to_i(IRubyObject[] args) {
long base = Arity.checkArgumentCount(getRuntime(), args, 0, 1) == 0 ? 10 : args[0].convertToInteger().getLongValue();
return RubyNumeric.str2inum(getRuntime(), this, (int) base);
}
/** rb_str_oct
*
*/
@JRubyMethod(name = "oct")
public IRubyObject oct() {
if (isEmpty()) {
return getRuntime().newFixnum(0);
}
int base = 8;
int ix = value.begin;
while(ix < value.begin+value.realSize && WHITESPACE[value.bytes[ix]+128]) {
ix++;
}
int pos = (value.bytes[ix] == '-' || value.bytes[ix] == '+') ? ix+1 : ix;
if((pos+1) < value.begin+value.realSize && value.bytes[pos] == '0') {
if(value.bytes[pos+1] == 'x' || value.bytes[pos+1] == 'X') {
base = 16;
} else if(value.bytes[pos+1] == 'b' || value.bytes[pos+1] == 'B') {
base = 2;
}
}
return RubyNumeric.str2inum(getRuntime(), this, base);
}
/** rb_str_hex
*
*/
@JRubyMethod(name = "hex")
public IRubyObject hex() {
return RubyNumeric.str2inum(getRuntime(), this, 16);
}
/** rb_str_to_f
*
*/
@JRubyMethod(name = "to_f")
public IRubyObject to_f() {
return RubyNumeric.str2fnum(getRuntime(), this);
}
/** rb_str_split_m
*
*/
@JRubyMethod(name = "split", optional = 2)
public RubyArray split(IRubyObject[] args) {
int beg, end, i = 0;
int lim = 0;
boolean limit = false;
IRubyObject tmp;
Ruby runtime = getRuntime();
if (Arity.checkArgumentCount(runtime, args, 0, 2) == 2) {
lim = RubyNumeric.fix2int(args[1]);
if (lim == 1) {
if (value.realSize == 0) return runtime.newArray();
return runtime.newArray(this);
} else if (lim > 0) {
limit = true;
}
if (lim > 0) limit = true;
i = 1;
}
IRubyObject spat = (args.length == 0 || args[0].isNil()) ? null : args[0];
boolean awkSplit = false;
if (spat == null && (spat = runtime.getGlobalVariables().get("$;")).isNil()) {
awkSplit = true;
} else {
if (spat instanceof RubyString && ((RubyString)spat).value.realSize == 1) {
if (((RubyString)spat).value.get(0) == ' ') {
awkSplit = true;
}
}
}
RubyArray result = runtime.newArray();
beg = 0;
if (awkSplit) { // awk split
int ptr = value.begin;
int eptr = ptr + value.realSize;
byte[]buff = value.bytes;
boolean skip = true;
for (end = beg = 0; ptr < eptr; ptr++) {
if (skip) {
if (Character.isWhitespace((char)(buff[ptr] & 0xff))) {
beg++;
} else {
end = beg + 1;
skip = false;
if (limit && lim <= i) break;
}
} else {
if (Character.isWhitespace((char)(buff[ptr] & 0xff))) {
result.append(makeShared(beg, end - beg));
skip = true;
beg = end + 1;
if (limit) i++;
} else {
end++;
}
}
}
if (value.realSize > 0 && (limit || value.realSize > beg || lim < 0)) {
if (value.length() == beg) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(makeShared(beg, value.realSize - beg));
}
}
} else if(spat instanceof RubyString) { // string split
ByteList rsep = ((RubyString)spat).value;
int rslen = rsep.realSize;
int ptr = value.begin;
int pend = ptr + value.realSize;
byte[]buff = value.bytes;
int p = ptr;
byte lastVal = rslen == 0 ? 0 : rsep.bytes[rsep.begin+rslen-1];
int s = p;
p+=rslen;
for(; p < pend; p++) {
if(ptr<p && (rslen ==0 || (buff[p-1] == lastVal &&
(rslen <= 1 ||
ByteList.memcmp(rsep.bytes, rsep.begin, rslen, buff, p-rslen, rslen) == 0)))) {
result.append(makeShared(s-ptr, (p - s) - rslen));
s = p;
if(limit) {
i++;
if(lim<=i) {
p = pend;
break;
}
}
}
}
if(s != pend) {
if(p > pend) {
p = pend;
}
- if(!(limit && lim<=i) && ByteList.memcmp(rsep.bytes, rsep.begin, rslen, buff, p-rslen, rslen) == 0) {
+ if(!(limit && lim<=i) && p-rslen >= ptr && ByteList.memcmp(rsep.bytes, rsep.begin, rslen, buff, p-rslen, rslen) == 0) {
result.append(makeShared(s-ptr, (p - s)-rslen));
if(lim < 0) {
result.append(newEmptyString(runtime, getMetaClass()));
}
} else {
result.append(makeShared(s-ptr, p - s));
}
}
} else { // regexp split
spat = getPat(spat,true);
int start = beg;
int idx;
boolean last_null = false;
Region regs;
while((end = ((RubyRegexp)spat).search(this, start, false)) >= 0) {
regs = ((RubyMatchData)getRuntime().getCurrentContext().getCurrentFrame().getBackRef()).regs;
if(start == end && regs.beg[0] == regs.end[0]) {
if(value.realSize == 0) {
result.append(newEmptyString(runtime, getMetaClass()));
break;
} else if(last_null) {
result.append(substr(beg, ((RubyRegexp)spat).getKCode().getEncoding().length(value.bytes[value.begin+beg])));
beg = start;
} else {
if(start < value.realSize) {
start += ((RubyRegexp)spat).getKCode().getEncoding().length(value.bytes[value.begin+start]);
} else {
start++;
}
last_null = true;
continue;
}
} else {
result.append(substr(beg,end-beg));
beg = start = regs.end[0];
}
last_null = false;
for(idx=1; idx < regs.numRegs; idx++) {
if(regs.beg[idx] == -1) {
continue;
}
if(regs.beg[idx] == regs.end[idx]) {
tmp = newEmptyString(runtime, getMetaClass());
} else {
tmp = substr(regs.beg[idx],regs.end[idx]-regs.beg[idx]);
}
result.append(tmp);
}
if(limit && lim <= ++i) {
break;
}
}
if (value.realSize > 0 && (limit || value.realSize > beg || lim < 0)) {
if (value.realSize == beg) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(substr(beg, value.realSize - beg));
}
}
} // regexp split
if (!limit && lim == 0) {
while (result.size() > 0 && ((RubyString)result.eltInternal(result.size() - 1)).value.realSize == 0)
result.pop();
}
return result;
}
/** get_pat
*
*/
private final RubyRegexp getPat(IRubyObject pattern, boolean quote) {
if (pattern instanceof RubyRegexp) {
return (RubyRegexp)pattern;
} else if (!(pattern instanceof RubyString)) {
IRubyObject val = pattern.checkStringType();
if(val.isNil()) throw getRuntime().newTypeError("wrong argument type " + pattern.getMetaClass() + " (expected Regexp)");
pattern = val;
}
RubyString strPattern = (RubyString)pattern;
if (quote) pattern = RubyRegexp.quote(strPattern,(KCode)null);
return RubyRegexp.newRegexp(pattern, 0, null);
}
/** rb_str_scan
*
*/
@JRubyMethod(name = "scan", required = 1, frame = true)
public IRubyObject scan(IRubyObject arg, Block block) {
IRubyObject result;
int[] start = new int[]{0};
IRubyObject match = getRuntime().getNil();
RubyRegexp pattern = getPat(arg, true);
Ruby runtime = getRuntime();
ThreadContext context = runtime.getCurrentContext();
byte[]_p = value.bytes;
int len = value.realSize;
if(!block.isGiven()) {
RubyArray ary = runtime.newArray();
while(!(result = scan_once(pattern, start)).isNil()) {
match = context.getCurrentFrame().getBackRef();
ary.append(result);
}
context.getPreviousFrame().setBackRef(match);
return ary;
}
while(!(result = scan_once(pattern, start)).isNil()) {
match = context.getCurrentFrame().getBackRef();
context.getPreviousFrame().setBackRef(match);
if(match instanceof RubyMatchData) {
((RubyMatchData)match).use();
}
block.yield(context,result);
modifyCheck(_p,len);
context.getPreviousFrame().setBackRef(match);
}
context.getPreviousFrame().setBackRef(match);
return this;
}
/**
* rb_enc_check
*/
private Encoding encodingCheck(RubyRegexp pattern) {
// For 1.9 compatibility, should check encoding compat between string and pattern
return pattern.getKCode().getEncoding();
}
private IRubyObject scan_once(RubyRegexp pat, int[] start) {
Encoding enc = encodingCheck(pat);
Region regs;
int i;
if(pat.search(this, start[0], false) >= 0) {
RubyMatchData match = (RubyMatchData)getRuntime().getCurrentContext().getCurrentFrame().getBackRef();
regs = match.regs;
if(regs.beg[0] == regs.end[0]) {
/*
* Always consume at least one character of the input string
*/
if(value.realSize > regs.end[0]) {
start[0] = regs.end[0] + enc.length(value.bytes[value.begin+regs.end[0]]);
} else {
start[0] = regs.end[0] + 1;
}
} else {
start[0] = regs.end[0];
}
if(regs.numRegs == 1) {
return RubyRegexp.nth_match(0,match);
}
RubyArray ary = getRuntime().newArray(regs.numRegs);
for(i=1;i<regs.numRegs;i++) {
ary.append(RubyRegexp.nth_match(i,match));
}
return ary;
}
return getRuntime().getNil();
}
private final RubyString substr(Ruby runtime, String str, int beg, int len, boolean utf8) {
if (utf8) {
if (len == 0) return newEmptyString(runtime, getMetaClass());
return new RubyString(runtime, getMetaClass(), new ByteList(toUTF(str.substring(beg, beg + len)), false));
} else {
return makeShared(beg, len);
}
}
private final String toString(boolean utf8) {
String str = toString();
if (utf8) {
try {
str = new String(ByteList.plain(str), "UTF8");
} catch(Exception e){}
}
return str;
}
private static final ByteList SPACE_BYTELIST = new ByteList(ByteList.plain(" "));
private final IRubyObject justify(IRubyObject[]args, char jflag) {
Ruby runtime = getRuntime();
Arity.scanArgs(runtime, args, 1, 1);
int width = RubyFixnum.num2int(args[0]);
int f, flen = 0;
byte[]fbuf;
IRubyObject pad;
if (args.length == 2) {
pad = args[1].convertToString();
ByteList fList = ((RubyString)pad).value;
f = fList.begin;
flen = fList.realSize;
if (flen == 0) throw getRuntime().newArgumentError("zero width padding");
fbuf = fList.bytes;
} else {
f = SPACE_BYTELIST.begin;
flen = SPACE_BYTELIST.realSize;
fbuf = SPACE_BYTELIST.bytes;
pad = runtime.getNil();
}
if (width < 0 || value.realSize >= width) return strDup();
ByteList res = new ByteList(width);
res.realSize = width;
int p = res.begin;
int pend;
byte[] pbuf = res.bytes;
if (jflag != 'l') {
int n = width - value.realSize;
pend = p + ((jflag == 'r') ? n : n / 2);
if (flen <= 1) {
while (p < pend) pbuf[p++] = fbuf[f];
} else {
int q = f;
while (p + flen <= pend) {
System.arraycopy(fbuf, f, pbuf, p, flen);
p += flen;
}
while (p < pend) pbuf[p++] = fbuf[q++];
}
}
System.arraycopy(value.bytes, value.begin, pbuf, p, value.realSize);
if (jflag != 'r') {
p += value.realSize;
pend = res.begin + width;
if (flen <= 1) {
while (p < pend) pbuf[p++] = fbuf[f];
} else {
while (p + flen <= pend) {
System.arraycopy(fbuf, f, pbuf, p, flen);
p += flen;
}
while (p < pend) pbuf[p++] = fbuf[f++];
}
}
RubyString resStr = new RubyString(runtime, getMetaClass(), res);
resStr.infectBy(this);
if (flen > 0) resStr.infectBy(pad);
return resStr;
}
/** rb_str_ljust
*
*/
@JRubyMethod(name = "ljust", required = 1, optional = 1)
public IRubyObject ljust(IRubyObject [] args) {
return justify(args, 'l');
}
/** rb_str_rjust
*
*/
@JRubyMethod(name = "rjust", required = 1, optional = 1)
public IRubyObject rjust(IRubyObject [] args) {
return justify(args, 'r');
}
@JRubyMethod(name = "center", required = 1, optional = 1)
public IRubyObject center(IRubyObject[] args) {
return justify(args, 'c');
}
@JRubyMethod(name = "chop")
public IRubyObject chop() {
RubyString str = strDup();
str.chop_bang();
return str;
}
/** rb_str_chop_bang
*
*/
@JRubyMethod(name = "chop!")
public IRubyObject chop_bang() {
int end = value.realSize - 1;
if (end < 0) return getRuntime().getNil();
if ((value.bytes[value.begin + end]) == '\n') {
if (end > 0 && (value.bytes[value.begin + end - 1]) == '\r') end--;
}
view(0, end);
return this;
}
/** rb_str_chop
*
*/
@JRubyMethod(name = "chomp", optional = 1)
public RubyString chomp(IRubyObject[] args) {
RubyString str = strDup();
str.chomp_bang(args);
return str;
}
/**
* rb_str_chomp_bang
*
* In the common case, removes CR and LF characters in various ways depending on the value of
* the optional args[0].
* If args.length==0 removes one instance of CR, CRLF or LF from the end of the string.
* If args.length>0 and args[0] is "\n" then same behaviour as args.length==0 .
* If args.length>0 and args[0] is "" then removes trailing multiple LF or CRLF (but no CRs at
* all(!)).
* @param args See method description.
*/
@JRubyMethod(name = "chomp!", optional = 1)
public IRubyObject chomp_bang(IRubyObject[] args) {
IRubyObject rsObj;
if (Arity.checkArgumentCount(getRuntime(), args, 0, 1) == 0) {
int len = value.length();
if (len == 0) return getRuntime().getNil();
byte[]buff = value.bytes;
rsObj = getRuntime().getGlobalVariables().get("$/");
if (rsObj == getRuntime().getGlobalVariables().getDefaultSeparator()) {
int realSize = value.realSize;
int begin = value.begin;
if ((buff[begin + len - 1] & 0xFF) == '\n') {
realSize--;
if (realSize > 0 && (buff[begin + realSize - 1] & 0xFF) == '\r') realSize--;
view(0, realSize);
} else if ((buff[begin + len - 1] & 0xFF) == '\r') {
realSize--;
view(0, realSize);
} else {
modifyCheck();
return getRuntime().getNil();
}
return this;
}
} else {
rsObj = args[0];
}
if (rsObj.isNil()) return getRuntime().getNil();
RubyString rs = rsObj.convertToString();
int len = value.realSize;
int begin = value.begin;
if (len == 0) return getRuntime().getNil();
byte[]buff = value.bytes;
int rslen = rs.value.realSize;
if (rslen == 0) {
while (len > 0 && (buff[begin + len - 1] & 0xFF) == '\n') {
len--;
if (len > 0 && (buff[begin + len - 1] & 0xFF) == '\r') len--;
}
if (len < value.realSize) {
view(0, len);
return this;
}
return getRuntime().getNil();
}
if (rslen > len) return getRuntime().getNil();
int newline = rs.value.bytes[rslen - 1] & 0xFF;
if (rslen == 1 && newline == '\n') {
buff = value.bytes;
int realSize = value.realSize;
if ((buff[begin + len - 1] & 0xFF) == '\n') {
realSize--;
if (realSize > 0 && (buff[begin + realSize - 1] & 0xFF) == '\r') realSize--;
view(0, realSize);
} else if ((buff[begin + len - 1] & 0xFF) == '\r') {
realSize--;
view(0, realSize);
} else {
modifyCheck();
return getRuntime().getNil();
}
return this;
}
if ((buff[begin + len - 1] & 0xFF) == newline && rslen <= 1 || value.endsWith(rs.value)) {
view(0, value.realSize - rslen);
return this;
}
return getRuntime().getNil();
}
/** rb_str_lstrip
*
*/
@JRubyMethod(name = "lstrip")
public IRubyObject lstrip() {
RubyString str = strDup();
str.lstrip_bang();
return str;
}
private final static boolean[] WHITESPACE = new boolean[256];
static {
WHITESPACE[((byte)' ')+128] = true;
WHITESPACE[((byte)'\t')+128] = true;
WHITESPACE[((byte)'\n')+128] = true;
WHITESPACE[((byte)'\r')+128] = true;
WHITESPACE[((byte)'\f')+128] = true;
}
/** rb_str_lstrip_bang
*/
@JRubyMethod(name = "lstrip!")
public IRubyObject lstrip_bang() {
if (value.realSize == 0) return getRuntime().getNil();
int i=0;
while (i < value.realSize && WHITESPACE[value.bytes[value.begin+i]+128]) i++;
if (i > 0) {
view(i, value.realSize - i);
return this;
}
return getRuntime().getNil();
}
/** rb_str_rstrip
*
*/
@JRubyMethod(name = "rstrip")
public IRubyObject rstrip() {
RubyString str = strDup();
str.rstrip_bang();
return str;
}
/** rb_str_rstrip_bang
*/
@JRubyMethod(name = "rstrip!")
public IRubyObject rstrip_bang() {
if (value.realSize == 0) return getRuntime().getNil();
int i=value.realSize - 1;
while (i >= 0 && value.bytes[value.begin+i] == 0) i--;
while (i >= 0 && WHITESPACE[value.bytes[value.begin+i]+128]) i--;
if (i < value.realSize - 1) {
view(0, i + 1);
return this;
}
return getRuntime().getNil();
}
/** rb_str_strip
*
*/
@JRubyMethod(name = "strip")
public IRubyObject strip() {
RubyString str = strDup();
str.strip_bang();
return str;
}
/** rb_str_strip_bang
*/
@JRubyMethod(name = "strip!")
public IRubyObject strip_bang() {
IRubyObject l = lstrip_bang();
IRubyObject r = rstrip_bang();
if(l.isNil() && r.isNil()) {
return l;
}
return this;
}
/** rb_str_count
*
*/
@JRubyMethod(name = "count", required = 1, rest = true)
public IRubyObject count(IRubyObject[] args) {
if (args.length < 1) throw getRuntime().newArgumentError("wrong number of arguments");
if (value.realSize == 0) return getRuntime().newFixnum(0);
boolean[]table = new boolean[TRANS_SIZE];
boolean init = true;
for (int i=0; i<args.length; i++) {
RubyString s = args[i].convertToString();
s.setup_table(table, init);
init = false;
}
int s = value.begin;
int send = s + value.realSize;
byte[]buf = value.bytes;
int i = 0;
while (s < send) if (table[buf[s++] & 0xff]) i++;
return getRuntime().newFixnum(i);
}
/** rb_str_delete
*
*/
@JRubyMethod(name = "delete", required = 1, rest = true)
public IRubyObject delete(IRubyObject[] args) {
RubyString str = strDup();
str.delete_bang(args);
return str;
}
/** rb_str_delete_bang
*
*/
@JRubyMethod(name = "delete!", required = 1, rest = true)
public IRubyObject delete_bang(IRubyObject[] args) {
if (args.length < 1) throw getRuntime().newArgumentError("wrong number of arguments");
boolean[]squeeze = new boolean[TRANS_SIZE];
boolean init = true;
for (int i=0; i<args.length; i++) {
RubyString s = args[i].convertToString();
s.setup_table(squeeze, init);
init = false;
}
modify();
if (value.realSize == 0) return getRuntime().getNil();
int s = value.begin;
int t = s;
int send = s + value.realSize;
byte[]buf = value.bytes;
boolean modify = false;
while (s < send) {
if (squeeze[buf[s] & 0xff]) {
modify = true;
} else {
buf[t++] = buf[s];
}
s++;
}
value.realSize = t - value.begin;
if (modify) return this;
return getRuntime().getNil();
}
/** rb_str_squeeze
*
*/
@JRubyMethod(name = "squeeze", rest = true)
public IRubyObject squeeze(IRubyObject[] args) {
RubyString str = strDup();
str.squeeze_bang(args);
return str;
}
/** rb_str_squeeze_bang
*
*/
@JRubyMethod(name = "squeeze!", rest = true)
public IRubyObject squeeze_bang(IRubyObject[] args) {
if (value.realSize == 0) return getRuntime().getNil();
final boolean squeeze[] = new boolean[TRANS_SIZE];
if (args.length == 0) {
for (int i=0; i<TRANS_SIZE; i++) squeeze[i] = true;
} else {
boolean init = true;
for (int i=0; i<args.length; i++) {
RubyString s = args[i].convertToString();
s.setup_table(squeeze, init);
init = false;
}
}
modify();
int s = value.begin;
int t = s;
int send = s + value.realSize;
byte[]buf = value.bytes;
int save = -1;
while (s < send) {
int c = buf[s++] & 0xff;
if (c != save || !squeeze[c]) buf[t++] = (byte)(save = c);
}
if (t - value.begin != value.realSize) { // modified
value.realSize = t - value.begin;
return this;
}
return getRuntime().getNil();
}
/** rb_str_tr
*
*/
@JRubyMethod(name = "tr", required = 2)
public IRubyObject tr(IRubyObject src, IRubyObject repl) {
RubyString str = strDup();
str.tr_trans(src, repl, false);
return str;
}
/** rb_str_tr_bang
*
*/
@JRubyMethod(name = "tr!", required = 2)
public IRubyObject tr_bang(IRubyObject src, IRubyObject repl) {
return tr_trans(src, repl, false);
}
private static final class TR {
int gen, now, max;
int p, pend;
byte[]buf;
}
private static final int TRANS_SIZE = 256;
/** tr_setup_table
*
*/
private final void setup_table(boolean[]table, boolean init) {
final boolean[]buf = new boolean[TRANS_SIZE];
final TR tr = new TR();
int c;
boolean cflag = false;
tr.p = value.begin;
tr.pend = value.begin + value.realSize;
tr.buf = value.bytes;
tr.gen = tr.now = tr.max = 0;
if (value.realSize > 1 && value.bytes[value.begin] == '^') {
cflag = true;
tr.p++;
}
if (init) for (int i=0; i<TRANS_SIZE; i++) table[i] = true;
for (int i=0; i<TRANS_SIZE; i++) buf[i] = cflag;
while ((c = trnext(tr)) >= 0) buf[c & 0xff] = !cflag;
for (int i=0; i<TRANS_SIZE; i++) table[i] = table[i] && buf[i];
}
/** tr_trans
*
*/
private final IRubyObject tr_trans(IRubyObject src, IRubyObject repl, boolean sflag) {
if (value.realSize == 0) return getRuntime().getNil();
ByteList replList = repl.convertToString().value;
if (replList.realSize == 0) return delete_bang(new IRubyObject[]{src});
ByteList srcList = src.convertToString().value;
final TR trsrc = new TR();
final TR trrepl = new TR();
boolean cflag = false;
boolean modify = false;
trsrc.p = srcList.begin;
trsrc.pend = srcList.begin + srcList.realSize;
trsrc.buf = srcList.bytes;
if (srcList.realSize >= 2 && srcList.bytes[srcList.begin] == '^') {
cflag = true;
trsrc.p++;
}
trrepl.p = replList.begin;
trrepl.pend = replList.begin + replList.realSize;
trrepl.buf = replList.bytes;
trsrc.gen = trrepl.gen = 0;
trsrc.now = trrepl.now = 0;
trsrc.max = trrepl.max = 0;
int c;
final int[]trans = new int[TRANS_SIZE];
if (cflag) {
for (int i=0; i<TRANS_SIZE; i++) trans[i] = 1;
while ((c = trnext(trsrc)) >= 0) trans[c & 0xff] = -1;
while ((c = trnext(trrepl)) >= 0);
for (int i=0; i<TRANS_SIZE; i++) {
if (trans[i] >= 0) trans[i] = trrepl.now;
}
} else {
for (int i=0; i<TRANS_SIZE; i++) trans[i] = -1;
while ((c = trnext(trsrc)) >= 0) {
int r = trnext(trrepl);
if (r == -1) r = trrepl.now;
trans[c & 0xff] = r;
}
}
modify();
int s = value.begin;
int send = s + value.realSize;
byte sbuf[] = value.bytes;
if (sflag) {
int t = s;
int c0, last = -1;
while (s < send) {
c0 = sbuf[s++];
if ((c = trans[c0 & 0xff]) >= 0) {
if (last == c) continue;
last = c;
sbuf[t++] = (byte)(c & 0xff);
modify = true;
} else {
last = -1;
sbuf[t++] = (byte)c0;
}
}
if (value.realSize > (t - value.begin)) {
value.realSize = t - value.begin;
modify = true;
}
} else {
while (s < send) {
if ((c = trans[sbuf[s] & 0xff]) >= 0) {
sbuf[s] = (byte)(c & 0xff);
modify = true;
}
s++;
}
}
if (modify) return this;
return getRuntime().getNil();
}
/** trnext
*
*/
private final int trnext(TR t) {
byte [] buf = t.buf;
for (;;) {
if (t.gen == 0) {
if (t.p == t.pend) return -1;
if (t.p < t.pend -1 && buf[t.p] == '\\') t.p++;
t.now = buf[t.p++];
if (t.p < t.pend - 1 && buf[t.p] == '-') {
t.p++;
if (t.p < t.pend) {
if (t.now > buf[t.p]) {
t.p++;
continue;
}
t.gen = 1;
t.max = buf[t.p++];
}
}
return t.now & 0xff;
} else if (++t.now < t.max) {
return t.now & 0xff;
} else {
t.gen = 0;
return t.max & 0xff;
}
}
}
/** rb_str_tr_s
*
*/
@JRubyMethod(name = "tr_s", required = 2)
public IRubyObject tr_s(IRubyObject src, IRubyObject repl) {
RubyString str = strDup();
str.tr_trans(src, repl, true);
return str;
}
/** rb_str_tr_s_bang
*
*/
@JRubyMethod(name = "tr_s!", required = 2)
public IRubyObject tr_s_bang(IRubyObject src, IRubyObject repl) {
return tr_trans(src, repl, true);
}
/** rb_str_each_line
*
*/
@JRubyMethod(name = {"each_line", "each"}, required = 0, optional = 1, frame = true)
public IRubyObject each_line(IRubyObject[] args, Block block) {
byte newline;
int p = value.begin;
int pend = p + value.realSize;
int s;
int ptr = p;
int len = value.realSize;
int rslen;
IRubyObject line;
IRubyObject _rsep;
if (Arity.checkArgumentCount(getRuntime(), args, 0, 1) == 0) {
_rsep = getRuntime().getGlobalVariables().get("$/");
} else {
_rsep = args[0];
}
ThreadContext tc = getRuntime().getCurrentContext();
if(_rsep.isNil()) {
block.yield(tc, this);
return this;
}
RubyString rsep = stringValue(_rsep);
ByteList rsepValue = rsep.value;
byte[] strBytes = value.bytes;
rslen = rsepValue.realSize;
if(rslen == 0) {
newline = '\n';
} else {
newline = rsepValue.bytes[rsepValue.begin + rslen-1];
}
s = p;
p+=rslen;
for(; p < pend; p++) {
if(rslen == 0 && strBytes[p] == '\n') {
if(strBytes[++p] != '\n') {
continue;
}
while(strBytes[p] == '\n') {
p++;
}
}
if(ptr<p && strBytes[p-1] == newline &&
(rslen <= 1 ||
ByteList.memcmp(rsepValue.bytes, rsepValue.begin, rslen, strBytes, p-rslen, rslen) == 0)) {
line = RubyString.newStringShared(getRuntime(), getMetaClass(), this.value.makeShared(s-ptr, p-s));
line.infectBy(this);
block.yield(tc, line);
modifyCheck(strBytes,len);
s = p;
}
}
if(s != pend) {
if(p > pend) {
p = pend;
}
line = RubyString.newStringShared(getRuntime(), getMetaClass(), this.value.makeShared(s-ptr, p-s));
line.infectBy(this);
block.yield(tc, line);
}
return this;
}
/**
* rb_str_each_byte
*/
@JRubyMethod(name = "each_byte", frame = true)
public RubyString each_byte(Block block) {
int lLength = value.length();
Ruby runtime = getRuntime();
ThreadContext context = runtime.getCurrentContext();
for (int i = 0; i < lLength; i++) {
block.yield(context, runtime.newFixnum(value.get(i) & 0xFF));
}
return this;
}
/** rb_str_intern
*
*/
public RubySymbol intern() {
String s = toString();
if (s.length() == 0) {
throw getRuntime().newArgumentError("interning empty string");
}
if (s.indexOf('\0') >= 0) {
throw getRuntime().newArgumentError("symbol string may not contain '\\0'");
}
return getRuntime().newSymbol(s);
}
@JRubyMethod(name = {"to_sym", "intern"})
public RubySymbol to_sym() {
return intern();
}
@JRubyMethod(name = "sum", optional = 1)
public RubyInteger sum(IRubyObject[] args) {
if (args.length > 1) {
throw getRuntime().newArgumentError("wrong number of arguments (" + args.length + " for 1)");
}
long bitSize = 16;
if (args.length == 1) {
long bitSizeArg = ((RubyInteger) args[0].convertToInteger()).getLongValue();
if (bitSizeArg > 0) {
bitSize = bitSizeArg;
}
}
long result = 0;
for (int i = 0; i < value.length(); i++) {
result += value.get(i) & 0xFF;
}
return getRuntime().newFixnum(bitSize == 0 ? result : result % (long) Math.pow(2, bitSize));
}
public static RubyString unmarshalFrom(UnmarshalStream input) throws java.io.IOException {
RubyString result = newString(input.getRuntime(), input.unmarshalString());
input.registerLinkTarget(result);
return result;
}
/**
* @see org.jruby.util.Pack#unpack
*/
@JRubyMethod(name = "unpack", required = 1)
public RubyArray unpack(IRubyObject obj) {
return Pack.unpack(getRuntime(), this.value, stringValue(obj).value);
}
/**
* Mutator for internal string representation.
*
* @param value The new java.lang.String this RubyString should encapsulate
*/
public void setValue(CharSequence value) {
view(ByteList.plain(value));
}
public void setValue(ByteList value) {
view(value);
}
public CharSequence getValue() {
return toString();
}
public String getUnicodeValue() {
try {
return new String(value.bytes,value.begin,value.realSize, "UTF8");
} catch (Exception e) {
throw new RuntimeException("Something's seriously broken with encodings", e);
}
}
public static byte[] toUTF(String string) {
try {
return string.getBytes("UTF8");
} catch (Exception e) {
throw new RuntimeException("Something's seriously broken with encodings", e);
}
}
public void setUnicodeValue(String newValue) {
view(toUTF(newValue));
}
public byte[] getBytes() {
return value.bytes();
}
public ByteList getByteList() {
return value;
}
}
| true | true | public RubyArray split(IRubyObject[] args) {
int beg, end, i = 0;
int lim = 0;
boolean limit = false;
IRubyObject tmp;
Ruby runtime = getRuntime();
if (Arity.checkArgumentCount(runtime, args, 0, 2) == 2) {
lim = RubyNumeric.fix2int(args[1]);
if (lim == 1) {
if (value.realSize == 0) return runtime.newArray();
return runtime.newArray(this);
} else if (lim > 0) {
limit = true;
}
if (lim > 0) limit = true;
i = 1;
}
IRubyObject spat = (args.length == 0 || args[0].isNil()) ? null : args[0];
boolean awkSplit = false;
if (spat == null && (spat = runtime.getGlobalVariables().get("$;")).isNil()) {
awkSplit = true;
} else {
if (spat instanceof RubyString && ((RubyString)spat).value.realSize == 1) {
if (((RubyString)spat).value.get(0) == ' ') {
awkSplit = true;
}
}
}
RubyArray result = runtime.newArray();
beg = 0;
if (awkSplit) { // awk split
int ptr = value.begin;
int eptr = ptr + value.realSize;
byte[]buff = value.bytes;
boolean skip = true;
for (end = beg = 0; ptr < eptr; ptr++) {
if (skip) {
if (Character.isWhitespace((char)(buff[ptr] & 0xff))) {
beg++;
} else {
end = beg + 1;
skip = false;
if (limit && lim <= i) break;
}
} else {
if (Character.isWhitespace((char)(buff[ptr] & 0xff))) {
result.append(makeShared(beg, end - beg));
skip = true;
beg = end + 1;
if (limit) i++;
} else {
end++;
}
}
}
if (value.realSize > 0 && (limit || value.realSize > beg || lim < 0)) {
if (value.length() == beg) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(makeShared(beg, value.realSize - beg));
}
}
} else if(spat instanceof RubyString) { // string split
ByteList rsep = ((RubyString)spat).value;
int rslen = rsep.realSize;
int ptr = value.begin;
int pend = ptr + value.realSize;
byte[]buff = value.bytes;
int p = ptr;
byte lastVal = rslen == 0 ? 0 : rsep.bytes[rsep.begin+rslen-1];
int s = p;
p+=rslen;
for(; p < pend; p++) {
if(ptr<p && (rslen ==0 || (buff[p-1] == lastVal &&
(rslen <= 1 ||
ByteList.memcmp(rsep.bytes, rsep.begin, rslen, buff, p-rslen, rslen) == 0)))) {
result.append(makeShared(s-ptr, (p - s) - rslen));
s = p;
if(limit) {
i++;
if(lim<=i) {
p = pend;
break;
}
}
}
}
if(s != pend) {
if(p > pend) {
p = pend;
}
if(!(limit && lim<=i) && ByteList.memcmp(rsep.bytes, rsep.begin, rslen, buff, p-rslen, rslen) == 0) {
result.append(makeShared(s-ptr, (p - s)-rslen));
if(lim < 0) {
result.append(newEmptyString(runtime, getMetaClass()));
}
} else {
result.append(makeShared(s-ptr, p - s));
}
}
} else { // regexp split
spat = getPat(spat,true);
int start = beg;
int idx;
boolean last_null = false;
Region regs;
while((end = ((RubyRegexp)spat).search(this, start, false)) >= 0) {
regs = ((RubyMatchData)getRuntime().getCurrentContext().getCurrentFrame().getBackRef()).regs;
if(start == end && regs.beg[0] == regs.end[0]) {
if(value.realSize == 0) {
result.append(newEmptyString(runtime, getMetaClass()));
break;
} else if(last_null) {
result.append(substr(beg, ((RubyRegexp)spat).getKCode().getEncoding().length(value.bytes[value.begin+beg])));
beg = start;
} else {
if(start < value.realSize) {
start += ((RubyRegexp)spat).getKCode().getEncoding().length(value.bytes[value.begin+start]);
} else {
start++;
}
last_null = true;
continue;
}
} else {
result.append(substr(beg,end-beg));
beg = start = regs.end[0];
}
last_null = false;
for(idx=1; idx < regs.numRegs; idx++) {
if(regs.beg[idx] == -1) {
continue;
}
if(regs.beg[idx] == regs.end[idx]) {
tmp = newEmptyString(runtime, getMetaClass());
} else {
tmp = substr(regs.beg[idx],regs.end[idx]-regs.beg[idx]);
}
result.append(tmp);
}
if(limit && lim <= ++i) {
break;
}
}
if (value.realSize > 0 && (limit || value.realSize > beg || lim < 0)) {
if (value.realSize == beg) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(substr(beg, value.realSize - beg));
}
}
} // regexp split
if (!limit && lim == 0) {
while (result.size() > 0 && ((RubyString)result.eltInternal(result.size() - 1)).value.realSize == 0)
result.pop();
}
return result;
}
| public RubyArray split(IRubyObject[] args) {
int beg, end, i = 0;
int lim = 0;
boolean limit = false;
IRubyObject tmp;
Ruby runtime = getRuntime();
if (Arity.checkArgumentCount(runtime, args, 0, 2) == 2) {
lim = RubyNumeric.fix2int(args[1]);
if (lim == 1) {
if (value.realSize == 0) return runtime.newArray();
return runtime.newArray(this);
} else if (lim > 0) {
limit = true;
}
if (lim > 0) limit = true;
i = 1;
}
IRubyObject spat = (args.length == 0 || args[0].isNil()) ? null : args[0];
boolean awkSplit = false;
if (spat == null && (spat = runtime.getGlobalVariables().get("$;")).isNil()) {
awkSplit = true;
} else {
if (spat instanceof RubyString && ((RubyString)spat).value.realSize == 1) {
if (((RubyString)spat).value.get(0) == ' ') {
awkSplit = true;
}
}
}
RubyArray result = runtime.newArray();
beg = 0;
if (awkSplit) { // awk split
int ptr = value.begin;
int eptr = ptr + value.realSize;
byte[]buff = value.bytes;
boolean skip = true;
for (end = beg = 0; ptr < eptr; ptr++) {
if (skip) {
if (Character.isWhitespace((char)(buff[ptr] & 0xff))) {
beg++;
} else {
end = beg + 1;
skip = false;
if (limit && lim <= i) break;
}
} else {
if (Character.isWhitespace((char)(buff[ptr] & 0xff))) {
result.append(makeShared(beg, end - beg));
skip = true;
beg = end + 1;
if (limit) i++;
} else {
end++;
}
}
}
if (value.realSize > 0 && (limit || value.realSize > beg || lim < 0)) {
if (value.length() == beg) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(makeShared(beg, value.realSize - beg));
}
}
} else if(spat instanceof RubyString) { // string split
ByteList rsep = ((RubyString)spat).value;
int rslen = rsep.realSize;
int ptr = value.begin;
int pend = ptr + value.realSize;
byte[]buff = value.bytes;
int p = ptr;
byte lastVal = rslen == 0 ? 0 : rsep.bytes[rsep.begin+rslen-1];
int s = p;
p+=rslen;
for(; p < pend; p++) {
if(ptr<p && (rslen ==0 || (buff[p-1] == lastVal &&
(rslen <= 1 ||
ByteList.memcmp(rsep.bytes, rsep.begin, rslen, buff, p-rslen, rslen) == 0)))) {
result.append(makeShared(s-ptr, (p - s) - rslen));
s = p;
if(limit) {
i++;
if(lim<=i) {
p = pend;
break;
}
}
}
}
if(s != pend) {
if(p > pend) {
p = pend;
}
if(!(limit && lim<=i) && p-rslen >= ptr && ByteList.memcmp(rsep.bytes, rsep.begin, rslen, buff, p-rslen, rslen) == 0) {
result.append(makeShared(s-ptr, (p - s)-rslen));
if(lim < 0) {
result.append(newEmptyString(runtime, getMetaClass()));
}
} else {
result.append(makeShared(s-ptr, p - s));
}
}
} else { // regexp split
spat = getPat(spat,true);
int start = beg;
int idx;
boolean last_null = false;
Region regs;
while((end = ((RubyRegexp)spat).search(this, start, false)) >= 0) {
regs = ((RubyMatchData)getRuntime().getCurrentContext().getCurrentFrame().getBackRef()).regs;
if(start == end && regs.beg[0] == regs.end[0]) {
if(value.realSize == 0) {
result.append(newEmptyString(runtime, getMetaClass()));
break;
} else if(last_null) {
result.append(substr(beg, ((RubyRegexp)spat).getKCode().getEncoding().length(value.bytes[value.begin+beg])));
beg = start;
} else {
if(start < value.realSize) {
start += ((RubyRegexp)spat).getKCode().getEncoding().length(value.bytes[value.begin+start]);
} else {
start++;
}
last_null = true;
continue;
}
} else {
result.append(substr(beg,end-beg));
beg = start = regs.end[0];
}
last_null = false;
for(idx=1; idx < regs.numRegs; idx++) {
if(regs.beg[idx] == -1) {
continue;
}
if(regs.beg[idx] == regs.end[idx]) {
tmp = newEmptyString(runtime, getMetaClass());
} else {
tmp = substr(regs.beg[idx],regs.end[idx]-regs.beg[idx]);
}
result.append(tmp);
}
if(limit && lim <= ++i) {
break;
}
}
if (value.realSize > 0 && (limit || value.realSize > beg || lim < 0)) {
if (value.realSize == beg) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(substr(beg, value.realSize - beg));
}
}
} // regexp split
if (!limit && lim == 0) {
while (result.size() > 0 && ((RubyString)result.eltInternal(result.size() - 1)).value.realSize == 0)
result.pop();
}
return result;
}
|
diff --git a/forum/webapp/src/main/java/org/exoplatform/forum/webui/UIForumPortlet.java b/forum/webapp/src/main/java/org/exoplatform/forum/webui/UIForumPortlet.java
index 4f7f437f..58beae40 100644
--- a/forum/webapp/src/main/java/org/exoplatform/forum/webui/UIForumPortlet.java
+++ b/forum/webapp/src/main/java/org/exoplatform/forum/webui/UIForumPortlet.java
@@ -1,1065 +1,1065 @@
/***************************************************************************
* Copyright (C) 2003-2007 eXo Platform SAS.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see<http://www.gnu.org/licenses/>.
***************************************************************************/
package org.exoplatform.forum.webui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import javax.portlet.ActionResponse;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletSession;
import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import org.exoplatform.container.ExoContainerContext;
import org.exoplatform.container.PortalContainer;
import org.exoplatform.forum.ForumUtils;
import org.exoplatform.forum.common.CommonUtils;
import org.exoplatform.forum.common.UserHelper;
import org.exoplatform.forum.common.webui.UIPopupAction;
import org.exoplatform.forum.common.webui.UIPopupContainer;
import org.exoplatform.forum.common.webui.WebUIUtils;
import org.exoplatform.forum.info.ForumParameter;
import org.exoplatform.forum.service.Category;
import org.exoplatform.forum.service.Forum;
import org.exoplatform.forum.service.ForumService;
import org.exoplatform.forum.service.ForumServiceUtils;
import org.exoplatform.forum.service.Post;
import org.exoplatform.forum.service.Topic;
import org.exoplatform.forum.service.UserProfile;
import org.exoplatform.forum.service.Utils;
import org.exoplatform.forum.webui.popup.UIPostForm;
import org.exoplatform.forum.webui.popup.UIPrivateMessageForm;
import org.exoplatform.forum.webui.popup.UISettingEditModeForm;
import org.exoplatform.forum.webui.popup.UIViewPostedByUser;
import org.exoplatform.forum.webui.popup.UIViewTopicCreatedByUser;
import org.exoplatform.forum.webui.popup.UIViewUserProfile;
import org.exoplatform.portal.application.PortalRequestContext;
import org.exoplatform.portal.application.RequestNavigationData;
import org.exoplatform.portal.webui.util.Util;
import org.exoplatform.services.organization.OrganizationService;
import org.exoplatform.social.common.router.ExoRouter;
import org.exoplatform.social.common.router.ExoRouter.Route;
import org.exoplatform.social.core.space.SpaceUtils;
import org.exoplatform.social.core.space.model.Space;
import org.exoplatform.social.core.space.spi.SpaceService;
import org.exoplatform.web.application.ApplicationMessage;
import org.exoplatform.webui.application.WebuiApplication;
import org.exoplatform.webui.application.WebuiRequestContext;
import org.exoplatform.webui.application.portlet.PortletApplication;
import org.exoplatform.webui.application.portlet.PortletRequestContext;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.config.annotation.EventConfig;
import org.exoplatform.webui.core.UIComponent;
import org.exoplatform.webui.core.UIPopupWindow;
import org.exoplatform.webui.core.UIPortletApplication;
import org.exoplatform.webui.core.lifecycle.UIApplicationLifecycle;
import org.exoplatform.webui.event.Event;
import org.exoplatform.webui.event.EventListener;
import org.exoplatform.ws.frameworks.cometd.ContinuationService;
import org.mortbay.cometd.AbstractBayeux;
import org.mortbay.cometd.continuation.EXoContinuationBayeux;
@ComponentConfig(
lifecycle = UIApplicationLifecycle.class,
template = "app:/templates/forum/webui/UIForumPortlet.gtmpl",
events = {
@EventConfig(listeners = UIForumPortlet.ReLoadPortletEventActionListener.class),
@EventConfig(listeners = UIForumPortlet.ViewPublicUserInfoActionListener.class ) ,
@EventConfig(listeners = UIForumPortlet.ViewPostedByUserActionListener.class ),
@EventConfig(listeners = UIForumPortlet.PrivateMessageActionListener.class ),
@EventConfig(listeners = UIForumPortlet.ViewThreadByUserActionListener.class ),
@EventConfig(listeners = UIForumPortlet.OpenLinkActionListener.class)
}
)
public class UIForumPortlet extends UIPortletApplication {
public static String QUICK_REPLY_EVENT_PARAMS = "UIForumPortlet.QuickReplyEventParams";
public static String FORUM_POLL_EVENT_PARAMS = "UIForumPortlet.ForumPollEventParams";
public static String RULE_EVENT_PARAMS = "UIForumPortlet.RuleEventParams";
public static String FORUM_MODERATE_EVENT_PARAMS = "UIForumPortlet.ForumModerateEvent";
private ForumService forumService;
private boolean isCategoryRendered = true;
private boolean isForumRendered = false;
private boolean isTagRendered = false;
private boolean isSearchRendered = false;
private boolean isShowPoll = false;
private boolean isShowModerators = false;
private boolean isShowRules = false;
private boolean isShowIconsLegend = false;
private boolean isShowStatistics = false;
private boolean isShowQuickReply = false;
private UserProfile userProfile = null;
private boolean enableIPLogging = false;
private boolean prefForumActionBar = false;
private boolean isRenderActionBar = false;
private boolean enableBanIP = false;
private boolean useAjax = true;
protected boolean forumSpDeleted = false;
private int dayForumNewPost = 0;
private String categorySpId = "";
private String forumSpId = null;
private String spaceGroupId = null;
protected String spaceDisplayName = null;
private List<String> invisibleForums = new ArrayList<String>();
private List<String> invisibleCategories = new ArrayList<String>();
private PortletMode portletMode;
public UIForumPortlet() throws Exception {
forumService = (ForumService) ExoContainerContext.getCurrentContainer().getComponentInstanceOfType(ForumService.class);
addChild(UIBreadcumbs.class, null, null);
isRenderActionBar = !UserHelper.isAnonim();
addChild(UIForumActionBar.class, null, null).setRendered(isRenderActionBar);
addChild(UICategoryContainer.class, null, null).setRendered(isCategoryRendered);
addChild(UIForumContainer.class, null, null).setRendered(isForumRendered);
addChild(UITopicsTag.class, null, null).setRendered(isTagRendered);
addChild(UISearchForm.class, null, null).setRendered(isSearchRendered);
UIPopupAction popupAction = addChild(UIPopupAction.class, null, "UIForumPopupAction");
popupAction.getChild(UIPopupWindow.class).setId("UIForumPopupWindow");
try {
loadPreferences();
} catch (Exception e) {
log.warn("Failed to load portlet preferences", e);
}
}
public void processRender(WebuiApplication app, WebuiRequestContext context) throws Exception {
PortletRequestContext portletReqContext = (PortletRequestContext) context;
portletMode = portletReqContext.getApplicationMode();
if (portletMode == PortletMode.VIEW) {
isRenderActionBar = !UserHelper.isAnonim();
if (getChild(UIBreadcumbs.class) == null) {
if (getChild(UISettingEditModeForm.class) != null)
removeChild(UISettingEditModeForm.class);
addChild(UIBreadcumbs.class, null, null);
addChild(UIForumActionBar.class, null, null).setRendered(isRenderActionBar);
UICategoryContainer categoryContainer = addChild(UICategoryContainer.class, null, null).setRendered(isCategoryRendered);
addChild(UIForumContainer.class, null, null).setRendered(isForumRendered);
addChild(UITopicsTag.class, null, null).setRendered(isTagRendered);
addChild(UISearchForm.class, null, null).setRendered(isSearchRendered);
updateIsRendered(ForumUtils.CATEGORIES);
categoryContainer.updateIsRender(true);
}
updateCurrentUserProfile();
} else if (portletMode == PortletMode.EDIT) {
if (getChild(UISettingEditModeForm.class) == null) {
UISettingEditModeForm editModeForm = addChild(UISettingEditModeForm.class, null, null);
editModeForm.setInitComponent();
removeAllChildPorletView();
}
}
try {
renderComponentByURL(context);
} catch (Exception e) {
log.error("Can not open component by url, view exception: ", e);
}
super.processRender(app, context);
}
private void removeAllChildPorletView() {
if (getChild(UIBreadcumbs.class) != null) {
removeChild(UIBreadcumbs.class);
removeChild(UIForumActionBar.class);
removeChild(UICategoryContainer.class);
removeChild(UIForumContainer.class);
removeChild(UITopicsTag.class);
removeChild(UISearchForm.class);
}
}
public void renderComponentByURL(WebuiRequestContext context) throws Exception {
forumSpDeleted = false;
PortalRequestContext portalContext = Util.getPortalRequestContext();
String isAjax = portalContext.getRequestParameter("ajaxRequest");
if (isAjax != null && Boolean.parseBoolean(isAjax))
return;
String url = ((HttpServletRequest) portalContext.getRequest()).getRequestURL().toString();
String pageNodeSelected = ForumUtils.SLASH + Util.getUIPortal().getSelectedUserNode().getURI();
String portalName = Util.getUIPortal().getName();
if(url.contains(portalName + pageNodeSelected)) {
url = url.substring(url.lastIndexOf(portalName + pageNodeSelected)+ (portalName + pageNodeSelected).length());
} else if(url.contains(pageNodeSelected)) {
url = url.substring(url.lastIndexOf(pageNodeSelected)+ pageNodeSelected.length());
}
if(!ForumUtils.isEmpty(url)) {
url = (url.contains(ForumUtils.SLASH+Utils.FORUM_SERVICE)) ? url.substring(url.lastIndexOf(Utils.FORUM_SERVICE)) :
((url.contains(ForumUtils.SLASH+Utils.CATEGORY)) ? url.substring(url.lastIndexOf(ForumUtils.SLASH+Utils.CATEGORY)+1) :
((url.contains(ForumUtils.SLASH+Utils.TOPIC)) ? url.substring(url.lastIndexOf(ForumUtils.SLASH+Utils.TOPIC)+1) :
((url.contains(ForumUtils.SLASH+Utils.FORUM)) ? url.substring(url.lastIndexOf(ForumUtils.SLASH+Utils.FORUM)+1) : url)));
} else {
if (!ForumUtils.isEmpty(getForumIdOfSpace())){
url = getForumIdOfSpace();
}
}
if (!ForumUtils.isEmpty(url) && url.length() > Utils.FORUM.length()) {
if(url.indexOf("&") > 0) {
url = url.substring(0, url.indexOf("&"));
}
calculateRenderComponent(url, context);
context.addUIComponentToUpdateByAjax(this);
}
}
public String getForumIdOfSpace() {
PortalRequestContext plcontext = Util.getPortalRequestContext();
String requestPath = plcontext.getControllerContext().getParameter(RequestNavigationData.REQUEST_PATH);
Route route = ExoRouter.route(requestPath);
if (route == null){
return null;
}
//
String spacePrettyName = route.localArgs.get("spacePrettyName");
if (spacePrettyName != null && ForumUtils.isEmpty(forumSpId)) {
SpaceService sService = getApplicationComponent(SpaceService.class);
Space space = sService.getSpaceByPrettyName(spacePrettyName);
try {
spaceGroupId = space.getGroupId();
forumSpId = Utils.FORUM_SPACE_ID_PREFIX + spaceGroupId.replaceAll(SpaceUtils.SPACE_GROUP + CommonUtils.SLASH, CommonUtils.EMPTY_STR);
spaceDisplayName = space.getDisplayName();
OrganizationService service = getApplicationComponent(OrganizationService.class);
String parentGrId = service.getGroupHandler().findGroupById(spaceGroupId).getParentId();
categorySpId = Utils.CATEGORY + parentGrId.replaceAll(CommonUtils.SLASH, CommonUtils.EMPTY_STR);
} catch (Exception e) {
return null;
}
}
return forumSpId;
}
public void updateIsRendered(String selected){
if (selected.equals(ForumUtils.CATEGORIES)) {
isCategoryRendered = true;
isForumRendered = false;
isTagRendered = false;
isSearchRendered = false;
} else if (selected.equals(ForumUtils.FORUM)) {
isForumRendered = true;
isCategoryRendered = false;
isTagRendered = false;
isSearchRendered = false;
} else if (selected.equals(ForumUtils.TAG)) {
isTagRendered = true;
isForumRendered = false;
isCategoryRendered = false;
isSearchRendered = false;
} else {
isTagRendered = false;
isForumRendered = false;
isCategoryRendered = false;
isSearchRendered = true;
}
if (prefForumActionBar == false && (isCategoryRendered == false || isSearchRendered)) {
isRenderActionBar = false;
}
getChild(UICategoryContainer.class).setRendered(isCategoryRendered);
getChild(UIForumActionBar.class).setRendered(isRenderActionBar);
getChild(UIForumContainer.class).setRendered(isForumRendered);
getChild(UITopicsTag.class).setRendered(isTagRendered);
getChild(UISearchForm.class).setRendered(isSearchRendered);
if (!isForumRendered) {
this.setRenderQuickReply();
}
}
public void renderForumHome() throws Exception{
updateIsRendered(ForumUtils.CATEGORIES);
UICategoryContainer categoryContainer = getChild(UICategoryContainer.class);
categoryContainer.updateIsRender(true);
categoryContainer.getChild(UICategories.class).setIsRenderChild(false);
getChild(UIBreadcumbs.class).setUpdataPath(Utils.FORUM_SERVICE);
}
public void setRenderQuickReply() {
PortletRequestContext pcontext = (PortletRequestContext) WebuiRequestContext.getCurrentInstance();
PortletSession portletSession = pcontext.getRequest().getPortletSession();
ActionResponse actionRes = null;
if (pcontext.getResponse() instanceof ActionResponse) {
actionRes = (ActionResponse) pcontext.getResponse();
}
ForumParameter param = new ForumParameter();
param.setRenderQuickReply(false);
param.setRenderPoll(false);
param.setRenderModerator(false);
param.setRenderRule(false);
if (actionRes != null) {
actionRes.setEvent(new QName("QuickReplyEvent"), param);
actionRes.setEvent(new QName("ForumPollEvent"), param);
actionRes.setEvent(new QName("ForumModerateEvent"), param);
actionRes.setEvent(new QName("ForumRuleEvent"), param);
} else {
portletSession.setAttribute(UIForumPortlet.QUICK_REPLY_EVENT_PARAMS, param, PortletSession.APPLICATION_SCOPE);
portletSession.setAttribute(UIForumPortlet.FORUM_POLL_EVENT_PARAMS, param, PortletSession.APPLICATION_SCOPE);
portletSession.setAttribute(UIForumPortlet.FORUM_MODERATE_EVENT_PARAMS, param, PortletSession.APPLICATION_SCOPE);
portletSession.setAttribute(UIForumPortlet.RULE_EVENT_PARAMS, param, PortletSession.APPLICATION_SCOPE);
}
}
public void loadPreferences() throws Exception {
WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
if (context instanceof PortletRequestContext){
PortletRequestContext pContext = (PortletRequestContext) context;
PortletPreferences portletPref = pContext.getRequest().getPreferences();
invisibleCategories.clear();
invisibleForums.clear();
prefForumActionBar = Boolean.parseBoolean(portletPref.getValue("showForumActionBar", ForumUtils.EMPTY_STR));
dayForumNewPost = Integer.parseInt(portletPref.getValue("forumNewPost", ForumUtils.EMPTY_STR));
useAjax = Boolean.parseBoolean(portletPref.getValue("useAjax", ForumUtils.EMPTY_STR));
enableIPLogging = Boolean.parseBoolean(portletPref.getValue("enableIPLogging", ForumUtils.EMPTY_STR));
enableBanIP = Boolean.parseBoolean(portletPref.getValue("enableIPFiltering", ForumUtils.EMPTY_STR));
isShowPoll = Boolean.parseBoolean(portletPref.getValue("isShowPoll", ForumUtils.EMPTY_STR));
isShowModerators = Boolean.parseBoolean(portletPref.getValue("isShowModerators", ForumUtils.EMPTY_STR));
isShowRules = Boolean.parseBoolean(portletPref.getValue("isShowRules", ForumUtils.EMPTY_STR));
isShowQuickReply = Boolean.parseBoolean(portletPref.getValue("isShowQuickReply", ForumUtils.EMPTY_STR));
isShowStatistics = Boolean.parseBoolean(portletPref.getValue("isShowStatistics", ForumUtils.EMPTY_STR));
isShowIconsLegend = Boolean.parseBoolean(portletPref.getValue("isShowIconsLegend", ForumUtils.EMPTY_STR));
invisibleCategories.addAll(getListInValus(portletPref.getValue("invisibleCategories", ForumUtils.EMPTY_STR)));
invisibleForums.addAll(getListInValus(portletPref.getValue("invisibleForums", ForumUtils.EMPTY_STR)));
if (invisibleCategories.size() == 1 && invisibleCategories.get(0).equals(" "))
invisibleCategories.clear();
}
}
private List<String> getListInValus(String value) throws Exception {
List<String> list = new ArrayList<String>();
if (!ForumUtils.isEmpty(value)) {
list.addAll(Arrays.asList(ForumUtils.addStringToString(value, value)));
}
return list;
}
public String[] getImportJSTagCode() {
return new String[] { "shCore", "shBrushBash", "shBrushCpp", "shBrushCSharp", "shBrushCss", "shBrushDelphi", "shBrushGroovy", "shBrushJava", "shBrushJScript", "shBrushPhp", "shBrushPython", "shBrushRuby", "shBrushScala", "shBrushSql", "shBrushVb", "shBrushXml" };
}
public List<String> getInvisibleForums() {
return invisibleForums;
}
public List<String> getInvisibleCategories() {
return invisibleCategories;
}
public boolean isEnableIPLogging() {
return enableIPLogging;
}
public boolean isEnableBanIp() {
return enableBanIP;
}
public boolean isShowForumActionBar() {
return prefForumActionBar;
}
public boolean isShowPoll() {
return isShowPoll;
}
public boolean isShowModerators() {
return isShowModerators;
}
public boolean isShowRules() {
return isShowRules;
}
public boolean isShowIconsLegend() {
return isShowIconsLegend;
}
public boolean isShowQuickReply() {
return isShowQuickReply;
}
public boolean isShowStatistics() {
return isShowStatistics;
}
public boolean isUseAjax() {
return useAjax;
}
public int getDayForumNewPost() {
return dayForumNewPost;
}
public String getSpaceGroupId() {
return spaceGroupId;
}
public void cancelAction() throws Exception {
WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
UIPopupAction popupAction = getChild(UIPopupAction.class);
popupAction.deActivate();
context.addUIComponentToUpdateByAjax(popupAction);
}
public void updateCurrentUserProfile() {
try {
String userId = UserHelper.getCurrentUser();
if (enableBanIP) {
userProfile = forumService.getDefaultUserProfile(userId, WebUIUtils.getRemoteIP());
} else {
userProfile = forumService.getDefaultUserProfile(userId, null);
}
if (!ForumUtils.isEmpty(userId))
userProfile.setEmail(UserHelper.getUserByUserId(userId).getEmail());
if (userProfile.getIsBanned())
userProfile.setUserRole((long) 3);
} catch (Exception e) {
userProfile = new UserProfile();
}
if(UserProfile.USER_DELETED == userProfile.getUserRole() ||
UserProfile.GUEST == userProfile.getUserRole() ) {
isRenderActionBar = false;
}
UIForumActionBar actionBar = getChild(UIForumActionBar.class);
if (actionBar != null) {
actionBar.setRendered(isRenderActionBar);
}
}
public UserProfile getUserProfile() {
if (userProfile == null) {
updateCurrentUserProfile();
}
return userProfile;
}
public void updateAccessTopic(String topicId) throws Exception {
String userId = getUserProfile().getUserId();
if (userId != null && userId.length() > 0) {
forumService.updateTopicAccess(userId, topicId);
}
userProfile.setLastTimeAccessTopic(topicId, CommonUtils.getGreenwichMeanTime().getTimeInMillis());
}
public void updateAccessForum(String forumId) throws Exception {
String userId = getUserProfile().getUserId();
if (userId != null && userId.length() > 0) {
forumService.updateForumAccess(userId, forumId);
}
userProfile.setLastTimeAccessForum(forumId, CommonUtils.getGreenwichMeanTime().getTimeInMillis());
}
public void removeCacheUserProfile() {
try {
forumService.removeCacheUserProfile(getUserProfile().getUserId());
} catch (Exception e) {
log.debug("Failed to remove cache userprofile with user: " + userProfile.getUserId());
}
}
public String getPortletLink(String actionName, String userName) {
try {
return event(actionName, userName);
} catch (Exception e) {
log.debug("Failed to set link to view info user.", e);
return null;
}
}
protected String getCometdContextName() {
EXoContinuationBayeux bayeux = (EXoContinuationBayeux) PortalContainer.getInstance()
.getComponentInstanceOfType(AbstractBayeux.class);
return (bayeux == null ? "cometd" : bayeux.getCometdContextName());
}
public String getUserToken() {
try {
ContinuationService continuation = (ContinuationService) PortalContainer.getInstance()
.getComponentInstanceOfType(ContinuationService.class);
return continuation.getUserToken(getUserProfile().getUserId());
} catch (Exception e) {
log.error("Could not retrieve continuation token for user " + userProfile.getUserId(), e);
}
return ForumUtils.EMPTY_STR;
}
protected void initSendNotification() throws Exception {
if(getUserProfile().getUserRole() <=2 ) {
String postLink = ForumUtils.createdSubForumLink(Utils.TOPIC, "topicID", false);
StringBuilder init = new StringBuilder("forumNotify.initCometd('");
init.append(userProfile.getUserId()).append("', '")
.append(getUserToken()).append("', '")
.append(getCometdContextName()).append("');");
StringBuilder initParam = new StringBuilder();
initParam.append("forumNotify.initParam(\"").append(getId()).append("\", \"").append(postLink).append("\", ")
.append("{")
.append("notification : \"").append(WebUIUtils.getLabel(getId(), "Notification")).append("\", ")
.append("message : \"").append(WebUIUtils.getLabel(getId(), "message")).append("\", ")
.append("post : \"").append(WebUIUtils.getLabel(getId(), "post")).append("\",")
.append("privatePost : \"").append(WebUIUtils.getLabel(getId(), "NewPrivatePost")).append("\", ")
.append("privateMessage : \"").append(WebUIUtils.getLabel(getId(), "NewPrivateMessage")).append("\", ")
.append("from : \"").append(WebUIUtils.getLabel(getId(), "from")).append("\", ")
.append("briefContent : \"").append(WebUIUtils.getLabel(getId(), "briefContent")).append("\", ")
.append("goDirectly : \"").append(WebUIUtils.getLabel(getId(), "GoDirectly")).append("\", ")
.append("clickHere : \"").append(WebUIUtils.getLabel(getId(), "ClickHere")).append("\", ")
.append("title : \"").append(WebUIUtils.getLabel(getId(), "Title")).append("\"")
.append("});");
//
ForumUtils.addScripts("ForumSendNotification", "forumNotify", new String[] { initParam.toString(), init.toString() });
}
}
private boolean isArrayNotNull(String[] strs) {
if (strs != null && strs.length > 0 && !strs[0].equals(" "))
return true;// private
else
return false;
}
public boolean checkForumHasAddTopic(String categoryId, String forumId) throws Exception {
if (getUserProfile().getUserRole() == 0) return true;
if (getUserProfile().getUserId().contains(UserProfile.USER_GUEST)) return false;
try {
Forum forum = (Forum) forumService.getForum(categoryId, forumId);
if (forum.getIsClosed() || forum.getIsLock())
return false;
if(userProfile.getUserRole() == 1 && ForumServiceUtils.hasPermission(forum.getModerators(), userProfile.getUserId())) {
return true;
}
Category cate = (Category) forumService.getCategory(categoryId);
boolean isAdd = true;
if(!Utils.isEmpty(cate.getUserPrivate())) {
isAdd = ForumServiceUtils.hasPermission(cate.getUserPrivate(), userProfile.getUserId());
}
if(isAdd) {
if (userProfile.getUserRole() > 1) {
String[] canCreadTopic = ForumUtils.arraysMerge(forum.getCreateTopicRole(), cate.getCreateTopicRole());
if (!Utils.isEmpty(canCreadTopic) && !canCreadTopic[0].equals(" ")) {
return ForumServiceUtils.hasPermission(canCreadTopic, userProfile.getUserId());
}
}
} else return false;
} catch (Exception e) {
log.debug("Failed to check: " + e.getMessage(), e);
return false;
}
return true;
}
public boolean checkForumHasAddPost(String categoryId, String forumId, String topicId) throws Exception {
if (getUserProfile().getUserRole() == 0) return true;
if (getUserProfile().getUserId().contains(UserProfile.USER_GUEST)) return false;
try {
Topic topic = (Topic) forumService.getObjectNameById(topicId, Utils.TOPIC);
if (topic.getIsClosed() || topic.getIsLock())
return false;
Forum forum = (Forum) forumService.getObjectNameById(forumId, Utils.FORUM);
if (forum.getIsClosed() || forum.getIsLock())
return false;
Category cate = (Category) forumService.getObjectNameById(categoryId, Utils.CATEGORY);
boolean isAdd = true;
if(!Utils.isEmpty(cate.getUserPrivate())) {
isAdd = ForumServiceUtils.hasPermission(cate.getUserPrivate(), userProfile.getUserId());
}
if(isAdd) {
if (userProfile.getUserRole() > 1 || (userProfile.getUserRole() == 1 && !ForumServiceUtils.hasPermission(forum.getModerators(), userProfile.getUserId()))) {
if (!topic.getIsActive() || !topic.getIsActiveByForum())
return false;
String[] canCreadPost = ForumUtils.arraysMerge(cate.getPoster(), ForumUtils.arraysMerge(topic.getCanPost(), forum.getPoster()));
if (!ForumUtils.isArrayEmpty(canCreadPost)) {
return ForumServiceUtils.hasPermission(canCreadPost, userProfile.getUserId());
}
}
} else return false;
} catch (Exception e) {
log.debug("Failed to check: " + e.getMessage(), e);
return false;
}
return true;
}
public boolean checkCanView(Category cate, Forum forum, Topic topic) throws Exception {
// check category scoping
if(invisibleCategories != null && invisibleCategories.isEmpty() == false
&& invisibleCategories.contains(cate.getId()) == false) {
return false;
}
// check forum scoping
if(forum != null && invisibleForums != null && invisibleForums.isEmpty() == false
&& invisibleForums.contains(forum.getId()) == false) {
return false;
}
//
if (getUserProfile().getUserRole() == 0)
return true;
List<String> userBound = UserHelper.getAllGroupAndMembershipOfUser(null);
String[] viewer = cate.getUserPrivate();
if (isArrayNotNull(viewer)) {
if (!Utils.hasPermission(Arrays.asList(viewer), userBound))
return false;
}
if (forum != null) {
if (isArrayNotNull(forum.getModerators())) {
if (Utils.hasPermission(Arrays.asList(forum.getModerators()), userBound))
return true;
} else if (forum.getIsClosed())
return false;
}
if (topic != null) {
List<String> list = new ArrayList<String>();
list = ForumUtils.addArrayToList(list, topic.getCanView());
list = ForumUtils.addArrayToList(list, forum.getViewer());
list = ForumUtils.addArrayToList(list, cate.getViewer());
if (!list.isEmpty() && topic.getOwner() != null)
list.add(topic.getOwner());
if (topic.getIsClosed() || !topic.getIsActive() || !topic.getIsActiveByForum() || !topic.getIsApproved() || topic.getIsWaiting() || (!list.isEmpty() && !Utils.hasPermission(list, userBound)))
return false;
}
return true;
}
public static void showWarningMessage(WebuiRequestContext context, String key, String... args) {
context.getUIApplication().addMessage(new ApplicationMessage(key, args, ApplicationMessage.WARNING));
}
public void calculateRenderComponent(String path, WebuiRequestContext context) throws Exception {
ResourceBundle res = context.getApplicationResourceBundle();
if (path.equals(Utils.FORUM_SERVICE)) {
renderForumHome();
- } else if (path.indexOf(ForumUtils.FIELD_SEARCHFORUM_LABEL) >= 0) {
+ } else if (path.equals(ForumUtils.FIELD_SEARCHFORUM_LABEL)) {
updateIsRendered(ForumUtils.FIELD_SEARCHFORUM_LABEL);
UISearchForm searchForm = getChild(UISearchForm.class);
searchForm.setPath(ForumUtils.EMPTY_STR);
searchForm.setSelectType(path.replaceFirst(ForumUtils.FIELD_SEARCHFORUM_LABEL, ""));
searchForm.setSearchOptionsObjectType(ForumUtils.EMPTY_STR);
path = ForumUtils.FIELD_EXOFORUM_LABEL;
- } else if (path.lastIndexOf(Utils.TAG) >= 0) {
+ } else if (path.indexOf(Utils.TAG) == 0) {
updateIsRendered(ForumUtils.TAG);
getChild(UITopicsTag.class).setIdTag(path);
} else if (isRenderedTopic(path)) {
boolean isReply = false, isQuote = false;
if (path.indexOf("/true") > 0) {
isQuote = true;
path = path.replaceFirst("/true", ForumUtils.EMPTY_STR);
} else if (path.indexOf("/false") > 0) {
isReply = true;
path = path.replaceFirst("/false", ForumUtils.EMPTY_STR);
}
if(path.indexOf(Utils.CATEGORY) > 0) {
path = path.substring(path.indexOf(Utils.CATEGORY));
}
String[] id = path.split(ForumUtils.SLASH);
String postId = "top";
int page = 0;
if (path.indexOf(ForumUtils.VIEW_LAST_POST) > 0) {
postId = ForumUtils.VIEW_LAST_POST;
path = path.replace(ForumUtils.SLASH + ForumUtils.VIEW_LAST_POST, ForumUtils.EMPTY_STR);
id = path.split(ForumUtils.SLASH);
} else if(path.indexOf(Utils.POST) > 0) {
postId = id[id.length - 1];
path = path.substring(0, path.lastIndexOf(ForumUtils.SLASH));
id = path.split(ForumUtils.SLASH);
} else if (id.length > 1) {
try {
page = Integer.parseInt(id[id.length - 1]);
} catch (NumberFormatException e) {
if (log.isDebugEnabled()){
log.debug("Failed to parse number " + id[id.length - 1], e);
}
}
if (page > 0) {
path = path.replace(ForumUtils.SLASH + id[id.length - 1], ForumUtils.EMPTY_STR);
id = path.split(ForumUtils.SLASH);
} else
page = 0;
}
try {
Topic topic;
if (id.length > 1) {
topic = this.forumService.getTopicByPath(path, false);
} else {
topic = (Topic) this.forumService.getObjectNameById(path, Utils.TOPIC);
}
if (topic != null) {
if (path.indexOf(ForumUtils.SLASH) < 0) {
path = topic.getPath();
path = path.substring(path.indexOf(Utils.CATEGORY));
id = path.split(ForumUtils.SLASH);
}
Category category = this.forumService.getCategory(id[0]);
Forum forum = this.forumService.getForum(id[0], id[1]);
if (this.checkCanView(category, forum, topic)) {
this.updateIsRendered(ForumUtils.FORUM);
UIForumContainer uiForumContainer = this.getChild(UIForumContainer.class);
UITopicDetailContainer uiTopicDetailContainer = uiForumContainer.getChild(UITopicDetailContainer.class);
uiForumContainer.setIsRenderChild(false);
uiForumContainer.getChild(UIForumDescription.class).setForum(forum);
UITopicDetail uiTopicDetail = uiTopicDetailContainer.getChild(UITopicDetail.class);
uiTopicDetail.setIsEditTopic(true);
uiTopicDetail.setUpdateForum(forum);
uiTopicDetail.initInfoTopic(id[0], id[1], topic, page);
uiTopicDetailContainer.getChild(UITopicPoll.class).updateFormPoll(id[0], id[1], topic.getId());
uiTopicDetail.setIdPostView(postId);
uiTopicDetail.setLastPostId(((path.indexOf(Utils.POST) < 0) ? ForumUtils.EMPTY_STR : postId));
if (isReply || isQuote) {
if (uiTopicDetail.getCanPost()) {
try {
UIPopupAction popupAction = this.getChild(UIPopupAction.class);
UIPopupContainer popupContainer = popupAction.createUIComponent(UIPopupContainer.class, null, null);
UIPostForm postForm = popupContainer.addChild(UIPostForm.class, null, null);
boolean isMod = ForumServiceUtils.hasPermission(forum.getModerators(), this.userProfile.getUserId());
postForm.setPostIds(id[0], id[1], topic.getId(), topic);
postForm.setMod(isMod);
Post post = this.forumService.getPost(id[0], id[1], topic.getId(), postId);
if (isQuote) {
if (post != null) {
postForm.updatePost(postId, true, (post.getUserPrivate().length == 2), post);
popupContainer.setId("UIQuoteContainer");
} else {
showWarningMessage(context, "UIBreadcumbs.msg.post-no-longer-exist", ForumUtils.EMPTY_STR);
uiTopicDetail.setIdPostView("normal");
}
} else {
if (post != null && post.getUserPrivate().length == 2) {
postForm.updatePost(post.getId(), false, true, post);
} else {
postForm.updatePost(ForumUtils.EMPTY_STR, false, false, null);
}
popupContainer.setId("UIAddPostContainer");
}
popupAction.activate(popupContainer, 900, 500);
context.addUIComponentToUpdateByAjax(popupAction);
} catch (Exception e) {
log.error(e);
}
} else {
showWarningMessage(context, "UIPostForm.msg.no-permission", ForumUtils.EMPTY_STR);
}
}
if (!UserHelper.isAnonim()) {
this.forumService.updateTopicAccess(userProfile.getUserId(), topic.getId());
this.getUserProfile().setLastTimeAccessTopic(topic.getId(), CommonUtils.getGreenwichMeanTime().getTimeInMillis());
}
} else {
showWarningMessage(context, "UIForumPortlet.msg.do-not-permission-view-topic",
new String[] {});
if (!ForumUtils.isEmpty(getForumIdOfSpace())) {
calculateRenderComponent(forumSpId, context);
} else {
renderForumHome();
path = Utils.FORUM_SERVICE;
}
}
} else if (ForumUtils.isEmpty(getForumIdOfSpace()) == false) {// open topic removed on forum of space
if (forumService.getForum(categorySpId, forumSpId) == null) {// the forum of space had been removed
forumSpDeleted = true;
removeAllChildPorletView();
log.info("The forum in space " + spaceDisplayName + " no longer exists.");
return;
} else {
showWarningMessage(context, "UIForumPortlet.msg.topicEmpty", ForumUtils.EMPTY_STR);
calculateRenderComponent(forumSpId, context);
}
} else {// open topic removed on normal forum.
showWarningMessage(context, "UIForumPortlet.msg.topicEmpty", ForumUtils.EMPTY_STR);
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} catch (Exception e) {// Unknown error
if (log.isDebugEnabled()){
log.debug("Failed to render forum link: [" + path + "]. Forum home will be rendered.\nCaused by:", e);
}
showWarningMessage(context, "UIShowBookMarkForm.msg.link-not-found", ForumUtils.EMPTY_STR);
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} else if ((path.lastIndexOf(Utils.FORUM) == 0 && path.lastIndexOf(Utils.CATEGORY) < 0) || (path.lastIndexOf(Utils.FORUM) > 0)) {
try {
Forum forum = null;
String cateId = null;
int page = 0;
if (path.indexOf(ForumUtils.SLASH) >= 0) {
String[] arr = path.split(ForumUtils.SLASH);
try {
page = Integer.parseInt(arr[arr.length - 1]);
} catch (Exception e) {
if (log.isDebugEnabled()){
log.debug("Failed to parse number " + arr[arr.length - 1], e);
}
}
if (arr[0].indexOf(Utils.CATEGORY) == 0) {
cateId = arr[0];
forum = this.forumService.getForum(cateId, arr[1]);
} else {
forum = (Forum) this.forumService.getObjectNameById(arr[0], Utils.FORUM);
}
}
if (forum == null) {
path = path.substring(path.lastIndexOf(ForumUtils.SLASH) + 1);
forum = (Forum) this.forumService.getObjectNameById(path, Utils.FORUM);
if (forum == null && path.equals(getForumIdOfSpace())) {
forum = forumService.getForum(this.categorySpId, path);
if(forum == null) {
forumSpDeleted = true;
removeAllChildPorletView();
log.info("The forum in space " + spaceDisplayName + " no longer exists.");
return;
}
}
}
if (cateId == null) {
cateId = forum.getCategoryId();
}
path = new StringBuilder(cateId).append("/").append(forum.getId()).toString();
Category category = this.forumService.getCategory(cateId);
if (this.checkCanView(category, forum, null)) {
this.updateIsRendered(ForumUtils.FORUM);
UIForumContainer forumContainer = this.findFirstComponentOfType(UIForumContainer.class);
forumContainer.setIsRenderChild(true);
forumContainer.getChild(UIForumDescription.class).setForum(forum);
UITopicContainer topicContainer = forumContainer.getChild(UITopicContainer.class);
topicContainer.setUpdateForum(cateId, forum, page);
if(!userProfile.getUserId().equals(UserProfile.USER_GUEST)) {
//
PortalRequestContext portalContext = Util.getPortalRequestContext();
String hasCreateTopic = portalContext.getRequestParameter(ForumUtils.HAS_CREATE_TOPIC);
if(!ForumUtils.isEmpty(hasCreateTopic) && Boolean.parseBoolean(hasCreateTopic)) {
Event<UIComponent> addTopicEvent = topicContainer.createEvent("AddTopic", Event.Phase.PROCESS, context);
if (addTopicEvent != null) {
addTopicEvent.broadcast();
}
} else {
String hasCreatePoll = portalContext.getRequestParameter(ForumUtils.HAS_CREATE_POLL);
if(!ForumUtils.isEmpty(hasCreatePoll) && Boolean.parseBoolean(hasCreatePoll)) {
Event<UIComponent> addTopicEvent = topicContainer.createEvent("AddPoll", Event.Phase.PROCESS, context);
if (addTopicEvent != null) {
addTopicEvent.broadcast();
}
}
}
}
} else {
showWarningMessage(context, "UIForumPortlet.msg.do-not-permission-view-forum",
new String[] {});
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} catch (Exception e) {
if (log.isDebugEnabled()){
log.debug("Failed to render forum link: [" + path + "]. Forum home will be rendered.\nCaused by:", e);
}
showWarningMessage(context, "UIShowBookMarkForm.msg.link-not-found",
new String[] { res.getString("UIForumPortlet.label.forum") });
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} else if (path.indexOf(Utils.CATEGORY) >= 0 && path.indexOf(ForumUtils.SLASH) < 0) {
UICategoryContainer categoryContainer = this.getChild(UICategoryContainer.class);
try {
Category category = this.forumService.getCategory(path);
if (this.checkCanView(category, null, null)) {
categoryContainer.getChild(UICategory.class).updateByLink(category);
categoryContainer.updateIsRender(false);
this.updateIsRendered(ForumUtils.CATEGORIES);
} else {
showWarningMessage(context, "UIForumPortlet.msg.do-not-permission-view-category",
new String[] {});
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} catch (Exception e) {
if (log.isDebugEnabled()){
log.debug("Failed to render forum link: [" + path + "]. Forum home will be rendered.\nCaused by:", e);
}
showWarningMessage(context, "UIShowBookMarkForm.msg.link-not-found", ForumUtils.EMPTY_STR);
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} else {
if (log.isDebugEnabled()){
log.debug("Failed to render forum link: [" + path + "]. Forum home will be rendered.");
}
showWarningMessage(context, "UIShowBookMarkForm.msg.link-not-found", ForumUtils.EMPTY_STR);
renderForumHome();
path = Utils.FORUM_SERVICE;
}
getChild(UIBreadcumbs.class).setUpdataPath(path);
}
/* Check if path is rendered topic. There are 2 syntax indicating a topic to render
* Case 1: topic(\w)*
* Case 2: CategorySpace(\w)* /ForumSpace(w)* /topic(w)*
* @param path the path to check
* @return isRendered Topic or not
*/
private boolean isRenderedTopic(String path) {
if (CommonUtils.isEmpty(path)) {
return false;
}
// Check case 1
if (path.startsWith(Utils.TOPIC)) {
return true;
}
// Check case 2
if (path.lastIndexOf("/" + Utils.TOPIC) >= 0) {
return true;
}
return false;
}
static public class ReLoadPortletEventActionListener extends EventListener<UIForumPortlet> {
public void execute(Event<UIForumPortlet> event) throws Exception {
UIForumPortlet forumPortlet = event.getSource();
ForumParameter params = (ForumParameter) event.getRequestContext().getAttribute(PortletApplication.PORTLET_EVENT_VALUE);
if (params.getTopicId() != null) {
forumPortlet.userProfile.setLastTimeAccessTopic(params.getTopicId(), CommonUtils.getGreenwichMeanTime().getTimeInMillis());
UITopicDetail topicDetail = forumPortlet.findFirstComponentOfType(UITopicDetail.class);
topicDetail.setIdPostView("lastpost");
}
if (params.isRenderPoll()) {
UITopicDetailContainer topicDetailContainer = forumPortlet.findFirstComponentOfType(UITopicDetailContainer.class);
topicDetailContainer.getChild(UITopicDetail.class).setIsEditTopic(true);
topicDetailContainer.getChild(UITopicPoll.class).setEditPoll(true);
}
event.getRequestContext().addUIComponentToUpdateByAjax(forumPortlet);
}
}
static public class OpenLinkActionListener extends EventListener<UIForumPortlet> {
public void execute(Event<UIForumPortlet> event) throws Exception {
UIForumPortlet forumPortlet = event.getSource();
String path = event.getRequestContext().getRequestParameter(OBJECTID);
if (ForumUtils.isEmpty(path)) {
ForumParameter params = (ForumParameter) event.getRequestContext().getAttribute(PortletApplication.PORTLET_EVENT_VALUE);
path = params.getPath();
}
if (ForumUtils.isEmpty(path))
return;
forumPortlet.calculateRenderComponent(path, event.getRequestContext());
event.getRequestContext().addUIComponentToUpdateByAjax(forumPortlet);
}
}
static public class ViewPublicUserInfoActionListener extends EventListener<UIForumPortlet> {
public void execute(Event<UIForumPortlet> event) throws Exception {
UIForumPortlet forumPortlet = event.getSource();
String userId = event.getRequestContext().getRequestParameter(OBJECTID).trim();
UIPopupAction popupAction = forumPortlet.getChild(UIPopupAction.class);
UIViewUserProfile viewUserProfile = popupAction.createUIComponent(UIViewUserProfile.class, null, null);
UserProfile selectProfile;
try {
selectProfile = forumPortlet.forumService.getUserInformations(forumPortlet.forumService.getQuickProfile(userId));
} catch (Exception e) {
selectProfile = ForumUtils.getDeletedUserProfile(forumPortlet.forumService, userId);
}
viewUserProfile.setUserProfileViewer(selectProfile);
popupAction.activate(viewUserProfile, 670, 400, true);
event.getRequestContext().addUIComponentToUpdateByAjax(popupAction);
}
}
static public class PrivateMessageActionListener extends EventListener<UIForumPortlet> {
public void execute(Event<UIForumPortlet> event) throws Exception {
UIForumPortlet forumPortlet = event.getSource();
if (forumPortlet.userProfile.getIsBanned()) {
showWarningMessage(event.getRequestContext(), "UITopicDetail.msg.userIsBannedCanNotSendMail", ForumUtils.EMPTY_STR);
return;
}
String userId = event.getRequestContext().getRequestParameter(OBJECTID);
int t = userId.indexOf(Utils.DELETED);
if (t < 0) {
try {
forumPortlet.forumService.getQuickProfile(userId.trim());
} catch (Exception e) {
t = 1;
}
}
if (t > 0) {
showWarningMessage(event.getRequestContext(), "UITopicDetail.msg.userIsDeleted", userId.substring(0, t) );
return;
}
UIPopupAction popupAction = forumPortlet.getChild(UIPopupAction.class);
UIPopupContainer popupContainer = popupAction.createUIComponent(UIPopupContainer.class, null, null);
UIPrivateMessageForm messageForm = popupContainer.addChild(UIPrivateMessageForm.class, null, null);
messageForm.setFullMessage(false);
messageForm.setUserProfile(forumPortlet.userProfile);
messageForm.setSendtoField(userId);
popupContainer.setId("PrivateMessageForm");
popupAction.activate(popupContainer, 720, 550);
event.getRequestContext().addUIComponentToUpdateByAjax(popupAction);
}
}
static public class ViewPostedByUserActionListener extends EventListener<UIForumPortlet> {
public void execute(Event<UIForumPortlet> event) throws Exception {
String userId = event.getRequestContext().getRequestParameter(OBJECTID);
UIForumPortlet forumPortlet = event.getSource();
UIPopupAction popupAction = forumPortlet.getChild(UIPopupAction.class);
UIPopupContainer popupContainer = popupAction.createUIComponent(UIPopupContainer.class, null, null);
UIViewPostedByUser viewPostedByUser = popupContainer.addChild(UIViewPostedByUser.class, null, null);
viewPostedByUser.setUserProfile(userId);
popupContainer.setId("ViewPostedByUser");
popupAction.activate(popupContainer, 760, 370);
event.getRequestContext().addUIComponentToUpdateByAjax(popupAction);
}
}
static public class ViewThreadByUserActionListener extends EventListener<UIForumPortlet> {
public void execute(Event<UIForumPortlet> event) throws Exception {
String userId = event.getRequestContext().getRequestParameter(OBJECTID);
UIForumPortlet forumPortlet = event.getSource();
UIPopupAction popupAction = forumPortlet.getChild(UIPopupAction.class);
UIPopupContainer popupContainer = popupAction.createUIComponent(UIPopupContainer.class, null, null);
UIViewTopicCreatedByUser topicCreatedByUser = popupContainer.addChild(UIViewTopicCreatedByUser.class, null, null);
topicCreatedByUser.setUserId(userId);
popupContainer.setId("ViewTopicCreatedByUser");
popupAction.activate(popupContainer, 760, 450);
event.getRequestContext().addUIComponentToUpdateByAjax(popupAction);
}
}
}
| false | true | public void calculateRenderComponent(String path, WebuiRequestContext context) throws Exception {
ResourceBundle res = context.getApplicationResourceBundle();
if (path.equals(Utils.FORUM_SERVICE)) {
renderForumHome();
} else if (path.indexOf(ForumUtils.FIELD_SEARCHFORUM_LABEL) >= 0) {
updateIsRendered(ForumUtils.FIELD_SEARCHFORUM_LABEL);
UISearchForm searchForm = getChild(UISearchForm.class);
searchForm.setPath(ForumUtils.EMPTY_STR);
searchForm.setSelectType(path.replaceFirst(ForumUtils.FIELD_SEARCHFORUM_LABEL, ""));
searchForm.setSearchOptionsObjectType(ForumUtils.EMPTY_STR);
path = ForumUtils.FIELD_EXOFORUM_LABEL;
} else if (path.lastIndexOf(Utils.TAG) >= 0) {
updateIsRendered(ForumUtils.TAG);
getChild(UITopicsTag.class).setIdTag(path);
} else if (isRenderedTopic(path)) {
boolean isReply = false, isQuote = false;
if (path.indexOf("/true") > 0) {
isQuote = true;
path = path.replaceFirst("/true", ForumUtils.EMPTY_STR);
} else if (path.indexOf("/false") > 0) {
isReply = true;
path = path.replaceFirst("/false", ForumUtils.EMPTY_STR);
}
if(path.indexOf(Utils.CATEGORY) > 0) {
path = path.substring(path.indexOf(Utils.CATEGORY));
}
String[] id = path.split(ForumUtils.SLASH);
String postId = "top";
int page = 0;
if (path.indexOf(ForumUtils.VIEW_LAST_POST) > 0) {
postId = ForumUtils.VIEW_LAST_POST;
path = path.replace(ForumUtils.SLASH + ForumUtils.VIEW_LAST_POST, ForumUtils.EMPTY_STR);
id = path.split(ForumUtils.SLASH);
} else if(path.indexOf(Utils.POST) > 0) {
postId = id[id.length - 1];
path = path.substring(0, path.lastIndexOf(ForumUtils.SLASH));
id = path.split(ForumUtils.SLASH);
} else if (id.length > 1) {
try {
page = Integer.parseInt(id[id.length - 1]);
} catch (NumberFormatException e) {
if (log.isDebugEnabled()){
log.debug("Failed to parse number " + id[id.length - 1], e);
}
}
if (page > 0) {
path = path.replace(ForumUtils.SLASH + id[id.length - 1], ForumUtils.EMPTY_STR);
id = path.split(ForumUtils.SLASH);
} else
page = 0;
}
try {
Topic topic;
if (id.length > 1) {
topic = this.forumService.getTopicByPath(path, false);
} else {
topic = (Topic) this.forumService.getObjectNameById(path, Utils.TOPIC);
}
if (topic != null) {
if (path.indexOf(ForumUtils.SLASH) < 0) {
path = topic.getPath();
path = path.substring(path.indexOf(Utils.CATEGORY));
id = path.split(ForumUtils.SLASH);
}
Category category = this.forumService.getCategory(id[0]);
Forum forum = this.forumService.getForum(id[0], id[1]);
if (this.checkCanView(category, forum, topic)) {
this.updateIsRendered(ForumUtils.FORUM);
UIForumContainer uiForumContainer = this.getChild(UIForumContainer.class);
UITopicDetailContainer uiTopicDetailContainer = uiForumContainer.getChild(UITopicDetailContainer.class);
uiForumContainer.setIsRenderChild(false);
uiForumContainer.getChild(UIForumDescription.class).setForum(forum);
UITopicDetail uiTopicDetail = uiTopicDetailContainer.getChild(UITopicDetail.class);
uiTopicDetail.setIsEditTopic(true);
uiTopicDetail.setUpdateForum(forum);
uiTopicDetail.initInfoTopic(id[0], id[1], topic, page);
uiTopicDetailContainer.getChild(UITopicPoll.class).updateFormPoll(id[0], id[1], topic.getId());
uiTopicDetail.setIdPostView(postId);
uiTopicDetail.setLastPostId(((path.indexOf(Utils.POST) < 0) ? ForumUtils.EMPTY_STR : postId));
if (isReply || isQuote) {
if (uiTopicDetail.getCanPost()) {
try {
UIPopupAction popupAction = this.getChild(UIPopupAction.class);
UIPopupContainer popupContainer = popupAction.createUIComponent(UIPopupContainer.class, null, null);
UIPostForm postForm = popupContainer.addChild(UIPostForm.class, null, null);
boolean isMod = ForumServiceUtils.hasPermission(forum.getModerators(), this.userProfile.getUserId());
postForm.setPostIds(id[0], id[1], topic.getId(), topic);
postForm.setMod(isMod);
Post post = this.forumService.getPost(id[0], id[1], topic.getId(), postId);
if (isQuote) {
if (post != null) {
postForm.updatePost(postId, true, (post.getUserPrivate().length == 2), post);
popupContainer.setId("UIQuoteContainer");
} else {
showWarningMessage(context, "UIBreadcumbs.msg.post-no-longer-exist", ForumUtils.EMPTY_STR);
uiTopicDetail.setIdPostView("normal");
}
} else {
if (post != null && post.getUserPrivate().length == 2) {
postForm.updatePost(post.getId(), false, true, post);
} else {
postForm.updatePost(ForumUtils.EMPTY_STR, false, false, null);
}
popupContainer.setId("UIAddPostContainer");
}
popupAction.activate(popupContainer, 900, 500);
context.addUIComponentToUpdateByAjax(popupAction);
} catch (Exception e) {
log.error(e);
}
} else {
showWarningMessage(context, "UIPostForm.msg.no-permission", ForumUtils.EMPTY_STR);
}
}
if (!UserHelper.isAnonim()) {
this.forumService.updateTopicAccess(userProfile.getUserId(), topic.getId());
this.getUserProfile().setLastTimeAccessTopic(topic.getId(), CommonUtils.getGreenwichMeanTime().getTimeInMillis());
}
} else {
showWarningMessage(context, "UIForumPortlet.msg.do-not-permission-view-topic",
new String[] {});
if (!ForumUtils.isEmpty(getForumIdOfSpace())) {
calculateRenderComponent(forumSpId, context);
} else {
renderForumHome();
path = Utils.FORUM_SERVICE;
}
}
} else if (ForumUtils.isEmpty(getForumIdOfSpace()) == false) {// open topic removed on forum of space
if (forumService.getForum(categorySpId, forumSpId) == null) {// the forum of space had been removed
forumSpDeleted = true;
removeAllChildPorletView();
log.info("The forum in space " + spaceDisplayName + " no longer exists.");
return;
} else {
showWarningMessage(context, "UIForumPortlet.msg.topicEmpty", ForumUtils.EMPTY_STR);
calculateRenderComponent(forumSpId, context);
}
} else {// open topic removed on normal forum.
showWarningMessage(context, "UIForumPortlet.msg.topicEmpty", ForumUtils.EMPTY_STR);
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} catch (Exception e) {// Unknown error
if (log.isDebugEnabled()){
log.debug("Failed to render forum link: [" + path + "]. Forum home will be rendered.\nCaused by:", e);
}
showWarningMessage(context, "UIShowBookMarkForm.msg.link-not-found", ForumUtils.EMPTY_STR);
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} else if ((path.lastIndexOf(Utils.FORUM) == 0 && path.lastIndexOf(Utils.CATEGORY) < 0) || (path.lastIndexOf(Utils.FORUM) > 0)) {
try {
Forum forum = null;
String cateId = null;
int page = 0;
if (path.indexOf(ForumUtils.SLASH) >= 0) {
String[] arr = path.split(ForumUtils.SLASH);
try {
page = Integer.parseInt(arr[arr.length - 1]);
} catch (Exception e) {
if (log.isDebugEnabled()){
log.debug("Failed to parse number " + arr[arr.length - 1], e);
}
}
if (arr[0].indexOf(Utils.CATEGORY) == 0) {
cateId = arr[0];
forum = this.forumService.getForum(cateId, arr[1]);
} else {
forum = (Forum) this.forumService.getObjectNameById(arr[0], Utils.FORUM);
}
}
if (forum == null) {
path = path.substring(path.lastIndexOf(ForumUtils.SLASH) + 1);
forum = (Forum) this.forumService.getObjectNameById(path, Utils.FORUM);
if (forum == null && path.equals(getForumIdOfSpace())) {
forum = forumService.getForum(this.categorySpId, path);
if(forum == null) {
forumSpDeleted = true;
removeAllChildPorletView();
log.info("The forum in space " + spaceDisplayName + " no longer exists.");
return;
}
}
}
if (cateId == null) {
cateId = forum.getCategoryId();
}
path = new StringBuilder(cateId).append("/").append(forum.getId()).toString();
Category category = this.forumService.getCategory(cateId);
if (this.checkCanView(category, forum, null)) {
this.updateIsRendered(ForumUtils.FORUM);
UIForumContainer forumContainer = this.findFirstComponentOfType(UIForumContainer.class);
forumContainer.setIsRenderChild(true);
forumContainer.getChild(UIForumDescription.class).setForum(forum);
UITopicContainer topicContainer = forumContainer.getChild(UITopicContainer.class);
topicContainer.setUpdateForum(cateId, forum, page);
if(!userProfile.getUserId().equals(UserProfile.USER_GUEST)) {
//
PortalRequestContext portalContext = Util.getPortalRequestContext();
String hasCreateTopic = portalContext.getRequestParameter(ForumUtils.HAS_CREATE_TOPIC);
if(!ForumUtils.isEmpty(hasCreateTopic) && Boolean.parseBoolean(hasCreateTopic)) {
Event<UIComponent> addTopicEvent = topicContainer.createEvent("AddTopic", Event.Phase.PROCESS, context);
if (addTopicEvent != null) {
addTopicEvent.broadcast();
}
} else {
String hasCreatePoll = portalContext.getRequestParameter(ForumUtils.HAS_CREATE_POLL);
if(!ForumUtils.isEmpty(hasCreatePoll) && Boolean.parseBoolean(hasCreatePoll)) {
Event<UIComponent> addTopicEvent = topicContainer.createEvent("AddPoll", Event.Phase.PROCESS, context);
if (addTopicEvent != null) {
addTopicEvent.broadcast();
}
}
}
}
} else {
showWarningMessage(context, "UIForumPortlet.msg.do-not-permission-view-forum",
new String[] {});
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} catch (Exception e) {
if (log.isDebugEnabled()){
log.debug("Failed to render forum link: [" + path + "]. Forum home will be rendered.\nCaused by:", e);
}
showWarningMessage(context, "UIShowBookMarkForm.msg.link-not-found",
new String[] { res.getString("UIForumPortlet.label.forum") });
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} else if (path.indexOf(Utils.CATEGORY) >= 0 && path.indexOf(ForumUtils.SLASH) < 0) {
UICategoryContainer categoryContainer = this.getChild(UICategoryContainer.class);
try {
Category category = this.forumService.getCategory(path);
if (this.checkCanView(category, null, null)) {
categoryContainer.getChild(UICategory.class).updateByLink(category);
categoryContainer.updateIsRender(false);
this.updateIsRendered(ForumUtils.CATEGORIES);
} else {
showWarningMessage(context, "UIForumPortlet.msg.do-not-permission-view-category",
new String[] {});
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} catch (Exception e) {
if (log.isDebugEnabled()){
log.debug("Failed to render forum link: [" + path + "]. Forum home will be rendered.\nCaused by:", e);
}
showWarningMessage(context, "UIShowBookMarkForm.msg.link-not-found", ForumUtils.EMPTY_STR);
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} else {
if (log.isDebugEnabled()){
log.debug("Failed to render forum link: [" + path + "]. Forum home will be rendered.");
}
showWarningMessage(context, "UIShowBookMarkForm.msg.link-not-found", ForumUtils.EMPTY_STR);
renderForumHome();
path = Utils.FORUM_SERVICE;
}
getChild(UIBreadcumbs.class).setUpdataPath(path);
}
| public void calculateRenderComponent(String path, WebuiRequestContext context) throws Exception {
ResourceBundle res = context.getApplicationResourceBundle();
if (path.equals(Utils.FORUM_SERVICE)) {
renderForumHome();
} else if (path.equals(ForumUtils.FIELD_SEARCHFORUM_LABEL)) {
updateIsRendered(ForumUtils.FIELD_SEARCHFORUM_LABEL);
UISearchForm searchForm = getChild(UISearchForm.class);
searchForm.setPath(ForumUtils.EMPTY_STR);
searchForm.setSelectType(path.replaceFirst(ForumUtils.FIELD_SEARCHFORUM_LABEL, ""));
searchForm.setSearchOptionsObjectType(ForumUtils.EMPTY_STR);
path = ForumUtils.FIELD_EXOFORUM_LABEL;
} else if (path.indexOf(Utils.TAG) == 0) {
updateIsRendered(ForumUtils.TAG);
getChild(UITopicsTag.class).setIdTag(path);
} else if (isRenderedTopic(path)) {
boolean isReply = false, isQuote = false;
if (path.indexOf("/true") > 0) {
isQuote = true;
path = path.replaceFirst("/true", ForumUtils.EMPTY_STR);
} else if (path.indexOf("/false") > 0) {
isReply = true;
path = path.replaceFirst("/false", ForumUtils.EMPTY_STR);
}
if(path.indexOf(Utils.CATEGORY) > 0) {
path = path.substring(path.indexOf(Utils.CATEGORY));
}
String[] id = path.split(ForumUtils.SLASH);
String postId = "top";
int page = 0;
if (path.indexOf(ForumUtils.VIEW_LAST_POST) > 0) {
postId = ForumUtils.VIEW_LAST_POST;
path = path.replace(ForumUtils.SLASH + ForumUtils.VIEW_LAST_POST, ForumUtils.EMPTY_STR);
id = path.split(ForumUtils.SLASH);
} else if(path.indexOf(Utils.POST) > 0) {
postId = id[id.length - 1];
path = path.substring(0, path.lastIndexOf(ForumUtils.SLASH));
id = path.split(ForumUtils.SLASH);
} else if (id.length > 1) {
try {
page = Integer.parseInt(id[id.length - 1]);
} catch (NumberFormatException e) {
if (log.isDebugEnabled()){
log.debug("Failed to parse number " + id[id.length - 1], e);
}
}
if (page > 0) {
path = path.replace(ForumUtils.SLASH + id[id.length - 1], ForumUtils.EMPTY_STR);
id = path.split(ForumUtils.SLASH);
} else
page = 0;
}
try {
Topic topic;
if (id.length > 1) {
topic = this.forumService.getTopicByPath(path, false);
} else {
topic = (Topic) this.forumService.getObjectNameById(path, Utils.TOPIC);
}
if (topic != null) {
if (path.indexOf(ForumUtils.SLASH) < 0) {
path = topic.getPath();
path = path.substring(path.indexOf(Utils.CATEGORY));
id = path.split(ForumUtils.SLASH);
}
Category category = this.forumService.getCategory(id[0]);
Forum forum = this.forumService.getForum(id[0], id[1]);
if (this.checkCanView(category, forum, topic)) {
this.updateIsRendered(ForumUtils.FORUM);
UIForumContainer uiForumContainer = this.getChild(UIForumContainer.class);
UITopicDetailContainer uiTopicDetailContainer = uiForumContainer.getChild(UITopicDetailContainer.class);
uiForumContainer.setIsRenderChild(false);
uiForumContainer.getChild(UIForumDescription.class).setForum(forum);
UITopicDetail uiTopicDetail = uiTopicDetailContainer.getChild(UITopicDetail.class);
uiTopicDetail.setIsEditTopic(true);
uiTopicDetail.setUpdateForum(forum);
uiTopicDetail.initInfoTopic(id[0], id[1], topic, page);
uiTopicDetailContainer.getChild(UITopicPoll.class).updateFormPoll(id[0], id[1], topic.getId());
uiTopicDetail.setIdPostView(postId);
uiTopicDetail.setLastPostId(((path.indexOf(Utils.POST) < 0) ? ForumUtils.EMPTY_STR : postId));
if (isReply || isQuote) {
if (uiTopicDetail.getCanPost()) {
try {
UIPopupAction popupAction = this.getChild(UIPopupAction.class);
UIPopupContainer popupContainer = popupAction.createUIComponent(UIPopupContainer.class, null, null);
UIPostForm postForm = popupContainer.addChild(UIPostForm.class, null, null);
boolean isMod = ForumServiceUtils.hasPermission(forum.getModerators(), this.userProfile.getUserId());
postForm.setPostIds(id[0], id[1], topic.getId(), topic);
postForm.setMod(isMod);
Post post = this.forumService.getPost(id[0], id[1], topic.getId(), postId);
if (isQuote) {
if (post != null) {
postForm.updatePost(postId, true, (post.getUserPrivate().length == 2), post);
popupContainer.setId("UIQuoteContainer");
} else {
showWarningMessage(context, "UIBreadcumbs.msg.post-no-longer-exist", ForumUtils.EMPTY_STR);
uiTopicDetail.setIdPostView("normal");
}
} else {
if (post != null && post.getUserPrivate().length == 2) {
postForm.updatePost(post.getId(), false, true, post);
} else {
postForm.updatePost(ForumUtils.EMPTY_STR, false, false, null);
}
popupContainer.setId("UIAddPostContainer");
}
popupAction.activate(popupContainer, 900, 500);
context.addUIComponentToUpdateByAjax(popupAction);
} catch (Exception e) {
log.error(e);
}
} else {
showWarningMessage(context, "UIPostForm.msg.no-permission", ForumUtils.EMPTY_STR);
}
}
if (!UserHelper.isAnonim()) {
this.forumService.updateTopicAccess(userProfile.getUserId(), topic.getId());
this.getUserProfile().setLastTimeAccessTopic(topic.getId(), CommonUtils.getGreenwichMeanTime().getTimeInMillis());
}
} else {
showWarningMessage(context, "UIForumPortlet.msg.do-not-permission-view-topic",
new String[] {});
if (!ForumUtils.isEmpty(getForumIdOfSpace())) {
calculateRenderComponent(forumSpId, context);
} else {
renderForumHome();
path = Utils.FORUM_SERVICE;
}
}
} else if (ForumUtils.isEmpty(getForumIdOfSpace()) == false) {// open topic removed on forum of space
if (forumService.getForum(categorySpId, forumSpId) == null) {// the forum of space had been removed
forumSpDeleted = true;
removeAllChildPorletView();
log.info("The forum in space " + spaceDisplayName + " no longer exists.");
return;
} else {
showWarningMessage(context, "UIForumPortlet.msg.topicEmpty", ForumUtils.EMPTY_STR);
calculateRenderComponent(forumSpId, context);
}
} else {// open topic removed on normal forum.
showWarningMessage(context, "UIForumPortlet.msg.topicEmpty", ForumUtils.EMPTY_STR);
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} catch (Exception e) {// Unknown error
if (log.isDebugEnabled()){
log.debug("Failed to render forum link: [" + path + "]. Forum home will be rendered.\nCaused by:", e);
}
showWarningMessage(context, "UIShowBookMarkForm.msg.link-not-found", ForumUtils.EMPTY_STR);
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} else if ((path.lastIndexOf(Utils.FORUM) == 0 && path.lastIndexOf(Utils.CATEGORY) < 0) || (path.lastIndexOf(Utils.FORUM) > 0)) {
try {
Forum forum = null;
String cateId = null;
int page = 0;
if (path.indexOf(ForumUtils.SLASH) >= 0) {
String[] arr = path.split(ForumUtils.SLASH);
try {
page = Integer.parseInt(arr[arr.length - 1]);
} catch (Exception e) {
if (log.isDebugEnabled()){
log.debug("Failed to parse number " + arr[arr.length - 1], e);
}
}
if (arr[0].indexOf(Utils.CATEGORY) == 0) {
cateId = arr[0];
forum = this.forumService.getForum(cateId, arr[1]);
} else {
forum = (Forum) this.forumService.getObjectNameById(arr[0], Utils.FORUM);
}
}
if (forum == null) {
path = path.substring(path.lastIndexOf(ForumUtils.SLASH) + 1);
forum = (Forum) this.forumService.getObjectNameById(path, Utils.FORUM);
if (forum == null && path.equals(getForumIdOfSpace())) {
forum = forumService.getForum(this.categorySpId, path);
if(forum == null) {
forumSpDeleted = true;
removeAllChildPorletView();
log.info("The forum in space " + spaceDisplayName + " no longer exists.");
return;
}
}
}
if (cateId == null) {
cateId = forum.getCategoryId();
}
path = new StringBuilder(cateId).append("/").append(forum.getId()).toString();
Category category = this.forumService.getCategory(cateId);
if (this.checkCanView(category, forum, null)) {
this.updateIsRendered(ForumUtils.FORUM);
UIForumContainer forumContainer = this.findFirstComponentOfType(UIForumContainer.class);
forumContainer.setIsRenderChild(true);
forumContainer.getChild(UIForumDescription.class).setForum(forum);
UITopicContainer topicContainer = forumContainer.getChild(UITopicContainer.class);
topicContainer.setUpdateForum(cateId, forum, page);
if(!userProfile.getUserId().equals(UserProfile.USER_GUEST)) {
//
PortalRequestContext portalContext = Util.getPortalRequestContext();
String hasCreateTopic = portalContext.getRequestParameter(ForumUtils.HAS_CREATE_TOPIC);
if(!ForumUtils.isEmpty(hasCreateTopic) && Boolean.parseBoolean(hasCreateTopic)) {
Event<UIComponent> addTopicEvent = topicContainer.createEvent("AddTopic", Event.Phase.PROCESS, context);
if (addTopicEvent != null) {
addTopicEvent.broadcast();
}
} else {
String hasCreatePoll = portalContext.getRequestParameter(ForumUtils.HAS_CREATE_POLL);
if(!ForumUtils.isEmpty(hasCreatePoll) && Boolean.parseBoolean(hasCreatePoll)) {
Event<UIComponent> addTopicEvent = topicContainer.createEvent("AddPoll", Event.Phase.PROCESS, context);
if (addTopicEvent != null) {
addTopicEvent.broadcast();
}
}
}
}
} else {
showWarningMessage(context, "UIForumPortlet.msg.do-not-permission-view-forum",
new String[] {});
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} catch (Exception e) {
if (log.isDebugEnabled()){
log.debug("Failed to render forum link: [" + path + "]. Forum home will be rendered.\nCaused by:", e);
}
showWarningMessage(context, "UIShowBookMarkForm.msg.link-not-found",
new String[] { res.getString("UIForumPortlet.label.forum") });
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} else if (path.indexOf(Utils.CATEGORY) >= 0 && path.indexOf(ForumUtils.SLASH) < 0) {
UICategoryContainer categoryContainer = this.getChild(UICategoryContainer.class);
try {
Category category = this.forumService.getCategory(path);
if (this.checkCanView(category, null, null)) {
categoryContainer.getChild(UICategory.class).updateByLink(category);
categoryContainer.updateIsRender(false);
this.updateIsRendered(ForumUtils.CATEGORIES);
} else {
showWarningMessage(context, "UIForumPortlet.msg.do-not-permission-view-category",
new String[] {});
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} catch (Exception e) {
if (log.isDebugEnabled()){
log.debug("Failed to render forum link: [" + path + "]. Forum home will be rendered.\nCaused by:", e);
}
showWarningMessage(context, "UIShowBookMarkForm.msg.link-not-found", ForumUtils.EMPTY_STR);
renderForumHome();
path = Utils.FORUM_SERVICE;
}
} else {
if (log.isDebugEnabled()){
log.debug("Failed to render forum link: [" + path + "]. Forum home will be rendered.");
}
showWarningMessage(context, "UIShowBookMarkForm.msg.link-not-found", ForumUtils.EMPTY_STR);
renderForumHome();
path = Utils.FORUM_SERVICE;
}
getChild(UIBreadcumbs.class).setUpdataPath(path);
}
|
diff --git a/core/src/main/java/brooklyn/util/task/BasicTask.java b/core/src/main/java/brooklyn/util/task/BasicTask.java
index d3779822e..806efb15f 100644
--- a/core/src/main/java/brooklyn/util/task/BasicTask.java
+++ b/core/src/main/java/brooklyn/util/task/BasicTask.java
@@ -1,444 +1,443 @@
package brooklyn.util.task;
import static brooklyn.util.JavaGroovyEquivalents.asString;
import static brooklyn.util.JavaGroovyEquivalents.elvisString;
import static brooklyn.util.JavaGroovyEquivalents.join;
import groovy.lang.Closure;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.LockInfo;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import brooklyn.management.ExecutionManager;
import brooklyn.management.Task;
import brooklyn.util.GroovyJavaMethods;
import com.google.common.base.Throwables;
/**
* The basic concrete implementation of a {@link Task} to be executed.
*
* A {@link Task} is a wrapper for an executable unit, such as a {@link Closure} or a {@link Runnable} or
* {@link Callable} and will run in its own {@link Thread}.
* <p>
* The task can be given an optional displayName and description in its constructor (as named
* arguments in the first {@link Map} parameter). It is guaranteed to have {@link Object#notify()} called
* once whenever the task starts running and once again when the task is about to complete. Due to
* the way executors work it is ugly to guarantee notification <em>after</em> completion, so instead we
* notify just before then expect the user to call {@link #get()} - which will throw errors if the underlying job
* did so - or {@link #blockUntilEnded()} which will not throw errors.
*
* @see BasicTaskStub
*/
public class BasicTask<T> extends BasicTaskStub implements Task<T> {
protected static final Logger log = LoggerFactory.getLogger(BasicTask.class);
protected Callable<T> job;
public final String displayName;
public final String description;
protected final Set tags = new LinkedHashSet();
protected String blockingDetails = null;
/**
* Constructor needed to prevent confusion in groovy stubs when looking for default constructor,
*
* The generics on {@link Closure} break it if that is first constructor.
*/
protected BasicTask() { this(Collections.emptyMap()); }
protected BasicTask(Map flags) { this(flags, (Closure) null); }
public BasicTask(Closure<T> job) { this(Collections.emptyMap(), job); }
public BasicTask(Map flags, Closure<T> job) {
this.job = job;
if (flags.containsKey("tag")) tags.add(flags.remove("tag"));
Object ftags = flags.remove("tags");
if (ftags!=null) {
if (ftags instanceof Collection) tags.addAll((Collection)ftags);
else {
log.info("discouraged use of non-collection argument for 'tags' ("+ftags+") in "+this, new Throwable("trace of discouraged use of non-colleciton tags argument"));
tags.add(ftags);
}
}
description = elvisString(flags.remove("description"), "");
String d = asString(flags.remove("displayName"));
if (d==null) d = join(tags, "-");
displayName = d;
}
public BasicTask(Runnable job) { this(GroovyJavaMethods.closureFromRunnable(job)); }
public BasicTask(Map flags, Runnable job) { this(flags, GroovyJavaMethods.closureFromRunnable(job)); }
public BasicTask(Callable<T> job) { this(GroovyJavaMethods.closureFromCallable(job)); }
public BasicTask(Map flags, Callable<T> job) { this(flags, GroovyJavaMethods.closureFromCallable(job)); }
@Override
public String toString() {
return "Task["+(displayName!=null && displayName.length()>0?displayName+
(tags!=null && !tags.isEmpty()?"":";")+" ":"")+
(tags!=null && !tags.isEmpty()?tags+"; ":"")+getId()+"]";
}
// housekeeping --------------------
/*
* These flags are set by BasicExecutionManager.submit.
*
* Order is guaranteed to be as shown below, in order of #. Within each # line it is currently in the order specified by commas but this is not guaranteed.
* (The spaces between the # section indicate longer delays / logical separation ... it should be clear!)
*
* # submitter, submit time set, tags and other submit-time fields set, task tag-linked preprocessors onSubmit invoked
*
* # thread set, ThreadLocal getCurrentTask set
* # start time set, isBegun is true
* # task tag-linked preprocessors onStart invoked
* # task end callback run, if supplied
*
* # task runs
*
* # task end callback run, if supplied
* # task tag-linked preprocessors onEnd invoked (in reverse order of tags)
* # end time set
* # thread cleared, ThreadLocal getCurrentTask set
* # Task.notifyAll()
* # Task.get() (result.get()) available, Task.isDone is true
*
* Few _consumers_ should care, but internally we rely on this so that, for example, status is displayed correctly.
* Tests should catch most things, but be careful if you change any of the above semantics.
*/
protected long submitTimeUtc = -1;
protected long startTimeUtc = -1;
protected long endTimeUtc = -1;
protected Task<?> submittedByTask;
protected volatile Thread thread = null;
private volatile boolean cancelled = false;
protected Future<T> result = null;
protected ExecutionManager em = null;
void initExecutionManager(ExecutionManager em) {
this.em = em;
}
synchronized void initResult(Future result) {
if (this.result != null)
throw new IllegalStateException("task "+this+" is being given a result twice");
this.result = result;
notifyAll();
}
// metadata accessors ------------
public Set<Object> getTags() { return Collections.unmodifiableSet(new LinkedHashSet(tags)); }
public long getSubmitTimeUtc() { return submitTimeUtc; }
public long getStartTimeUtc() { return startTimeUtc; }
public long getEndTimeUtc() { return endTimeUtc; }
public Future<T> getResult() { return result; }
public Task<?> getSubmittedByTask() { return submittedByTask; }
/** the thread where the task is running, if it is running */
public Thread getThread() { return thread; }
// basic fields --------------------
public boolean isSubmitted() {
return submitTimeUtc >= 0;
}
public boolean isBegun() {
return startTimeUtc >= 0;
}
public synchronized boolean cancel() { return cancel(true); }
public synchronized boolean cancel(boolean mayInterruptIfRunning) {
if (isDone()) return false;
boolean cancel = true;
if (GroovyJavaMethods.truth(result)) { cancel = result.cancel(mayInterruptIfRunning); }
cancelled = true;
notifyAll();
return cancel;
}
public boolean isCancelled() {
return cancelled || (result!=null && result.isCancelled());
}
public boolean isDone() {
return cancelled || (result!=null && result.isDone());
}
/**
* Returns true if the task has had an error.
*
* Only true if calling {@link #get()} will throw an exception when it completes (including cancel).
* Implementations may set this true before completion if they have that insight, or
* (the default) they may compute it lazily after completion (returning false before completion).
*/
public boolean isError() {
if (!isDone()) return false;
if (isCancelled()) return true;
try {
get();
return false;
} catch (Throwable t) {
return true;
}
}
public T get() throws InterruptedException, ExecutionException {
blockUntilStarted();
return result.get();
}
// future value --------------------
public synchronized void blockUntilStarted() {
while (true) {
if (cancelled) throw new CancellationException();
if (result==null)
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Throwables.propagate(e);
}
if (result!=null) return;
}
}
public void blockUntilEnded() {
try { blockUntilStarted(); } catch (Throwable t) {
if (log.isDebugEnabled())
log.debug("call from "+Thread.currentThread()+" blocking until "+this+" finishes ended with error: "+t);
/* contract is just to log errors at debug, otherwise do nothing */
return;
}
try { result.get(); } catch (Throwable t) {
if (log.isDebugEnabled())
log.debug("call from "+Thread.currentThread()+" blocking until "+this+" finishes ended with error: "+t);
/* contract is just to log errors at debug, otherwise do nothing */
return;
}
}
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
long start = System.currentTimeMillis();
long milliseconds = TimeUnit.MILLISECONDS.convert(timeout, unit);
long end = start + milliseconds;
while (end > System.currentTimeMillis()) {
if (cancelled) throw new CancellationException();
if (result == null) wait(end - System.currentTimeMillis());
if (result != null) break;
}
long remaining = end - System.currentTimeMillis();
if (remaining > 0) {
return result.get(remaining, TimeUnit.MILLISECONDS);
} else {
throw new TimeoutException();
}
}
/**
* Returns a brief status string
*
* Plain-text format. Reported status if there is one, otherwise state which will be one of:
* <ul>
* <li>Not submitted
* <li>Submitted for execution
* <li>Ended by error
* <li>Ended by cancellation
* <li>Ended normally
* <li>Running
* <li>Waiting
* </ul>
*/
public String getStatusSummary() {
return getStatusString(0);
}
/**
* Returns detailed status, suitable for a hover
*
* Plain-text format, with new-lines (and sometimes extra info) if multiline enabled.
*/
public String getStatusDetail(boolean multiline) {
return getStatusString(multiline?2:1);
}
/**
* This method is useful for callers to see the status of a task.
*
* Also for developers to see best practices for examining status fields etc
*
* @param verbosity 0 = brief, 1 = one-line with some detail, 2 = lots of detail
*/
protected String getStatusString(int verbosity) {
// Thread t = getThread();
String rv;
if (submitTimeUtc <= 0) rv = "Not submitted";
else if (!isCancelled() && startTimeUtc <= 0) {
rv = "Submitted for execution";
if (verbosity>0) {
long elapsed = System.currentTimeMillis() - submitTimeUtc;
rv += " "+elapsed+" ms ago";
}
} else if (isDone()) {
long elapsed = endTimeUtc - submitTimeUtc;
String duration = ""+elapsed+" ms";
rv = "Ended ";
if (isCancelled()) {
rv += "by cancellation";
if (verbosity >= 1) rv+=" after "+duration;
} else if (isError()) {
rv += "by error";
if (verbosity >= 1) {
rv += " after "+duration;
Object error;
try { String rvx = ""+get(); error = "no error, return value "+rvx; /* shouldn't happen */ }
catch (Throwable tt) { error = tt; }
//remove outer ExecException which is reported by the get(), we want the exception the task threw
if (error instanceof ExecutionException) error = ((Throwable)error).getCause();
if (verbosity == 1) rv += " ("+error+")";
else {
StringWriter sw = new StringWriter();
- if (error instanceof ExecutionException)
- ((Throwable)error).printStackTrace(new PrintWriter(sw));
+ ((Throwable)error).printStackTrace(new PrintWriter(sw));
rv += "\n"+sw.getBuffer();
}
}
} else {
rv += "normally";
if (verbosity>=1) {
if (verbosity==1) {
try {
rv += ", result "+get();
} catch (Exception e) {
rv += ", but error accessing result ["+e+"]"; //shouldn't happen
}
} else {
rv += " after "+duration;
try {
rv += "\n" + "Result: "+get();
} catch (Exception e) {
rv += " at first\n" +
"Error accessing result ["+e+"]"; //shouldn't happen
}
}
}
}
} else {
rv = getActiveTaskStatusString(verbosity);
}
return rv;
}
protected String getActiveTaskStatusString(int verbosity) {
String rv = "";
Thread t = getThread();
// Normally, it's not possible for thread==null as we were started and not ended
// However, there is a race where the task starts sand completes between the calls to getThread()
// at the start of the method and this call to getThread(), so both return null even though
// the intermediate checks returned started==true isDone()==false.
if (t == null) {
if (isDone()) {
return getStatusString(verbosity);
} else {
//should only happen for repeating task which is not active
return "Sleeping";
}
}
ThreadInfo ti = ManagementFactory.getThreadMXBean().getThreadInfo(t.getId(), (verbosity<=0 ? 0 : verbosity==1 ? 1 : Integer.MAX_VALUE));
if (getThread()==null)
//thread might have moved on to a new task; if so, recompute (it should now say "done")
return getStatusString(verbosity);
LockInfo lock = ti.getLockInfo();
if (!GroovyJavaMethods.truth(lock) && ti.getThreadState()==Thread.State.RUNNABLE) {
//not blocked
if (ti.isSuspended()) {
// when does this happen?
rv = "Waiting";
if (verbosity >= 1) rv += ", thread suspended";
} else {
rv = "Running";
if (verbosity >= 1) rv += " ("+ti.getThreadState()+")";
}
} else {
rv = "Waiting";
if (verbosity>=1) {
if (ti.getThreadState() == Thread.State.BLOCKED) {
rv += " (mutex) on "+lookup(lock);
//TODO could say who holds it
} else if (ti.getThreadState() == Thread.State.WAITING) {
rv += " (notify) on "+lookup(lock);
} else if (ti.getThreadState() == Thread.State.TIMED_WAITING) {
rv += " (timed) on "+lookup(lock);
} else {
rv = " ("+ti.getThreadState()+") on "+lookup(lock);
}
if (GroovyJavaMethods.truth(blockingDetails)) rv += " - "+blockingDetails;
}
}
if (verbosity>=2) {
StackTraceElement[] st = ti.getStackTrace();
st = StackTraceSimplifier.cleanStackTrace(st);
if (st!=null && st.length>0)
rv += "\n" +"At: "+st[0];
for (int ii=1; ii<st.length; ii++) {
rv += "\n" +" "+st[ii];
}
}
return rv;
}
protected String lookup(LockInfo info) {
return GroovyJavaMethods.truth(info) ? ""+info : "unknown (sleep)";
}
public String getDisplayName() {
return displayName;
}
public String getDescription() {
return description;
}
/** allows a task user to specify why a task is blocked; for use immediately before a blocking/wait,
* and typically cleared immediately afterwards; referenced by management api to inspect a task
* which is blocking
*/
public void setBlockingDetails(String blockingDetails) {
this.blockingDetails = blockingDetails;
}
public String getBlockingDetails() {
return blockingDetails;
}
}
| true | true | protected String getStatusString(int verbosity) {
// Thread t = getThread();
String rv;
if (submitTimeUtc <= 0) rv = "Not submitted";
else if (!isCancelled() && startTimeUtc <= 0) {
rv = "Submitted for execution";
if (verbosity>0) {
long elapsed = System.currentTimeMillis() - submitTimeUtc;
rv += " "+elapsed+" ms ago";
}
} else if (isDone()) {
long elapsed = endTimeUtc - submitTimeUtc;
String duration = ""+elapsed+" ms";
rv = "Ended ";
if (isCancelled()) {
rv += "by cancellation";
if (verbosity >= 1) rv+=" after "+duration;
} else if (isError()) {
rv += "by error";
if (verbosity >= 1) {
rv += " after "+duration;
Object error;
try { String rvx = ""+get(); error = "no error, return value "+rvx; /* shouldn't happen */ }
catch (Throwable tt) { error = tt; }
//remove outer ExecException which is reported by the get(), we want the exception the task threw
if (error instanceof ExecutionException) error = ((Throwable)error).getCause();
if (verbosity == 1) rv += " ("+error+")";
else {
StringWriter sw = new StringWriter();
if (error instanceof ExecutionException)
((Throwable)error).printStackTrace(new PrintWriter(sw));
rv += "\n"+sw.getBuffer();
}
}
} else {
rv += "normally";
if (verbosity>=1) {
if (verbosity==1) {
try {
rv += ", result "+get();
} catch (Exception e) {
rv += ", but error accessing result ["+e+"]"; //shouldn't happen
}
} else {
rv += " after "+duration;
try {
rv += "\n" + "Result: "+get();
} catch (Exception e) {
rv += " at first\n" +
"Error accessing result ["+e+"]"; //shouldn't happen
}
}
}
}
} else {
rv = getActiveTaskStatusString(verbosity);
}
return rv;
}
| protected String getStatusString(int verbosity) {
// Thread t = getThread();
String rv;
if (submitTimeUtc <= 0) rv = "Not submitted";
else if (!isCancelled() && startTimeUtc <= 0) {
rv = "Submitted for execution";
if (verbosity>0) {
long elapsed = System.currentTimeMillis() - submitTimeUtc;
rv += " "+elapsed+" ms ago";
}
} else if (isDone()) {
long elapsed = endTimeUtc - submitTimeUtc;
String duration = ""+elapsed+" ms";
rv = "Ended ";
if (isCancelled()) {
rv += "by cancellation";
if (verbosity >= 1) rv+=" after "+duration;
} else if (isError()) {
rv += "by error";
if (verbosity >= 1) {
rv += " after "+duration;
Object error;
try { String rvx = ""+get(); error = "no error, return value "+rvx; /* shouldn't happen */ }
catch (Throwable tt) { error = tt; }
//remove outer ExecException which is reported by the get(), we want the exception the task threw
if (error instanceof ExecutionException) error = ((Throwable)error).getCause();
if (verbosity == 1) rv += " ("+error+")";
else {
StringWriter sw = new StringWriter();
((Throwable)error).printStackTrace(new PrintWriter(sw));
rv += "\n"+sw.getBuffer();
}
}
} else {
rv += "normally";
if (verbosity>=1) {
if (verbosity==1) {
try {
rv += ", result "+get();
} catch (Exception e) {
rv += ", but error accessing result ["+e+"]"; //shouldn't happen
}
} else {
rv += " after "+duration;
try {
rv += "\n" + "Result: "+get();
} catch (Exception e) {
rv += " at first\n" +
"Error accessing result ["+e+"]"; //shouldn't happen
}
}
}
}
} else {
rv = getActiveTaskStatusString(verbosity);
}
return rv;
}
|
diff --git a/src/org/yi/acru/bukkit/Lockette/LockettePlayerListener.java b/src/org/yi/acru/bukkit/Lockette/LockettePlayerListener.java
index c324c34..0363919 100644
--- a/src/org/yi/acru/bukkit/Lockette/LockettePlayerListener.java
+++ b/src/org/yi/acru/bukkit/Lockette/LockettePlayerListener.java
@@ -1,630 +1,634 @@
//
// This file is a component of Lockette for Bukkit, and was written by Acru Jovian.
// Distributed under the The Non-Profit Open Software License version 3.0 (NPOSL-3.0)
// http://www.opensource.org/licenses/NOSL3.0
//
package org.yi.acru.bukkit.Lockette;
// Imports.
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.Event.Result;
import org.bukkit.event.block.Action;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class LockettePlayerListener implements Listener{
private static Lockette plugin;
final static int materialFenceGate = 107;
public LockettePlayerListener(Lockette instance){
plugin = instance;
}
protected void registerEvents(){
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
}
//********************************************************************************************************************
// Start of event section
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event){
String[] command = event.getMessage().split(" ", 3);
if(command.length < 1) return;
if(!(command[0].equalsIgnoreCase("/lockette") || command[0].equalsIgnoreCase("/lock"))) return;
event.setCancelled(true);
Player player = event.getPlayer();
// Reload config files, for admins only.
if(command.length == 2){
if(command[1].equalsIgnoreCase("reload")){
if(!plugin.hasPermission(player.getWorld(), player, "lockette.admin.reload")) return;
plugin.loadProperties(true);
plugin.localizedMessage(player, Lockette.broadcastReloadTarget, "msg-admin-reload");
return;
}
if(command[1].equalsIgnoreCase("version")){
player.sendMessage(ChatColor.RED + "Lockette version " + plugin.getDescription().getVersion() + " loaded. (Core: " + Lockette.getCoreVersion() + ")");
return;
}
if(command[1].equalsIgnoreCase("fix")){
if(fixDoor(player)){
plugin.localizedMessage(player, null, "msg-error-fix");
}
return;
}
}
// Edit sign text.
if((command.length == 2) || (command.length == 3)){
if(command[1].equals("1") || command[1].equals("2") || command[1].equals("3") || command[1].equals("4")){
Block block = plugin.playerList.get(player.getName());
//boolean error = false;
// Check if the selected block is a valid sign.
if(block == null){plugin.localizedMessage(player, null, "msg-error-edit"); return;}
else if(block.getTypeId() != Material.WALL_SIGN.getId()){plugin.localizedMessage(player, null, "msg-error-edit"); return;}
Sign sign = (Sign) block.getState();
Sign owner = sign;
String text = sign.getLine(0).replaceAll("(?i)\u00A7[0-F]", "").toLowerCase();
boolean privateSign;
// Check if it is our sign that is selected.
if(text.equals("[private]") || text.equalsIgnoreCase(Lockette.altPrivate)) privateSign = true;
else if(text.equals("[more users]") || text.equalsIgnoreCase(Lockette.altMoreUsers)){
privateSign = false;
Block checkBlock = Lockette.getSignAttachedBlock(block);
if(checkBlock == null){plugin.localizedMessage(player, null, "msg-error-edit"); return;}
Block signBlock = Lockette.findBlockOwner(checkBlock);
if(signBlock == null){plugin.localizedMessage(player, null, "msg-error-edit"); return;}
owner = (Sign) signBlock.getState();
}
else{plugin.localizedMessage(player, null, "msg-error-edit"); return;}
int length = player.getName().length();
if(length > 15) length = 15;
// Check owner.
if(owner.getLine(1).replaceAll("(?i)\u00A7[0-F]", "").equals(player.getName().substring(0, length)) || Lockette.debugMode){
int line = Integer.parseInt(command[1]) - 1;
// Disallow editing [Private] line 1/2 here.
if(!Lockette.debugMode){
if(line <= 0) return;
else if(line <= 1) if(privateSign) return;
}
if(command.length == 3){
length = command[2].length();
if(length > 15) length = 15;
if(Lockette.colorTags) sign.setLine(line, command[2].substring(0, length).replaceAll("&([0-9A-Fa-f])", "\u00A7$1"));
else sign.setLine(line, command[2].substring(0, length));
}
else sign.setLine(line, "");
sign.update();
plugin.localizedMessage(player, null, "msg-owner-edit");
return;
}
else{plugin.localizedMessage(player, null, "msg-error-edit"); return;}
}
}
// If none of the above, print out the help text.
// Commands:
// reload
// 2-4 <text> - sign editing
// link - linking?
// set <value> <string> - config?
plugin.localizedMessage(player, null, "msg-help-command1");
plugin.localizedMessage(player, null, "msg-help-command2");
plugin.localizedMessage(player, null, "msg-help-command3");
plugin.localizedMessage(player, null, "msg-help-command4");
plugin.localizedMessage(player, null, "msg-help-command5");
plugin.localizedMessage(player, null, "msg-help-command6");
plugin.localizedMessage(player, null, "msg-help-command7");
plugin.localizedMessage(player, null, "msg-help-command8");
plugin.localizedMessage(player, null, "msg-help-command9");
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerInteract(PlayerInteractEvent event){
if(!event.hasBlock()) return;
Action action = event.getAction();
Player player = event.getPlayer();
Block block = event.getClickedBlock();
int type = block.getTypeId();
BlockFace face = event.getBlockFace();
if(action == Action.RIGHT_CLICK_BLOCK){
if(Lockette.protectTrapDoors) if(type == Material.TRAP_DOOR.getId()){
if(interactDoor(block, player)) return;
event.setUseInteractedBlock(Result.DENY);
event.setUseItemInHand(Result.DENY);
return;
}
if(Lockette.protectDoors) if((type == Material.WOODEN_DOOR.getId()) || (type == Material.IRON_DOOR_BLOCK.getId()) || (type == materialFenceGate)){
if(interactDoor(block, player)) return;
event.setUseInteractedBlock(Result.DENY);
event.setUseItemInHand(Result.DENY);
return;
}
if(type == Material.WALL_SIGN.getId()){
interactSign(block, player);
return;
}
if(type == Material.CHEST.getId()){
// Try at making a 1.7->1.8 chest fixer.
Lockette.rotateChestOrientation(block, face);
}
if((type == Material.CHEST.getId()) || (type == Material.DISPENSER.getId()) ||
(type == Material.FURNACE.getId()) || (type == Material.BURNING_FURNACE.getId()) ||
(type == Material.BREWING_STAND.getId()) || Lockette.isInList(type, Lockette.customBlockList)){
// Trying something out....
if(Lockette.directPlacement) if(event.hasItem()) if((face != BlockFace.UP) && (face != BlockFace.DOWN)){
ItemStack item = event.getItem();
if(item.getTypeId() == Material.SIGN.getId()){
Block checkBlock = block.getRelative(face);
type = checkBlock.getTypeId();
if(type == Material.AIR.getId()){
boolean place = false;
if(Lockette.isProtected(block)){
// Add a users sign only if owner.
if(Lockette.isOwner(block, player.getName())) place = true;
}
else place = true;
//if(Lockette.altPrivate == null){}//if(Lockette.altMoreUsers == null){}
if(place){
//player.sendMessage(ChatColor.RED + "Lockette: Using a sign on a container");
event.setUseItemInHand(Result.ALLOW); //? seems to work in 568
event.setUseInteractedBlock(Result.DENY);
return;
}
}
}
}
if(interactContainer(block, player)) return;
event.setUseInteractedBlock(Result.DENY);
event.setUseItemInHand(Result.DENY);
return;
}
if(type == Material.DIRT.getId()) if(event.hasItem()){
ItemStack item = event.getItem();
type = item.getTypeId();
if((type == Material.DIAMOND_HOE.getId()) || (type == Material.GOLD_HOE.getId()) || (type == Material.IRON_HOE.getId()) ||
(type == Material.STONE_HOE.getId()) || (type == Material.WOOD_HOE.getId())){
Block checkBlock = block.getRelative(BlockFace.UP);
type = checkBlock.getTypeId();
if((type == Material.WOODEN_DOOR.getId()) || (type == Material.IRON_DOOR_BLOCK.getId()) || (type == materialFenceGate)){
event.setUseInteractedBlock(Result.DENY);
return;
}
if(hasAttachedTrapDoor(block)){
event.setUseInteractedBlock(Result.DENY);
return;
}
}
}
}
else if(action == Action.LEFT_CLICK_BLOCK){
if(Lockette.protectTrapDoors) if(type == Material.TRAP_DOOR.getId()){
if(interactDoor(block, player)) return;
event.setUseInteractedBlock(Result.DENY);
event.setUseItemInHand(Result.DENY);
return;
}
if(Lockette.protectDoors) if((type == Material.WOODEN_DOOR.getId()) || (type == Material.IRON_DOOR_BLOCK.getId()) || (type == materialFenceGate)){
if(interactDoor(block, player)) return;
event.setUseInteractedBlock(Result.DENY);
event.setUseItemInHand(Result.DENY);
return;
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerQuit(PlayerQuitEvent event){
Player player = event.getPlayer();
// Player left, so forget about them.
plugin.playerList.remove(player.getName());
}
//********************************************************************************************************************
// Start of interact section
// Returns true if it should be allowed, false if it should be canceled.
private static boolean interactDoor(Block block, Player player){
Block signBlock = Lockette.findBlockOwner(block);
if(signBlock == null) return(true);
boolean wooden = (block.getTypeId() == Material.WOODEN_DOOR.getId());
boolean trap = false;
if(block.getTypeId() == materialFenceGate) wooden = true;
if(Lockette.protectTrapDoors) if(block.getTypeId() == Material.TRAP_DOOR.getId()){
wooden = true;
trap = true;
}
// Someone touched an owned door, lets see if they are allowed.
boolean allow = false;
if(canInteract(block, signBlock, player, true)) allow = true;
/*
// Fee stuff...
if(!allow){
// Check if we can pay a fee to activate.
int fee = getSignOption(signBlock, "fee", Lockette.altFee, 0);
if(signBlock.equals(plugin.playerList.get(player.getName()))){
if(fee == 0){
player.sendMessage("unable to pay fee");
}
else{
player.sendMessage("Fee of " +plugin.economyFormat(fee)+" paid (fake)");
plugin.playerList.put(player.getName(), block);
allow = true;
}
/
if(fee != 0){
Sign sign = (Sign) signBlock.getState();
String text = sign.getLine(1).replaceAll("(?i)\u00A7[0-F]", "");
if(plugin.economyTransfer(player.getName(), text, fee)){
allow = true;
plugin.playerList.put(player.getName(), block);
}
else{}
}/
}
else if(fee != 0){
player.sendMessage("first touch sign to pay fee.");
}
}
*/
if(allow){
List<Block> list = Lockette.toggleDoors(block, Lockette.getSignAttachedBlock(signBlock), wooden, trap);
int delta = Lockette.getSignOption(signBlock, "timer", Lockette.altTimer, Lockette.defaultDoorTimer);
plugin.doorCloser.add(list, delta != 0, delta);
return(true);
}
// Don't have permission.
//event.setCancelled(true);
//if(Lockette.oldListener){
// if(wooden) Lockette.toggleSingleDoor(block);
//}
// Report only once, unless a different block is clicked.
if(block.equals(plugin.playerList.get(player.getName()))) return(false);
plugin.playerList.put(player.getName(), block);
plugin.localizedMessage(player, null, "msg-user-denied-door");
return(false);
}
private static void interactSign(Block block, Player player){
Sign sign = (Sign) block.getState();
String text = sign.getLine(0).replaceAll("(?i)\u00A7[0-F]", "").toLowerCase();
Block signBlock = block;
// Check if it is our sign that was clicked.
if(text.equals("[private]") || text.equalsIgnoreCase(Lockette.altPrivate)){}
else if(text.equals("[more users]") || text.equalsIgnoreCase(Lockette.altMoreUsers)){
Block checkBlock = Lockette.getSignAttachedBlock(block);
if(checkBlock == null) return;
signBlock = Lockette.findBlockOwner(checkBlock);
if(signBlock == null) return;
sign = (Sign) signBlock.getState();
}
else return;
int length = player.getName().length();
if(length > 15) length = 15;
// Check owner.
if(sign.getLine(1).replaceAll("(?i)\u00A7[0-F]", "").equals(player.getName().substring(0, length)) || Lockette.debugMode){
if(!block.equals(plugin.playerList.get(player.getName()))){
// Associate the user with the owned sign.
plugin.playerList.put(player.getName(), block);
plugin.localizedMessage(player, null, "msg-help-select");
}
}
else{/*
int fee = getSignOption(signBlock, "fee", Lockette.altFee, 0);
if(fee != 0){
if(!signBlock.equals(plugin.playerList.get(player.getName()))){
// First half of fee approval.
plugin.playerList.put(player.getName(), signBlock);
plugin.localizedMessage(player, null, "msg-user-touch-fee", sign.getLine(1), plugin.economyFormat(fee));
}
}
else{*/
if(!block.equals(plugin.playerList.get(player.getName()))){
// Only print this message once as well.
plugin.playerList.put(player.getName(), block);
plugin.localizedMessage(player, null, "msg-user-touch-owned", sign.getLine(1));
}
//}
}
}
// Returns true if it should be allowed, false if it should be canceled.
private static boolean interactContainer(Block block, Player player){
Block signBlock = Lockette.findBlockOwner(block);
if(signBlock == null) return(true);
// Someone touched an owned container, lets see if they are allowed.
if(canInteract(block, signBlock, player, false)) return(true);
// Don't have permission.
// Report only once, unless a different block is clicked.
if(block.equals(plugin.playerList.get(player.getName()))) return(false);
plugin.playerList.put(player.getName(), block);
plugin.localizedMessage(player, null, "msg-user-denied");
return(false);
}
// Block is the container or door, signBlock is the owning [Private] sign.
// Returns true if it should be allowed, false if it should be canceled.
private static boolean canInteract(Block block, Block signBlock, Player player, boolean isDoor){
// Check if the block is owned first.
// Moved to outer..
// Lets see if the player is allowed to touch...
Sign sign = (Sign) signBlock.getState();
int length = player.getName().length();
String line;
if(length > 15) length = 15;
// Check owner.
line = sign.getLine(1).replaceAll("(?i)\u00A7[0-F]", "");
if(line.equals(player.getName().substring(0, length))) return(true);
if(plugin.inGroup(block.getWorld(), player, line)) return(true);
// Check main two users.
int y;
for(y = 2; y <= 3; ++y) if(!sign.getLine(y).isEmpty()){
line = sign.getLine(y).replaceAll("(?i)\u00A7[0-F]", "");
if(plugin.inGroup(block.getWorld(), player, line)) return(true);
if(line.equalsIgnoreCase(player.getName().substring(0, length))) return(true);
}
// Check for more users.
List<Block> list = Lockette.findBlockUsers(block, signBlock);
int x, count = list.size();
Sign sign2;
for(x = 0; x < count; ++x){
sign2 = (Sign) list.get(x).getState();
for(y = 1; y <= 3; ++y) if(!sign2.getLine(y).isEmpty()){
line = sign2.getLine(y).replaceAll("(?i)\u00A7[0-F]", "");
if(plugin.inGroup(block.getWorld(), player, line)) return(true);
if(line.equalsIgnoreCase(player.getName().substring(0, length))) return(true);
}
}
// Check admin list last.
boolean snoop = false;
if(isDoor){
if(Lockette.adminBypass){
if(plugin.hasPermission(block.getWorld(), player, "lockette.admin.bypass")) snoop = true;
if(snoop){
Lockette.log.info("[" + plugin.getDescription().getName() + "] (Admin) " + player.getName() + " has bypassed a door owned by " + sign.getLine(1));
plugin.localizedMessage(player, null, "msg-admin-bypass", sign.getLine(1));
return(true);
}
}
}
else if(Lockette.adminSnoop){
if(plugin.hasPermission(block.getWorld(), player, "lockette.admin.snoop")) snoop = true;
if(snoop){
Lockette.log.info("[" + plugin.getDescription().getName() + "] (Admin) " + player.getName() + " has snooped around in a container owned by " + sign.getLine(1) + "!");
plugin.localizedMessage(player, Lockette.broadcastSnoopTarget, "msg-admin-snoop", sign.getLine(1));
return(true);
}
}
// Don't have permission.
return(false);
}
//********************************************************************************************************************
// Start of utility section
// Returns true if a door wasn't changed.
private static boolean fixDoor(Player player){
Block block = player.getTargetBlock(null, 10);
int type = block.getTypeId();
boolean doCheck = false;
// Check if the block being looked at is a door block.
if(Lockette.protectTrapDoors){
if(type == Material.TRAP_DOOR.getId()) doCheck = true;
}
if(Lockette.protectDoors){
if((type == Material.WOODEN_DOOR.getId()) || (type == Material.IRON_DOOR_BLOCK.getId()) || (type == materialFenceGate)) doCheck = true;
}
if(!doCheck) return(true);
Block signBlock = Lockette.findBlockOwner(block);
if(signBlock == null) return(true);
Sign sign = (Sign) signBlock.getState();
int length = player.getName().length();
if(length > 15) length = 15;
// Check owner only.
if(sign.getLine(1).replaceAll("(?i)\u00A7[0-F]", "").equals(player.getName().substring(0, length))){
Lockette.toggleSingleDoor(block);
return(false);
}
return(true);
}
- public static boolean hasTrapDoorAttached(Block block){
+ public static boolean hasAttachedTrapDoor(Block block){
Block checkBlock;
int type;
- int face = block.getData() & 0x3;
+ int face;
checkBlock = block.getRelative(BlockFace.NORTH);
type = checkBlock.getTypeId();
if(type == Material.TRAP_DOOR.getId()){
+ face = checkBlock.getData() & 0x3;
if(face == 2) return(true);
}
checkBlock = block.getRelative(BlockFace.EAST);
type = checkBlock.getTypeId();
if(type == Material.TRAP_DOOR.getId()){
+ face = checkBlock.getData() & 0x3;
if(face == 0) return(true);
}
checkBlock = block.getRelative(BlockFace.SOUTH);
type = checkBlock.getTypeId();
if(type == Material.TRAP_DOOR.getId()){
+ face = checkBlock.getData() & 0x3;
if(face == 3) return(true);
}
checkBlock = block.getRelative(BlockFace.WEST);
type = checkBlock.getTypeId();
if(type == Material.TRAP_DOOR.getId()){
+ face = checkBlock.getData() & 0x3;
if(face == 1) return(true);
}
return(false);
}
}
| false | true | private static void interactSign(Block block, Player player){
Sign sign = (Sign) block.getState();
String text = sign.getLine(0).replaceAll("(?i)\u00A7[0-F]", "").toLowerCase();
Block signBlock = block;
// Check if it is our sign that was clicked.
if(text.equals("[private]") || text.equalsIgnoreCase(Lockette.altPrivate)){}
else if(text.equals("[more users]") || text.equalsIgnoreCase(Lockette.altMoreUsers)){
Block checkBlock = Lockette.getSignAttachedBlock(block);
if(checkBlock == null) return;
signBlock = Lockette.findBlockOwner(checkBlock);
if(signBlock == null) return;
sign = (Sign) signBlock.getState();
}
else return;
int length = player.getName().length();
if(length > 15) length = 15;
// Check owner.
if(sign.getLine(1).replaceAll("(?i)\u00A7[0-F]", "").equals(player.getName().substring(0, length)) || Lockette.debugMode){
if(!block.equals(plugin.playerList.get(player.getName()))){
// Associate the user with the owned sign.
plugin.playerList.put(player.getName(), block);
plugin.localizedMessage(player, null, "msg-help-select");
}
}
else{/*
int fee = getSignOption(signBlock, "fee", Lockette.altFee, 0);
if(fee != 0){
if(!signBlock.equals(plugin.playerList.get(player.getName()))){
// First half of fee approval.
plugin.playerList.put(player.getName(), signBlock);
plugin.localizedMessage(player, null, "msg-user-touch-fee", sign.getLine(1), plugin.economyFormat(fee));
}
}
else{*/
if(!block.equals(plugin.playerList.get(player.getName()))){
// Only print this message once as well.
plugin.playerList.put(player.getName(), block);
plugin.localizedMessage(player, null, "msg-user-touch-owned", sign.getLine(1));
}
//}
}
}
// Returns true if it should be allowed, false if it should be canceled.
private static boolean interactContainer(Block block, Player player){
Block signBlock = Lockette.findBlockOwner(block);
if(signBlock == null) return(true);
// Someone touched an owned container, lets see if they are allowed.
if(canInteract(block, signBlock, player, false)) return(true);
// Don't have permission.
// Report only once, unless a different block is clicked.
if(block.equals(plugin.playerList.get(player.getName()))) return(false);
plugin.playerList.put(player.getName(), block);
plugin.localizedMessage(player, null, "msg-user-denied");
return(false);
}
// Block is the container or door, signBlock is the owning [Private] sign.
// Returns true if it should be allowed, false if it should be canceled.
private static boolean canInteract(Block block, Block signBlock, Player player, boolean isDoor){
// Check if the block is owned first.
// Moved to outer..
// Lets see if the player is allowed to touch...
Sign sign = (Sign) signBlock.getState();
int length = player.getName().length();
String line;
if(length > 15) length = 15;
// Check owner.
line = sign.getLine(1).replaceAll("(?i)\u00A7[0-F]", "");
if(line.equals(player.getName().substring(0, length))) return(true);
if(plugin.inGroup(block.getWorld(), player, line)) return(true);
// Check main two users.
int y;
for(y = 2; y <= 3; ++y) if(!sign.getLine(y).isEmpty()){
line = sign.getLine(y).replaceAll("(?i)\u00A7[0-F]", "");
if(plugin.inGroup(block.getWorld(), player, line)) return(true);
if(line.equalsIgnoreCase(player.getName().substring(0, length))) return(true);
}
// Check for more users.
List<Block> list = Lockette.findBlockUsers(block, signBlock);
int x, count = list.size();
Sign sign2;
for(x = 0; x < count; ++x){
sign2 = (Sign) list.get(x).getState();
for(y = 1; y <= 3; ++y) if(!sign2.getLine(y).isEmpty()){
line = sign2.getLine(y).replaceAll("(?i)\u00A7[0-F]", "");
if(plugin.inGroup(block.getWorld(), player, line)) return(true);
if(line.equalsIgnoreCase(player.getName().substring(0, length))) return(true);
}
}
// Check admin list last.
boolean snoop = false;
if(isDoor){
if(Lockette.adminBypass){
if(plugin.hasPermission(block.getWorld(), player, "lockette.admin.bypass")) snoop = true;
if(snoop){
Lockette.log.info("[" + plugin.getDescription().getName() + "] (Admin) " + player.getName() + " has bypassed a door owned by " + sign.getLine(1));
plugin.localizedMessage(player, null, "msg-admin-bypass", sign.getLine(1));
return(true);
}
}
}
else if(Lockette.adminSnoop){
if(plugin.hasPermission(block.getWorld(), player, "lockette.admin.snoop")) snoop = true;
if(snoop){
Lockette.log.info("[" + plugin.getDescription().getName() + "] (Admin) " + player.getName() + " has snooped around in a container owned by " + sign.getLine(1) + "!");
plugin.localizedMessage(player, Lockette.broadcastSnoopTarget, "msg-admin-snoop", sign.getLine(1));
return(true);
}
}
// Don't have permission.
return(false);
}
//********************************************************************************************************************
// Start of utility section
// Returns true if a door wasn't changed.
private static boolean fixDoor(Player player){
Block block = player.getTargetBlock(null, 10);
int type = block.getTypeId();
boolean doCheck = false;
// Check if the block being looked at is a door block.
if(Lockette.protectTrapDoors){
if(type == Material.TRAP_DOOR.getId()) doCheck = true;
}
if(Lockette.protectDoors){
if((type == Material.WOODEN_DOOR.getId()) || (type == Material.IRON_DOOR_BLOCK.getId()) || (type == materialFenceGate)) doCheck = true;
}
if(!doCheck) return(true);
Block signBlock = Lockette.findBlockOwner(block);
if(signBlock == null) return(true);
Sign sign = (Sign) signBlock.getState();
int length = player.getName().length();
if(length > 15) length = 15;
// Check owner only.
if(sign.getLine(1).replaceAll("(?i)\u00A7[0-F]", "").equals(player.getName().substring(0, length))){
Lockette.toggleSingleDoor(block);
return(false);
}
return(true);
}
public static boolean hasTrapDoorAttached(Block block){
Block checkBlock;
int type;
int face = block.getData() & 0x3;
checkBlock = block.getRelative(BlockFace.NORTH);
type = checkBlock.getTypeId();
if(type == Material.TRAP_DOOR.getId()){
if(face == 2) return(true);
}
checkBlock = block.getRelative(BlockFace.EAST);
type = checkBlock.getTypeId();
if(type == Material.TRAP_DOOR.getId()){
if(face == 0) return(true);
}
checkBlock = block.getRelative(BlockFace.SOUTH);
type = checkBlock.getTypeId();
if(type == Material.TRAP_DOOR.getId()){
if(face == 3) return(true);
}
checkBlock = block.getRelative(BlockFace.WEST);
type = checkBlock.getTypeId();
if(type == Material.TRAP_DOOR.getId()){
if(face == 1) return(true);
}
return(false);
}
}
| private static void interactSign(Block block, Player player){
Sign sign = (Sign) block.getState();
String text = sign.getLine(0).replaceAll("(?i)\u00A7[0-F]", "").toLowerCase();
Block signBlock = block;
// Check if it is our sign that was clicked.
if(text.equals("[private]") || text.equalsIgnoreCase(Lockette.altPrivate)){}
else if(text.equals("[more users]") || text.equalsIgnoreCase(Lockette.altMoreUsers)){
Block checkBlock = Lockette.getSignAttachedBlock(block);
if(checkBlock == null) return;
signBlock = Lockette.findBlockOwner(checkBlock);
if(signBlock == null) return;
sign = (Sign) signBlock.getState();
}
else return;
int length = player.getName().length();
if(length > 15) length = 15;
// Check owner.
if(sign.getLine(1).replaceAll("(?i)\u00A7[0-F]", "").equals(player.getName().substring(0, length)) || Lockette.debugMode){
if(!block.equals(plugin.playerList.get(player.getName()))){
// Associate the user with the owned sign.
plugin.playerList.put(player.getName(), block);
plugin.localizedMessage(player, null, "msg-help-select");
}
}
else{/*
int fee = getSignOption(signBlock, "fee", Lockette.altFee, 0);
if(fee != 0){
if(!signBlock.equals(plugin.playerList.get(player.getName()))){
// First half of fee approval.
plugin.playerList.put(player.getName(), signBlock);
plugin.localizedMessage(player, null, "msg-user-touch-fee", sign.getLine(1), plugin.economyFormat(fee));
}
}
else{*/
if(!block.equals(plugin.playerList.get(player.getName()))){
// Only print this message once as well.
plugin.playerList.put(player.getName(), block);
plugin.localizedMessage(player, null, "msg-user-touch-owned", sign.getLine(1));
}
//}
}
}
// Returns true if it should be allowed, false if it should be canceled.
private static boolean interactContainer(Block block, Player player){
Block signBlock = Lockette.findBlockOwner(block);
if(signBlock == null) return(true);
// Someone touched an owned container, lets see if they are allowed.
if(canInteract(block, signBlock, player, false)) return(true);
// Don't have permission.
// Report only once, unless a different block is clicked.
if(block.equals(plugin.playerList.get(player.getName()))) return(false);
plugin.playerList.put(player.getName(), block);
plugin.localizedMessage(player, null, "msg-user-denied");
return(false);
}
// Block is the container or door, signBlock is the owning [Private] sign.
// Returns true if it should be allowed, false if it should be canceled.
private static boolean canInteract(Block block, Block signBlock, Player player, boolean isDoor){
// Check if the block is owned first.
// Moved to outer..
// Lets see if the player is allowed to touch...
Sign sign = (Sign) signBlock.getState();
int length = player.getName().length();
String line;
if(length > 15) length = 15;
// Check owner.
line = sign.getLine(1).replaceAll("(?i)\u00A7[0-F]", "");
if(line.equals(player.getName().substring(0, length))) return(true);
if(plugin.inGroup(block.getWorld(), player, line)) return(true);
// Check main two users.
int y;
for(y = 2; y <= 3; ++y) if(!sign.getLine(y).isEmpty()){
line = sign.getLine(y).replaceAll("(?i)\u00A7[0-F]", "");
if(plugin.inGroup(block.getWorld(), player, line)) return(true);
if(line.equalsIgnoreCase(player.getName().substring(0, length))) return(true);
}
// Check for more users.
List<Block> list = Lockette.findBlockUsers(block, signBlock);
int x, count = list.size();
Sign sign2;
for(x = 0; x < count; ++x){
sign2 = (Sign) list.get(x).getState();
for(y = 1; y <= 3; ++y) if(!sign2.getLine(y).isEmpty()){
line = sign2.getLine(y).replaceAll("(?i)\u00A7[0-F]", "");
if(plugin.inGroup(block.getWorld(), player, line)) return(true);
if(line.equalsIgnoreCase(player.getName().substring(0, length))) return(true);
}
}
// Check admin list last.
boolean snoop = false;
if(isDoor){
if(Lockette.adminBypass){
if(plugin.hasPermission(block.getWorld(), player, "lockette.admin.bypass")) snoop = true;
if(snoop){
Lockette.log.info("[" + plugin.getDescription().getName() + "] (Admin) " + player.getName() + " has bypassed a door owned by " + sign.getLine(1));
plugin.localizedMessage(player, null, "msg-admin-bypass", sign.getLine(1));
return(true);
}
}
}
else if(Lockette.adminSnoop){
if(plugin.hasPermission(block.getWorld(), player, "lockette.admin.snoop")) snoop = true;
if(snoop){
Lockette.log.info("[" + plugin.getDescription().getName() + "] (Admin) " + player.getName() + " has snooped around in a container owned by " + sign.getLine(1) + "!");
plugin.localizedMessage(player, Lockette.broadcastSnoopTarget, "msg-admin-snoop", sign.getLine(1));
return(true);
}
}
// Don't have permission.
return(false);
}
//********************************************************************************************************************
// Start of utility section
// Returns true if a door wasn't changed.
private static boolean fixDoor(Player player){
Block block = player.getTargetBlock(null, 10);
int type = block.getTypeId();
boolean doCheck = false;
// Check if the block being looked at is a door block.
if(Lockette.protectTrapDoors){
if(type == Material.TRAP_DOOR.getId()) doCheck = true;
}
if(Lockette.protectDoors){
if((type == Material.WOODEN_DOOR.getId()) || (type == Material.IRON_DOOR_BLOCK.getId()) || (type == materialFenceGate)) doCheck = true;
}
if(!doCheck) return(true);
Block signBlock = Lockette.findBlockOwner(block);
if(signBlock == null) return(true);
Sign sign = (Sign) signBlock.getState();
int length = player.getName().length();
if(length > 15) length = 15;
// Check owner only.
if(sign.getLine(1).replaceAll("(?i)\u00A7[0-F]", "").equals(player.getName().substring(0, length))){
Lockette.toggleSingleDoor(block);
return(false);
}
return(true);
}
public static boolean hasAttachedTrapDoor(Block block){
Block checkBlock;
int type;
int face;
checkBlock = block.getRelative(BlockFace.NORTH);
type = checkBlock.getTypeId();
if(type == Material.TRAP_DOOR.getId()){
face = checkBlock.getData() & 0x3;
if(face == 2) return(true);
}
checkBlock = block.getRelative(BlockFace.EAST);
type = checkBlock.getTypeId();
if(type == Material.TRAP_DOOR.getId()){
face = checkBlock.getData() & 0x3;
if(face == 0) return(true);
}
checkBlock = block.getRelative(BlockFace.SOUTH);
type = checkBlock.getTypeId();
if(type == Material.TRAP_DOOR.getId()){
face = checkBlock.getData() & 0x3;
if(face == 3) return(true);
}
checkBlock = block.getRelative(BlockFace.WEST);
type = checkBlock.getTypeId();
if(type == Material.TRAP_DOOR.getId()){
face = checkBlock.getData() & 0x3;
if(face == 1) return(true);
}
return(false);
}
}
|
diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/tasklet/ExceptionRestartableTaskletTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/tasklet/ExceptionRestartableTaskletTests.java
index 5279dc52a..f70c9fe77 100644
--- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/tasklet/ExceptionRestartableTaskletTests.java
+++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/tasklet/ExceptionRestartableTaskletTests.java
@@ -1,65 +1,65 @@
package org.springframework.batch.sample.tasklet;
import java.util.ArrayList;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.exception.BatchCriticalException;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.provider.ListItemReader;
import org.springframework.batch.repeat.context.RepeatContextSupport;
import org.springframework.batch.repeat.synch.RepeatSynchronizationManager;
import org.springframework.batch.sample.tasklet.ExceptionRestartableTasklet;
public class ExceptionRestartableTaskletTests extends TestCase {
//expected call count before exception is thrown (exception should be thrown in next iteration)
private static final int ITER_COUNT = 5;
protected void tearDown() throws Exception {
RepeatSynchronizationManager.clear();
}
public void testProcess() throws Exception {
- //create mock item processor wich will be called by module.process() method
+ //create mock item processor which will be called by module.process() method
MockControl processorControl = MockControl.createControl(ItemProcessor.class);
ItemProcessor itemProcessor = (ItemProcessor)processorControl.getMock();
//set expected call count and argument matcher
itemProcessor.process(null);
processorControl.setMatcher(MockControl.ALWAYS_MATCHER);
processorControl.setVoidCallable(ITER_COUNT);
processorControl.replay();
//create module and set item processor and iteration count
ExceptionRestartableTasklet module = new ExceptionRestartableTasklet();
module.setItemProcessor(itemProcessor);
module.setThrowExceptionOnRecordNumber(ITER_COUNT + 1);
module.setItemReader(new ListItemReader(new ArrayList() {{
add("a");
add("b");
add("c");
add("d");
add("e");
add("f");
}}));
RepeatSynchronizationManager.register(new RepeatContextSupport(null));
//call process method multiple times and verify whether exception is thrown when expected
for (int i = 0; i <= ITER_COUNT; i++) {
try {
module.execute();
assertTrue(i < ITER_COUNT);
} catch (BatchCriticalException bce) {
assertEquals(ITER_COUNT,i);
}
}
//verify method calls
processorControl.verify();
}
}
| true | true | public void testProcess() throws Exception {
//create mock item processor wich will be called by module.process() method
MockControl processorControl = MockControl.createControl(ItemProcessor.class);
ItemProcessor itemProcessor = (ItemProcessor)processorControl.getMock();
//set expected call count and argument matcher
itemProcessor.process(null);
processorControl.setMatcher(MockControl.ALWAYS_MATCHER);
processorControl.setVoidCallable(ITER_COUNT);
processorControl.replay();
//create module and set item processor and iteration count
ExceptionRestartableTasklet module = new ExceptionRestartableTasklet();
module.setItemProcessor(itemProcessor);
module.setThrowExceptionOnRecordNumber(ITER_COUNT + 1);
module.setItemReader(new ListItemReader(new ArrayList() {{
add("a");
add("b");
add("c");
add("d");
add("e");
add("f");
}}));
RepeatSynchronizationManager.register(new RepeatContextSupport(null));
//call process method multiple times and verify whether exception is thrown when expected
for (int i = 0; i <= ITER_COUNT; i++) {
try {
module.execute();
assertTrue(i < ITER_COUNT);
} catch (BatchCriticalException bce) {
assertEquals(ITER_COUNT,i);
}
}
//verify method calls
processorControl.verify();
}
| public void testProcess() throws Exception {
//create mock item processor which will be called by module.process() method
MockControl processorControl = MockControl.createControl(ItemProcessor.class);
ItemProcessor itemProcessor = (ItemProcessor)processorControl.getMock();
//set expected call count and argument matcher
itemProcessor.process(null);
processorControl.setMatcher(MockControl.ALWAYS_MATCHER);
processorControl.setVoidCallable(ITER_COUNT);
processorControl.replay();
//create module and set item processor and iteration count
ExceptionRestartableTasklet module = new ExceptionRestartableTasklet();
module.setItemProcessor(itemProcessor);
module.setThrowExceptionOnRecordNumber(ITER_COUNT + 1);
module.setItemReader(new ListItemReader(new ArrayList() {{
add("a");
add("b");
add("c");
add("d");
add("e");
add("f");
}}));
RepeatSynchronizationManager.register(new RepeatContextSupport(null));
//call process method multiple times and verify whether exception is thrown when expected
for (int i = 0; i <= ITER_COUNT; i++) {
try {
module.execute();
assertTrue(i < ITER_COUNT);
} catch (BatchCriticalException bce) {
assertEquals(ITER_COUNT,i);
}
}
//verify method calls
processorControl.verify();
}
|
diff --git a/org/xbill/DNS/Name.java b/org/xbill/DNS/Name.java
index 9dd76ad..4a998d8 100644
--- a/org/xbill/DNS/Name.java
+++ b/org/xbill/DNS/Name.java
@@ -1,736 +1,739 @@
// Copyright (c) 1999 Brian Wellington ([email protected])
package org.xbill.DNS;
import java.io.*;
import java.text.*;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* A representation of a domain name.
*
* @author Brian Wellington
*/
public class Name implements Comparable {
private static final int LABEL_NORMAL = 0;
private static final int LABEL_COMPRESSION = 0xC0;
private static final int LABEL_MASK = 0xC0;
private byte [] name;
private long offsets;
private int hashcode;
private static final byte [] emptyLabel = new byte[] {(byte)0};
private static final byte [] wildLabel = new byte[] {(byte)1, (byte)'*'};
/** The root name */
public static final Name root;
/** The maximum length of a Name */
private static final int MAXNAME = 255;
/** The maximum length of labels a label a Name */
private static final int MAXLABEL = 63;
/** The maximum number of labels in a Name */
private static final int MAXLABELS = 128;
/** The maximum number of cached offsets */
private static final int MAXOFFSETS = 7;
/* Used for printing non-printable characters */
private static final DecimalFormat byteFormat = new DecimalFormat();
/* Used to efficiently convert bytes to lowercase */
private static final byte lowercase[] = new byte[256];
/* Used in wildcard names. */
private static final Name wild;
static {
byteFormat.setMinimumIntegerDigits(3);
for (int i = 0; i < lowercase.length; i++) {
if (i < 'A' || i > 'Z')
lowercase[i] = (byte)i;
else
lowercase[i] = (byte)(i - 'A' + 'a');
}
root = new Name();
wild = new Name();
root.appendSafe(emptyLabel, 0, 1);
wild.appendSafe(wildLabel, 0, 1);
}
private
Name() {
}
private final void
dump(String prefix) {
String s;
try {
s = toString();
} catch (Exception e) {
s = "<unprintable>";
}
System.out.println(prefix + ": " + s);
byte labels = labels();
for (int i = 0; i < labels; i++)
System.out.print(offset(i) + " ");
System.out.println("");
for (int i = 0; name != null && i < name.length; i++)
System.out.print((name[i] & 0xFF) + " ");
System.out.println("");
}
private final void
setoffset(int n, int offset) {
if (n >= MAXOFFSETS)
return;
int shift = 8 * (7 - n);
offsets &= (~(0xFFL << shift));
offsets |= ((long)offset << shift);
}
private final int
offset(int n) {
if (n < MAXOFFSETS) {
int shift = 8 * (7 - n);
return ((int)(offsets >>> shift) & 0xFF);
} else {
int pos = offset(MAXOFFSETS - 1);
for (int i = MAXOFFSETS - 1; i < n; i++)
pos += (name[pos] + 1);
return (pos);
}
}
private final void
setlabels(byte labels) {
offsets &= ~(0xFF);
offsets |= labels;
}
private final byte
getlabels() {
return (byte)(offsets & 0xFF);
}
private static final void
copy(Name src, Name dst) {
dst.name = src.name;
dst.offsets = src.offsets;
}
private final void
append(byte [] array, int start, int n) throws NameTooLongException {
int length = (name == null ? 0 : (name.length - offset(0)));
int alength = 0;
for (int i = 0, pos = start; i < n; i++) {
int len = array[pos];
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
len++;
pos += len;
alength += len;
}
int newlength = length + alength;
if (newlength > MAXNAME)
throw new NameTooLongException();
byte labels = getlabels();
int newlabels = labels + n;
if (newlabels > MAXLABELS)
throw new IllegalStateException("too many labels");
byte [] newname = new byte[newlength];
if (length != 0)
System.arraycopy(name, offset(0), newname, 0, length);
System.arraycopy(array, start, newname, length, alength);
name = newname;
for (int i = 0, pos = length; i < n; i++) {
setoffset(labels + i, pos);
pos += (newname[pos] + 1);
}
setlabels((byte) newlabels);
}
private final void
appendFromString(byte [] array, int start, int n) throws TextParseException {
try {
append(array, start, n);
}
catch (NameTooLongException e) {
throw new TextParseException("Name too long");
}
}
private final void
appendSafe(byte [] array, int start, int n) {
try {
append(array, start, n);
}
catch (NameTooLongException e) {
}
}
/**
* Create a new name from a string and an origin
* @param s The string to be converted
* @param origin If the name is not absolute, the origin to be appended
* @deprecated As of dnsjava 1.3.0, replaced by <code>Name.fromString</code>.
*/
public
Name(String s, Name origin) {
Name n;
try {
n = Name.fromString(s, origin);
}
catch (TextParseException e) {
StringBuffer sb = new StringBuffer(s);
if (origin != null)
sb.append("." + origin);
sb.append(": "+ e.getMessage());
System.err.println(sb.toString());
return;
}
if (!n.isAbsolute() && !Options.check("pqdn") &&
n.getlabels() > 1 && n.getlabels() < MAXLABELS - 1)
{
/*
* This isn't exactly right, but it's close.
* Partially qualified names are evil.
*/
n.appendSafe(emptyLabel, 0, 1);
}
copy(n, this);
}
/**
* Create a new name from a string
* @param s The string to be converted
* @deprecated as of dnsjava 1.3.0, replaced by <code>Name.fromString</code>.
*/
public
Name(String s) {
this (s, null);
}
/**
* Create a new name from a string and an origin. This does not automatically
* make the name absolute; it will be absolute if it has a trailing dot or an
* absolute origin is appended.
* @param s The string to be converted
* @param origin If the name is not absolute, the origin to be appended.
* @throws TextParseException The name is invalid.
*/
public static Name
fromString(String s, Name origin) throws TextParseException {
Name name = new Name();
if (s.equals(""))
throw new TextParseException("empty name");
else if (s.equals("@")) {
if (origin == null)
return name;
return origin;
} else if (s.equals("."))
return (root);
int labelstart = -1;
int pos = 1;
byte [] label = new byte[MAXLABEL + 1];
boolean escaped = false;
int digits = 0;
int intval = 0;
boolean absolute = false;
for (int i = 0; i < s.length(); i++) {
byte b = (byte) s.charAt(i);
if (escaped) {
if (b >= '0' && b <= '9' && digits < 3) {
digits++;
- intval *= 10 + (b - '0');
+ intval *= 10;
intval += (b - '0');
+ if (intval > 255)
+ throw new TextParseException
+ ("bad escape");
if (digits < 3)
continue;
b = (byte) intval;
}
else if (digits > 0 && digits < 3)
throw new TextParseException("bad escape");
if (pos >= MAXLABEL)
throw new TextParseException("label too long");
labelstart = pos;
label[pos++] = b;
escaped = false;
} else if (b == '\\') {
escaped = true;
digits = 0;
intval = 0;
} else if (b == '.') {
if (labelstart == -1)
throw new TextParseException("invalid label");
label[0] = (byte)(pos - 1);
name.appendFromString(label, 0, 1);
labelstart = -1;
pos = 1;
} else {
if (labelstart == -1)
labelstart = i;
if (pos >= MAXLABEL)
throw new TextParseException("label too long");
label[pos++] = b;
}
}
if (labelstart == -1) {
name.appendFromString(emptyLabel, 0, 1);
absolute = true;
} else {
label[0] = (byte)(pos - 1);
name.appendFromString(label, 0, 1);
}
if (origin != null && !absolute)
name.appendFromString(origin.name, 0, origin.getlabels());
return (name);
}
/**
* Create a new name from a string. This does not automatically make the name
* absolute; it will be absolute if it has a trailing dot.
* @param s The string to be converted
* @throws TextParseException The name is invalid.
*/
public static Name
fromString(String s) throws TextParseException {
return fromString(s, null);
}
/**
* Create a new name from a constant string. This should only be used when
the name is known to be good - that is, when it is constant.
* @param s The string to be converted
* @throws IllegalArgumentException The name is invalid.
*/
public static Name
fromConstantString(String s) {
try {
return fromString(s, null);
}
catch (TextParseException e) {
throw new IllegalArgumentException("Invalid name '" + s + "'");
}
}
/**
* Create a new name from DNS wire format
* @param in A stream containing the input data
*/
public
Name(DataByteInputStream in) throws IOException {
int len, pos, savedpos;
Name name2;
boolean done = false;
byte [] label = new byte[MAXLABEL + 1];
while (!done) {
len = in.readUnsignedByte();
switch (len & LABEL_MASK) {
case LABEL_NORMAL:
if (getlabels() >= MAXLABELS)
throw new WireParseException("too many labels");
if (len == 0) {
append(emptyLabel, 0, 1);
done = true;
} else {
label[0] = (byte)len;
in.readArray(label, 1, len);
append(label, 0, 1);
}
break;
case LABEL_COMPRESSION:
pos = in.readUnsignedByte();
pos += ((len & ~LABEL_MASK) << 8);
if (Options.check("verbosecompression"))
System.err.println("currently " + in.getPos() +
", pointer to " + pos);
savedpos = in.getPos();
if (pos >= savedpos)
throw new WireParseException("bad compression");
in.setPos(pos);
if (Options.check("verbosecompression"))
System.err.println("current name '" + this +
"', seeking to " + pos);
try {
name2 = new Name(in);
}
finally {
in.setPos(savedpos);
}
append(name2.name, 0, name2.labels());
done = true;
break;
}
}
}
/**
* Create a new name by removing labels from the beginning of an existing Name
* @param src An existing Name
* @param n The number of labels to remove from the beginning in the copy
*/
public
Name(Name src, int n) {
byte slabels = src.labels();
if (n > slabels)
throw new IllegalArgumentException("attempted to remove too " +
"many labels");
name = src.name;
setlabels((byte)(slabels - n));
for (int i = 0; i < MAXOFFSETS && i < slabels - n; i++)
setoffset(i, src.offset(i + n));
}
/**
* Creates a new name by concatenating two existing names.
* @param prefix The prefix name.
* @param suffix The suffix name.
* @return The concatenated name.
* @throws NameTooLongException The name is too long.
*/
public static Name
concatenate(Name prefix, Name suffix) throws NameTooLongException {
if (prefix.isAbsolute())
return (prefix);
Name newname = new Name();
copy(prefix, newname);
newname.append(suffix.name, suffix.offset(0), suffix.getlabels());
return newname;
}
/**
* Generates a new Name with the first n labels replaced by a wildcard
* @return The wildcard name
*/
public Name
wild(int n) {
if (n < 1)
throw new IllegalArgumentException("must replace 1 or more " +
"labels");
try {
Name newname = new Name();
copy(wild, newname);
newname.append(name, offset(n), getlabels() - n);
return newname;
}
catch (NameTooLongException e) {
throw new IllegalStateException
("Name.wild: concatenate failed");
}
}
/**
* Generates a new Name to be used when following a DNAME.
* @param dname The DNAME record to follow.
* @return The constructed name.
* @throws NameTooLongException The resulting name is too long.
*/
public Name
fromDNAME(DNAMERecord dname) throws NameTooLongException {
Name dnameowner = dname.getName();
Name dnametarget = dname.getTarget();
if (!subdomain(dnameowner))
return null;
int plabels = labels() - dnameowner.labels();
int plength = length() - dnameowner.length();
int pstart = offset(0);
int dlabels = dnametarget.labels();
int dlength = dnametarget.length();
if (plength + dlength > MAXNAME)
throw new NameTooLongException();
Name newname = new Name();
newname.setlabels((byte)(plabels + dlabels));
newname.name = new byte[plength + dlength];
System.arraycopy(name, pstart, newname.name, 0, plength);
System.arraycopy(dnametarget.name, 0, newname.name, plength, dlength);
for (int i = 0, pos = 0; i < MAXOFFSETS && i < plabels + dlabels; i++) {
newname.setoffset(i, pos);
pos += (newname.name[pos] + 1);
}
return newname;
}
/**
* Is this name a wildcard?
*/
public boolean
isWild() {
if (labels() == 0)
return false;
return (name[0] == (byte)1 && name[1] == (byte)'*');
}
/**
* Is this name fully qualified (that is, absolute)?
* @deprecated As of dnsjava 1.3.0, replaced by <code>isAbsolute</code>.
*/
public boolean
isQualified() {
return (isAbsolute());
}
/**
* Is this name absolute?
*/
public boolean
isAbsolute() {
if (labels() == 0)
return false;
return (name[name.length - 1] == 0);
}
/**
* The length of the name.
*/
public short
length() {
return (short)(name.length - offset(0));
}
/**
* The number of labels in the name.
*/
public byte
labels() {
return getlabels();
}
/**
* Is the current Name a subdomain of the specified name?
*/
public boolean
subdomain(Name domain) {
byte labels = labels();
byte dlabels = domain.labels();
if (dlabels > labels)
return false;
if (dlabels == labels)
return equals(domain);
return domain.equals(name, offset(labels - dlabels));
}
private String
byteString(byte [] array, int pos) {
StringBuffer sb = new StringBuffer();
int len = array[pos++];
for (int i = pos; i < pos + len; i++) {
short b = (short)(array[i] & 0xFF);
if (b <= 0x20 || b >= 0x7f) {
sb.append('\\');
sb.append(byteFormat.format(b));
}
else if (b == '"' || b == '(' || b == ')' || b == '.' ||
b == ';' || b == '\\' || b == '@' || b == '$')
{
sb.append('\\');
sb.append((char)b);
}
else
sb.append((char)b);
}
return sb.toString();
}
/**
* Convert Name to a String
*/
public String
toString() {
byte labels = labels();
if (labels == 0)
return "@";
else if (labels == 1 && name[offset(0)] == 0)
return ".";
StringBuffer sb = new StringBuffer();
for (int i = 0, pos = offset(0); i < labels; i++) {
int len = name[pos];
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
if (len == 0)
break;
sb.append(byteString(name, pos));
sb.append('.');
pos += (1 + len);
}
if (!isAbsolute())
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
/**
* Convert the nth label in a Name to a String
* @param n The label to be converted to a String
*/
public String
getLabelString(int n) {
int pos = offset(n);
return byteString(name, pos);
}
/**
* Convert Name to DNS wire format
* @param out The output stream containing the DNS message.
* @param c The compression context, or null of no compression is desired.
* @throws IOException An error occurred writing the name.
* @throws IllegalArgumentException The name is not absolute.
*/
public void
toWire(DataByteOutputStream out, Compression c) throws IOException {
if (!isAbsolute())
throw new IllegalArgumentException("toWire() called on " +
"non-absolute name");
byte labels = labels();
for (int i = 0; i < labels - 1; i++) {
Name tname;
if (i == 0)
tname = this;
else
tname = new Name(this, i);
int pos = -1;
if (c != null)
pos = c.get(tname);
if (pos >= 0) {
pos |= (LABEL_MASK << 8);
out.writeShort(pos);
return;
} else {
if (c != null)
c.add(out.getPos(), tname);
out.writeString(name, offset(i));
}
}
out.writeByte(0);
}
/**
* Convert Name to canonical DNS wire format (all lowercase)
* @param out The output stream to which the message is written.
* @throws IOException An error occurred writing the name.
*/
public void
toWireCanonical(DataByteOutputStream out) throws IOException {
byte [] b = toWireCanonical();
out.write(b);
}
/**
* Convert Name to canonical DNS wire format (all lowercase)
* @throws IOException An error occurred writing the name.
*/
public byte []
toWireCanonical() throws IOException {
byte labels = labels();
if (labels == 0)
return (new byte[0]);
byte [] b = new byte[name.length - offset(0)];
for (int i = 0, pos = offset(0); i < labels; i++) {
int len = name[pos];
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
b[pos] = name[pos++];
for (int j = 0; j < len; j++)
b[pos] = lowercase[name[pos++]];
}
return b;
}
private final boolean
equals(byte [] b, int bpos) {
byte labels = labels();
for (int i = 0, pos = offset(0); i < labels; i++) {
if (name[pos] != b[bpos])
return false;
int len = name[pos++];
bpos++;
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
for (int j = 0; j < len; j++)
if (lowercase[name[pos++]] != lowercase[b[bpos++]])
return false;
}
return true;
}
/**
* Are these two Names equivalent?
*/
public boolean
equals(Object arg) {
if (arg == this)
return true;
if (arg == null || !(arg instanceof Name))
return false;
Name d = (Name) arg;
if (d.labels() != labels())
return false;
return equals(d.name, d.offset(0));
}
/**
* Computes a hashcode based on the value
*/
public int
hashCode() {
if (hashcode != 0)
return (hashcode);
int code = 0;
for (int i = offset(0); i < name.length; i++)
code += ((code << 3) + lowercase[name[i]]);
hashcode = code;
return hashcode;
}
/**
* Compares this Name to another Object.
* @param o The Object to be compared.
* @return The value 0 if the argument is a name equivalent to this name;
* a value less than 0 if the argument is less than this name in the canonical
* ordering, and a value greater than 0 if the argument is greater than this
* name in the canonical ordering.
* @throws ClassCastException if the argument is not a Name.
*/
public int
compareTo(Object o) {
Name arg = (Name) o;
if (this == arg)
return (0);
byte labels = labels();
byte alabels = arg.labels();
int compares = labels > alabels ? alabels : labels;
for (int i = 1; i <= compares; i++) {
int start = offset(labels - i);
int astart = arg.offset(alabels - i);
int length = name[start];
int alength = arg.name[astart];
for (int j = 0; j < length && j < alength; j++) {
int n = lowercase[name[j + start]] -
lowercase[arg.name[j + astart]];
if (n != 0)
return (n);
}
if (length != alength)
return (length - alength);
}
return (labels - alabels);
}
}
| false | true | public static Name
fromString(String s, Name origin) throws TextParseException {
Name name = new Name();
if (s.equals(""))
throw new TextParseException("empty name");
else if (s.equals("@")) {
if (origin == null)
return name;
return origin;
} else if (s.equals("."))
return (root);
int labelstart = -1;
int pos = 1;
byte [] label = new byte[MAXLABEL + 1];
boolean escaped = false;
int digits = 0;
int intval = 0;
boolean absolute = false;
for (int i = 0; i < s.length(); i++) {
byte b = (byte) s.charAt(i);
if (escaped) {
if (b >= '0' && b <= '9' && digits < 3) {
digits++;
intval *= 10 + (b - '0');
intval += (b - '0');
if (digits < 3)
continue;
b = (byte) intval;
}
else if (digits > 0 && digits < 3)
throw new TextParseException("bad escape");
if (pos >= MAXLABEL)
throw new TextParseException("label too long");
labelstart = pos;
label[pos++] = b;
escaped = false;
} else if (b == '\\') {
escaped = true;
digits = 0;
intval = 0;
} else if (b == '.') {
if (labelstart == -1)
throw new TextParseException("invalid label");
label[0] = (byte)(pos - 1);
name.appendFromString(label, 0, 1);
labelstart = -1;
pos = 1;
} else {
if (labelstart == -1)
labelstart = i;
if (pos >= MAXLABEL)
throw new TextParseException("label too long");
label[pos++] = b;
}
}
if (labelstart == -1) {
name.appendFromString(emptyLabel, 0, 1);
absolute = true;
} else {
label[0] = (byte)(pos - 1);
name.appendFromString(label, 0, 1);
}
if (origin != null && !absolute)
name.appendFromString(origin.name, 0, origin.getlabels());
return (name);
}
| public static Name
fromString(String s, Name origin) throws TextParseException {
Name name = new Name();
if (s.equals(""))
throw new TextParseException("empty name");
else if (s.equals("@")) {
if (origin == null)
return name;
return origin;
} else if (s.equals("."))
return (root);
int labelstart = -1;
int pos = 1;
byte [] label = new byte[MAXLABEL + 1];
boolean escaped = false;
int digits = 0;
int intval = 0;
boolean absolute = false;
for (int i = 0; i < s.length(); i++) {
byte b = (byte) s.charAt(i);
if (escaped) {
if (b >= '0' && b <= '9' && digits < 3) {
digits++;
intval *= 10;
intval += (b - '0');
if (intval > 255)
throw new TextParseException
("bad escape");
if (digits < 3)
continue;
b = (byte) intval;
}
else if (digits > 0 && digits < 3)
throw new TextParseException("bad escape");
if (pos >= MAXLABEL)
throw new TextParseException("label too long");
labelstart = pos;
label[pos++] = b;
escaped = false;
} else if (b == '\\') {
escaped = true;
digits = 0;
intval = 0;
} else if (b == '.') {
if (labelstart == -1)
throw new TextParseException("invalid label");
label[0] = (byte)(pos - 1);
name.appendFromString(label, 0, 1);
labelstart = -1;
pos = 1;
} else {
if (labelstart == -1)
labelstart = i;
if (pos >= MAXLABEL)
throw new TextParseException("label too long");
label[pos++] = b;
}
}
if (labelstart == -1) {
name.appendFromString(emptyLabel, 0, 1);
absolute = true;
} else {
label[0] = (byte)(pos - 1);
name.appendFromString(label, 0, 1);
}
if (origin != null && !absolute)
name.appendFromString(origin.name, 0, origin.getlabels());
return (name);
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/breakpoints/StandardJavaBreakpointEditor.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/breakpoints/StandardJavaBreakpointEditor.java
index 4327702c9..1e06a99d3 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/breakpoints/StandardJavaBreakpointEditor.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/breakpoints/StandardJavaBreakpointEditor.java
@@ -1,232 +1,233 @@
/*******************************************************************************
* Copyright (c) 2009, 2010 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.jdt.internal.debug.ui.breakpoints;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.debug.core.IJavaBreakpoint;
import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
import org.eclipse.jdt.internal.debug.ui.SWTFactory;
import org.eclipse.jdt.internal.debug.ui.propertypages.PropertyPageMessages;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Text;
/**
* @since 3.6
*/
public class StandardJavaBreakpointEditor extends AbstractJavaBreakpointEditor {
private IJavaBreakpoint fBreakpoint;
private Button fHitCountButton;
private Text fHitCountText;
private Combo fSuspendPolicy;
/**
* Property id for hit count enabled state.
*/
public static final int PROP_HIT_COUNT_ENABLED = 0x1005;
/**
* Property id for breakpoint hit count.
*/
public static final int PROP_HIT_COUNT = 0x1006;
/**
* Property id for suspend policy.
*/
public static final int PROP_SUSPEND_POLICY = 0x1007;
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.debug.ui.breakpoints.AbstractJavaBreakpointEditor#createControl(org.eclipse.swt.widgets.Composite)
*/
public Control createControl(Composite parent) {
return createStandardControls(parent);
}
protected Control createStandardControls(Composite parent) {
Composite composite = SWTFactory.createComposite(parent, parent.getFont(), 2, 1, GridData.FILL_VERTICAL, 5, 5);
SWTFactory.createLabel(composite, PropertyPageMessages.JavaBreakpointPage_6, 1);
fSuspendPolicy = new Combo(composite, SWT.BORDER | SWT.READ_ONLY);
fSuspendPolicy.add(PropertyPageMessages.JavaBreakpointPage_7);
fSuspendPolicy.add(PropertyPageMessages.JavaBreakpointPage_8);
fSuspendPolicy.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setDirty(PROP_SUSPEND_POLICY);
}
});
fHitCountButton = SWTFactory.createCheckButton(composite, PropertyPageMessages.JavaBreakpointPage_4, null, false, 1);
fHitCountButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
fHitCountText.setEnabled(fHitCountButton.getSelection());
setDirty(PROP_HIT_COUNT_ENABLED);
}
});
fHitCountText = new Text(composite, SWT.SINGLE | SWT.BORDER);
- GridData gd = new GridData(GridData.GRAB_HORIZONTAL);
+ GridData gd = new GridData();
+ gd.widthHint = 100;
fHitCountText.setLayoutData(gd);
fHitCountText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
setDirty(PROP_HIT_COUNT);
}
});
composite.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
dispose();
}
});
return composite;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.debug.ui.breakpoints.AbstractJavaBreakpointEditor#setInput(java.lang.Object)
*/
public void setInput(Object breakpoint) throws CoreException {
if (breakpoint instanceof IJavaBreakpoint) {
setBreakpoint((IJavaBreakpoint) breakpoint);
} else {
setBreakpoint(null);
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.debug.ui.breakpoints.AbstractJavaBreakpointEditor#getInput()
*/
public Object getInput() {
return fBreakpoint;
}
/**
* Sets the breakpoint to edit. The same editor can be used iteratively for different breakpoints.
*
* @param breakpoint the breakpoint to edit or <code>null</code> if none
* @exception CoreException if unable to access breakpoint attributes
*/
protected void setBreakpoint(IJavaBreakpoint breakpoint) throws CoreException {
fBreakpoint = breakpoint;
boolean enabled = false;
boolean hasHitCount = false;
String text = ""; //$NON-NLS-1$
boolean suspendThread = true;
if (breakpoint != null) {
enabled = true;
int hitCount = breakpoint.getHitCount();
if (hitCount > 0) {
text = new Integer(hitCount).toString();
hasHitCount = true;
}
suspendThread= breakpoint.getSuspendPolicy() == IJavaBreakpoint.SUSPEND_THREAD;
}
fHitCountButton.setEnabled(enabled);
fHitCountButton.setSelection(enabled & hasHitCount);
fHitCountText.setEnabled(hasHitCount);
fHitCountText.setText(text);
fSuspendPolicy.setEnabled(enabled);
if(suspendThread) {
fSuspendPolicy.select(0);
} else {
fSuspendPolicy.select(1);
}
setDirty(false);
}
/**
* Returns the current breakpoint being edited or <code>null</code> if none.
*
* @return breakpoint or <code>null</code>
*/
protected IJavaBreakpoint getBreakpoint() {
return fBreakpoint;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.debug.ui.breakpoints.AbstractJavaBreakpointEditor#setFocus()
*/
public void setFocus() {
// do nothing
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.debug.ui.breakpoints.AbstractJavaBreakpointEditor#doSave()
*/
public void doSave() throws CoreException {
if (fBreakpoint != null) {
int suspendPolicy = IJavaBreakpoint.SUSPEND_VM;
if(fSuspendPolicy.getSelectionIndex() == 0) {
suspendPolicy = IJavaBreakpoint.SUSPEND_THREAD;
}
fBreakpoint.setSuspendPolicy(suspendPolicy);
int hitCount = -1;
if (fHitCountButton.getSelection()) {
try {
hitCount = Integer.parseInt(fHitCountText.getText());
}
catch (NumberFormatException e) {
throw new CoreException(new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, PropertyPageMessages.JavaBreakpointPage_0, e));
}
}
fBreakpoint.setHitCount(hitCount);
}
setDirty(false);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.debug.ui.breakpoints.AbstractJavaBreakpointEditor#getStatus()
*/
public IStatus getStatus() {
if (fHitCountButton.getSelection()) {
String hitCountText= fHitCountText.getText();
int hitCount= -1;
try {
hitCount = Integer.parseInt(hitCountText);
} catch (NumberFormatException e1) {
return new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, PropertyPageMessages.JavaBreakpointPage_0, null);
}
if (hitCount < 1) {
return new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, PropertyPageMessages.JavaBreakpointPage_0, null);
}
}
return Status.OK_STATUS;
}
/**
* Creates and returns a check box button with the given text.
*
* @param parent parent composite
* @param text label
* @param propId property id to fire on modification
* @return check box
*/
protected Button createSusupendPropertyEditor(Composite parent, String text, final int propId) {
Button button = new Button(parent, SWT.CHECK);
button.setFont(parent.getFont());
button.setText(text);
GridData gd = new GridData(SWT.BEGINNING);
button.setLayoutData(gd);
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setDirty(propId);
}
});
return button;
}
}
| true | true | protected Control createStandardControls(Composite parent) {
Composite composite = SWTFactory.createComposite(parent, parent.getFont(), 2, 1, GridData.FILL_VERTICAL, 5, 5);
SWTFactory.createLabel(composite, PropertyPageMessages.JavaBreakpointPage_6, 1);
fSuspendPolicy = new Combo(composite, SWT.BORDER | SWT.READ_ONLY);
fSuspendPolicy.add(PropertyPageMessages.JavaBreakpointPage_7);
fSuspendPolicy.add(PropertyPageMessages.JavaBreakpointPage_8);
fSuspendPolicy.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setDirty(PROP_SUSPEND_POLICY);
}
});
fHitCountButton = SWTFactory.createCheckButton(composite, PropertyPageMessages.JavaBreakpointPage_4, null, false, 1);
fHitCountButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
fHitCountText.setEnabled(fHitCountButton.getSelection());
setDirty(PROP_HIT_COUNT_ENABLED);
}
});
fHitCountText = new Text(composite, SWT.SINGLE | SWT.BORDER);
GridData gd = new GridData(GridData.GRAB_HORIZONTAL);
fHitCountText.setLayoutData(gd);
fHitCountText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
setDirty(PROP_HIT_COUNT);
}
});
composite.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
dispose();
}
});
return composite;
}
| protected Control createStandardControls(Composite parent) {
Composite composite = SWTFactory.createComposite(parent, parent.getFont(), 2, 1, GridData.FILL_VERTICAL, 5, 5);
SWTFactory.createLabel(composite, PropertyPageMessages.JavaBreakpointPage_6, 1);
fSuspendPolicy = new Combo(composite, SWT.BORDER | SWT.READ_ONLY);
fSuspendPolicy.add(PropertyPageMessages.JavaBreakpointPage_7);
fSuspendPolicy.add(PropertyPageMessages.JavaBreakpointPage_8);
fSuspendPolicy.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setDirty(PROP_SUSPEND_POLICY);
}
});
fHitCountButton = SWTFactory.createCheckButton(composite, PropertyPageMessages.JavaBreakpointPage_4, null, false, 1);
fHitCountButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
fHitCountText.setEnabled(fHitCountButton.getSelection());
setDirty(PROP_HIT_COUNT_ENABLED);
}
});
fHitCountText = new Text(composite, SWT.SINGLE | SWT.BORDER);
GridData gd = new GridData();
gd.widthHint = 100;
fHitCountText.setLayoutData(gd);
fHitCountText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
setDirty(PROP_HIT_COUNT);
}
});
composite.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
dispose();
}
});
return composite;
}
|
diff --git a/src/org/bukkit/craftbukkit/generator/CustomChunkGenerator.java b/src/org/bukkit/craftbukkit/generator/CustomChunkGenerator.java
index 668fc95..9531e0b 100644
--- a/src/org/bukkit/craftbukkit/generator/CustomChunkGenerator.java
+++ b/src/org/bukkit/craftbukkit/generator/CustomChunkGenerator.java
@@ -1,309 +1,309 @@
package org.bukkit.craftbukkit.generator;
import java.util.List;
import java.util.Random;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.util.IProgressUpdate;
import net.minecraft.world.ChunkPosition;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import net.minecraft.world.gen.feature.MapGenScatteredFeature;
import net.minecraft.world.gen.structure.MapGenMineshaft;
import net.minecraft.world.gen.structure.MapGenStronghold;
import net.minecraft.world.gen.structure.MapGenVillage;
import org.bukkit.block.Biome;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.craftbukkit.block.CraftBlock;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
//import net.minecraft.src.ChunkSection;
//import org.bukkit.craftbukkit.block.CraftBlock;
public class CustomChunkGenerator extends InternalChunkGenerator {
private final ChunkGenerator generator;
private final WorldServer world;
private final Random random;
//UNUSED: private HashMap<int[],net.minecraft.world.chunk.Chunk> loadedChunks = new HashMap<int[], Chunk>();
private final MapGenStronghold strongholdGen = new MapGenStronghold();
private final MapGenVillage villageGen = new MapGenVillage();
private final MapGenScatteredFeature scatteredGen = new MapGenScatteredFeature();
private final MapGenMineshaft mineshaftGen = new MapGenMineshaft();
private static class CustomBiomeGrid implements BiomeGrid {
BiomeGenBase[] biome;
public Biome getBiome(int x, int z) {
return CraftBlock.BiomeGenBaseToBiome(biome[(z << 4) | x]);
}
public void setBiome(int x, int z, Biome bio) {
biome[(z << 4) | x] = CraftBlock.biomeToBiomeGenBase(bio);
}
}
public CustomChunkGenerator(World world, long seed, ChunkGenerator generator) {
this.world = (WorldServer) world;
this.generator = generator;
this.random = new Random(seed);
}
public boolean isChunkLoaded(int x, int z) {
return true;
}
public Chunk getOrCreateChunk(int x, int z) {
random.setSeed((long) x * 341873128712L + (long) z * 132897987541L);
Chunk chunk;
// Get default biome data for chunk
CustomBiomeGrid biomegrid = new CustomBiomeGrid();
biomegrid.biome = new BiomeGenBase[256];
world.getWorldChunkManager().getBiomeGenAt(biomegrid.biome, x << 4, z << 4, 16, 16, false);
// Try extended block method (1.2+)
short[][] xbtypes = generator.generateExtBlockSections(CraftServer.instance().getWorld(world.provider.dimensionId), this.random, x, z, biomegrid);
if (xbtypes != null) {
chunk = new Chunk(this.world, x, z);
ExtendedBlockStorage[] csect = chunk.getBlockStorageArray();
int scnt = Math.min(csect.length, xbtypes.length);
// Loop through returned sections
for (int sec = 0; sec < scnt; sec++) {
if (xbtypes[sec] == null) {
continue;
}
byte[] secBlkID = new byte[4096]; // Allocate blk ID bytes
byte[] secExtBlkID = (byte[]) null; // Delay getting extended ID nibbles
short[] bdata = xbtypes[sec];
// Loop through data, 2 blocks at a time
for (int i = 0, j = 0; i < bdata.length; i += 2, j++) {
short b1 = bdata[i];
short b2 = bdata[i + 1];
byte extb = (byte) ((b1 >> 8) | ((b2 >> 4) & 0xF0));
secBlkID[i] = (byte) b1;
secBlkID[(i + 1)] = (byte) b2;
if (extb != 0) { // If extended block ID data
if (secExtBlkID == null) { // Allocate if needed
secExtBlkID = new byte[2048];
}
secExtBlkID[j] = extb;
}
}
// Build chunk section
csect[sec] = new ExtendedBlockStorage(sec << 4, false);//, secBlkID, secExtBlkID);
}
}
else { // Else check for byte-per-block section data
byte[][] btypes = generator.generateBlockSections(getWorld(world), this.random, x, z, biomegrid);
if (btypes != null) {
chunk = new Chunk(this.world, x, z);
ExtendedBlockStorage[] csect = chunk.getBlockStorageArray();
int scnt = Math.min(csect.length, btypes.length);
for (int sec = 0; sec < scnt; sec++) {
if (btypes[sec] == null) {
continue;
}
csect[sec] = new ExtendedBlockStorage(sec << 4, false);//, btypes[sec], null);
}
}
else { // Else, fall back to pre 1.2 method
@SuppressWarnings("deprecation")
byte[] types = generator.generate(getWorld(world), this.random, x, z);
int ydim = types.length / 256;
int scnt = ydim / 16;
chunk = new Chunk(this.world, x, z); // Create empty chunk
ExtendedBlockStorage[] csect = chunk.getBlockStorageArray();
scnt = Math.min(scnt, csect.length);
// Loop through sections
for (int sec = 0; sec < scnt; sec++) {
ExtendedBlockStorage cs = null; // Add sections when needed
byte[] csbytes = (byte[]) null;
for (int cy = 0; cy < 16; cy++) {
int cyoff = cy | (sec << 4);
for (int cx = 0; cx < 16; cx++) {
int cxyoff = (cx * ydim * 16) + cyoff;
for (int cz = 0; cz < 16; cz++) {
byte blk = types[cxyoff + (cz * ydim)];
if (blk != 0) { // If non-empty
if (cs == null) { // If no section yet, get one
- cs = csect[sec] = new ExtendedBlockStorage(sec << 4, false);
+ cs = csect[sec] = new ExtendedBlockStorage(sec << 4, true);
csbytes = cs.getBlockLSBArray();
}
csbytes[(cy << 8) | (cz << 4) | cx] = blk;
}
}
}
}
// If section built, finish prepping its state
if (cs != null) {
- cs.createBlockMSBArray();
+ cs.getYLocation();
}
}
}
}
// Set biome grid
byte[] biomeIndex = chunk.getBiomeArray();
for (int i = 0; i < biomeIndex.length; i++) {
biomeIndex[i] = (byte) (biomegrid.biome[i].biomeID & 0xFF);
}
// Initialize lighting
chunk.generateSkylightMap();
return chunk;
}
private org.bukkit.World getWorld(WorldServer world2) {
return CraftServer.instance().getWorld(world2.provider.dimensionId);
}
public void getChunkAt(IChunkProvider icp, int i, int i1) {
// Nothing!
}
public boolean saveChunks(boolean bln, IProgressUpdate ipu) {
return true;
}
public boolean unloadChunks() {
return false;
}
public boolean canSave() {
return true;
}
@SuppressWarnings("deprecation")
public byte[] generate(org.bukkit.World world, Random random, int x, int z) {
return generator.generate(world, random, x, z);
}
public byte[][] generateBlockSections(org.bukkit.World world, Random random, int x, int z, BiomeGrid biomes) {
return generator.generateBlockSections(world, random, x, z, biomes);
}
public short[][] generateExtBlockSections(org.bukkit.World world, Random random, int x, int z, BiomeGrid biomes) {
return generator.generateExtBlockSections(world, random, x, z, biomes);
}
public Chunk getChunkAt(int x, int z) {
return getOrCreateChunk(x, z);
}
@Override
public boolean canSpawn(org.bukkit.World world, int x, int z) {
return generator.canSpawn(world, x, z);
}
@Override
public List<BlockPopulator> getDefaultPopulators(org.bukkit.World world) {
return generator.getDefaultPopulators(world);
}
public List<?> getMobsFor(EnumCreatureType type, int x, int y, int z) {
BiomeGenBase biomebase = world.getBiomeGenForCoords(x, z);
return biomebase == null ? null : biomebase.getSpawnableList(type);
}
public List<?> getPossibleCreatures(EnumCreatureType type, int x, int y, int z) {
return this.getMobsFor(type, x, y, z);
}
public ChunkPosition findNearestMapFeature(World world, String type, int x, int y, int z) {
return "Stronghold".equals(type) && this.strongholdGen != null ? this.strongholdGen.getNearestInstance(world, x, y, z) : null;
}
public int getLoadedChunks() {
return 0;
}
public String getName() {
return "CustomChunkGenerator";
}
@Override
public boolean chunkExists(int x, int z) {
return this.getChunkAt(x, z) == null ? false : true;
}
@Override
public ChunkPosition findClosestStructure(World var1, String var2,
int x, int y, int z) {
return this.findNearestMapFeature(var1, var2, x, y, z);
}
@Override
public int getLoadedChunkCount() {
return this.getLoadedChunks();
}
@Override
public Chunk loadChunk(int x, int z) {
return this.getChunkAt(x, z);
}
@Override
public String makeString() {
return "CustomChunkGenerator";
}
@Override
public void populate(IChunkProvider var1, int var2, int var3) {
// WOO!
}
@Override
public Chunk provideChunk(int x, int z) {
return this.getOrCreateChunk(x, z);
}
@Override
public boolean unload100OldestChunks() {
return this.unloadChunks();
}
@Override
/**
* Generate structure
* @param x
* @param y
*/
public void recreateStructures(int arg0, int arg1) {
this.strongholdGen.generate(this, this.world, arg0, arg1, (byte[])null);
this.mineshaftGen.generate(this, this.world, arg0, arg1, (byte[])null);
this.scatteredGen.generate(this, this.world, arg0, arg1, (byte[])null);
this.villageGen.generate(this, this.world, arg0, arg1, (byte[])null);
}
}
| false | true | public Chunk getOrCreateChunk(int x, int z) {
random.setSeed((long) x * 341873128712L + (long) z * 132897987541L);
Chunk chunk;
// Get default biome data for chunk
CustomBiomeGrid biomegrid = new CustomBiomeGrid();
biomegrid.biome = new BiomeGenBase[256];
world.getWorldChunkManager().getBiomeGenAt(biomegrid.biome, x << 4, z << 4, 16, 16, false);
// Try extended block method (1.2+)
short[][] xbtypes = generator.generateExtBlockSections(CraftServer.instance().getWorld(world.provider.dimensionId), this.random, x, z, biomegrid);
if (xbtypes != null) {
chunk = new Chunk(this.world, x, z);
ExtendedBlockStorage[] csect = chunk.getBlockStorageArray();
int scnt = Math.min(csect.length, xbtypes.length);
// Loop through returned sections
for (int sec = 0; sec < scnt; sec++) {
if (xbtypes[sec] == null) {
continue;
}
byte[] secBlkID = new byte[4096]; // Allocate blk ID bytes
byte[] secExtBlkID = (byte[]) null; // Delay getting extended ID nibbles
short[] bdata = xbtypes[sec];
// Loop through data, 2 blocks at a time
for (int i = 0, j = 0; i < bdata.length; i += 2, j++) {
short b1 = bdata[i];
short b2 = bdata[i + 1];
byte extb = (byte) ((b1 >> 8) | ((b2 >> 4) & 0xF0));
secBlkID[i] = (byte) b1;
secBlkID[(i + 1)] = (byte) b2;
if (extb != 0) { // If extended block ID data
if (secExtBlkID == null) { // Allocate if needed
secExtBlkID = new byte[2048];
}
secExtBlkID[j] = extb;
}
}
// Build chunk section
csect[sec] = new ExtendedBlockStorage(sec << 4, false);//, secBlkID, secExtBlkID);
}
}
else { // Else check for byte-per-block section data
byte[][] btypes = generator.generateBlockSections(getWorld(world), this.random, x, z, biomegrid);
if (btypes != null) {
chunk = new Chunk(this.world, x, z);
ExtendedBlockStorage[] csect = chunk.getBlockStorageArray();
int scnt = Math.min(csect.length, btypes.length);
for (int sec = 0; sec < scnt; sec++) {
if (btypes[sec] == null) {
continue;
}
csect[sec] = new ExtendedBlockStorage(sec << 4, false);//, btypes[sec], null);
}
}
else { // Else, fall back to pre 1.2 method
@SuppressWarnings("deprecation")
byte[] types = generator.generate(getWorld(world), this.random, x, z);
int ydim = types.length / 256;
int scnt = ydim / 16;
chunk = new Chunk(this.world, x, z); // Create empty chunk
ExtendedBlockStorage[] csect = chunk.getBlockStorageArray();
scnt = Math.min(scnt, csect.length);
// Loop through sections
for (int sec = 0; sec < scnt; sec++) {
ExtendedBlockStorage cs = null; // Add sections when needed
byte[] csbytes = (byte[]) null;
for (int cy = 0; cy < 16; cy++) {
int cyoff = cy | (sec << 4);
for (int cx = 0; cx < 16; cx++) {
int cxyoff = (cx * ydim * 16) + cyoff;
for (int cz = 0; cz < 16; cz++) {
byte blk = types[cxyoff + (cz * ydim)];
if (blk != 0) { // If non-empty
if (cs == null) { // If no section yet, get one
cs = csect[sec] = new ExtendedBlockStorage(sec << 4, false);
csbytes = cs.getBlockLSBArray();
}
csbytes[(cy << 8) | (cz << 4) | cx] = blk;
}
}
}
}
// If section built, finish prepping its state
if (cs != null) {
cs.createBlockMSBArray();
}
}
}
}
// Set biome grid
byte[] biomeIndex = chunk.getBiomeArray();
for (int i = 0; i < biomeIndex.length; i++) {
biomeIndex[i] = (byte) (biomegrid.biome[i].biomeID & 0xFF);
}
// Initialize lighting
chunk.generateSkylightMap();
return chunk;
}
| public Chunk getOrCreateChunk(int x, int z) {
random.setSeed((long) x * 341873128712L + (long) z * 132897987541L);
Chunk chunk;
// Get default biome data for chunk
CustomBiomeGrid biomegrid = new CustomBiomeGrid();
biomegrid.biome = new BiomeGenBase[256];
world.getWorldChunkManager().getBiomeGenAt(biomegrid.biome, x << 4, z << 4, 16, 16, false);
// Try extended block method (1.2+)
short[][] xbtypes = generator.generateExtBlockSections(CraftServer.instance().getWorld(world.provider.dimensionId), this.random, x, z, biomegrid);
if (xbtypes != null) {
chunk = new Chunk(this.world, x, z);
ExtendedBlockStorage[] csect = chunk.getBlockStorageArray();
int scnt = Math.min(csect.length, xbtypes.length);
// Loop through returned sections
for (int sec = 0; sec < scnt; sec++) {
if (xbtypes[sec] == null) {
continue;
}
byte[] secBlkID = new byte[4096]; // Allocate blk ID bytes
byte[] secExtBlkID = (byte[]) null; // Delay getting extended ID nibbles
short[] bdata = xbtypes[sec];
// Loop through data, 2 blocks at a time
for (int i = 0, j = 0; i < bdata.length; i += 2, j++) {
short b1 = bdata[i];
short b2 = bdata[i + 1];
byte extb = (byte) ((b1 >> 8) | ((b2 >> 4) & 0xF0));
secBlkID[i] = (byte) b1;
secBlkID[(i + 1)] = (byte) b2;
if (extb != 0) { // If extended block ID data
if (secExtBlkID == null) { // Allocate if needed
secExtBlkID = new byte[2048];
}
secExtBlkID[j] = extb;
}
}
// Build chunk section
csect[sec] = new ExtendedBlockStorage(sec << 4, false);//, secBlkID, secExtBlkID);
}
}
else { // Else check for byte-per-block section data
byte[][] btypes = generator.generateBlockSections(getWorld(world), this.random, x, z, biomegrid);
if (btypes != null) {
chunk = new Chunk(this.world, x, z);
ExtendedBlockStorage[] csect = chunk.getBlockStorageArray();
int scnt = Math.min(csect.length, btypes.length);
for (int sec = 0; sec < scnt; sec++) {
if (btypes[sec] == null) {
continue;
}
csect[sec] = new ExtendedBlockStorage(sec << 4, false);//, btypes[sec], null);
}
}
else { // Else, fall back to pre 1.2 method
@SuppressWarnings("deprecation")
byte[] types = generator.generate(getWorld(world), this.random, x, z);
int ydim = types.length / 256;
int scnt = ydim / 16;
chunk = new Chunk(this.world, x, z); // Create empty chunk
ExtendedBlockStorage[] csect = chunk.getBlockStorageArray();
scnt = Math.min(scnt, csect.length);
// Loop through sections
for (int sec = 0; sec < scnt; sec++) {
ExtendedBlockStorage cs = null; // Add sections when needed
byte[] csbytes = (byte[]) null;
for (int cy = 0; cy < 16; cy++) {
int cyoff = cy | (sec << 4);
for (int cx = 0; cx < 16; cx++) {
int cxyoff = (cx * ydim * 16) + cyoff;
for (int cz = 0; cz < 16; cz++) {
byte blk = types[cxyoff + (cz * ydim)];
if (blk != 0) { // If non-empty
if (cs == null) { // If no section yet, get one
cs = csect[sec] = new ExtendedBlockStorage(sec << 4, true);
csbytes = cs.getBlockLSBArray();
}
csbytes[(cy << 8) | (cz << 4) | cx] = blk;
}
}
}
}
// If section built, finish prepping its state
if (cs != null) {
cs.getYLocation();
}
}
}
}
// Set biome grid
byte[] biomeIndex = chunk.getBiomeArray();
for (int i = 0; i < biomeIndex.length; i++) {
biomeIndex[i] = (byte) (biomegrid.biome[i].biomeID & 0xFF);
}
// Initialize lighting
chunk.generateSkylightMap();
return chunk;
}
|
diff --git a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/RepositoryConfiguration.java b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/RepositoryConfiguration.java
index bd95a5b74..56268097a 100644
--- a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/RepositoryConfiguration.java
+++ b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/RepositoryConfiguration.java
@@ -1,687 +1,696 @@
/*******************************************************************************
* Copyright (c) 2004, 2008 Tasktop Technologies 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:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.bugzilla.core;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants.BUGZILLA_REPORT_STATUS;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskData;
import org.eclipse.mylyn.tasks.core.data.TaskOperation;
/**
* Class describing the configuration of products and components for a given Bugzilla installation.
*
* @author Rob Elves
*/
public class RepositoryConfiguration implements Serializable {
private static final long serialVersionUID = -3600257926613730005L;
private String repositoryUrl = "<unknown>"; //$NON-NLS-1$
private final Map<String, ProductEntry> products = new HashMap<String, ProductEntry>();
private final List<String> platforms = new ArrayList<String>();
private final List<String> operatingSystems = new ArrayList<String>();
private final List<String> priorities = new ArrayList<String>();
private final List<String> severities = new ArrayList<String>();
private final List<String> bugStatus = new ArrayList<String>();
private final List<String> openStatusValues = new ArrayList<String>();
private final List<String> resolutionValues = new ArrayList<String>();
private final List<String> keywords = new ArrayList<String>();
// master lists
private final List<String> versions = new ArrayList<String>();
private final List<String> components = new ArrayList<String>();
private final List<String> milestones = new ArrayList<String>();
private final List<BugzillaCustomField> customFields = new ArrayList<BugzillaCustomField>();
private final List<BugzillaFlag> flags = new ArrayList<BugzillaFlag>();
private BugzillaVersion version = BugzillaVersion.MIN_VERSION;
public RepositoryConfiguration() {
super();
}
public void addStatus(String status) {
bugStatus.add(status);
}
public List<String> getStatusValues() {
return bugStatus;
}
public void addResolution(String res) {
resolutionValues.add(res);
}
public List<String> getResolutions() {
return resolutionValues;
}
/**
* Adds a product to the configuration.
*/
public void addProduct(String name) {
if (!products.containsKey(name)) {
ProductEntry product = new ProductEntry(name);
products.put(name, product);
}
}
/**
* Returns an array of names of current products.
*/
public List<String> getProducts() {
ArrayList<String> productList = new ArrayList<String>(products.keySet());
Collections.sort(productList);
return productList;
}
/**
* Returns an array of names of component that exist for a given product or <code>null</code> if the product does
* not exist.
*/
public List<String> getComponents(String product) {
ProductEntry entry = products.get(product);
if (entry != null) {
return entry.getComponents();
} else {
return Collections.emptyList();
}
}
/**
* Returns an array of names of versions that exist for a given product or <code>null</code> if the product does not
* exist.
*/
public List<String> getVersions(String product) {
ProductEntry entry = products.get(product);
if (entry != null) {
return entry.getVersions();
} else {
return Collections.emptyList();
}
}
/**
* Returns an array of names of valid severity values.
*/
public List<String> getSeverities() {
return severities;
}
/**
* Returns an array of names of valid OS values.
*/
public List<String> getOSs() {
return operatingSystems;
}
public void addOS(String os) {
operatingSystems.add(os);
}
/**
* Returns an array of names of valid platform values.
*/
public List<String> getPlatforms() {
return platforms;
}
/**
* Returns an array of names of valid platform values.
*/
public List<String> getPriorities() {
return priorities;
}
/**
* Adds a component to the given product.
*/
public void addComponent(String product, String component) {
if (!components.contains(component)) {
components.add(component);
}
ProductEntry entry = products.get(product);
if (entry == null) {
entry = new ProductEntry(product);
products.put(product, entry);
}
entry.addComponent(component);
}
public void addVersion(String product, String version) {
if (!versions.contains(version)) {
versions.add(version);
}
ProductEntry entry = products.get(product);
if (entry == null) {
entry = new ProductEntry(product);
products.put(product, entry);
}
entry.addVersion(version);
}
public void addKeyword(String keyword) {
keywords.add(keyword);
}
public List<String> getKeywords() {
return keywords;
}
public void addPlatform(String platform) {
platforms.add(platform);
}
public void addPriority(String priority) {
priorities.add(priority);
}
public void addSeverity(String severity) {
severities.add(severity);
}
public void setInstallVersion(String version) {
this.version = new BugzillaVersion(version);
}
public BugzillaVersion getInstallVersion() {
return version;
}
public void addTargetMilestone(String product, String target) {
if (!milestones.contains(target)) {
milestones.add(target);
}
ProductEntry entry = products.get(product);
if (entry == null) {
entry = new ProductEntry(product);
products.put(product, entry);
}
entry.addTargetMilestone(target);
}
public List<String> getTargetMilestones(String product) {
ProductEntry entry = products.get(product);
if (entry != null) {
return entry.getTargetMilestones();
} else {
return Collections.emptyList();
}
}
/**
* Container for product information: name, components.
*/
private static class ProductEntry implements Serializable {
private static final long serialVersionUID = 4120139521246741120L;
String productName;
List<String> components = new ArrayList<String>();
List<String> versions = new ArrayList<String>();
List<String> milestones = new ArrayList<String>();
ProductEntry(String name) {
this.productName = name;
}
List<String> getComponents() {
return components;
}
void addComponent(String componentName) {
if (!components.contains(componentName)) {
components.add(componentName);
}
}
List<String> getVersions() {
return versions;
}
void addVersion(String name) {
if (!versions.contains(name)) {
versions.add(name);
}
}
List<String> getTargetMilestones() {
return milestones;
}
void addTargetMilestone(String target) {
milestones.add(target);
}
}
public List<String> getOpenStatusValues() {
return openStatusValues;
}
public void addOpenStatusValue(String value) {
openStatusValues.add(value);
}
public List<String> getComponents() {
return components;
}
public List<String> getTargetMilestones() {
return milestones;
}
public List<String> getVersions() {
return versions;
}
public String getRepositoryUrl() {
return repositoryUrl;
}
public void setRepositoryUrl(String repositoryUrl) {
this.repositoryUrl = repositoryUrl;
}
/*
* Intermediate step until configuration is made generic.
*/
public List<String> getOptionValues(BugzillaAttribute element, String product) {
switch (element) {
case PRODUCT:
return getProducts();
case TARGET_MILESTONE:
return getTargetMilestones(product);
case BUG_STATUS:
return getStatusValues();
case VERSION:
return getVersions(product);
case COMPONENT:
return getComponents(product);
case REP_PLATFORM:
return getPlatforms();
case OP_SYS:
return getOSs();
case PRIORITY:
return getPriorities();
case BUG_SEVERITY:
return getSeverities();
case KEYWORDS:
return getKeywords();
case RESOLUTION:
return getResolutions();
default:
return Collections.emptyList();
}
}
/**
* Adds a field to the configuration.
*/
public void addCustomField(BugzillaCustomField newField) {
customFields.add(newField);
}
public List<BugzillaCustomField> getCustomFields() {
return customFields;
}
public void configureTaskData(TaskData taskData) {
if (taskData != null) {
addMissingFlags(taskData);
updateAttributeOptions(taskData);
addValidOperations(taskData);
}
}
private void addMissingFlags(TaskData taskData) {
List<String> existingFlags = new ArrayList<String>();
List<BugzillaFlag> flags = getFlags();
for (TaskAttribute attribute : new HashSet<TaskAttribute>(taskData.getRoot().getAttributes().values())) {
if (attribute.getId().startsWith("task.common.kind.flag")) { //$NON-NLS-1$
TaskAttribute state = attribute.getAttribute("state"); //$NON-NLS-1$
if (state != null) {
String nameValue = state.getMetaData().getLabel();
if (!existingFlags.contains(nameValue)) {
existingFlags.add(nameValue);
}
String desc = attribute.getMetaData().getLabel();
if (desc == null || desc.equals("")) { //$NON-NLS-1$
for (BugzillaFlag bugzillaFlag : flags) {
if (bugzillaFlag.getType().equals("attachment")) { //$NON-NLS-1$
continue;
}
if (bugzillaFlag.getName().equals(nameValue)) {
attribute.getMetaData().setLabel(bugzillaFlag.getDescription());
}
}
}
}
}
}
TaskAttribute productAttribute = taskData.getRoot().getMappedAttribute(BugzillaAttribute.PRODUCT.getKey());
TaskAttribute componentAttribute = taskData.getRoot().getMappedAttribute(BugzillaAttribute.COMPONENT.getKey());
for (BugzillaFlag bugzillaFlag : flags) {
if (bugzillaFlag.getType().equals("attachment")) { //$NON-NLS-1$
continue;
}
if (!bugzillaFlag.isUsedIn(productAttribute.getValue(), componentAttribute.getValue())) {
continue;
}
if (existingFlags.contains(bugzillaFlag.getName()) && !bugzillaFlag.isMultiplicable()) {
continue;
}
BugzillaFlagMapper mapper = new BugzillaFlagMapper();
mapper.setRequestee(""); //$NON-NLS-1$
mapper.setSetter(""); //$NON-NLS-1$
mapper.setState(" "); //$NON-NLS-1$
mapper.setFlagId(bugzillaFlag.getName());
mapper.setNumber(0);
mapper.setDescription(bugzillaFlag.getDescription());
TaskAttribute attribute = taskData.getRoot().createAttribute(
"task.common.kind.flag_type" + bugzillaFlag.getFlagId()); //$NON-NLS-1$
mapper.applyTo(attribute);
}
setFlagsRequestee(taskData);
}
private void setFlagsRequestee(TaskData taskData) {
for (TaskAttribute attribute : new HashSet<TaskAttribute>(taskData.getRoot().getAttributes().values())) {
if (attribute.getId().startsWith("task.common.kind.flag")) { //$NON-NLS-1$
TaskAttribute state = attribute.getAttribute("state"); //$NON-NLS-1$
if (state != null) {
String nameValue = state.getMetaData().getLabel();
for (BugzillaFlag bugzillaFlag : flags) {
if (nameValue.equals(bugzillaFlag.getName())) {
TaskAttribute requestee = attribute.getAttribute("requestee"); //$NON-NLS-1$
if (requestee == null) {
requestee = attribute.createMappedAttribute("requestee"); //$NON-NLS-1$
requestee.getMetaData().defaults().setType(TaskAttribute.TYPE_SHORT_TEXT);
requestee.setValue(""); //$NON-NLS-1$
}
requestee.getMetaData().setReadOnly(!bugzillaFlag.isSpecifically_requestable());
}
}
}
}
}
}
public void updateAttributeOptions(TaskData existingReport) {
TaskAttribute attributeProduct = existingReport.getRoot()
.getMappedAttribute(BugzillaAttribute.PRODUCT.getKey());
if (attributeProduct == null) {
return;
}
String product = attributeProduct.getValue();
for (TaskAttribute attribute : new HashSet<TaskAttribute>(existingReport.getRoot().getAttributes().values())) {
List<String> optionValues = getAttributeOptions(product, attribute);
if (attribute.getId().equals(BugzillaAttribute.TARGET_MILESTONE.getKey()) && optionValues.isEmpty()) {
existingReport.getRoot().removeAttribute(BugzillaAttribute.TARGET_MILESTONE.getKey());
continue;
}
if (attribute.getId().startsWith("task.common.kind.flag")) { //$NON-NLS-1$
attribute = attribute.getAttribute("state"); //$NON-NLS-1$
}
attribute.clearOptions();
for (String option : optionValues) {
attribute.putOption(option, option);
}
}
}
public List<String> getAttributeOptions(String product, TaskAttribute attribute) {
List<String> options = new ArrayList<String>();
if (attribute.getId().startsWith(BugzillaCustomField.CUSTOM_FIELD_PREFIX)) {
for (BugzillaCustomField bugzillaCustomField : customFields) {
if (bugzillaCustomField.getName().equals(attribute.getId())) {
options = bugzillaCustomField.getOptions();
break;
}
}
} else if (attribute.getId().startsWith("task.common.kind.flag")) { //$NON-NLS-1$
TaskAttribute state = attribute.getAttribute("state"); //$NON-NLS-1$
if (state != null) {
String nameValue = state.getMetaData().getLabel();
options.add(""); //$NON-NLS-1$
for (BugzillaFlag bugzillaFlag : flags) {
if (nameValue.equals(bugzillaFlag.getName())) {
if (nameValue.equals(bugzillaFlag.getName())) {
if (bugzillaFlag.isRequestable()) {
options.add("?"); //$NON-NLS-1$
}
break;
}
}
}
options.add("+"); //$NON-NLS-1$
options.add("-"); //$NON-NLS-1$
}
}
else {
String type = attribute.getMetaData().getType();
if (type != null && type.equals(IBugzillaConstants.EDITOR_TYPE_FLAG)) {
options.add(""); //$NON-NLS-1$
options.add("?"); //$NON-NLS-1$
options.add("+"); //$NON-NLS-1$
options.add("-"); //$NON-NLS-1$
} else {
BugzillaAttribute element;
try {
element = BugzillaAttribute.valueOf(attribute.getId().trim().toUpperCase(Locale.ENGLISH));
} catch (RuntimeException e) {
if (e instanceof IllegalArgumentException) {
// ignore unrecognized tags
return options;
}
throw e;
}
options = getOptionValues(element, product);
if (element != BugzillaAttribute.RESOLUTION && element != BugzillaAttribute.OP_SYS
&& element != BugzillaAttribute.BUG_SEVERITY && element != BugzillaAttribute.PRIORITY
&& element != BugzillaAttribute.BUG_STATUS) {
Collections.sort(options);
}
}
}
return options;
}
public void addValidOperations(TaskData bugReport) {
TaskAttribute attributeStatus = bugReport.getRoot().getMappedAttribute(TaskAttribute.STATUS);
BUGZILLA_REPORT_STATUS status = BUGZILLA_REPORT_STATUS.NEW;
if (attributeStatus != null) {
try {
status = BUGZILLA_REPORT_STATUS.valueOf(attributeStatus.getValue());
} catch (RuntimeException e) {
// StatusHandler.log(new Status(IStatus.INFO, BugzillaCorePlugin.PLUGIN_ID, "Unrecognized status: "
// + attributeStatus.getValue(), e));
status = BUGZILLA_REPORT_STATUS.NEW;
}
}
+ BugzillaVersion bugzillaVersion = getInstallVersion();
+ if (bugzillaVersion == null) {
+ bugzillaVersion = BugzillaVersion.MIN_VERSION;
+ }
switch (status) {
case UNCONFIRMED:
case REOPENED:
case NEW:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.accept);
addOperation(bugReport, BugzillaOperation.resolve);
addOperation(bugReport, BugzillaOperation.duplicate);
break;
case ASSIGNED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.resolve);
addOperation(bugReport, BugzillaOperation.duplicate);
break;
case RESOLVED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
addOperation(bugReport, BugzillaOperation.verify);
addOperation(bugReport, BugzillaOperation.close);
+ if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
+ addOperation(bugReport, BugzillaOperation.duplicate);
+ }
break;
case CLOSED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
+ if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
+ addOperation(bugReport, BugzillaOperation.duplicate);
+ }
break;
case VERIFIED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
addOperation(bugReport, BugzillaOperation.close);
- }
- BugzillaVersion bugzillaVersion = getInstallVersion();
- if (bugzillaVersion == null) {
- bugzillaVersion = BugzillaVersion.MIN_VERSION;
+ if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
+ addOperation(bugReport, BugzillaOperation.duplicate);
+ }
}
if (bugzillaVersion.compareTo(BugzillaVersion.BUGZILLA_3_0) < 0) {
// Product change is only supported for Versions >= 3.0 without verify html page
TaskAttribute productAttribute = bugReport.getRoot().getMappedAttribute(BugzillaAttribute.PRODUCT.getKey());
productAttribute.getMetaData().setReadOnly(true);
}
if (status == BUGZILLA_REPORT_STATUS.NEW || status == BUGZILLA_REPORT_STATUS.ASSIGNED
|| status == BUGZILLA_REPORT_STATUS.REOPENED || status == BUGZILLA_REPORT_STATUS.UNCONFIRMED) {
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) <= 0) {
// old bugzilla workflow is used
addOperation(bugReport, BugzillaOperation.reassign);
addOperation(bugReport, BugzillaOperation.reassignbycomponent);
} else {
BugzillaAttribute key = BugzillaAttribute.SET_DEFAULT_ASSIGNEE;
TaskAttribute operationAttribute = bugReport.getRoot().getAttribute(key.getKey());
if (operationAttribute == null) {
operationAttribute = bugReport.getRoot().createAttribute(key.getKey());
operationAttribute.getMetaData()
.defaults()
.setReadOnly(key.isReadOnly())
.setKind(key.getKind())
.setLabel(key.toString())
.setType(key.getType());
operationAttribute.setValue("0"); //$NON-NLS-1$
}
operationAttribute = bugReport.getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED);
if (operationAttribute != null) {
operationAttribute.getMetaData().setReadOnly(false);
}
}
}
}
public void addOperation(TaskData bugReport, BugzillaOperation opcode) {
TaskAttribute attribute;
TaskAttribute operationAttribute = bugReport.getRoot().getAttribute(TaskAttribute.OPERATION);
if (operationAttribute == null) {
operationAttribute = bugReport.getRoot().createAttribute(TaskAttribute.OPERATION);
}
switch (opcode) {
case none:
attribute = bugReport.getRoot().createAttribute(TaskAttribute.PREFIX_OPERATION + opcode.toString());
String label = "Leave"; //$NON-NLS-1$
TaskAttribute attributeStatus = bugReport.getRoot().getMappedAttribute(TaskAttribute.STATUS);
TaskAttribute attributeResolution = bugReport.getRoot().getMappedAttribute(TaskAttribute.RESOLUTION);
if (attributeStatus != null && attributeResolution != null) {
label = String.format(opcode.getLabel(), attributeStatus.getValue(), attributeResolution.getValue());
}
TaskOperation.applyTo(attribute, opcode.toString(), label);
// set as default
TaskOperation.applyTo(operationAttribute, opcode.toString(), label);
break;
case resolve:
attribute = bugReport.getRoot().createAttribute(TaskAttribute.PREFIX_OPERATION + opcode.toString());
TaskOperation.applyTo(attribute, opcode.toString(), opcode.getLabel());
TaskAttribute attrResolvedInput = attribute.getTaskData().getRoot().createAttribute(opcode.getInputId());
attrResolvedInput.getMetaData().setType(opcode.getInputType());
attribute.getMetaData().putValue(TaskAttribute.META_ASSOCIATED_ATTRIBUTE_ID, opcode.getInputId());
for (String resolution : getResolutions()) {
// DUPLICATE and MOVED have special meanings so do not show as resolution
if (resolution.compareTo("DUPLICATE") != 0 && resolution.compareTo("MOVED") != 0) { //$NON-NLS-1$ //$NON-NLS-2$
attrResolvedInput.putOption(resolution, resolution);
}
}
if (getResolutions().size() > 0) {
attrResolvedInput.setValue(getResolutions().get(0));
}
break;
default:
attribute = bugReport.getRoot().createAttribute(TaskAttribute.PREFIX_OPERATION + opcode.toString());
TaskOperation.applyTo(attribute, opcode.toString(), opcode.getLabel());
if (opcode.getInputId() != null) {
TaskAttribute attrInput = bugReport.getRoot().createAttribute(opcode.getInputId());
attrInput.getMetaData().defaults().setReadOnly(false).setType(opcode.getInputType());
attribute.getMetaData().putValue(TaskAttribute.META_ASSOCIATED_ATTRIBUTE_ID, opcode.getInputId());
}
break;
}
}
/**
* Adds a flag to the configuration.
*/
public void addFlag(BugzillaFlag newFlag) {
flags.add(newFlag);
}
public List<BugzillaFlag> getFlags() {
return flags;
}
public BugzillaFlag getFlagWithId(Integer id) {
for (BugzillaFlag bugzillaFlag : flags) {
if (bugzillaFlag.getFlagId() == id) {
return bugzillaFlag;
}
}
return null;
}
}
| false | true | public void addValidOperations(TaskData bugReport) {
TaskAttribute attributeStatus = bugReport.getRoot().getMappedAttribute(TaskAttribute.STATUS);
BUGZILLA_REPORT_STATUS status = BUGZILLA_REPORT_STATUS.NEW;
if (attributeStatus != null) {
try {
status = BUGZILLA_REPORT_STATUS.valueOf(attributeStatus.getValue());
} catch (RuntimeException e) {
// StatusHandler.log(new Status(IStatus.INFO, BugzillaCorePlugin.PLUGIN_ID, "Unrecognized status: "
// + attributeStatus.getValue(), e));
status = BUGZILLA_REPORT_STATUS.NEW;
}
}
switch (status) {
case UNCONFIRMED:
case REOPENED:
case NEW:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.accept);
addOperation(bugReport, BugzillaOperation.resolve);
addOperation(bugReport, BugzillaOperation.duplicate);
break;
case ASSIGNED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.resolve);
addOperation(bugReport, BugzillaOperation.duplicate);
break;
case RESOLVED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
addOperation(bugReport, BugzillaOperation.verify);
addOperation(bugReport, BugzillaOperation.close);
break;
case CLOSED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
break;
case VERIFIED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
addOperation(bugReport, BugzillaOperation.close);
}
BugzillaVersion bugzillaVersion = getInstallVersion();
if (bugzillaVersion == null) {
bugzillaVersion = BugzillaVersion.MIN_VERSION;
}
if (bugzillaVersion.compareTo(BugzillaVersion.BUGZILLA_3_0) < 0) {
// Product change is only supported for Versions >= 3.0 without verify html page
TaskAttribute productAttribute = bugReport.getRoot().getMappedAttribute(BugzillaAttribute.PRODUCT.getKey());
productAttribute.getMetaData().setReadOnly(true);
}
if (status == BUGZILLA_REPORT_STATUS.NEW || status == BUGZILLA_REPORT_STATUS.ASSIGNED
|| status == BUGZILLA_REPORT_STATUS.REOPENED || status == BUGZILLA_REPORT_STATUS.UNCONFIRMED) {
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) <= 0) {
// old bugzilla workflow is used
addOperation(bugReport, BugzillaOperation.reassign);
addOperation(bugReport, BugzillaOperation.reassignbycomponent);
} else {
BugzillaAttribute key = BugzillaAttribute.SET_DEFAULT_ASSIGNEE;
TaskAttribute operationAttribute = bugReport.getRoot().getAttribute(key.getKey());
if (operationAttribute == null) {
operationAttribute = bugReport.getRoot().createAttribute(key.getKey());
operationAttribute.getMetaData()
.defaults()
.setReadOnly(key.isReadOnly())
.setKind(key.getKind())
.setLabel(key.toString())
.setType(key.getType());
operationAttribute.setValue("0"); //$NON-NLS-1$
}
operationAttribute = bugReport.getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED);
if (operationAttribute != null) {
operationAttribute.getMetaData().setReadOnly(false);
}
}
}
}
| public void addValidOperations(TaskData bugReport) {
TaskAttribute attributeStatus = bugReport.getRoot().getMappedAttribute(TaskAttribute.STATUS);
BUGZILLA_REPORT_STATUS status = BUGZILLA_REPORT_STATUS.NEW;
if (attributeStatus != null) {
try {
status = BUGZILLA_REPORT_STATUS.valueOf(attributeStatus.getValue());
} catch (RuntimeException e) {
// StatusHandler.log(new Status(IStatus.INFO, BugzillaCorePlugin.PLUGIN_ID, "Unrecognized status: "
// + attributeStatus.getValue(), e));
status = BUGZILLA_REPORT_STATUS.NEW;
}
}
BugzillaVersion bugzillaVersion = getInstallVersion();
if (bugzillaVersion == null) {
bugzillaVersion = BugzillaVersion.MIN_VERSION;
}
switch (status) {
case UNCONFIRMED:
case REOPENED:
case NEW:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.accept);
addOperation(bugReport, BugzillaOperation.resolve);
addOperation(bugReport, BugzillaOperation.duplicate);
break;
case ASSIGNED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.resolve);
addOperation(bugReport, BugzillaOperation.duplicate);
break;
case RESOLVED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
addOperation(bugReport, BugzillaOperation.verify);
addOperation(bugReport, BugzillaOperation.close);
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
addOperation(bugReport, BugzillaOperation.duplicate);
}
break;
case CLOSED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
addOperation(bugReport, BugzillaOperation.duplicate);
}
break;
case VERIFIED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
addOperation(bugReport, BugzillaOperation.close);
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
addOperation(bugReport, BugzillaOperation.duplicate);
}
}
if (bugzillaVersion.compareTo(BugzillaVersion.BUGZILLA_3_0) < 0) {
// Product change is only supported for Versions >= 3.0 without verify html page
TaskAttribute productAttribute = bugReport.getRoot().getMappedAttribute(BugzillaAttribute.PRODUCT.getKey());
productAttribute.getMetaData().setReadOnly(true);
}
if (status == BUGZILLA_REPORT_STATUS.NEW || status == BUGZILLA_REPORT_STATUS.ASSIGNED
|| status == BUGZILLA_REPORT_STATUS.REOPENED || status == BUGZILLA_REPORT_STATUS.UNCONFIRMED) {
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) <= 0) {
// old bugzilla workflow is used
addOperation(bugReport, BugzillaOperation.reassign);
addOperation(bugReport, BugzillaOperation.reassignbycomponent);
} else {
BugzillaAttribute key = BugzillaAttribute.SET_DEFAULT_ASSIGNEE;
TaskAttribute operationAttribute = bugReport.getRoot().getAttribute(key.getKey());
if (operationAttribute == null) {
operationAttribute = bugReport.getRoot().createAttribute(key.getKey());
operationAttribute.getMetaData()
.defaults()
.setReadOnly(key.isReadOnly())
.setKind(key.getKind())
.setLabel(key.toString())
.setType(key.getType());
operationAttribute.setValue("0"); //$NON-NLS-1$
}
operationAttribute = bugReport.getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED);
if (operationAttribute != null) {
operationAttribute.getMetaData().setReadOnly(false);
}
}
}
}
|
diff --git a/webapp/WEB-INF/classes/org/makumba/parade/model/managers/WebappManager.java b/webapp/WEB-INF/classes/org/makumba/parade/model/managers/WebappManager.java
index 198d4a2..359e247 100644
--- a/webapp/WEB-INF/classes/org/makumba/parade/model/managers/WebappManager.java
+++ b/webapp/WEB-INF/classes/org/makumba/parade/model/managers/WebappManager.java
@@ -1,206 +1,207 @@
package org.makumba.parade.model.managers;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.servlet.jsp.PageContext;
import org.apache.log4j.Logger;
import org.makumba.parade.init.ParadeProperties;
import org.makumba.parade.model.Row;
import org.makumba.parade.model.RowCVS;
import org.makumba.parade.model.RowWebapp;
import org.makumba.parade.model.interfaces.ParadeManager;
import org.makumba.parade.model.interfaces.RowRefresher;
public class WebappManager implements RowRefresher, ParadeManager {
static String reloadLog = ParadeProperties.getParadeBase() + java.io.File.separator + "tomcat" + java.io.File.separator
+ "logs" + java.io.File.separator + "paradeReloadResult.txt";
ServletContainer container;
Properties config;
private static String DEFAULT_SERVLETCONTEXTPROPERTIES = "/servletContext.properties";
static Logger logger = Logger.getLogger(WebappManager.class.getName());
{
loadConfig();
}
public void newRow(String name, Row r, Map m) {
RowWebapp webappdata = new RowWebapp();
webappdata.setDataType("webapp");
webappdata.setWebappPath((String) m.get("webapp"));
r.addManagerData(webappdata);
}
public void rowRefresh(Row row) {
logger.debug("Refreshing row information for row "+row.getRowname());
RowWebapp webappdata = (RowWebapp) row.getRowdata().get("webapp");
setWebappInfo(row, webappdata);
row.addManagerData(webappdata);
}
private void loadConfig() {
try {
config = new Properties();
config.load(this.getClass().getResourceAsStream(DEFAULT_SERVLETCONTEXTPROPERTIES));
} catch (Throwable t) {
logger.error("Error loading servletcontext.properties", t);
}
}
private synchronized ServletContainer getServletContainer() {
if (container == null)
try {
container = (ServletContainer) ParadeProperties.class.getClassLoader().loadClass(
config.getProperty("parade.servletContext.servletContainer")).newInstance();
config.put("parade.servletContext.paradeContext", new File(ParadeProperties.getParadeBase())
.getCanonicalPath());
container.makeConfig(config);
config.store(new FileOutputStream(ParadeProperties.getClassesPath() + java.io.File.separator + "servletcontext.properties"), "Parade servlet context config");
container.init(config);
} catch (Throwable t) {
logger.error("Error getting servlet container", t);
}
return container;
}
/* stores information about Row's servletContext */
public void setWebappInfo(Row row, RowWebapp webappdata) {
// checks if there's a WEB-INF dir
String webinfDir = row.getRowpath() + java.io.File.separator + webappdata.getWebappPath()
+ java.io.File.separator + "WEB-INF";
if (!new java.io.File(webinfDir).isDirectory()) {
logger.warn("No WEB-INF directory found for row "+row.getRowname()+": directory "+webinfDir+" does not exist");
webinfDir = "NO WEBINF";
webappdata.setWebappPath("NO WEBINF");
webappdata.setStatus(new Integer(ServletContainer.NOT_INSTALLED));
}
if (!webinfDir.equals("NO WEBINF")) {
if(row.getRowname().equals("(root)")) {
webappdata.setContextname("/");
} else {
webappdata.setContextname("/" + row.getRowname());
}
webappdata.setStatus(new Integer(getServletContainer().getContextStatus(webappdata.getContextname())));
}
}
public String servletContextStartRow(Row row) {
RowWebapp data = (RowWebapp) row.getRowdata().get("webapp");
if (!isParadeCheck(row)) {
String result = getServletContainer().startContext(data.getContextname());
setWebappInfo(row, data);
return result;
}
return "ParaDe is already running";
}
public String servletContextStopRow(Row row) {
RowWebapp data = (RowWebapp) row.getRowdata().get("webapp");
if (!isParadeCheck(row)) {
String result = getServletContainer().stopContext(data.getContextname());
setWebappInfo(row, data);
return result;
}
return "Error: you cannot stop ParaDe like this !";
}
public String servletContextReloadRow(Row row) {
+ RowWebapp data = (RowWebapp) row.getRowdata().get("webapp");
String result = "";
// must check if it's not this one
if (!isParade(row)) {
- result = getServletContainer().reloadContext(row.getRowname());
+ result = getServletContainer().reloadContext(data.getContextname());
} else {
try {
String antCommand = "ant";
File f = new File(reloadLog);
Runtime.getRuntime().exec(antCommand + " -buildfile " + ParadeProperties.getParadeBase() + java.io.File.separator + "build.xml reload");
f.delete();
while (!f.exists()) {
try {
Thread.currentThread().sleep(100);
} catch (Throwable t) {
logger.warn("Context reload thread sleep failed");
}
}
loadConfig();
// TODO make this work
result = config.getProperty("parade.servletContext.selfReloadWait");
} catch (IOException e) {
result = "Cannot reload Parade " + e;
logger.error("Cannot reload ParaDe", e);
}
}
return result;
}
public String servletContextInstallRow(Row row) {
RowWebapp data = (RowWebapp) row.getRowdata().get("webapp");
if (!isParadeCheck(row)) {
String webapp = row.getRowpath() + File.separator + data.getWebappPath();
String result = getServletContainer().installContext(data.getContextname(), webapp);
setWebappInfo(row, data);
return result;
}
return "Internal error: ParaDe should not be installed in this way !";
}
public String servletContextRemoveRow(Row row) {
RowWebapp data = (RowWebapp) row.getRowdata().get("webapp");
if (!isParadeCheck(row)) {
String result = getServletContainer().unInstallContext(data.getContextname());
setWebappInfo(row, data);
return result;
}
return "Error: you cannot uninstall ParaDe !";
}
private boolean isParadeCheck(Row row) {
if (isParade(row)) {
// row.put("result", "You can only reload Parade!");
return true;
}
return false;
}
private boolean isParade(Row row) {
try {
return row.getRowpath().equals(new File(ParadeProperties.getParadeBase()).getCanonicalPath());
} catch (Throwable t) {
logger.error("Internal error: couldn't get row path", t);
}
return true;
}
}
| false | true | public String servletContextReloadRow(Row row) {
String result = "";
// must check if it's not this one
if (!isParade(row)) {
result = getServletContainer().reloadContext(row.getRowname());
} else {
try {
String antCommand = "ant";
File f = new File(reloadLog);
Runtime.getRuntime().exec(antCommand + " -buildfile " + ParadeProperties.getParadeBase() + java.io.File.separator + "build.xml reload");
f.delete();
while (!f.exists()) {
try {
Thread.currentThread().sleep(100);
} catch (Throwable t) {
logger.warn("Context reload thread sleep failed");
}
}
loadConfig();
// TODO make this work
result = config.getProperty("parade.servletContext.selfReloadWait");
} catch (IOException e) {
result = "Cannot reload Parade " + e;
logger.error("Cannot reload ParaDe", e);
}
}
return result;
}
| public String servletContextReloadRow(Row row) {
RowWebapp data = (RowWebapp) row.getRowdata().get("webapp");
String result = "";
// must check if it's not this one
if (!isParade(row)) {
result = getServletContainer().reloadContext(data.getContextname());
} else {
try {
String antCommand = "ant";
File f = new File(reloadLog);
Runtime.getRuntime().exec(antCommand + " -buildfile " + ParadeProperties.getParadeBase() + java.io.File.separator + "build.xml reload");
f.delete();
while (!f.exists()) {
try {
Thread.currentThread().sleep(100);
} catch (Throwable t) {
logger.warn("Context reload thread sleep failed");
}
}
loadConfig();
// TODO make this work
result = config.getProperty("parade.servletContext.selfReloadWait");
} catch (IOException e) {
result = "Cannot reload Parade " + e;
logger.error("Cannot reload ParaDe", e);
}
}
return result;
}
|
diff --git a/src/cytoscape/dialogs/plugins/PluginManageDialog.java b/src/cytoscape/dialogs/plugins/PluginManageDialog.java
index 2489f758b..43d8c3d0b 100644
--- a/src/cytoscape/dialogs/plugins/PluginManageDialog.java
+++ b/src/cytoscape/dialogs/plugins/PluginManageDialog.java
@@ -1,826 +1,826 @@
/*
File: PluginManageDialog.java
Copyright (c) 2006, 2007, The Cytoscape Consortium (www.cytoscape.org)
The Cytoscape Consortium is:
- Institute for Systems Biology
- University of California San Diego
- Memorial Sloan-Kettering Cancer Center
- Institut Pasteur
- Agilent Technologies
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. See
the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package cytoscape.dialogs.plugins;
import cytoscape.Cytoscape;
import cytoscape.plugin.DownloadableInfo;
import cytoscape.plugin.ThemeInfo;
import cytoscape.plugin.PluginInfo;
import cytoscape.plugin.PluginManager;
import cytoscape.task.TaskMonitor;
import cytoscape.task.ui.JTaskConfig;
import cytoscape.task.util.TaskManager;
import cytoscape.util.OpenBrowser;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;
public class PluginManageDialog extends javax.swing.JDialog implements
TreeSelectionListener, ActionListener {
public enum PluginInstallStatus {
INSTALLED("Currently Installed"), AVAILABLE("Available for Install");
private String typeText;
private PluginInstallStatus(String type) {
typeText = type;
}
public String toString() {
return typeText;
}
}
public enum CommonError {
NOXML("ERROR: Failed to read XML file "), BADXML(
"ERROR: XML file may be incorrectly formatted, unable to read ");
private String errorText;
private CommonError(String error) {
errorText = error;
}
public String toString() {
return errorText;
}
}
private String baseSiteLabel = "Plugins available for download from: ";
public PluginManageDialog() {
this.setTitle("Manage Plugins");
initComponents();
initTree();
}
public PluginManageDialog(javax.swing.JDialog owner) {
super(owner, "Manage Plugins");
setLocationRelativeTo(owner);
initComponents();
initTree();
}
public PluginManageDialog(javax.swing.JFrame owner) {
super(owner, "Manage Plugins");
setLocationRelativeTo(owner);
initComponents();
initTree();
}
// trying to listen to events in the Url dialog
public void actionPerformed(ActionEvent evt) {
System.out.println("URL DIALOG: " + evt.getSource().toString());
}
/**
* Enables the delete/install buttons when the correct leaf node is selected
*/
public void valueChanged(TreeSelectionEvent e) {
TreeNode Node = (TreeNode) pluginTree.getLastSelectedPathComponent();
if (Node == null) {
return;
}
if (Node.isLeaf()) {
// display any object selected
infoTextPane.setContentType("text/html");
infoTextPane.setText(((DownloadableInfo) Node.getObject()).htmlOutput());
infoTextPane.setCaretPosition(0);
infoTextPane.setEditable(false);
infoTextPane.addHyperlinkListener(new javax.swing.event.HyperlinkListener() {
public void hyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) {
if (evt.getEventType() == javax.swing.event.HyperlinkEvent.EventType.ACTIVATED) {
// call open browser on the link
OpenBrowser.openURL(evt.getURL().toString());
}
}
});
if (Node.isNodeAncestor(installedNode)) {
installDeleteButton.setText("Delete");
if (PluginManager.usingWebstartManager()) {
installDeleteButton.setEnabled(false);
setMessage("Delete is unavailable when using Web Start");
} else {
installDeleteButton.setEnabled(true);
}
} else if (Node.isNodeAncestor(availableNode)) {
installDeleteButton.setText("Install");
installDeleteButton.setEnabled(true);
}
} else {
installDeleteButton.setEnabled(false);
}
}
/**
* Sets a message to be shown to the user regarding the plugin management
* actions.
*
* @param Msg
*/
public void setMessage(String Msg) {
msgLabel.setForeground(java.awt.Color.BLACK);
msgLabel.setText(Msg);
}
public void setError(String Msg) {
msgLabel.setForeground(new java.awt.Color(204, 0, 51));
msgLabel.setText(Msg);
}
/**
* Set the name of the site the available plugins are from.
*
* @param SiteName
*/
public void setSiteName(String SiteName) {
availablePluginsLabel.setText(baseSiteLabel + " " + SiteName);
}
/**
* Call this when changing download sites to clear out the old available
* list in order to create a new one.
*/
public void switchDownloadSites() {
hiddenNodes.clear();
java.util.Vector<TreeNode> AvailableNodes = new java.util.Vector<TreeNode>(
availableNode.getChildren());
for (TreeNode child : AvailableNodes) {
treeModel.removeNodeFromParent(child);
}
}
/**
* Adds a category and it's list of plugins to the appropriate tree (based
* on Status) in the dialog.
*
* @param CategoryName
* String category for this list of plugins
* @param Plugins
* List of DownloadableInfo objects to be shown in the given
* category
* @param Status
* PluginInstallStatus (currently installed or available for
* install)
*/
public void addCategory(String CategoryName,
List<DownloadableInfo> Plugins, PluginInstallStatus Status) {
switch (Status) {
case INSTALLED:
addCategory(CategoryName, Plugins, installedNode);
break;
case AVAILABLE:
addCategory(CategoryName, Plugins, availableNode);
if (treeModel.getIndexOfChild(rootTreeNode, availableNode) < 0) {
treeModel.addNodeToParent(rootTreeNode, availableNode);
}
break;
}
javax.swing.ToolTipManager.sharedInstance().registerComponent(
pluginTree);
javax.swing.ImageIcon warningIcon = createImageIcon(
"/cytoscape/images/misc/alert-red2.gif", "Warning");
javax.swing.ImageIcon okIcon = createImageIcon(
"/cytoscape/images/misc/check-mark.gif", "Ok");
if (warningIcon != null) {
treeRenderer = new TreeCellRenderer(warningIcon, okIcon);
pluginTree.setCellRenderer(treeRenderer);
}
pluginTree.expandPath( new TreePath(availableNode.getPath()) );
pluginTree.expandPath( new TreePath(installedNode.getPath()) );
}
// add category to the set of plugins under given node
private void addCategory(String CategoryName,
List<DownloadableInfo> Plugins, TreeNode node) {
TreeNode Category = new TreeNode(CategoryName, true);
for (DownloadableInfo CurrentPlugin : Plugins) {
TreeNode PluginNode = new TreeNode(CurrentPlugin);
if (node.equals(availableNode)
&& !CurrentPlugin.isCytoscapeVersionCurrent()) {
java.util.List<TreeNode> hiddenCat = hiddenNodes.get(Category);
if (hiddenCat == null)
hiddenCat = new java.util.ArrayList<TreeNode>();
hiddenCat.add(PluginNode);
hiddenNodes.put(Category, hiddenCat);
if (versionCheck.isSelected())
treeModel.addNodeToParent(Category, PluginNode);
} else {
treeModel.addNodeToParent(Category, PluginNode);
}
}
if (Category.getChildCount() > 0)
treeModel.addNodeToParent(node, Category);
}
// change site url
private void changeSiteButtonActionPerformed(java.awt.event.ActionEvent evt) {
PluginUrlDialog dialog = new PluginUrlDialog(this);
dialog.setVisible(true);
}
// allow for outdated versions
private void versionCheckItemStateChanged(java.awt.event.ItemEvent evt) {
TreePath[] SelectedPaths = pluginTree.getSelectionPaths();
if (evt.getStateChange() == ItemEvent.SELECTED) {
pluginTree.collapsePath( new TreePath(availableNode.getPath()) );
availableNode.removeChildren();
for (TreeNode Category : hiddenNodes.keySet()) {
for (TreeNode Plugin : hiddenNodes.get(Category)) {
treeModel.addNodeToParent(Category, Plugin);
}
treeModel.addNodeToParent(availableNode, Category);
}
} else if (evt.getStateChange() == ItemEvent.DESELECTED) {
for (TreeNode Category : hiddenNodes.keySet()) {
for (TreeNode Plugin: hiddenNodes.get(Category)) {
hiddenNodes.get(Category);
treeModel.removeNodesFromParent(hiddenNodes.get(Category));
if (Category.getChildCount() <= 0) {
availableNode.removeChild(Category);
treeModel.reload();
}
}
}
}
if (SelectedPaths != null) {
for (TreePath Path: SelectedPaths) {
pluginTree.expandPath(Path);
pluginTree.setSelectionPath(Path);
}
} else {
pluginTree.expandPath( new TreePath(availableNode.getPath()) );
pluginTree.expandPath( new TreePath(installedNode.getPath()) );
}
}
private void installDeleteButtonActionPerformed(ActionEvent evt) {
if (installDeleteButton.getText().equals("Delete")) {
deleteButtonActionPerformed(evt);
} else if (installDeleteButton.getText().equals("Install")) {
installButtonActionPerformed(evt);
}
}
// delete event
private void deleteButtonActionPerformed(ActionEvent evt) {
TreeNode Node = (TreeNode) pluginTree.getLastSelectedPathComponent();
if (Node == null) {
return;
}
DownloadableInfo NodeInfo = (DownloadableInfo) Node.getObject();
String ChangeMsg = "Changes will not take effect until you have restarted Cytoscape.";
String VerifyMsg = "";
if (NodeInfo.getCategory().equalsIgnoreCase("core")) {
VerifyMsg = "This is a 'core' plugin and other plugins may depend on it, "
+ "are you sure you want to delete it?\n" + ChangeMsg;
} else {
VerifyMsg = "Are you sure you want to delete the plugin '"
+ NodeInfo.getName() + "'?\n" + ChangeMsg;
}
if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,
VerifyMsg, "Verify Delete Plugin", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE)) {
try {
PluginManager.getPluginManager().delete(NodeInfo);
treeModel.removeNodeFromParent(Node);
setMessage(NodeInfo.getName()
+ " will be removed when you restart Cytoscape.");
} catch (cytoscape.plugin.WebstartException we) {
we.printStackTrace();
}
}
}
// install new downloadable obj
private void installButtonActionPerformed(java.awt.event.ActionEvent evt) {
final TreeNode node = (TreeNode) pluginTree
.getLastSelectedPathComponent();
if (node == null) { // error
return;
}
Object nodeInfo = node.getObject();
if (node.isLeaf()) {
boolean licenseRequired = false;
final LicenseDialog License = new LicenseDialog(this);
final DownloadableInfo infoObj = (DownloadableInfo) nodeInfo;
switch (infoObj.getType()) {
case PLUGIN:
if (infoObj.getLicenseText() != null) {
License.addPlugin(infoObj);
licenseRequired = true;
}
break;
case THEME:
ThemeInfo themeInfo = (ThemeInfo) infoObj;
for (PluginInfo pInfo : themeInfo.getPlugins()) {
if (pInfo.getLicenseText() != null) {
License.addPlugin(pInfo);
licenseRequired = true;
}
}
break;
case FILE: // currently nothing, there are no FileInfo objects
// right now
break;
}
if (licenseRequired) {
License.addListenerToOk(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
License.dispose();
createInstallTask(infoObj, node);
}
});
License.selectDefault();
License.setVisible(true);
} else {
createInstallTask(infoObj, node);
}
}
}
private void updateCurrent(DownloadableInfo info) {
boolean categoryMatched = false;
for (TreeNode Child : installedNode.getChildren()) {
if (Child.getTitle().equals(info.getCategory())) {
Child.addChild(new TreeNode(info));
categoryMatched = true;
}
}
if (!categoryMatched) {
List<DownloadableInfo> NewPlugin = new java.util.ArrayList<DownloadableInfo>();
NewPlugin.add(info);
addCategory(info.getCategory(), NewPlugin,
PluginInstallStatus.INSTALLED);
}
}
// close button
private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
}
// initialize the JTree and base nodes
private void initTree() {
pluginTree.setRootVisible(false);
pluginTree.addTreeSelectionListener(this);
pluginTree.getSelectionModel().setSelectionMode(
javax.swing.tree.TreeSelectionModel.SINGLE_TREE_SELECTION);
rootTreeNode = new TreeNode("Plugins", true);
installedNode = new TreeNode(PluginInstallStatus.INSTALLED.toString(),
true);
availableNode = new TreeNode(PluginInstallStatus.AVAILABLE.toString(),
true);
treeModel = new ManagerModel(rootTreeNode);
treeModel.addNodeToParent(rootTreeNode, installedNode);
treeModel.addNodeToParent(rootTreeNode, availableNode);
pluginTree.setModel(treeModel);
hiddenNodes = new java.util.HashMap<TreeNode, java.util.List<TreeNode>>();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
jSplitPane1 = new javax.swing.JSplitPane();
infoScrollPane = new javax.swing.JScrollPane();
infoTextPane = new javax.swing.JEditorPane();
treeScrollPane = new javax.swing.JScrollPane();
pluginTree = new javax.swing.JTree();
availablePluginsLabel = new javax.swing.JLabel();
msgLabel = new javax.swing.JLabel();
buttonPanel = new javax.swing.JPanel();
installDeleteButton = new javax.swing.JButton();
closeButton = new javax.swing.JButton();
sitePanel = new javax.swing.JPanel();
changeSiteButton = new javax.swing.JButton();
versionCheck = new javax.swing.JCheckBox();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jSplitPane1.setDividerLocation(250);
infoScrollPane.setViewportView(infoTextPane);
jSplitPane1.setRightComponent(infoScrollPane);
treeScrollPane.setViewportView(pluginTree);
jSplitPane1.setLeftComponent(treeScrollPane);
availablePluginsLabel.setLabelFor(jSplitPane1);
availablePluginsLabel.setText("Plugins available for download from:");
availablePluginsLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
msgLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
msgLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
msgLabel.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
msgLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
installDeleteButton.setText("Install");
installDeleteButton.setEnabled(false);
installDeleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
installDeleteButtonActionPerformed(evt);
}
});
closeButton.setText("Close");
closeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout buttonPanelLayout = new org.jdesktop.layout.GroupLayout(buttonPanel);
buttonPanel.setLayout(buttonPanelLayout);
buttonPanelLayout.setHorizontalGroup(
buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.addContainerGap()
- .add(installDeleteButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 75, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(installDeleteButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 80, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(closeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 75, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
buttonPanelLayout.setVerticalGroup(
buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.addContainerGap()
.add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(installDeleteButton)
.add(closeButton))
.addContainerGap(8, Short.MAX_VALUE))
);
changeSiteButton.setText("Change Download Site");
changeSiteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
changeSiteButtonActionPerformed(evt);
}
});
versionCheck.setText("Show Outdated Plugins ");
versionCheck.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
versionCheck.setMargin(new java.awt.Insets(0, 0, 0, 0));
versionCheck.setVerticalAlignment(javax.swing.SwingConstants.TOP);
versionCheck.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
versionCheck.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
versionCheckItemStateChanged(evt);
}
});
org.jdesktop.layout.GroupLayout sitePanelLayout = new org.jdesktop.layout.GroupLayout(sitePanel);
sitePanel.setLayout(sitePanelLayout);
sitePanelLayout.setHorizontalGroup(
sitePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(sitePanelLayout.createSequentialGroup()
.add(sitePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(changeSiteButton)
.add(sitePanelLayout.createSequentialGroup()
.add(2, 2, 2)
.add(versionCheck)))
.addContainerGap())
);
sitePanelLayout.setVerticalGroup(
sitePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(sitePanelLayout.createSequentialGroup()
.addContainerGap()
.add(changeSiteButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(versionCheck, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 18, Short.MAX_VALUE)
.addContainerGap())
);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING, jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE)
.add(layout.createSequentialGroup()
.add(msgLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 432, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(buttonPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(availablePluginsLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
.add(191, 191, 191)
.add(sitePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(74, 74, 74))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(16, 16, 16)
.add(availablePluginsLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
.add(41, 41, 41))
.add(layout.createSequentialGroup()
.addContainerGap()
.add(sitePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(msgLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE)
.add(buttonPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}// </editor-fold>
/*
* --- create the tasks and task monitors to show the user what's going on
* during download/install ---
*/
private void createInstallTask(DownloadableInfo obj, TreeNode node) {
// Create Task
InstallTask task = new InstallTask(obj, node);
// Configure JTask Dialog Pop-Up Box
JTaskConfig jTaskConfig = new JTaskConfig();
jTaskConfig.setOwner(Cytoscape.getDesktop());
jTaskConfig.displayCloseButton(false);
jTaskConfig.displayStatus(true);
jTaskConfig.setAutoDispose(true);
jTaskConfig.displayCancelButton(true);
// Execute Task in New Thread; pop open JTask Dialog Box.
TaskManager.executeTask(task, jTaskConfig);
DownloadableInfo info = task.getDownloadedPlugin();
if (info != null) {
updateCurrent(info);
cleanTree(node);
} else {
// TODO somehow disable the node??
}
}
private void cleanTree(TreeNode node) {
DownloadableInfo info = (DownloadableInfo) node.getObject();
List<TreeNode> RemovableNodes = new java.util.ArrayList<TreeNode>();
for (int i = 0; i < node.getParent().getChildCount(); i++) {
TreeNode Child = (TreeNode) node.getParent().getChildAt(i);
DownloadableInfo childInfo = (DownloadableInfo) Child.getObject();
if (childInfo.getID().equals(info.getID())
&& childInfo.getName().equals(info.getName())) {
RemovableNodes.add(Child);
}
}
for (TreeNode treeNode : RemovableNodes) {
treeModel.removeNodeFromParent(treeNode);
}
}
public static void main(String[] args) {
PluginManageDialog pd = new PluginManageDialog();
List<DownloadableInfo> Plugins = new java.util.ArrayList<DownloadableInfo>();
PluginInfo infoC = new PluginInfo("1", "A Plugin");
infoC.addCytoscapeVersion(cytoscape.CytoscapeVersion.version);
Plugins.add(infoC);
infoC = new PluginInfo("2", "B Plugin");
infoC.addCytoscapeVersion(cytoscape.CytoscapeVersion.version);
Plugins.add(infoC);
infoC = new PluginInfo("3", "C");
infoC.addCytoscapeVersion(cytoscape.CytoscapeVersion.version);
Plugins.add(infoC);
pd.addCategory(cytoscape.plugin.Category.NONE.toString(), Plugins,
PluginInstallStatus.AVAILABLE);
List<DownloadableInfo> Outdated = new java.util.ArrayList<DownloadableInfo>();
PluginInfo infoOD = new PluginInfo("11", "CyGoose");
infoOD.addCytoscapeVersion("2.3");
Outdated.add(infoOD);
infoOD = new PluginInfo("12", "Y");
infoOD.addCytoscapeVersion("2.3");
Outdated.add(infoOD);
pd.addCategory("Outdated", Outdated, PluginInstallStatus.AVAILABLE);
pd.setMessage("Foo bar");
pd.setVisible(true);
}
/** Returns an ImageIcon, or null if the path was invalid. */
private javax.swing.ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new javax.swing.ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
private class InstallTask implements cytoscape.task.Task {
private cytoscape.task.TaskMonitor taskMonitor;
private DownloadableInfo infoObj;
private TreeNode node;
public InstallTask(DownloadableInfo Info, TreeNode Node)
throws java.lang.IllegalArgumentException {
String ErrorMsg = null;
if (Info == null) {
ErrorMsg = "DownloadableInfo object cannot be null\n";
throw new java.lang.IllegalArgumentException(ErrorMsg);
}
infoObj = Info;
node = Node;
}
public void run() {
if (taskMonitor == null) {
throw new IllegalStateException("Task Monitor is not set.");
}
taskMonitor.setStatus("Installing " + infoObj.getName() + " v"
+ infoObj.getObjectVersion());
taskMonitor.setPercentCompleted(-1);
PluginManager Mgr = PluginManager.getPluginManager();
try {
infoObj = Mgr.download(infoObj, taskMonitor);
taskMonitor.setStatus(infoObj.getName() + " v"
+ infoObj.getObjectVersion() + " complete.");
PluginManageDialog.this.setMessage(infoObj.getName()
+ " install complete.");
taskMonitor.setStatus(infoObj.getName() + " v"
+ infoObj.getObjectVersion() + " loading...");
Mgr.install(infoObj);
Mgr.loadPlugin(infoObj);
} catch (java.io.IOException ioe) {
taskMonitor
.setException(ioe, "Failed to download "
+ infoObj.getName() + " from "
+ infoObj.getObjectUrl());
infoObj = null;
ioe.printStackTrace();
} catch (cytoscape.plugin.ManagerException me) {
PluginManageDialog.this.setError("Failed to install "
+ infoObj.toString());
taskMonitor.setException(me, me.getMessage());
infoObj = null;
me.printStackTrace();
} catch (cytoscape.plugin.PluginException pe) {
PluginManageDialog.this.setError("Failed to install "
+ infoObj.toString());
infoObj = null;
taskMonitor.setException(pe, pe.getMessage());
pe.printStackTrace();
} catch (ClassNotFoundException cne) {
taskMonitor.setException(cne, cne.getMessage());
PluginManageDialog.this.setError("Failed to install "
+ infoObj.toString());
infoObj = null;
cne.printStackTrace();
} finally {
taskMonitor.setPercentCompleted(100);
}
}
public DownloadableInfo getDownloadedPlugin() {
return infoObj;
}
public void halt() {
// not haltable
}
public void setTaskMonitor(TaskMonitor monitor)
throws IllegalThreadStateException {
this.taskMonitor = monitor;
}
public String getTitle() {
return "Installing Cytoscape Plugin '" + infoObj.getName() + "'";
}
}
// Variables declaration - do not modify
private javax.swing.JLabel availablePluginsLabel;
private javax.swing.JButton changeSiteButton;
private javax.swing.JButton closeButton;
private javax.swing.JButton installDeleteButton;
private javax.swing.JPanel buttonPanel;
private javax.swing.JPanel sitePanel;
private javax.swing.JScrollPane infoScrollPane;
private javax.swing.JEditorPane infoTextPane;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JLabel msgLabel;
private javax.swing.JTree pluginTree;
private javax.swing.JScrollPane treeScrollPane;
private javax.swing.JCheckBox versionCheck;
private TreeNode rootTreeNode;
private TreeNode installedNode;
private TreeNode availableNode;
private ManagerModel treeModel;
private TreeCellRenderer treeRenderer;
private java.util.HashMap<TreeNode, java.util.List<TreeNode>> hiddenNodes;
}
| true | true | private void initComponents() {
jSplitPane1 = new javax.swing.JSplitPane();
infoScrollPane = new javax.swing.JScrollPane();
infoTextPane = new javax.swing.JEditorPane();
treeScrollPane = new javax.swing.JScrollPane();
pluginTree = new javax.swing.JTree();
availablePluginsLabel = new javax.swing.JLabel();
msgLabel = new javax.swing.JLabel();
buttonPanel = new javax.swing.JPanel();
installDeleteButton = new javax.swing.JButton();
closeButton = new javax.swing.JButton();
sitePanel = new javax.swing.JPanel();
changeSiteButton = new javax.swing.JButton();
versionCheck = new javax.swing.JCheckBox();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jSplitPane1.setDividerLocation(250);
infoScrollPane.setViewportView(infoTextPane);
jSplitPane1.setRightComponent(infoScrollPane);
treeScrollPane.setViewportView(pluginTree);
jSplitPane1.setLeftComponent(treeScrollPane);
availablePluginsLabel.setLabelFor(jSplitPane1);
availablePluginsLabel.setText("Plugins available for download from:");
availablePluginsLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
msgLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
msgLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
msgLabel.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
msgLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
installDeleteButton.setText("Install");
installDeleteButton.setEnabled(false);
installDeleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
installDeleteButtonActionPerformed(evt);
}
});
closeButton.setText("Close");
closeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout buttonPanelLayout = new org.jdesktop.layout.GroupLayout(buttonPanel);
buttonPanel.setLayout(buttonPanelLayout);
buttonPanelLayout.setHorizontalGroup(
buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.addContainerGap()
.add(installDeleteButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 75, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(closeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 75, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
buttonPanelLayout.setVerticalGroup(
buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.addContainerGap()
.add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(installDeleteButton)
.add(closeButton))
.addContainerGap(8, Short.MAX_VALUE))
);
changeSiteButton.setText("Change Download Site");
changeSiteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
changeSiteButtonActionPerformed(evt);
}
});
versionCheck.setText("Show Outdated Plugins ");
versionCheck.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
versionCheck.setMargin(new java.awt.Insets(0, 0, 0, 0));
versionCheck.setVerticalAlignment(javax.swing.SwingConstants.TOP);
versionCheck.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
versionCheck.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
versionCheckItemStateChanged(evt);
}
});
org.jdesktop.layout.GroupLayout sitePanelLayout = new org.jdesktop.layout.GroupLayout(sitePanel);
sitePanel.setLayout(sitePanelLayout);
sitePanelLayout.setHorizontalGroup(
sitePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(sitePanelLayout.createSequentialGroup()
.add(sitePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(changeSiteButton)
.add(sitePanelLayout.createSequentialGroup()
.add(2, 2, 2)
.add(versionCheck)))
.addContainerGap())
);
sitePanelLayout.setVerticalGroup(
sitePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(sitePanelLayout.createSequentialGroup()
.addContainerGap()
.add(changeSiteButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(versionCheck, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 18, Short.MAX_VALUE)
.addContainerGap())
);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING, jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE)
.add(layout.createSequentialGroup()
.add(msgLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 432, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(buttonPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(availablePluginsLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
.add(191, 191, 191)
.add(sitePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(74, 74, 74))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(16, 16, 16)
.add(availablePluginsLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
.add(41, 41, 41))
.add(layout.createSequentialGroup()
.addContainerGap()
.add(sitePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(msgLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE)
.add(buttonPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}// </editor-fold>
| private void initComponents() {
jSplitPane1 = new javax.swing.JSplitPane();
infoScrollPane = new javax.swing.JScrollPane();
infoTextPane = new javax.swing.JEditorPane();
treeScrollPane = new javax.swing.JScrollPane();
pluginTree = new javax.swing.JTree();
availablePluginsLabel = new javax.swing.JLabel();
msgLabel = new javax.swing.JLabel();
buttonPanel = new javax.swing.JPanel();
installDeleteButton = new javax.swing.JButton();
closeButton = new javax.swing.JButton();
sitePanel = new javax.swing.JPanel();
changeSiteButton = new javax.swing.JButton();
versionCheck = new javax.swing.JCheckBox();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jSplitPane1.setDividerLocation(250);
infoScrollPane.setViewportView(infoTextPane);
jSplitPane1.setRightComponent(infoScrollPane);
treeScrollPane.setViewportView(pluginTree);
jSplitPane1.setLeftComponent(treeScrollPane);
availablePluginsLabel.setLabelFor(jSplitPane1);
availablePluginsLabel.setText("Plugins available for download from:");
availablePluginsLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
msgLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
msgLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
msgLabel.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
msgLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
installDeleteButton.setText("Install");
installDeleteButton.setEnabled(false);
installDeleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
installDeleteButtonActionPerformed(evt);
}
});
closeButton.setText("Close");
closeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout buttonPanelLayout = new org.jdesktop.layout.GroupLayout(buttonPanel);
buttonPanel.setLayout(buttonPanelLayout);
buttonPanelLayout.setHorizontalGroup(
buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.addContainerGap()
.add(installDeleteButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 80, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(closeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 75, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
buttonPanelLayout.setVerticalGroup(
buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.addContainerGap()
.add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(installDeleteButton)
.add(closeButton))
.addContainerGap(8, Short.MAX_VALUE))
);
changeSiteButton.setText("Change Download Site");
changeSiteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
changeSiteButtonActionPerformed(evt);
}
});
versionCheck.setText("Show Outdated Plugins ");
versionCheck.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
versionCheck.setMargin(new java.awt.Insets(0, 0, 0, 0));
versionCheck.setVerticalAlignment(javax.swing.SwingConstants.TOP);
versionCheck.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
versionCheck.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
versionCheckItemStateChanged(evt);
}
});
org.jdesktop.layout.GroupLayout sitePanelLayout = new org.jdesktop.layout.GroupLayout(sitePanel);
sitePanel.setLayout(sitePanelLayout);
sitePanelLayout.setHorizontalGroup(
sitePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(sitePanelLayout.createSequentialGroup()
.add(sitePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(changeSiteButton)
.add(sitePanelLayout.createSequentialGroup()
.add(2, 2, 2)
.add(versionCheck)))
.addContainerGap())
);
sitePanelLayout.setVerticalGroup(
sitePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(sitePanelLayout.createSequentialGroup()
.addContainerGap()
.add(changeSiteButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(versionCheck, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 18, Short.MAX_VALUE)
.addContainerGap())
);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING, jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE)
.add(layout.createSequentialGroup()
.add(msgLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 432, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(buttonPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(availablePluginsLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
.add(191, 191, 191)
.add(sitePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(74, 74, 74))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(16, 16, 16)
.add(availablePluginsLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
.add(41, 41, 41))
.add(layout.createSequentialGroup()
.addContainerGap()
.add(sitePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(msgLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE)
.add(buttonPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}// </editor-fold>
|
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyBranchImpl.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyBranchImpl.java
index 9948360c1..bb62ad7e7 100644
--- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyBranchImpl.java
+++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyBranchImpl.java
@@ -1,718 +1,718 @@
/*
* 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.proxy;
import gov.nist.javax.sip.message.SIPMessage;
import gov.nist.javax.sip.stack.SIPClientTransaction;
import gov.nist.javax.sip.stack.SIPTransaction;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import javax.servlet.ServletException;
import javax.servlet.sip.Proxy;
import javax.servlet.sip.ProxyBranch;
import javax.servlet.sip.ServletParseException;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.SipURI;
import javax.servlet.sip.URI;
import javax.servlet.sip.ar.SipApplicationRoutingDirective;
import javax.sip.ClientTransaction;
import javax.sip.SipException;
import javax.sip.SipProvider;
import javax.sip.header.RouteHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.Request;
import org.apache.log4j.Logger;
import org.mobicents.servlet.sip.GenericUtils;
import org.mobicents.servlet.sip.JainSipUtils;
import org.mobicents.servlet.sip.address.SipURIImpl;
import org.mobicents.servlet.sip.core.RoutingState;
import org.mobicents.servlet.sip.core.SipApplicationDispatcherImpl;
import org.mobicents.servlet.sip.core.dispatchers.MessageDispatcher;
import org.mobicents.servlet.sip.core.session.MobicentsSipSession;
import org.mobicents.servlet.sip.message.SipServletRequestImpl;
import org.mobicents.servlet.sip.message.SipServletResponseImpl;
import org.mobicents.servlet.sip.message.TransactionApplicationData;
/**
* @author root
*
*/
public class ProxyBranchImpl implements ProxyBranch, Serializable {
private static transient Logger logger = Logger.getLogger(ProxyBranchImpl.class);
private ProxyImpl proxy;
private transient SipServletRequestImpl originalRequest;
private transient SipServletRequestImpl prackOriginalRequest;
private transient SipServletRequestImpl outgoingRequest;
private transient SipServletResponseImpl lastResponse;
private transient URI targetURI;
private transient SipURI outboundInterface;
private transient SipURI recordRouteURI;
private boolean recordRoutingEnabled;
private boolean recurse;
private transient SipURI pathURI;
private boolean started;
private boolean timedOut;
private int proxyBranchTimeout;
private transient ProxyBranchTimerTask proxyTimeoutTask;
private boolean canceled;
private boolean isAddToPath;
private transient List<ProxyBranch> recursedBranches;
private boolean waitingForPrack;
public transient ViaHeader viaHeader;
private static transient Timer timer = new Timer();
public ProxyBranchImpl(URI uri, ProxyImpl proxy)
{
this.targetURI = uri;
this.proxy = proxy;
isAddToPath = proxy.getAddToPath();
this.originalRequest = (SipServletRequestImpl) proxy.getOriginalRequest();
this.recordRouteURI = proxy.recordRouteURI;
this.pathURI = proxy.pathURI;
this.outboundInterface = proxy.getOutboundInterface();
if(recordRouteURI != null) {
this.recordRouteURI = (SipURI)((SipURIImpl)recordRouteURI).clone();
}
this.proxyBranchTimeout = proxy.getProxyTimeout();
this.canceled = false;
this.recursedBranches = new ArrayList<ProxyBranch>();
// Here we create a clone which is available through getRequest(), the user can add
// custom headers and push routes here. Later when we actually proxy the request we
// will clone this request (with it's custome headers and routes), but we will override
// the modified RR and Path parameters (as defined in the spec).
Request cloned = (Request)originalRequest.getMessage().clone();
((SIPMessage)cloned).setApplicationData(null);
this.outgoingRequest = new SipServletRequestImpl(
cloned,
proxy.getSipFactoryImpl(),
this.originalRequest.getSipSession(),
null, null, false);
}
/* (non-Javadoc)
* @see javax.servlet.sip.ProxyBranch#cancel()
*/
public void cancel() {
cancel(null, null, null);
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.ProxyBranch#cancel(java.lang.String[], int[], java.lang.String[])
*/
public void cancel(String[] protocol, int[] reasonCode, String[] reasonText) {
if(proxy.getAckReceived()) throw new IllegalStateException("There has been an ACK received on this branch. Can not cancel.");
try {
cancelTimer();
if(this.isStarted() && !canceled && !timedOut &&
outgoingRequest.getMethod().equalsIgnoreCase(Request.INVITE)) {
if(lastResponse != null) { /* According to SIP RFC we should send cancel only if we receive any response first*/
SipServletRequest cancelRequest = outgoingRequest.createCancel();
//Adding reason headers if needed
if(protocol != null && reasonCode != null && reasonText != null
&& protocol.length == reasonCode.length && reasonCode.length == reasonText.length) {
for (int i = 0; i < protocol.length; i++) {
((SipServletRequestImpl)cancelRequest).
addHeaderInternal("Reason",
protocol[i] + ";cause=" + reasonCode[i] + ";text=\"" + reasonText[i] + "\"",
false);
}
}
cancelRequest.send();
} else {
// We dont send cancel, but we must stop the invite retrans
SIPClientTransaction tx = (SIPClientTransaction) outgoingRequest.getTransaction();
Method disableRetransmissionTimer = SIPTransaction.class.getDeclaredMethod("disableRetransmissionTimer");
Method disableTimeoutTimer = SIPTransaction.class.getDeclaredMethod("disableTimeoutTimer");
disableRetransmissionTimer.setAccessible(true);
disableTimeoutTimer.setAccessible(true);
disableRetransmissionTimer.invoke(tx);
disableTimeoutTimer.invoke(tx);
try {
tx.terminate();
} catch(Exception e2) {
logger.error("Can not terminate transaction", e2);
}
}
canceled = true;
}
if(!this.isStarted() &&
outgoingRequest.getMethod().equalsIgnoreCase(Request.INVITE)) {
canceled = true;
}
}
catch(Exception e) {
throw new IllegalStateException("Failed canceling proxy branch", e);
}
}
/* (non-Javadoc)
* @see javax.servlet.sip.ProxyBranch#getProxy()
*/
public Proxy getProxy() {
return proxy;
}
/* (non-Javadoc)
* @see javax.servlet.sip.ProxyBranch#getProxyBranchTimeout()
*/
public int getProxyBranchTimeout() {
return proxyBranchTimeout;
}
/* (non-Javadoc)
* @see javax.servlet.sip.ProxyBranch#getRecordRouteURI()
*/
public SipURI getRecordRouteURI() {
if(this.getRecordRoute()) {
if(this.recordRouteURI == null)
this.recordRouteURI = proxy.getSipFactoryImpl().createSipURI("proxy", "localhost");
return this.recordRouteURI;
}
else throw new IllegalStateException("Record Route not enabled for this ProxyBranch. You must call proxyBranch.setRecordRoute(true) before getting an URI.");
}
/* (non-Javadoc)
* @see javax.servlet.sip.ProxyBranch#getRecursedProxyBranches()
*/
public List<ProxyBranch> getRecursedProxyBranches() {
return recursedBranches;
}
public void addRecursedBranch(ProxyBranchImpl branch) {
recursedBranches.add(branch);
}
/* (non-Javadoc)
* @see javax.servlet.sip.ProxyBranch#getRequest()
*/
public SipServletRequest getRequest() {
return outgoingRequest;
}
/* (non-Javadoc)
* @see javax.servlet.sip.ProxyBranch#getResponse()
*/
public SipServletResponse getResponse() {
return lastResponse;
}
public void setResponse(SipServletResponse response) {
lastResponse = (SipServletResponseImpl) response;
}
/* (non-Javadoc)
* @see javax.servlet.sip.ProxyBranch#isStarted()
*/
public boolean isStarted() {
return started;
}
/* (non-Javadoc)
* @see javax.servlet.sip.ProxyBranch#setProxyBranchTimeout(int)
*/
public void setProxyBranchTimeout(int seconds) {
if(seconds<=0)
throw new IllegalArgumentException("Negative or zero timeout not allowed");
this.proxyBranchTimeout = seconds;
if(this.started) updateTimer();
}
/**
* After the branch is initialized, this method proxies the initial request to the
* specified destination. Subsequent requests are proxied through proxySubsequentRequest
*/
public void start() {
if(started) {
throw new IllegalStateException("Proxy branch alredy started!");
}
if(canceled) {
throw new IllegalStateException("Proxy branch was cancelled, you must create a new branch!");
}
if(timedOut) {
throw new IllegalStateException("Proxy brnach has timed out!");
}
if(proxy.getAckReceived()) {
throw new IllegalStateException("An ACK request has been received on this proxy. Can not start new branches.");
}
// Initialize these here for efficiency.
updateTimer();
SipURI recordRoute = null;
// If the proxy is not adding record-route header, set it to null and it
// will be ignored in the Proxying
if(proxy.getRecordRoute() || this.getRecordRoute()) {
if(recordRouteURI == null) {
recordRouteURI = proxy.getSipFactoryImpl().createSipURI("proxy", "localhost");
}
recordRoute = recordRouteURI;
}
Request cloned = proxy.getProxyUtils().createProxiedRequest(
outgoingRequest,
this,
new ProxyParams(this.targetURI,
this.outboundInterface,
recordRoute,
this.pathURI));
//tells the application dispatcher to stop routing the original request
//since it has been proxied
originalRequest.setRoutingState(RoutingState.PROXIED);
forwardRequest(cloned, false);
started = true;
}
/**
* Forward the request to the specified destination. The method is used internally.
* @param request
* @param subsequent Set to false if the the method is initial
*/
private void forwardRequest(Request request, boolean subsequent) {
if(logger.isDebugEnabled()) {
logger.debug("creating cloned Request for proxybranch " + request);
}
SipServletRequestImpl clonedRequest = new SipServletRequestImpl(
request,
proxy.getSipFactoryImpl(),
null,
null, null, false);
if(subsequent) {
clonedRequest.setRoutingState(RoutingState.SUBSEQUENT);
}
this.outgoingRequest = clonedRequest;
// Initialize the sip session for the new request if initial
clonedRequest.setCurrentApplicationName(originalRequest.getCurrentApplicationName());
if(clonedRequest.getCurrentApplicationName() == null && subsequent) {
clonedRequest.setCurrentApplicationName(originalRequest.getSipSession().getSipApplicationSession().getApplicationName());
}
clonedRequest.setSipSession(originalRequest.getSipSession());
MobicentsSipSession newSession = (MobicentsSipSession) clonedRequest.getSession(true);
try {
newSession.setHandler(((MobicentsSipSession)this.originalRequest.getSession()).getHandler());
} catch (ServletException e) {
logger.error("could not set the session handler while forwarding the request", e);
throw new RuntimeException(e);
}
// Use the original dialog in the new session
newSession.setSessionCreatingDialog(originalRequest.getSipSession().getSessionCreatingDialog());
// And set a reference to the proxy
newSession.setProxy(proxy);
//JSR 289 Section 15.1.6
if(!subsequent) {
// Subsequent requests can't have a routing directive?
clonedRequest.setRoutingDirective(SipApplicationRoutingDirective.CONTINUE, originalRequest);
}
clonedRequest.getTransactionApplicationData().setProxyBranch(this);
clonedRequest.send();
}
/**
* A callback. Here we receive all responses from the proxied requests we have sent.
*
* @param response
*/
public void onResponse(SipServletResponseImpl response)
{
// We have already sent TRYING, don't send another one
if(response.getStatus() == 100)
return;
// Send informational responses back immediately
if((response.getStatus() > 100 && response.getStatus() < 200) || (response.getStatus() == 200 && Request.PRACK.equals(response.getMethod())))
{
// Deterimine if the response is reliable. We just look at RSeq, because
// every such response is required to have it.
if(response.getHeader("RSeq") != null) {
this.setWaitingForPrack(true); // this branch is expecting a PRACK now
}
SipServletResponse proxiedResponse =
proxy.getProxyUtils().createProxiedResponse(response, this);
if(proxiedResponse == null)
return; // this response was addressed to this proxy
try {
proxiedResponse.send();
} catch (IOException e) {
logger.error("A problem occured while proxying a response", e);
}
return;
}
// Non-provisional responses must also cancel the timer, otherwise it will timeout
// and return multiple responses for a single transaction.
cancelTimer();
if(response.getStatus() >= 600) // Cancel all 10.2.4
this.proxy.cancelAllExcept(this, null, null, null, false);
// FYI: ACK is sent automatically by jsip when needed
boolean recursed = false;
if(response.getStatus() >= 300 && response.getStatus()<400 && recurse) {
String contact = response.getHeader("Contact");
if(contact != null) {
//javax.sip.address.SipURI uri = SipFactories.addressFactory.createAddress(contact);
try {
int start = contact.indexOf('<');
int end = contact.indexOf('>');
contact = contact.substring(start + 1, end);
URI uri = proxy.getSipFactoryImpl().createURI(contact);
ArrayList<SipURI> list = new ArrayList<SipURI>();
list.add((SipURI)uri);
List<ProxyBranch> pblist = proxy.createProxyBranches(list);
ProxyBranchImpl pbi = (ProxyBranchImpl)pblist.get(0);
this.addRecursedBranch(pbi);
pbi.start();
recursed = true;
} catch (ServletParseException e) {
throw new RuntimeException("Can not parse contact header", e);
}
}
}
if(response.getStatus() >= 200 && !recursed)
{
if(outgoingRequest != null && outgoingRequest.isInitial()) {
this.proxy.onFinalResponse(this);
} else {
this.proxy.sendFinalResponse(response, this);
}
}
}
/**
* Has the branch timed out?
*
* @return
*/
public boolean isTimedOut() {
return timedOut;
}
/**
* Call this method when a subsequent request must be proxied through the branch.
*
* @param request
*/
public void proxySubsequentRequest(SipServletRequestImpl request) {
// A re-INVITE needs special handling without goind through the dialog-stateful methods
if(request.getMethod().equalsIgnoreCase("INVITE")) {
if(logger.isDebugEnabled()) {
logger.debug("Proxying reinvite request " + request);
}
// reset the ack received flag for reINVITE
request.getSipSession().setAckReceived(false);
proxyDialogStateless(request);
return;
}
if(logger.isDebugEnabled()) {
logger.debug("Proxying subsequent request " + request);
}
// Update the last proxied request
request.setRoutingState(RoutingState.PROXIED);
proxy.setOriginalRequest(request);
this.originalRequest = request;
// No proxy params, sine the target is already in the Route headers
ProxyParams params = new ProxyParams(null, null, null, null);
Request clonedRequest =
proxy.getProxyUtils().createProxiedRequest(request, this, params);
// There is no need for that, it makes application composition fail (The subsequent request is not dispatched to the next application since the route header is removed)
// RouteHeader routeHeader = (RouteHeader) clonedRequest.getHeader(RouteHeader.NAME);
// if(routeHeader != null) {
// if(!((SipApplicationDispatcherImpl)proxy.getSipFactoryImpl().getSipApplicationDispatcher()).isRouteExternal(routeHeader)) {
// clonedRequest.removeFirst(RouteHeader.NAME);
// }
// }
try {
// Reset the proxy supervised state to default Chapter 6.2.1 - page down list bullet number 6
proxy.setSupervised(true);
if(clonedRequest.getMethod().equalsIgnoreCase(Request.ACK) ) { //|| clonedRequest.getMethod().equalsIgnoreCase(Request.PRACK)) {
String transport = JainSipUtils.findTransport(clonedRequest);
SipProvider sipProvider = proxy.getSipFactoryImpl().getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
sipProvider.sendRequest(clonedRequest);
}
else {
forwardRequest(clonedRequest, true);
}
} catch (SipException e) {
logger.error("A problem occured while proxying a subsequent request", e);
}
}
/**
* This method proxies requests without updating JSIP dialog state. PRACK and re-INVITE
* requests require this kind of handling because:
* 1. PRACK occurs before a dialog has been established (and also produces OKs before
* the final response)
* 2. re-INVITE when sent with the dialog method resets the internal JSIP CSeq counter
* to 1 every time you need it, which causes issues like
* http://groups.google.com/group/mobicents-public/browse_thread/thread/1a22ccdc4c481f47
*
* @param request
*/
public void proxyDialogStateless(SipServletRequestImpl request) {
if(logger.isDebugEnabled()) {
logger.debug("Proxying request dialog-statelessly" + request);
}
// Update the last proxied request
request.setRoutingState(RoutingState.PROXIED);
this.prackOriginalRequest = request;
URI targetURI = this.targetURI;
// Determine the direction of the request. Either it's from the dialog initiator (the caller)
// or from the callee
if(!request.getFrom().toString().equals(proxy.getCallerFromHeader())) {
// If it's from the callee we should send it in the other direction
targetURI = proxy.getPreviousNode();
}
ProxyParams params = new ProxyParams(targetURI, null, null, null);
Request clonedRequest =
proxy.getProxyUtils().createProxiedRequest(request, this, params);
ViaHeader viaHeader = (ViaHeader) clonedRequest.getHeader(ViaHeader.NAME);
try {
viaHeader.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME,
proxy.getSipFactoryImpl().getSipApplicationDispatcher().getHashFromApplicationName(request.getSipSession().getKey().getApplicationName()));
viaHeader.setParameter(MessageDispatcher.APP_ID,
request.getSipSession().getSipApplicationSession().getKey().getId());
} catch (ParseException pe) {
logger.error("A problem occured while proxying a request in a dialog-stateless transaction", pe);
}
RouteHeader routeHeader = (RouteHeader) clonedRequest.getHeader(RouteHeader.NAME);
if(routeHeader != null) {
if(!((SipApplicationDispatcherImpl)proxy.getSipFactoryImpl().getSipApplicationDispatcher()).isRouteExternal(routeHeader)) {
clonedRequest.removeFirst(RouteHeader.NAME);
}
}
String transport = JainSipUtils.findTransport(clonedRequest);
SipProvider sipProvider = proxy.getSipFactoryImpl().getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
if(logger.isDebugEnabled()) {
logger.debug("Getting new Client Tx for request " + clonedRequest);
}
try {
ClientTransaction ctx = sipProvider
.getNewClientTransaction(clonedRequest);
TransactionApplicationData appData = (TransactionApplicationData) request.getTransactionApplicationData();
appData.setProxyBranch(this);
ctx.setApplicationData(appData);
ctx.sendRequest();
} catch (SipException e) {
logger.error("A problem occured while proxying a request in a dialog-stateless transaction", e);
}
}
/**
* This callback is called when the remote side has been idle too long while
* establishing the dialog.
*
*/
public void onTimeout()
{
this.cancel();
this.timedOut = true;
// Just do a timeout response
proxy.onBranchTimeOut(this);
}
/**
* Restart the timer. Call this method when some activity shows the remote
* party is still online.
*
*/
- void updateTimer() {
+ synchronized void updateTimer() {
if(proxyTimeoutTask != null) {
proxyTimeoutTask.cancel();
}
proxyTimeoutTask = new ProxyBranchTimerTask(this);
if(logger.isDebugEnabled()) {
logger.debug("Proxy Branch Timeout set to " + proxyBranchTimeout);
}
if(proxyBranchTimeout != 0)
timer.schedule(proxyTimeoutTask, proxyBranchTimeout * 1000);
}
/**
* Stop the C Timer.
*/
public void cancelTimer()
{
if(proxyTimeoutTask != null)
{
proxyTimeoutTask.cancel();
proxyTimeoutTask = null;
}
}
public boolean isCanceled() {
return canceled;
}
/**
* {@inheritDoc}
*/
public boolean getAddToPath() {
return isAddToPath;
}
/**
* {@inheritDoc}
*/
public SipURI getPathURI() {
if(!isAddToPath) {
throw new IllegalStateException("addToPath is not enabled!");
}
return this.pathURI;
}
/**
* {@inheritDoc}
*/
public boolean getRecordRoute() {
return recordRoutingEnabled;
}
/**
* {@inheritDoc}
*/
public boolean getRecurse() {
return recurse;
}
/**
* {@inheritDoc}
*/
public void setAddToPath(boolean isAddToPath) {
if(started) {
throw new IllegalStateException("Cannot set a record route on an already started proxy");
}
if(this.pathURI == null) {
this.pathURI = new SipURIImpl ( JainSipUtils.createRecordRouteURI( proxy.getSipFactoryImpl().getSipNetworkInterfaceManager(), null));
}
this.isAddToPath = isAddToPath;
}
/**
* {@inheritDoc}
*/
public void setOutboundInterface(InetAddress inetAddress) {
//TODO check against our defined outbound interfaces
checkSessionValidity();
String address = inetAddress.getHostAddress();
outboundInterface = proxy.getSipFactoryImpl().createSipURI(null, address);
}
/**
* {@inheritDoc}
*/
public void setOutboundInterface(InetSocketAddress inetSocketAddress) {
//TODO check against our defined outbound interfaces
checkSessionValidity();
String address = inetSocketAddress.getAddress().getHostAddress() + ":" + inetSocketAddress.getPort();
outboundInterface = proxy.getSipFactoryImpl().createSipURI(null, address);
}
/**
* {@inheritDoc}
*/
public void setRecordRoute(boolean isRecordRoute) {
recordRoutingEnabled = isRecordRoute;
}
/**
* {@inheritDoc}
*/
public void setRecurse(boolean isRecurse) {
recurse = isRecurse;
}
private void checkSessionValidity() {
if(this.originalRequest.getApplicationSession().isValid()
&& this.originalRequest.getSession().isValid())
return;
throw new IllegalStateException("Invalid session.");
}
/**
* @param prackOriginalRequest the prackOriginalRequest to set
*/
public void setPrackOriginalRequest(SipServletRequestImpl prackOriginalRequest) {
this.prackOriginalRequest = prackOriginalRequest;
}
/**
* @return the prackOriginalRequest
*/
public SipServletRequestImpl getPrackOriginalRequest() {
return prackOriginalRequest;
}
public boolean isWaitingForPrack() {
return waitingForPrack;
}
public void setWaitingForPrack(boolean waitingForPrack) {
this.waitingForPrack = waitingForPrack;
}
}
| true | true | public void proxySubsequentRequest(SipServletRequestImpl request) {
// A re-INVITE needs special handling without goind through the dialog-stateful methods
if(request.getMethod().equalsIgnoreCase("INVITE")) {
if(logger.isDebugEnabled()) {
logger.debug("Proxying reinvite request " + request);
}
// reset the ack received flag for reINVITE
request.getSipSession().setAckReceived(false);
proxyDialogStateless(request);
return;
}
if(logger.isDebugEnabled()) {
logger.debug("Proxying subsequent request " + request);
}
// Update the last proxied request
request.setRoutingState(RoutingState.PROXIED);
proxy.setOriginalRequest(request);
this.originalRequest = request;
// No proxy params, sine the target is already in the Route headers
ProxyParams params = new ProxyParams(null, null, null, null);
Request clonedRequest =
proxy.getProxyUtils().createProxiedRequest(request, this, params);
// There is no need for that, it makes application composition fail (The subsequent request is not dispatched to the next application since the route header is removed)
// RouteHeader routeHeader = (RouteHeader) clonedRequest.getHeader(RouteHeader.NAME);
// if(routeHeader != null) {
// if(!((SipApplicationDispatcherImpl)proxy.getSipFactoryImpl().getSipApplicationDispatcher()).isRouteExternal(routeHeader)) {
// clonedRequest.removeFirst(RouteHeader.NAME);
// }
// }
try {
// Reset the proxy supervised state to default Chapter 6.2.1 - page down list bullet number 6
proxy.setSupervised(true);
if(clonedRequest.getMethod().equalsIgnoreCase(Request.ACK) ) { //|| clonedRequest.getMethod().equalsIgnoreCase(Request.PRACK)) {
String transport = JainSipUtils.findTransport(clonedRequest);
SipProvider sipProvider = proxy.getSipFactoryImpl().getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
sipProvider.sendRequest(clonedRequest);
}
else {
forwardRequest(clonedRequest, true);
}
} catch (SipException e) {
logger.error("A problem occured while proxying a subsequent request", e);
}
}
/**
* This method proxies requests without updating JSIP dialog state. PRACK and re-INVITE
* requests require this kind of handling because:
* 1. PRACK occurs before a dialog has been established (and also produces OKs before
* the final response)
* 2. re-INVITE when sent with the dialog method resets the internal JSIP CSeq counter
* to 1 every time you need it, which causes issues like
* http://groups.google.com/group/mobicents-public/browse_thread/thread/1a22ccdc4c481f47
*
* @param request
*/
public void proxyDialogStateless(SipServletRequestImpl request) {
if(logger.isDebugEnabled()) {
logger.debug("Proxying request dialog-statelessly" + request);
}
// Update the last proxied request
request.setRoutingState(RoutingState.PROXIED);
this.prackOriginalRequest = request;
URI targetURI = this.targetURI;
// Determine the direction of the request. Either it's from the dialog initiator (the caller)
// or from the callee
if(!request.getFrom().toString().equals(proxy.getCallerFromHeader())) {
// If it's from the callee we should send it in the other direction
targetURI = proxy.getPreviousNode();
}
ProxyParams params = new ProxyParams(targetURI, null, null, null);
Request clonedRequest =
proxy.getProxyUtils().createProxiedRequest(request, this, params);
ViaHeader viaHeader = (ViaHeader) clonedRequest.getHeader(ViaHeader.NAME);
try {
viaHeader.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME,
proxy.getSipFactoryImpl().getSipApplicationDispatcher().getHashFromApplicationName(request.getSipSession().getKey().getApplicationName()));
viaHeader.setParameter(MessageDispatcher.APP_ID,
request.getSipSession().getSipApplicationSession().getKey().getId());
} catch (ParseException pe) {
logger.error("A problem occured while proxying a request in a dialog-stateless transaction", pe);
}
RouteHeader routeHeader = (RouteHeader) clonedRequest.getHeader(RouteHeader.NAME);
if(routeHeader != null) {
if(!((SipApplicationDispatcherImpl)proxy.getSipFactoryImpl().getSipApplicationDispatcher()).isRouteExternal(routeHeader)) {
clonedRequest.removeFirst(RouteHeader.NAME);
}
}
String transport = JainSipUtils.findTransport(clonedRequest);
SipProvider sipProvider = proxy.getSipFactoryImpl().getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
if(logger.isDebugEnabled()) {
logger.debug("Getting new Client Tx for request " + clonedRequest);
}
try {
ClientTransaction ctx = sipProvider
.getNewClientTransaction(clonedRequest);
TransactionApplicationData appData = (TransactionApplicationData) request.getTransactionApplicationData();
appData.setProxyBranch(this);
ctx.setApplicationData(appData);
ctx.sendRequest();
} catch (SipException e) {
logger.error("A problem occured while proxying a request in a dialog-stateless transaction", e);
}
}
/**
* This callback is called when the remote side has been idle too long while
* establishing the dialog.
*
*/
public void onTimeout()
{
this.cancel();
this.timedOut = true;
// Just do a timeout response
proxy.onBranchTimeOut(this);
}
/**
* Restart the timer. Call this method when some activity shows the remote
* party is still online.
*
*/
void updateTimer() {
if(proxyTimeoutTask != null) {
proxyTimeoutTask.cancel();
}
proxyTimeoutTask = new ProxyBranchTimerTask(this);
if(logger.isDebugEnabled()) {
logger.debug("Proxy Branch Timeout set to " + proxyBranchTimeout);
}
if(proxyBranchTimeout != 0)
timer.schedule(proxyTimeoutTask, proxyBranchTimeout * 1000);
}
/**
* Stop the C Timer.
*/
public void cancelTimer()
{
if(proxyTimeoutTask != null)
{
proxyTimeoutTask.cancel();
proxyTimeoutTask = null;
}
}
public boolean isCanceled() {
return canceled;
}
/**
* {@inheritDoc}
*/
public boolean getAddToPath() {
return isAddToPath;
}
/**
* {@inheritDoc}
*/
public SipURI getPathURI() {
if(!isAddToPath) {
throw new IllegalStateException("addToPath is not enabled!");
}
return this.pathURI;
}
/**
* {@inheritDoc}
*/
public boolean getRecordRoute() {
return recordRoutingEnabled;
}
/**
* {@inheritDoc}
*/
public boolean getRecurse() {
return recurse;
}
/**
* {@inheritDoc}
*/
public void setAddToPath(boolean isAddToPath) {
if(started) {
throw new IllegalStateException("Cannot set a record route on an already started proxy");
}
if(this.pathURI == null) {
this.pathURI = new SipURIImpl ( JainSipUtils.createRecordRouteURI( proxy.getSipFactoryImpl().getSipNetworkInterfaceManager(), null));
}
this.isAddToPath = isAddToPath;
}
/**
* {@inheritDoc}
*/
public void setOutboundInterface(InetAddress inetAddress) {
//TODO check against our defined outbound interfaces
checkSessionValidity();
String address = inetAddress.getHostAddress();
outboundInterface = proxy.getSipFactoryImpl().createSipURI(null, address);
}
/**
* {@inheritDoc}
*/
public void setOutboundInterface(InetSocketAddress inetSocketAddress) {
//TODO check against our defined outbound interfaces
checkSessionValidity();
String address = inetSocketAddress.getAddress().getHostAddress() + ":" + inetSocketAddress.getPort();
outboundInterface = proxy.getSipFactoryImpl().createSipURI(null, address);
}
/**
* {@inheritDoc}
*/
public void setRecordRoute(boolean isRecordRoute) {
recordRoutingEnabled = isRecordRoute;
}
/**
* {@inheritDoc}
*/
public void setRecurse(boolean isRecurse) {
recurse = isRecurse;
}
private void checkSessionValidity() {
if(this.originalRequest.getApplicationSession().isValid()
&& this.originalRequest.getSession().isValid())
return;
throw new IllegalStateException("Invalid session.");
}
/**
* @param prackOriginalRequest the prackOriginalRequest to set
*/
public void setPrackOriginalRequest(SipServletRequestImpl prackOriginalRequest) {
this.prackOriginalRequest = prackOriginalRequest;
}
/**
* @return the prackOriginalRequest
*/
public SipServletRequestImpl getPrackOriginalRequest() {
return prackOriginalRequest;
}
public boolean isWaitingForPrack() {
return waitingForPrack;
}
public void setWaitingForPrack(boolean waitingForPrack) {
this.waitingForPrack = waitingForPrack;
}
}
| public void proxySubsequentRequest(SipServletRequestImpl request) {
// A re-INVITE needs special handling without goind through the dialog-stateful methods
if(request.getMethod().equalsIgnoreCase("INVITE")) {
if(logger.isDebugEnabled()) {
logger.debug("Proxying reinvite request " + request);
}
// reset the ack received flag for reINVITE
request.getSipSession().setAckReceived(false);
proxyDialogStateless(request);
return;
}
if(logger.isDebugEnabled()) {
logger.debug("Proxying subsequent request " + request);
}
// Update the last proxied request
request.setRoutingState(RoutingState.PROXIED);
proxy.setOriginalRequest(request);
this.originalRequest = request;
// No proxy params, sine the target is already in the Route headers
ProxyParams params = new ProxyParams(null, null, null, null);
Request clonedRequest =
proxy.getProxyUtils().createProxiedRequest(request, this, params);
// There is no need for that, it makes application composition fail (The subsequent request is not dispatched to the next application since the route header is removed)
// RouteHeader routeHeader = (RouteHeader) clonedRequest.getHeader(RouteHeader.NAME);
// if(routeHeader != null) {
// if(!((SipApplicationDispatcherImpl)proxy.getSipFactoryImpl().getSipApplicationDispatcher()).isRouteExternal(routeHeader)) {
// clonedRequest.removeFirst(RouteHeader.NAME);
// }
// }
try {
// Reset the proxy supervised state to default Chapter 6.2.1 - page down list bullet number 6
proxy.setSupervised(true);
if(clonedRequest.getMethod().equalsIgnoreCase(Request.ACK) ) { //|| clonedRequest.getMethod().equalsIgnoreCase(Request.PRACK)) {
String transport = JainSipUtils.findTransport(clonedRequest);
SipProvider sipProvider = proxy.getSipFactoryImpl().getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
sipProvider.sendRequest(clonedRequest);
}
else {
forwardRequest(clonedRequest, true);
}
} catch (SipException e) {
logger.error("A problem occured while proxying a subsequent request", e);
}
}
/**
* This method proxies requests without updating JSIP dialog state. PRACK and re-INVITE
* requests require this kind of handling because:
* 1. PRACK occurs before a dialog has been established (and also produces OKs before
* the final response)
* 2. re-INVITE when sent with the dialog method resets the internal JSIP CSeq counter
* to 1 every time you need it, which causes issues like
* http://groups.google.com/group/mobicents-public/browse_thread/thread/1a22ccdc4c481f47
*
* @param request
*/
public void proxyDialogStateless(SipServletRequestImpl request) {
if(logger.isDebugEnabled()) {
logger.debug("Proxying request dialog-statelessly" + request);
}
// Update the last proxied request
request.setRoutingState(RoutingState.PROXIED);
this.prackOriginalRequest = request;
URI targetURI = this.targetURI;
// Determine the direction of the request. Either it's from the dialog initiator (the caller)
// or from the callee
if(!request.getFrom().toString().equals(proxy.getCallerFromHeader())) {
// If it's from the callee we should send it in the other direction
targetURI = proxy.getPreviousNode();
}
ProxyParams params = new ProxyParams(targetURI, null, null, null);
Request clonedRequest =
proxy.getProxyUtils().createProxiedRequest(request, this, params);
ViaHeader viaHeader = (ViaHeader) clonedRequest.getHeader(ViaHeader.NAME);
try {
viaHeader.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME,
proxy.getSipFactoryImpl().getSipApplicationDispatcher().getHashFromApplicationName(request.getSipSession().getKey().getApplicationName()));
viaHeader.setParameter(MessageDispatcher.APP_ID,
request.getSipSession().getSipApplicationSession().getKey().getId());
} catch (ParseException pe) {
logger.error("A problem occured while proxying a request in a dialog-stateless transaction", pe);
}
RouteHeader routeHeader = (RouteHeader) clonedRequest.getHeader(RouteHeader.NAME);
if(routeHeader != null) {
if(!((SipApplicationDispatcherImpl)proxy.getSipFactoryImpl().getSipApplicationDispatcher()).isRouteExternal(routeHeader)) {
clonedRequest.removeFirst(RouteHeader.NAME);
}
}
String transport = JainSipUtils.findTransport(clonedRequest);
SipProvider sipProvider = proxy.getSipFactoryImpl().getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
if(logger.isDebugEnabled()) {
logger.debug("Getting new Client Tx for request " + clonedRequest);
}
try {
ClientTransaction ctx = sipProvider
.getNewClientTransaction(clonedRequest);
TransactionApplicationData appData = (TransactionApplicationData) request.getTransactionApplicationData();
appData.setProxyBranch(this);
ctx.setApplicationData(appData);
ctx.sendRequest();
} catch (SipException e) {
logger.error("A problem occured while proxying a request in a dialog-stateless transaction", e);
}
}
/**
* This callback is called when the remote side has been idle too long while
* establishing the dialog.
*
*/
public void onTimeout()
{
this.cancel();
this.timedOut = true;
// Just do a timeout response
proxy.onBranchTimeOut(this);
}
/**
* Restart the timer. Call this method when some activity shows the remote
* party is still online.
*
*/
synchronized void updateTimer() {
if(proxyTimeoutTask != null) {
proxyTimeoutTask.cancel();
}
proxyTimeoutTask = new ProxyBranchTimerTask(this);
if(logger.isDebugEnabled()) {
logger.debug("Proxy Branch Timeout set to " + proxyBranchTimeout);
}
if(proxyBranchTimeout != 0)
timer.schedule(proxyTimeoutTask, proxyBranchTimeout * 1000);
}
/**
* Stop the C Timer.
*/
public void cancelTimer()
{
if(proxyTimeoutTask != null)
{
proxyTimeoutTask.cancel();
proxyTimeoutTask = null;
}
}
public boolean isCanceled() {
return canceled;
}
/**
* {@inheritDoc}
*/
public boolean getAddToPath() {
return isAddToPath;
}
/**
* {@inheritDoc}
*/
public SipURI getPathURI() {
if(!isAddToPath) {
throw new IllegalStateException("addToPath is not enabled!");
}
return this.pathURI;
}
/**
* {@inheritDoc}
*/
public boolean getRecordRoute() {
return recordRoutingEnabled;
}
/**
* {@inheritDoc}
*/
public boolean getRecurse() {
return recurse;
}
/**
* {@inheritDoc}
*/
public void setAddToPath(boolean isAddToPath) {
if(started) {
throw new IllegalStateException("Cannot set a record route on an already started proxy");
}
if(this.pathURI == null) {
this.pathURI = new SipURIImpl ( JainSipUtils.createRecordRouteURI( proxy.getSipFactoryImpl().getSipNetworkInterfaceManager(), null));
}
this.isAddToPath = isAddToPath;
}
/**
* {@inheritDoc}
*/
public void setOutboundInterface(InetAddress inetAddress) {
//TODO check against our defined outbound interfaces
checkSessionValidity();
String address = inetAddress.getHostAddress();
outboundInterface = proxy.getSipFactoryImpl().createSipURI(null, address);
}
/**
* {@inheritDoc}
*/
public void setOutboundInterface(InetSocketAddress inetSocketAddress) {
//TODO check against our defined outbound interfaces
checkSessionValidity();
String address = inetSocketAddress.getAddress().getHostAddress() + ":" + inetSocketAddress.getPort();
outboundInterface = proxy.getSipFactoryImpl().createSipURI(null, address);
}
/**
* {@inheritDoc}
*/
public void setRecordRoute(boolean isRecordRoute) {
recordRoutingEnabled = isRecordRoute;
}
/**
* {@inheritDoc}
*/
public void setRecurse(boolean isRecurse) {
recurse = isRecurse;
}
private void checkSessionValidity() {
if(this.originalRequest.getApplicationSession().isValid()
&& this.originalRequest.getSession().isValid())
return;
throw new IllegalStateException("Invalid session.");
}
/**
* @param prackOriginalRequest the prackOriginalRequest to set
*/
public void setPrackOriginalRequest(SipServletRequestImpl prackOriginalRequest) {
this.prackOriginalRequest = prackOriginalRequest;
}
/**
* @return the prackOriginalRequest
*/
public SipServletRequestImpl getPrackOriginalRequest() {
return prackOriginalRequest;
}
public boolean isWaitingForPrack() {
return waitingForPrack;
}
public void setWaitingForPrack(boolean waitingForPrack) {
this.waitingForPrack = waitingForPrack;
}
}
|
diff --git a/src/main/java/org/gatein/rhq/plugins/jmx/MBeanAttributeDiscoveryComponent.java b/src/main/java/org/gatein/rhq/plugins/jmx/MBeanAttributeDiscoveryComponent.java
index f0d7c58..a3e3c8e 100644
--- a/src/main/java/org/gatein/rhq/plugins/jmx/MBeanAttributeDiscoveryComponent.java
+++ b/src/main/java/org/gatein/rhq/plugins/jmx/MBeanAttributeDiscoveryComponent.java
@@ -1,111 +1,111 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.gatein.rhq.plugins.jmx;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mc4j.ems.connection.bean.EmsBean;
import org.mc4j.ems.connection.bean.attribute.EmsAttribute;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails;
import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent;
import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
import org.rhq.plugins.jmx.MBeanResourceComponent;
import java.util.HashSet;
import java.util.Set;
/**
* This class will discover resource based on an 'listAttributeName' attribute of a JMX bean which returns a list
* of values (String[]) to create resources from.
*
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
*/
public abstract class MBeanAttributeDiscoveryComponent implements ResourceDiscoveryComponent<MBeanResourceComponent<?>>
{
private static final Log log = LogFactory.getLog("org.gatein.rhq.plugins.jmx");
@Override
public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<MBeanResourceComponent<?>> context) throws InvalidPluginConfigurationException, Exception
{
boolean trace = log.isTraceEnabled();
// Make sure listAttributeName is present in configuration.
Configuration config = context.getDefaultPluginConfiguration();
String listAttributeName = config.getSimpleValue("listAttributeName", null);
if (listAttributeName == null) throw new InvalidPluginConfigurationException("listAttributeName is a required configuration property for this plugin.");
// Get the JMX bean from the parent, or if an objectName is configured, use that instead.
EmsBean bean = context.getParentResourceComponent().getEmsBean();
String objectName = config.getSimpleValue(MBeanResourceComponent.OBJECT_NAME_PROP, null);
if (objectName != null)
{
objectName = TemplateResolver.resolve(objectName, context.getParentResourceContext().getPluginConfiguration());
bean = context.getParentResourceComponent().getEmsConnection().getBean(objectName);
}
if (bean == null) throw new Exception("JMX bean not found.");
if (trace) log.trace("Using JMX bean " + bean.getBeanName() + " for this discovery component");
// Get attribute that returns a list of values ot be discovered.
EmsAttribute attribute = bean.getAttribute(listAttributeName);
if (attribute == null) throw new Exception("Unknown attribute '" + listAttributeName + "' for JMX bean " + bean.getBeanName());
if (trace) log.trace("Looking up list of values for attribute " + attribute.getName());
// Discover
Object object = attribute.getValue();
if (object instanceof String[])
{
String[] values = (String[]) object;
if (trace)
{
- log.trace("Found " + values.length + " values for attribute " + values.length);
+ log.trace("Found " + values.length + " values for attribute " + attribute.getName());
}
Set<DiscoveredResourceDetails> details = new HashSet<DiscoveredResourceDetails>(values.length);
for (String value : values)
{
if (trace)
{
log.trace("Creating resource detail for attribute value " + value);
}
details.add(createResourceDetails(context, value));
}
return details;
}
else
{
throw new Exception("Attribute '" + listAttributeName +"' for JMX bean " + bean.getBeanName() + " must return a string array (String[])");
}
}
/**
* Create DiscoveredResourceDetails based on values found during invocation of the 'listAttributeName' attribute of the
* JMX bean.
*
* @param context the {@link ResourceDiscoveryContext} of the discovery request
* @param attributeValue a value
* @return
*/
protected abstract DiscoveredResourceDetails createResourceDetails(ResourceDiscoveryContext<MBeanResourceComponent<?>> context, String attributeValue);
}
| true | true | public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<MBeanResourceComponent<?>> context) throws InvalidPluginConfigurationException, Exception
{
boolean trace = log.isTraceEnabled();
// Make sure listAttributeName is present in configuration.
Configuration config = context.getDefaultPluginConfiguration();
String listAttributeName = config.getSimpleValue("listAttributeName", null);
if (listAttributeName == null) throw new InvalidPluginConfigurationException("listAttributeName is a required configuration property for this plugin.");
// Get the JMX bean from the parent, or if an objectName is configured, use that instead.
EmsBean bean = context.getParentResourceComponent().getEmsBean();
String objectName = config.getSimpleValue(MBeanResourceComponent.OBJECT_NAME_PROP, null);
if (objectName != null)
{
objectName = TemplateResolver.resolve(objectName, context.getParentResourceContext().getPluginConfiguration());
bean = context.getParentResourceComponent().getEmsConnection().getBean(objectName);
}
if (bean == null) throw new Exception("JMX bean not found.");
if (trace) log.trace("Using JMX bean " + bean.getBeanName() + " for this discovery component");
// Get attribute that returns a list of values ot be discovered.
EmsAttribute attribute = bean.getAttribute(listAttributeName);
if (attribute == null) throw new Exception("Unknown attribute '" + listAttributeName + "' for JMX bean " + bean.getBeanName());
if (trace) log.trace("Looking up list of values for attribute " + attribute.getName());
// Discover
Object object = attribute.getValue();
if (object instanceof String[])
{
String[] values = (String[]) object;
if (trace)
{
log.trace("Found " + values.length + " values for attribute " + values.length);
}
Set<DiscoveredResourceDetails> details = new HashSet<DiscoveredResourceDetails>(values.length);
for (String value : values)
{
if (trace)
{
log.trace("Creating resource detail for attribute value " + value);
}
details.add(createResourceDetails(context, value));
}
return details;
}
else
{
throw new Exception("Attribute '" + listAttributeName +"' for JMX bean " + bean.getBeanName() + " must return a string array (String[])");
}
}
| public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<MBeanResourceComponent<?>> context) throws InvalidPluginConfigurationException, Exception
{
boolean trace = log.isTraceEnabled();
// Make sure listAttributeName is present in configuration.
Configuration config = context.getDefaultPluginConfiguration();
String listAttributeName = config.getSimpleValue("listAttributeName", null);
if (listAttributeName == null) throw new InvalidPluginConfigurationException("listAttributeName is a required configuration property for this plugin.");
// Get the JMX bean from the parent, or if an objectName is configured, use that instead.
EmsBean bean = context.getParentResourceComponent().getEmsBean();
String objectName = config.getSimpleValue(MBeanResourceComponent.OBJECT_NAME_PROP, null);
if (objectName != null)
{
objectName = TemplateResolver.resolve(objectName, context.getParentResourceContext().getPluginConfiguration());
bean = context.getParentResourceComponent().getEmsConnection().getBean(objectName);
}
if (bean == null) throw new Exception("JMX bean not found.");
if (trace) log.trace("Using JMX bean " + bean.getBeanName() + " for this discovery component");
// Get attribute that returns a list of values ot be discovered.
EmsAttribute attribute = bean.getAttribute(listAttributeName);
if (attribute == null) throw new Exception("Unknown attribute '" + listAttributeName + "' for JMX bean " + bean.getBeanName());
if (trace) log.trace("Looking up list of values for attribute " + attribute.getName());
// Discover
Object object = attribute.getValue();
if (object instanceof String[])
{
String[] values = (String[]) object;
if (trace)
{
log.trace("Found " + values.length + " values for attribute " + attribute.getName());
}
Set<DiscoveredResourceDetails> details = new HashSet<DiscoveredResourceDetails>(values.length);
for (String value : values)
{
if (trace)
{
log.trace("Creating resource detail for attribute value " + value);
}
details.add(createResourceDetails(context, value));
}
return details;
}
else
{
throw new Exception("Attribute '" + listAttributeName +"' for JMX bean " + bean.getBeanName() + " must return a string array (String[])");
}
}
|
diff --git a/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/Hierarchy.java b/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/Hierarchy.java
index 641e02fb5..8da764722 100644
--- a/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/Hierarchy.java
+++ b/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/Hierarchy.java
@@ -1,192 +1,192 @@
/**
* This document is a part of the source code and related artifacts
* for CollectionSpace, an open source collections management system
* for museums and related institutions:
* http://www.collectionspace.org
* http://wiki.collectionspace.org
* Copyright 2011 University of California at Berkeley
* Licensed under the Educational Community License (ECL), Version 2.0.
* You may not use this file except in compliance with this License.
* You may obtain a copy of the ECL 2.0 License at
* https://source.collectionspace.org/collection-space/LICENSE.txt
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.collectionspace.services.common.vocabulary;
import org.collectionspace.services.common.XmlTools;
import org.collectionspace.services.common.api.Tools;
import org.collectionspace.services.common.context.ServiceContext;
import org.collectionspace.services.common.relation.IRelationsManager;
import org.collectionspace.services.relation.RelationResource;
import org.collectionspace.services.relation.RelationsCommonList;
import org.collectionspace.services.relation.RelationsDocListItem;
import org.collectionspace.services.relation.RelationshipType;
import javax.ws.rs.core.MultivaluedMap;
import java.util.List;
/**
* @author Laramie Crocker
*/
public class Hierarchy {
public static final String directionQP = "direction";
public static final String direction_parents = "parents";
/**Call with the URI and CSID of the root element of the tree you wish to inspect. The uri can be a blank string.
* @param uri informational, optional - if not known, pass an empty String.
* @return String of XML document, including xml processing instruction, root node is "<hierarchy>".
*/
public static String dive(ServiceContext ctx, String itemcsid, String uri) {
String result = dive(ctx, itemcsid, uri, true);
result = "<?xml version='1.0' ?><hierarchy>"+result+"</hierarchy>";
try {
result = XmlTools.prettyPrint(result);
} catch (Exception e){
}
return result;
}
private static String dive(ServiceContext ctx, String itemcsid, String uri, boolean lookupFirstName) {
MultivaluedMap queryParams = ctx.getUriInfo().getQueryParameters();
//Run getList() once as sent to get childListOuter:
queryParams.putSingle(IRelationsManager.PREDICATE_QP, RelationshipType.HAS_BROADER.value());
queryParams.putSingle(IRelationsManager.SUBJECT_QP, null);
queryParams.putSingle(IRelationsManager.SUBJECT_TYPE_QP, null);
queryParams.putSingle(IRelationsManager.OBJECT_QP, itemcsid);
queryParams.putSingle(IRelationsManager.OBJECT_TYPE_QP, null);
RelationsCommonList childListOuter = (new RelationResource()).getList(ctx.getUriInfo()); //magically knows all query params because they are in the context.
List<RelationsCommonList.RelationListItem> childList = childListOuter.getRelationListItem();
StringBuffer sb = new StringBuffer();
if (lookupFirstName && childList.size() > 0) {
RelationsCommonList.RelationListItem firstItem = childList.get(0);
sb.append("<uri>" + firstItem.getObject().getUri() + "</uri>\r\n");
sb.append("<uri-called>" + uri + "</uri-called>\r\n");
sb.append("<name>" + firstItem.getObject().getName() + "</name><number>" + firstItem.getObject().getNumber() + "</number>\r\n");
} else {
sb.append("<uri>" + uri + "</uri>\r\n");
}
sb.append("<csid>" + itemcsid + "</csid>\r\n");
sb.append("<children>\r\n");
for (RelationsCommonList.RelationListItem item : childList) {
RelationsDocListItem parent = item.getObject();
RelationsDocListItem child = item.getSubject();
String childCSID = child.getCsid();
String childURI = child.getUri();
sb.append("<child>\r\n");
sb.append("<parent-uri>" +parent.getUri() + "</parent-uri>\r\n");
sb.append(" <name>" + child.getName() + "</name><number>" + child.getNumber() + "</number>\r\n");
String s = dive(ctx, childCSID, childURI, false);
sb.append(s);
sb.append("</child>\r\n");
}
sb.append("</children>\r\n");
return sb.toString();
}
public static String surface(ServiceContext ctx, String itemcsid, String uri) {
String result = surface(ctx, itemcsid, uri, true).resultBuffer.toString();
result = "<?xml version='1.0' ?><hierarchy direction='"+direction_parents+"'>"+result+"</hierarchy>";
try {
result = XmlTools.prettyPrint(result);
} catch (Exception e){
}
return result;
}
private static class SurfaceResultStruct {
public StringBuffer resultBuffer;
public boolean noParents = false;
}
private static SurfaceResultStruct surface(ServiceContext ctx, String itemcsid, String uri, boolean first) {
MultivaluedMap queryParams = ctx.getUriInfo().getQueryParameters();
//Run getList() once as sent to get parentListOuter:
queryParams.putSingle(IRelationsManager.PREDICATE_QP, RelationshipType.HAS_BROADER.value());
queryParams.putSingle(IRelationsManager.SUBJECT_QP, itemcsid);
queryParams.putSingle(IRelationsManager.SUBJECT_TYPE_QP, null);
queryParams.putSingle(IRelationsManager.OBJECT_QP, null);
queryParams.putSingle(IRelationsManager.OBJECT_TYPE_QP, null);
RelationsCommonList parentListOuter = (new RelationResource()).getList(ctx.getUriInfo()); //magically knows all query params because they are in the context.
List<RelationsCommonList.RelationListItem> parentList = parentListOuter.getRelationListItem();
StringBuffer sbOuter = new StringBuffer();
SurfaceResultStruct resultStruct = new SurfaceResultStruct();
resultStruct.resultBuffer = sbOuter;
sbOuter.append("<uri>" + uri + "</uri>\r\n");
sbOuter.append("<csid>" + itemcsid + "</csid>\r\n");
StringBuffer sb = new StringBuffer();
String name = "";
String otherNames="";
String number = "";
String otherNumbers = "";
sb.append("<parents>\r\n");
if (parentList.size()==0){
resultStruct.noParents = true;
}
for (RelationsCommonList.RelationListItem item : parentList) {
resultStruct.noParents = false;
RelationsDocListItem parent = item.getObject();
RelationsDocListItem child = item.getSubject();
String parentCSID =parent.getCsid();
String parentURI = parent.getUri();
String aName = child.getName();
String aNumber = child.getNumber();
if (name.length()>0 && (!name.equals(aName))){
otherNames = otherNames+";"+aName;
} else {
name = aName;
}
if (number.length()>0 && (!number.equals(aNumber))){
otherNumbers = otherNumbers+";"+aNumber;
} else {
number = aName;
}
sb.append("<parent>\r\n");
//sb.append("<parent-uri>" +parentURI + "</parent-uri>\r\n");
SurfaceResultStruct struct = surface(ctx, parentCSID, parentURI, false);
StringBuffer surfaceResult = struct.resultBuffer;
if (struct.noParents){
//when there are no more parents, there is no way to look up the name and number, so use this trick:
sb.append("<name>" + parent.getName() + "</name><number>" + parent.getNumber() + "</number>\r\n");
}
sb.append(surfaceResult);
sb.append("</parent>\r\n");
}
sb.append("</parents>\r\n");
- if (name.length()>0)sbOuter.append(" <name>" +name + "</name>\r\n");
- if (otherNames.length()>0) sbOuter.append(" <name-mismatches-by-parents>" +otherNames + "</name-mismatches-by-parents>\r\n");
+ if (Tools.notBlank(name))sbOuter.append(" <name>" +name + "</name>\r\n");
+ if (Tools.notBlank(otherNames)) sbOuter.append(" <name-mismatches-by-parents>" +otherNames + "</name-mismatches-by-parents>\r\n");
- if (number.length()>0) sbOuter.append("<number>" +number + "</number>\r\n");
- if (otherNumbers.length()>0) sbOuter.append(" <number-mismatches-by-parents>" +otherNumbers + "</number-mismatches-by-parents>\r\n");
+ if (Tools.notBlank(number)) sbOuter.append("<number>" +number + "</number>\r\n");
+ if (Tools.notBlank(otherNumbers)) sbOuter.append(" <number-mismatches-by-parents>" +otherNumbers + "</number-mismatches-by-parents>\r\n");
sbOuter.append(sb);
return resultStruct;
}
}
| false | true | private static SurfaceResultStruct surface(ServiceContext ctx, String itemcsid, String uri, boolean first) {
MultivaluedMap queryParams = ctx.getUriInfo().getQueryParameters();
//Run getList() once as sent to get parentListOuter:
queryParams.putSingle(IRelationsManager.PREDICATE_QP, RelationshipType.HAS_BROADER.value());
queryParams.putSingle(IRelationsManager.SUBJECT_QP, itemcsid);
queryParams.putSingle(IRelationsManager.SUBJECT_TYPE_QP, null);
queryParams.putSingle(IRelationsManager.OBJECT_QP, null);
queryParams.putSingle(IRelationsManager.OBJECT_TYPE_QP, null);
RelationsCommonList parentListOuter = (new RelationResource()).getList(ctx.getUriInfo()); //magically knows all query params because they are in the context.
List<RelationsCommonList.RelationListItem> parentList = parentListOuter.getRelationListItem();
StringBuffer sbOuter = new StringBuffer();
SurfaceResultStruct resultStruct = new SurfaceResultStruct();
resultStruct.resultBuffer = sbOuter;
sbOuter.append("<uri>" + uri + "</uri>\r\n");
sbOuter.append("<csid>" + itemcsid + "</csid>\r\n");
StringBuffer sb = new StringBuffer();
String name = "";
String otherNames="";
String number = "";
String otherNumbers = "";
sb.append("<parents>\r\n");
if (parentList.size()==0){
resultStruct.noParents = true;
}
for (RelationsCommonList.RelationListItem item : parentList) {
resultStruct.noParents = false;
RelationsDocListItem parent = item.getObject();
RelationsDocListItem child = item.getSubject();
String parentCSID =parent.getCsid();
String parentURI = parent.getUri();
String aName = child.getName();
String aNumber = child.getNumber();
if (name.length()>0 && (!name.equals(aName))){
otherNames = otherNames+";"+aName;
} else {
name = aName;
}
if (number.length()>0 && (!number.equals(aNumber))){
otherNumbers = otherNumbers+";"+aNumber;
} else {
number = aName;
}
sb.append("<parent>\r\n");
//sb.append("<parent-uri>" +parentURI + "</parent-uri>\r\n");
SurfaceResultStruct struct = surface(ctx, parentCSID, parentURI, false);
StringBuffer surfaceResult = struct.resultBuffer;
if (struct.noParents){
//when there are no more parents, there is no way to look up the name and number, so use this trick:
sb.append("<name>" + parent.getName() + "</name><number>" + parent.getNumber() + "</number>\r\n");
}
sb.append(surfaceResult);
sb.append("</parent>\r\n");
}
sb.append("</parents>\r\n");
if (name.length()>0)sbOuter.append(" <name>" +name + "</name>\r\n");
if (otherNames.length()>0) sbOuter.append(" <name-mismatches-by-parents>" +otherNames + "</name-mismatches-by-parents>\r\n");
if (number.length()>0) sbOuter.append("<number>" +number + "</number>\r\n");
if (otherNumbers.length()>0) sbOuter.append(" <number-mismatches-by-parents>" +otherNumbers + "</number-mismatches-by-parents>\r\n");
sbOuter.append(sb);
return resultStruct;
}
| private static SurfaceResultStruct surface(ServiceContext ctx, String itemcsid, String uri, boolean first) {
MultivaluedMap queryParams = ctx.getUriInfo().getQueryParameters();
//Run getList() once as sent to get parentListOuter:
queryParams.putSingle(IRelationsManager.PREDICATE_QP, RelationshipType.HAS_BROADER.value());
queryParams.putSingle(IRelationsManager.SUBJECT_QP, itemcsid);
queryParams.putSingle(IRelationsManager.SUBJECT_TYPE_QP, null);
queryParams.putSingle(IRelationsManager.OBJECT_QP, null);
queryParams.putSingle(IRelationsManager.OBJECT_TYPE_QP, null);
RelationsCommonList parentListOuter = (new RelationResource()).getList(ctx.getUriInfo()); //magically knows all query params because they are in the context.
List<RelationsCommonList.RelationListItem> parentList = parentListOuter.getRelationListItem();
StringBuffer sbOuter = new StringBuffer();
SurfaceResultStruct resultStruct = new SurfaceResultStruct();
resultStruct.resultBuffer = sbOuter;
sbOuter.append("<uri>" + uri + "</uri>\r\n");
sbOuter.append("<csid>" + itemcsid + "</csid>\r\n");
StringBuffer sb = new StringBuffer();
String name = "";
String otherNames="";
String number = "";
String otherNumbers = "";
sb.append("<parents>\r\n");
if (parentList.size()==0){
resultStruct.noParents = true;
}
for (RelationsCommonList.RelationListItem item : parentList) {
resultStruct.noParents = false;
RelationsDocListItem parent = item.getObject();
RelationsDocListItem child = item.getSubject();
String parentCSID =parent.getCsid();
String parentURI = parent.getUri();
String aName = child.getName();
String aNumber = child.getNumber();
if (name.length()>0 && (!name.equals(aName))){
otherNames = otherNames+";"+aName;
} else {
name = aName;
}
if (number.length()>0 && (!number.equals(aNumber))){
otherNumbers = otherNumbers+";"+aNumber;
} else {
number = aName;
}
sb.append("<parent>\r\n");
//sb.append("<parent-uri>" +parentURI + "</parent-uri>\r\n");
SurfaceResultStruct struct = surface(ctx, parentCSID, parentURI, false);
StringBuffer surfaceResult = struct.resultBuffer;
if (struct.noParents){
//when there are no more parents, there is no way to look up the name and number, so use this trick:
sb.append("<name>" + parent.getName() + "</name><number>" + parent.getNumber() + "</number>\r\n");
}
sb.append(surfaceResult);
sb.append("</parent>\r\n");
}
sb.append("</parents>\r\n");
if (Tools.notBlank(name))sbOuter.append(" <name>" +name + "</name>\r\n");
if (Tools.notBlank(otherNames)) sbOuter.append(" <name-mismatches-by-parents>" +otherNames + "</name-mismatches-by-parents>\r\n");
if (Tools.notBlank(number)) sbOuter.append("<number>" +number + "</number>\r\n");
if (Tools.notBlank(otherNumbers)) sbOuter.append(" <number-mismatches-by-parents>" +otherNumbers + "</number-mismatches-by-parents>\r\n");
sbOuter.append(sb);
return resultStruct;
}
|
diff --git a/src/main/java/suite/rt/Plane.java b/src/main/java/suite/rt/Plane.java
index 934941842..ca4019366 100644
--- a/src/main/java/suite/rt/Plane.java
+++ b/src/main/java/suite/rt/Plane.java
@@ -1,68 +1,67 @@
package suite.rt;
import suite.math.MathUtil;
import suite.math.Vector;
import suite.rt.RayTracer.RayHit;
import suite.rt.RayTracer.RayHitDetail;
import suite.rt.RayTracer.RayTraceObject;
public class Plane implements RayTraceObject {
private Vector normal;
private float originIndex;
public Plane(Vector normal, float originIndex) {
this.normal = normal;
this.originIndex = originIndex;
}
@Override
public RayHit hit(final Vector startPoint, final Vector direction) {
- float norm = (float) Math.sqrt(Vector.normsq(direction));
float denum = Vector.dot(normal, direction);
float adv;
if (Math.abs(denum) > MathUtil.epsilon)
- adv = -(Vector.dot(normal, startPoint) + originIndex) * norm / denum;
+ adv = -(Vector.dot(normal, startPoint) + originIndex) / denum;
else
adv = -1f; // Treats as not-hit
final float advance = adv;
if (advance > RayTracer.negligibleAdvance)
return new RayHit() {
public float advance() {
return advance;
}
public RayHitDetail detail() {
final Vector hitPoint = Vector.add(startPoint, Vector.mul(direction, advance));
return new RayHitDetail() {
public Vector hitPoint() {
return hitPoint;
}
public Vector normal() {
return normal;
}
public Vector litIndex() {
return new Vector(0.5f, 0.5f, 0.5f);
}
public Vector reflectionIndex() {
return new Vector(0.5f, 0.5f, 0.5f);
}
public Vector refractionIndex() {
return new Vector(0f, 0f, 0f);
}
};
}
};
else
return null;
}
}
| false | true | public RayHit hit(final Vector startPoint, final Vector direction) {
float norm = (float) Math.sqrt(Vector.normsq(direction));
float denum = Vector.dot(normal, direction);
float adv;
if (Math.abs(denum) > MathUtil.epsilon)
adv = -(Vector.dot(normal, startPoint) + originIndex) * norm / denum;
else
adv = -1f; // Treats as not-hit
final float advance = adv;
if (advance > RayTracer.negligibleAdvance)
return new RayHit() {
public float advance() {
return advance;
}
public RayHitDetail detail() {
final Vector hitPoint = Vector.add(startPoint, Vector.mul(direction, advance));
return new RayHitDetail() {
public Vector hitPoint() {
return hitPoint;
}
public Vector normal() {
return normal;
}
public Vector litIndex() {
return new Vector(0.5f, 0.5f, 0.5f);
}
public Vector reflectionIndex() {
return new Vector(0.5f, 0.5f, 0.5f);
}
public Vector refractionIndex() {
return new Vector(0f, 0f, 0f);
}
};
}
};
else
return null;
}
| public RayHit hit(final Vector startPoint, final Vector direction) {
float denum = Vector.dot(normal, direction);
float adv;
if (Math.abs(denum) > MathUtil.epsilon)
adv = -(Vector.dot(normal, startPoint) + originIndex) / denum;
else
adv = -1f; // Treats as not-hit
final float advance = adv;
if (advance > RayTracer.negligibleAdvance)
return new RayHit() {
public float advance() {
return advance;
}
public RayHitDetail detail() {
final Vector hitPoint = Vector.add(startPoint, Vector.mul(direction, advance));
return new RayHitDetail() {
public Vector hitPoint() {
return hitPoint;
}
public Vector normal() {
return normal;
}
public Vector litIndex() {
return new Vector(0.5f, 0.5f, 0.5f);
}
public Vector reflectionIndex() {
return new Vector(0.5f, 0.5f, 0.5f);
}
public Vector refractionIndex() {
return new Vector(0f, 0f, 0f);
}
};
}
};
else
return null;
}
|
diff --git a/src/net/sourceforge/servestream/activity/MediaPlaybackActivity.java b/src/net/sourceforge/servestream/activity/MediaPlaybackActivity.java
index 2f6ec10..3fcb8ba 100644
--- a/src/net/sourceforge/servestream/activity/MediaPlaybackActivity.java
+++ b/src/net/sourceforge/servestream/activity/MediaPlaybackActivity.java
@@ -1,1188 +1,1188 @@
/*
* ServeStream: A HTTP stream browser/player for Android
* Copyright 2012 William Seemann
*
* 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 net.sourceforge.servestream.activity;
import net.sourceforge.servestream.R;
import net.sourceforge.servestream.button.RepeatingImageButton;
import net.sourceforge.servestream.provider.Media;
import net.sourceforge.servestream.service.IMediaPlaybackService;
import net.sourceforge.servestream.service.MediaPlaybackService;
import net.sourceforge.servestream.utils.CoverView;
import net.sourceforge.servestream.utils.CoverView.CoverViewListener;
import net.sourceforge.servestream.utils.MusicUtils;
import net.sourceforge.servestream.utils.PreferenceConstants;
import net.sourceforge.servestream.utils.MusicUtils.ServiceToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.preference.PreferenceManager;
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.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MediaPlaybackActivity extends Activity implements MusicUtils.Defs,
OnSharedPreferenceChangeListener,
CoverViewListener
{
private static final String TAG = MediaPlaybackActivity.class.getName();
private static final int MAX_SLEEP_TIMER_MINUTES = 120;
private int mParentActivityState = VISIBLE;
private static int VISIBLE = 1;
private static int GONE = 2;
private final static int PREPARING_MEDIA = 1;
private final static int DIALOG_SLEEP_TIMER = 2;
private SharedPreferences mPreferences;
private boolean mSeeking = false;
private boolean mDeviceHasDpad;
private long mStartSeekPos = 0;
private long mLastSeekEventTime;
private IMediaPlaybackService mService = null;
private ImageButton mCloseButton = null;
private ImageButton mPlayQueue = null;
private RepeatingImageButton mPrevButton;
private ImageButton mPauseButton;
private RepeatingImageButton mNextButton;
private ImageButton mRepeatButton;
private ImageButton mShuffleButton;
private Worker mAlbumArtWorker;
private AlbumArtHandler mAlbumArtHandler;
private Toast mToast;
private ServiceToken mToken;
private TextView mTrackNumber;
public MediaPlaybackActivity()
{
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mAlbumArtWorker = new Worker("album art worker");
mAlbumArtHandler = new AlbumArtHandler(mAlbumArtWorker.getLooper());
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mPreferences.registerOnSharedPreferenceChangeListener(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_media_player);
mCurrentTime = (TextView) findViewById(R.id.position_text);
mTotalTime = (TextView) findViewById(R.id.duration_text);
mProgress = (ProgressBar) findViewById(R.id.seek_bar);
mAlbum = (CoverView) findViewById(R.id.album_art);
mAlbum.setup(mAlbumArtWorker.getLooper(), this);
mTrackName = (TextView) findViewById(R.id.trackname);
mArtistAndAlbumName = (TextView) findViewById(R.id.artist_and_album);
mTrackNumber = (TextView) findViewById(R.id.track_number_text);
mCloseButton = (ImageButton) findViewById(R.id.close);
mCloseButton.setOnClickListener(mCloseListener);
mPlayQueue = (ImageButton) findViewById(R.id.play_queue);
mPlayQueue.setOnClickListener(mPlayQueueListener);
mPrevButton = (RepeatingImageButton) findViewById(R.id.previous_button);
mPrevButton.setOnClickListener(mPrevListener);
mPrevButton.setRepeatListener(mRewListener, 260);
mPauseButton = (ImageButton) findViewById(R.id.play_pause_button);
mPauseButton.setOnClickListener(mPauseListener);
mNextButton = (RepeatingImageButton) findViewById(R.id.next_button);
mNextButton.setOnClickListener(mNextListener);
mNextButton.setRepeatListener(mFfwdListener, 260);
seekmethod = 1;
mDeviceHasDpad = (getResources().getConfiguration().navigation ==
Configuration.NAVIGATION_DPAD);
mShuffleButton = (ImageButton) findViewById(R.id.shuffle_button);
mShuffleButton.setOnClickListener(mShuffleListener);
mRepeatButton = (ImageButton) findViewById(R.id.repeat_button);
mRepeatButton.setOnClickListener(mRepeatListener);
if (mProgress instanceof SeekBar) {
SeekBar seeker = (SeekBar) mProgress;
seeker.setOnSeekBarChangeListener(mSeekListener);
}
mProgress.setMax(1000);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals(PreferenceConstants.WAKELOCK)) {
if (sharedPreferences.getBoolean(PreferenceConstants.WAKELOCK, true)) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
}
private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
public void onStartTrackingTouch(SeekBar bar) {
mLastSeekEventTime = 0;
mFromTouch = true;
}
public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
if (!fromuser || (mService == null)) return;
long now = SystemClock.elapsedRealtime();
if ((now - mLastSeekEventTime) > 250) {
mLastSeekEventTime = now;
mPosOverride = mDuration * progress / 1000;
try {
mService.seek(mPosOverride);
} catch (RemoteException ex) {
}
// trackball event, allow progress updates
if (!mFromTouch) {
refreshNow();
mPosOverride = -1;
}
}
}
public void onStopTrackingTouch(SeekBar bar) {
mPosOverride = -1;
mFromTouch = false;
}
};
private View.OnClickListener mCloseListener = new View.OnClickListener() {
public void onClick(View v) {
finish();
}
};
private View.OnClickListener mPlayQueueListener = new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MediaPlaybackActivity.this, NowPlayingActivity.class));
}
};
private View.OnClickListener mShuffleListener = new View.OnClickListener() {
public void onClick(View v) {
toggleShuffle();
}
};
private View.OnClickListener mRepeatListener = new View.OnClickListener() {
public void onClick(View v) {
cycleRepeat();
}
};
private View.OnClickListener mPauseListener = new View.OnClickListener() {
public void onClick(View v) {
doPauseResume();
}
};
private View.OnClickListener mPrevListener = new View.OnClickListener() {
public void onClick(View v) {
if (mService == null) return;
try {
mService.prev();
} catch (RemoteException ex) {
}
}
};
private View.OnClickListener mNextListener = new View.OnClickListener() {
public void onClick(View v) {
if (mService == null) return;
try {
mService.next();
} catch (RemoteException ex) {
}
}
};
private RepeatingImageButton.RepeatListener mRewListener =
new RepeatingImageButton.RepeatListener() {
public void onRepeat(View v, long howlong, int repcnt) {
scanBackward(repcnt, howlong);
}
};
private RepeatingImageButton.RepeatListener mFfwdListener =
new RepeatingImageButton.RepeatListener() {
public void onRepeat(View v, long howlong, int repcnt) {
scanForward(repcnt, howlong);
}
};
@Override
public void onStart() {
super.onStart();
paused = false;
if (mPreferences.getBoolean(PreferenceConstants.WAKELOCK, true)) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
mToken = MusicUtils.bindToService(this, osc);
if (mToken == null) {
// something went wrong
mHandler.sendEmptyMessage(QUIT);
}
IntentFilter f = new IntentFilter();
f.addAction(MediaPlaybackService.PLAYSTATE_CHANGED);
f.addAction(MediaPlaybackService.META_CHANGED);
f.addAction(MediaPlaybackService.START_DIALOG);
f.addAction(MediaPlaybackService.STOP_DIALOG);
registerReceiver(mStatusListener, new IntentFilter(f));
updateTrackInfo();
long next = refreshNow();
queueNextRefresh(next);
}
@Override
public void onResume() {
super.onResume();
mParentActivityState = VISIBLE;
updateTrackInfo();
setPauseButtonImage();
}
@Override
public void onPause() {
super.onPause();
mParentActivityState = GONE;
removeDialog(PREPARING_MEDIA);
}
@Override
public void onStop() {
paused = true;
mHandler.removeMessages(REFRESH);
unregisterReceiver(mStatusListener);
MusicUtils.unbindFromService(mToken);
mService = null;
super.onStop();
}
@Override
public void onDestroy() {
mAlbumArtWorker.quit();
super.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case (R.id.menu_item_stop):
doStop();
return true;
case (R.id.menu_item_sleep_timer):
showDialog(DIALOG_SLEEP_TIMER);
return true;
case (R.id.menu_item_settings):
startActivity(new Intent(MediaPlaybackActivity.this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
protected Dialog onCreateDialog(int id) {
Dialog dialog;
ProgressDialog progressDialog = null;
switch(id) {
case PREPARING_MEDIA:
progressDialog = new ProgressDialog(MediaPlaybackActivity.this);
progressDialog.setMessage(getString(R.string.opening_url_message));
progressDialog.setCancelable(true);
return progressDialog;
case DIALOG_SLEEP_TIMER:
dialog = null;
- if (mService != null) {
+ if (mService == null) {
break;
}
int sleepTimerMode = -1;
try {
sleepTimerMode = mService.getSleepTimerMode();
} catch (RemoteException e) {
break;
}
LayoutInflater factory = LayoutInflater.from(this);
final View sleepTimerView = factory.inflate(R.layout.alert_dialog_sleep_timer, null);
final TextView sleepTimerText = (TextView) sleepTimerView.findViewById(R.id.sleep_timer_text);
final SeekBar seekbar = (SeekBar) sleepTimerView.findViewById(R.id.seekbar);
seekbar.setMax(MAX_SLEEP_TIMER_MINUTES);
sleepTimerText.setText(makeTimeString(sleepTimerMode));
seekbar.setProgress(sleepTimerMode);
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
sleepTimerText.setText(makeTimeString(progress));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
return new AlertDialog.Builder(MediaPlaybackActivity.this)
.setTitle(R.string.menu_sleep_timer)
.setView(sleepTimerView)
.setCancelable(true)
.setPositiveButton(R.string.set_alarm, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
setSleepTimer(seekbar.getProgress());
dialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
removeDialog(DIALOG_SLEEP_TIMER);
}
})
.create();
default:
dialog = null;
}
return dialog;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_media_playback, menu);
return true;
}
private final int keyboard[][] = {
{
KeyEvent.KEYCODE_Q,
KeyEvent.KEYCODE_W,
KeyEvent.KEYCODE_E,
KeyEvent.KEYCODE_R,
KeyEvent.KEYCODE_T,
KeyEvent.KEYCODE_Y,
KeyEvent.KEYCODE_U,
KeyEvent.KEYCODE_I,
KeyEvent.KEYCODE_O,
KeyEvent.KEYCODE_P,
},
{
KeyEvent.KEYCODE_A,
KeyEvent.KEYCODE_S,
KeyEvent.KEYCODE_D,
KeyEvent.KEYCODE_F,
KeyEvent.KEYCODE_G,
KeyEvent.KEYCODE_H,
KeyEvent.KEYCODE_J,
KeyEvent.KEYCODE_K,
KeyEvent.KEYCODE_L,
KeyEvent.KEYCODE_DEL,
},
{
KeyEvent.KEYCODE_Z,
KeyEvent.KEYCODE_X,
KeyEvent.KEYCODE_C,
KeyEvent.KEYCODE_V,
KeyEvent.KEYCODE_B,
KeyEvent.KEYCODE_N,
KeyEvent.KEYCODE_M,
KeyEvent.KEYCODE_COMMA,
KeyEvent.KEYCODE_PERIOD,
KeyEvent.KEYCODE_ENTER
}
};
private int lastX;
private int lastY;
private boolean seekMethod1(int keyCode)
{
if (mService == null) return false;
for(int x=0;x<10;x++) {
for(int y=0;y<3;y++) {
if(keyboard[y][x] == keyCode) {
int dir = 0;
// top row
if(x == lastX && y == lastY) dir = 0;
else if (y == 0 && lastY == 0 && x > lastX) dir = 1;
else if (y == 0 && lastY == 0 && x < lastX) dir = -1;
// bottom row
else if (y == 2 && lastY == 2 && x > lastX) dir = -1;
else if (y == 2 && lastY == 2 && x < lastX) dir = 1;
// moving up
else if (y < lastY && x <= 4) dir = 1;
else if (y < lastY && x >= 5) dir = -1;
// moving down
else if (y > lastY && x <= 4) dir = -1;
else if (y > lastY && x >= 5) dir = 1;
lastX = x;
lastY = y;
try {
mService.seek(mService.position() + dir * 5);
} catch (RemoteException ex) {
}
refreshNow();
return true;
}
}
}
lastX = -1;
lastY = -1;
return false;
}
private boolean seekMethod2(int keyCode)
{
if (mService == null) return false;
for(int i=0;i<10;i++) {
if(keyboard[0][i] == keyCode) {
int seekpercentage = 100*i/10;
try {
mService.seek(mService.duration() * seekpercentage / 100);
} catch (RemoteException ex) {
}
refreshNow();
return true;
}
}
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
try {
switch(keyCode)
{
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!useDpadMusicControl()) {
break;
}
if (mService != null) {
if (!mSeeking && mStartSeekPos >= 0) {
mPauseButton.requestFocus();
if (mStartSeekPos < 1000) {
mService.prev();
} else {
mService.seek(0);
}
} else {
scanBackward(-1, event.getEventTime() - event.getDownTime());
mPauseButton.requestFocus();
mStartSeekPos = -1;
}
}
mSeeking = false;
mPosOverride = -1;
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (!useDpadMusicControl()) {
break;
}
if (mService != null) {
if (!mSeeking && mStartSeekPos >= 0) {
mPauseButton.requestFocus();
mService.next();
} else {
scanForward(-1, event.getEventTime() - event.getDownTime());
mPauseButton.requestFocus();
mStartSeekPos = -1;
}
}
mSeeking = false;
mPosOverride = -1;
return true;
}
} catch (RemoteException ex) {
}
return super.onKeyUp(keyCode, event);
}
private boolean useDpadMusicControl() {
if (mDeviceHasDpad && (mPrevButton.isFocused() ||
mNextButton.isFocused() ||
mPauseButton.isFocused())) {
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
int repcnt = event.getRepeatCount();
if((seekmethod==0)?seekMethod1(keyCode):seekMethod2(keyCode))
return true;
switch(keyCode)
{
case KeyEvent.KEYCODE_SLASH:
seekmethod = 1 - seekmethod;
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!useDpadMusicControl()) {
break;
}
if (!mPrevButton.hasFocus()) {
mPrevButton.requestFocus();
}
scanBackward(repcnt, event.getEventTime() - event.getDownTime());
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (!useDpadMusicControl()) {
break;
}
if (!mNextButton.hasFocus()) {
mNextButton.requestFocus();
}
scanForward(repcnt, event.getEventTime() - event.getDownTime());
return true;
case KeyEvent.KEYCODE_S:
toggleShuffle();
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_SPACE:
doPauseResume();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void scanBackward(int repcnt, long delta) {
if(mService == null) return;
try {
if(repcnt == 0) {
mStartSeekPos = mService.position();
mLastSeekEventTime = 0;
mSeeking = false;
} else {
mSeeking = true;
if (delta < 5000) {
// seek at 10x speed for the first 5 seconds
delta = delta * 10;
} else {
// seek at 40x after that
delta = 50000 + (delta - 5000) * 40;
}
long newpos = mStartSeekPos - delta;
if (newpos < 0) {
// move to previous track
mService.prev();
long duration = mService.duration();
mStartSeekPos += duration;
newpos += duration;
}
if (((delta - mLastSeekEventTime) > 250) || repcnt < 0){
mService.seek(newpos);
mLastSeekEventTime = delta;
}
if (repcnt >= 0) {
mPosOverride = newpos;
} else {
mPosOverride = -1;
}
refreshNow();
}
} catch (RemoteException ex) {
}
}
private void scanForward(int repcnt, long delta) {
if(mService == null) return;
try {
if(repcnt == 0) {
mStartSeekPos = mService.position();
mLastSeekEventTime = 0;
mSeeking = false;
} else {
mSeeking = true;
if (delta < 5000) {
// seek at 10x speed for the first 5 seconds
delta = delta * 10;
} else {
// seek at 40x after that
delta = 50000 + (delta - 5000) * 40;
}
long newpos = mStartSeekPos + delta;
long duration = mService.duration();
if (newpos >= duration) {
// move to next track
mService.next();
mStartSeekPos -= duration; // is OK to go negative
newpos -= duration;
}
if (((delta - mLastSeekEventTime) > 250) || repcnt < 0){
mService.seek(newpos);
mLastSeekEventTime = delta;
}
if (repcnt >= 0) {
mPosOverride = newpos;
} else {
mPosOverride = -1;
}
refreshNow();
}
} catch (RemoteException ex) {
}
}
private void doPauseResume() {
try {
if(mService != null) {
if (mService.isPlaying()) {
mService.pause();
} else {
mService.play();
}
refreshNow();
setPauseButtonImage();
}
} catch (RemoteException ex) {
}
}
private void doStop() {
try {
if(mService != null) {
mService.stop();
refreshNow();
setPauseButtonImage();
}
} catch (RemoteException ex) {
}
}
private void toggleShuffle() {
if (mService == null) {
return;
}
try {
int shuffle = mService.getShuffleMode();
if (shuffle == MediaPlaybackService.SHUFFLE_NONE) {
mService.setShuffleMode(MediaPlaybackService.SHUFFLE_ON);
if (mService.getRepeatMode() == MediaPlaybackService.REPEAT_CURRENT) {
mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
setRepeatButtonImage();
}
showToast(R.string.shuffle_on_notif);
} else if (shuffle == MediaPlaybackService.SHUFFLE_ON) {
mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
showToast(R.string.shuffle_off_notif);
} else {
Log.e(TAG, "Invalid shuffle mode: " + shuffle);
}
setShuffleButtonImage();
} catch (RemoteException ex) {
}
}
private void cycleRepeat() {
if (mService == null) {
return;
}
try {
int mode = mService.getRepeatMode();
if (mode == MediaPlaybackService.REPEAT_NONE) {
mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
showToast(R.string.repeat_all_notif);
} else if (mode == MediaPlaybackService.REPEAT_ALL) {
mService.setRepeatMode(MediaPlaybackService.REPEAT_CURRENT);
if (mService.getShuffleMode() != MediaPlaybackService.SHUFFLE_NONE) {
mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
setShuffleButtonImage();
}
showToast(R.string.repeat_current_notif);
} else {
mService.setRepeatMode(MediaPlaybackService.REPEAT_NONE);
showToast(R.string.repeat_off_notif);
}
setRepeatButtonImage();
} catch (RemoteException ex) {
}
}
private void setSleepTimer(int pos) {
if (mService == null) {
return;
}
try {
MusicUtils.sService.setSleepTimerMode(pos);
if (pos == MediaPlaybackService.SLEEP_TIMER_OFF) {
showToast(R.string.sleep_timer_off_notif);
} else {
showToast(getString(R.string.sleep_timer_on_notif) + " " + makeTimeString(pos));
}
} catch (RemoteException e) {
}
}
private String makeTimeString(int pos) {
String minuteText;
if (pos == MediaPlaybackService.SLEEP_TIMER_OFF) {
minuteText = getResources().getString(R.string.minute_picker_cancel);
} else if (pos == 1) {
minuteText = getResources().getString(R.string.minute);
} else if (pos % 60 == 0 && pos > 60) {
minuteText = getResources().getString(R.string.hours, String.valueOf(pos / 60));
} else if (pos % 60 == 0) {
minuteText = getResources().getString(R.string.hour);
} else {
minuteText = getResources().getString(R.string.minutes, String.valueOf(pos));
}
return minuteText;
}
private void showToast(int resid) {
if (mToast == null) {
mToast = Toast.makeText(this, null, Toast.LENGTH_SHORT);
}
mToast.setText(resid);
mToast.show();
}
private void showToast(String message) {
if (mToast == null) {
mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
}
mToast.setText(message);
mToast.show();
}
private void startPlayback() {
if(mService == null)
return;
updateTrackInfo();
long next = refreshNow();
queueNextRefresh(next);
}
private ServiceConnection osc = new ServiceConnection() {
public void onServiceConnected(ComponentName classname, IBinder obj) {
mService = IMediaPlaybackService.Stub.asInterface(obj);
startPlayback();
try {
// Assume something is playing when the service says it is,
// but also if the audio ID is valid but the service is paused.
if (mService.getAudioId() >= 0 || mService.isPlaying() ||
mService.getPath() != null) {
// something is playing now, we're done
mRepeatButton.setVisibility(View.VISIBLE);
mShuffleButton.setVisibility(View.VISIBLE);
setRepeatButtonImage();
setShuffleButtonImage();
setPauseButtonImage();
return;
}
} catch (RemoteException ex) {
}
// Service is dead or not playing anything. Return to the previous
// activity.
finish();
}
public void onServiceDisconnected(ComponentName classname) {
mService = null;
}
};
private void setRepeatButtonImage() {
if (mService == null) return;
try {
switch (mService.getRepeatMode()) {
case MediaPlaybackService.REPEAT_ALL:
mRepeatButton.setImageResource(R.drawable.btn_player_repeat_checked);
break;
case MediaPlaybackService.REPEAT_CURRENT:
mRepeatButton.setImageResource(R.drawable.btn_player_repeat_one_checked);
break;
default:
mRepeatButton.setImageResource(R.drawable.btn_player_repeat_normal);
break;
}
} catch (RemoteException ex) {
}
}
private void setShuffleButtonImage() {
if (mService == null) return;
try {
switch (mService.getShuffleMode()) {
case MediaPlaybackService.SHUFFLE_NONE:
mShuffleButton.setImageResource(R.drawable.btn_player_shuffle_normal);
break;
default:
mShuffleButton.setImageResource(R.drawable.btn_player_shuffle_checked);
break;
}
} catch (RemoteException ex) {
}
}
private void setPauseButtonImage() {
try {
if (mService != null && mService.isPlaying()) {
mPauseButton.setImageResource(R.drawable.btn_player_pause);
} else {
mPauseButton.setImageResource(R.drawable.btn_player_play);
}
} catch (RemoteException ex) {
}
}
private void setSeekControls() {
if (mService == null) {
return;
}
try {
if (mService.duration() > 0) {
mProgress.setEnabled(true);
mPrevButton.setRepeatListener(mRewListener, 260);
mNextButton.setRepeatListener(mFfwdListener, 260);
} else {
mProgress.setEnabled(false);
mPrevButton.setRepeatListener(null, -1);
mNextButton.setRepeatListener(null, -1);
}
} catch (RemoteException e) {
}
}
private CoverView mAlbum;
private TextView mCurrentTime;
private TextView mTotalTime;
private TextView mArtistAndAlbumName;
private TextView mTrackName;
private ProgressBar mProgress;
private long mPosOverride = -1;
private boolean mFromTouch = false;
private long mDuration;
private int seekmethod;
private boolean paused;
private static final int REFRESH = 1;
private static final int QUIT = 2;
private static final int GET_ALBUM_ART = 3;
private void queueNextRefresh(long delay) {
if (!paused) {
Message msg = mHandler.obtainMessage(REFRESH);
mHandler.removeMessages(REFRESH);
mHandler.sendMessageDelayed(msg, delay);
}
}
private long refreshNow() {
if(mService == null)
return 500;
try {
if (!mService.isStreaming()) {
if (!mService.isCompleteFileAvailable()) {
mProgress.setSecondaryProgress((int) (mService.getPercentDownloaded() * 1000));
mPrevButton.setRepeatListener(null, -1);
mNextButton.setRepeatListener(null, -1);
mProgress.setEnabled(false);
} else {
mDuration = mService.getCompleteFileDuration();
mTotalTime.setText(MusicUtils.makeTimeString(this, mDuration / 1000));
mPrevButton.setRepeatListener(mRewListener, 260);
mNextButton.setRepeatListener(mFfwdListener, 260);
mProgress.setEnabled(true);
}
}
long pos = mPosOverride < 0 ? mService.position() : mPosOverride;
long remaining = 1000 - (pos % 1000);
if ((pos >= 0) && (mDuration > 0)) {
mCurrentTime.setText(MusicUtils.makeTimeString(this, pos / 1000));
if (mService.isPlaying()) {
mCurrentTime.setVisibility(View.VISIBLE);
} else {
// blink the counter
int vis = mCurrentTime.getVisibility();
mCurrentTime.setVisibility(vis == View.INVISIBLE ? View.VISIBLE : View.INVISIBLE);
remaining = 500;
}
mProgress.setProgress((int) (1000 * pos / mDuration));
} else {
mCurrentTime.setText("--:--");
mProgress.setProgress(1000);
}
// return the number of milliseconds until the next full second, so
// the counter can be updated at just the right time
return remaining;
} catch (RemoteException ex) {
}
return 500;
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case REFRESH:
long next = refreshNow();
queueNextRefresh(next);
break;
case QUIT:
// This can be moved back to onCreate once the bug that prevents
// Dialogs from being started from onCreate/onResume is fixed.
new AlertDialog.Builder(MediaPlaybackActivity.this)
.setTitle(R.string.service_start_error_title)
.setMessage(R.string.service_start_error_msg)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
})
.setCancelable(false)
.show();
break;
default:
break;
}
}
};
private BroadcastReceiver mStatusListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(MediaPlaybackService.META_CHANGED)) {
// redraw the artist/title info and
// set new max for progress bar
updateTrackInfo();
setSeekControls();
setPauseButtonImage();
queueNextRefresh(1);
} else if (action.equals(MediaPlaybackService.PLAYSTATE_CHANGED)) {
setPauseButtonImage();
} else if (action.equals(MediaPlaybackService.START_DIALOG)) {
try {
if (mParentActivityState == VISIBLE) {
showDialog(PREPARING_MEDIA);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (action.equals(MediaPlaybackService.STOP_DIALOG)) {
if (mParentActivityState == VISIBLE) {
try {
removeDialog(PREPARING_MEDIA);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
};
private static class IdWrapper {
public long id;
IdWrapper(long id) {
this.id = id;
}
}
private void updateTrackInfo() {
if (mService == null) {
return;
}
try {
String path = mService.getPath();
if (path == null) {
finish();
return;
}
mTrackNumber.setText(mService.getTrackNumber());
String trackName = mService.getTrackName();
if (trackName == null || trackName.equals(Media.UNKNOWN_STRING)) {
trackName = mService.getMediaUri();
}
mTrackName.setText(trackName);
String artistName = mService.getArtistName();
String albumName = mService.getAlbumName();
String artistAndAlbumName = null;
if ((artistName == null || artistName.equals(Media.UNKNOWN_STRING)) &&
albumName == null || albumName.equals(Media.UNKNOWN_STRING)) {
artistAndAlbumName = "";
} else {
artistAndAlbumName = mService.getArtistName() + " - " + mService.getAlbumName();
}
mArtistAndAlbumName.setText(artistAndAlbumName);
mAlbumArtHandler.removeMessages(GET_ALBUM_ART);
mAlbumArtHandler.obtainMessage(GET_ALBUM_ART, new IdWrapper(mService.getTrackId())).sendToTarget();
if (mService.isStreaming()) {
mDuration = mService.duration();
mProgress.setSecondaryProgress(0);
} else {
if (mService.isCompleteFileAvailable()) {
mDuration = mService.getCompleteFileDuration();
} else {
mDuration = 0;
}
}
mTotalTime.setText(MusicUtils.makeTimeString(this, mDuration / 1000));
} catch (RemoteException ex) {
finish();
}
}
public class AlbumArtHandler extends Handler {
private long mId = -1;
public AlbumArtHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg)
{
long id = ((IdWrapper) msg.obj).id;
if (msg.what == GET_ALBUM_ART && mId != id && id >= 0) {
mAlbum.setSong((int) id);
}
}
}
private static class Worker implements Runnable {
private final Object mLock = new Object();
private Looper mLooper;
/**
* Creates a worker thread with the given name. The thread
* then runs a {@link android.os.Looper}.
* @param name A name for the new thread
*/
Worker(String name) {
Thread t = new Thread(null, this, name);
t.setPriority(Thread.MIN_PRIORITY);
t.start();
synchronized (mLock) {
while (mLooper == null) {
try {
mLock.wait();
} catch (InterruptedException ex) {
}
}
}
}
public Looper getLooper() {
return mLooper;
}
public void run() {
synchronized (mLock) {
Looper.prepare();
mLooper = Looper.myLooper();
mLock.notifyAll();
}
Looper.loop();
}
public void quit() {
mLooper.quit();
}
}
@Override
public void onCoverViewInitialized() {
if (mService == null) {
return;
}
try {
mAlbumArtHandler.removeMessages(GET_ALBUM_ART);
mAlbumArtHandler.obtainMessage(GET_ALBUM_ART, new IdWrapper(mService.getTrackId())).sendToTarget();
} catch (RemoteException e) {
}
}
}
| true | true | protected Dialog onCreateDialog(int id) {
Dialog dialog;
ProgressDialog progressDialog = null;
switch(id) {
case PREPARING_MEDIA:
progressDialog = new ProgressDialog(MediaPlaybackActivity.this);
progressDialog.setMessage(getString(R.string.opening_url_message));
progressDialog.setCancelable(true);
return progressDialog;
case DIALOG_SLEEP_TIMER:
dialog = null;
if (mService != null) {
break;
}
int sleepTimerMode = -1;
try {
sleepTimerMode = mService.getSleepTimerMode();
} catch (RemoteException e) {
break;
}
LayoutInflater factory = LayoutInflater.from(this);
final View sleepTimerView = factory.inflate(R.layout.alert_dialog_sleep_timer, null);
final TextView sleepTimerText = (TextView) sleepTimerView.findViewById(R.id.sleep_timer_text);
final SeekBar seekbar = (SeekBar) sleepTimerView.findViewById(R.id.seekbar);
seekbar.setMax(MAX_SLEEP_TIMER_MINUTES);
sleepTimerText.setText(makeTimeString(sleepTimerMode));
seekbar.setProgress(sleepTimerMode);
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
sleepTimerText.setText(makeTimeString(progress));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
return new AlertDialog.Builder(MediaPlaybackActivity.this)
.setTitle(R.string.menu_sleep_timer)
.setView(sleepTimerView)
.setCancelable(true)
.setPositiveButton(R.string.set_alarm, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
setSleepTimer(seekbar.getProgress());
dialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
removeDialog(DIALOG_SLEEP_TIMER);
}
})
.create();
default:
dialog = null;
}
return dialog;
}
| protected Dialog onCreateDialog(int id) {
Dialog dialog;
ProgressDialog progressDialog = null;
switch(id) {
case PREPARING_MEDIA:
progressDialog = new ProgressDialog(MediaPlaybackActivity.this);
progressDialog.setMessage(getString(R.string.opening_url_message));
progressDialog.setCancelable(true);
return progressDialog;
case DIALOG_SLEEP_TIMER:
dialog = null;
if (mService == null) {
break;
}
int sleepTimerMode = -1;
try {
sleepTimerMode = mService.getSleepTimerMode();
} catch (RemoteException e) {
break;
}
LayoutInflater factory = LayoutInflater.from(this);
final View sleepTimerView = factory.inflate(R.layout.alert_dialog_sleep_timer, null);
final TextView sleepTimerText = (TextView) sleepTimerView.findViewById(R.id.sleep_timer_text);
final SeekBar seekbar = (SeekBar) sleepTimerView.findViewById(R.id.seekbar);
seekbar.setMax(MAX_SLEEP_TIMER_MINUTES);
sleepTimerText.setText(makeTimeString(sleepTimerMode));
seekbar.setProgress(sleepTimerMode);
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
sleepTimerText.setText(makeTimeString(progress));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
return new AlertDialog.Builder(MediaPlaybackActivity.this)
.setTitle(R.string.menu_sleep_timer)
.setView(sleepTimerView)
.setCancelable(true)
.setPositiveButton(R.string.set_alarm, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
setSleepTimer(seekbar.getProgress());
dialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
removeDialog(DIALOG_SLEEP_TIMER);
}
})
.create();
default:
dialog = null;
}
return dialog;
}
|
diff --git a/src/minecraft/ljdp/minechem/common/recipe/MinechemRecipes.java b/src/minecraft/ljdp/minechem/common/recipe/MinechemRecipes.java
index 6d74c9f..02ecbeb 100644
--- a/src/minecraft/ljdp/minechem/common/recipe/MinechemRecipes.java
+++ b/src/minecraft/ljdp/minechem/common/recipe/MinechemRecipes.java
@@ -1,764 +1,764 @@
package ljdp.minechem.common.recipe;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import ljdp.minechem.api.core.Chemical;
import ljdp.minechem.api.core.Element;
import ljdp.minechem.api.core.EnumElement;
import ljdp.minechem.api.core.EnumMolecule;
import ljdp.minechem.api.core.Molecule;
import ljdp.minechem.api.recipe.DecomposerRecipe;
import ljdp.minechem.api.recipe.DecomposerRecipeChance;
import ljdp.minechem.api.recipe.DecomposerRecipeSelect;
import ljdp.minechem.api.recipe.SynthesisRecipe;
import ljdp.minechem.api.util.Util;
import ljdp.minechem.common.MinechemBlocks;
import ljdp.minechem.common.MinechemItems;
import ljdp.minechem.common.blueprint.MinechemBlueprint;
import ljdp.minechem.common.items.ItemElement;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.oredict.OreDictionary;
import biomesoplenty.api.BlockReferences;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.Loader;
public class MinechemRecipes {
private static final MinechemRecipes instance = new MinechemRecipes();
public ArrayList unbondingRecipes = new ArrayList();
public ArrayList synthesisRecipes = new ArrayList();
private SynthesisRecipe recipeIron;
private SynthesisRecipe recipeGold;
private SynthesisRecipe recipeCoalChunk;
public static MinechemRecipes getInstance() {
return instance;
}
public void RegisterRecipes() {
boolean isbop = Loader.isModLoaded("BiomesOPlenty");
ItemStack var1 = new ItemStack(Block.stone);
new ItemStack(Block.cobblestone);
ItemStack var3 = new ItemStack(Block.dirt);
ItemStack var4 = new ItemStack(Block.sand);
ItemStack var5 = new ItemStack(Block.gravel);
ItemStack var6 = new ItemStack(Block.glass);
ItemStack var7 = new ItemStack(Block.thinGlass);
ItemStack oreIron = new ItemStack(Block.oreIron);
ItemStack oreGold = new ItemStack(Block.oreGold);
ItemStack var10 = new ItemStack(Block.oreDiamond);
ItemStack var11 = new ItemStack(Block.oreEmerald);
ItemStack oreCoal = new ItemStack(Block.oreCoal);
ItemStack var13 = new ItemStack(Block.oreRedstone);
ItemStack var14 = new ItemStack(Block.oreLapis);
ItemStack ingotIron = new ItemStack(Item.ingotIron);
ItemStack blockIron = new ItemStack(Block.blockIron);
ItemStack var17 = new ItemStack(MinechemItems.atomicManipulator);
ItemStack var18 = new ItemStack(Item.redstone);
ItemStack var19 = new ItemStack(MinechemItems.testTube, 16);
GameRegistry.addRecipe(var19, new Object[] { " G ", " G ", " G ", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.concaveLens, new Object[] { "G G", "GGG", "G G", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.convexLens, new Object[] { " G ", "GGG", " G ", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.microscopeLens, new Object[] { "A", "B", "A", Character.valueOf('A'), MinechemItems.convexLens, Character.valueOf('B'), MinechemItems.concaveLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.microscope), new Object[] { " LI", " PI", "III", Character.valueOf('L'), MinechemItems.microscopeLens, Character.valueOf('P'), var7, Character.valueOf('I'), ingotIron });
GameRegistry.addRecipe(new ItemStack(MinechemItems.atomicManipulator), new Object[] { "PPP", "PIP", "PPP", Character.valueOf('P'), new ItemStack(Block.pistonBase), Character.valueOf('I'), blockIron });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.decomposer), new Object[] { "III", "IAI", "IRI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18 });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.synthesis), new Object[] { "IRI", "IAI", "IDI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18, Character.valueOf('D'), new ItemStack(Item.diamond) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 0), new Object[] { "ILI", "ILI", "ILI", Character.valueOf('I'), ingotIron, Character.valueOf('L'), ItemElement.createStackOf(EnumElement.Pb, 1) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 1), new Object[] { "IWI", "IBI", "IWI", Character.valueOf('I'), ingotIron, Character.valueOf('W'), ItemElement.createStackOf(EnumElement.W, 1), Character.valueOf('B'), ItemElement.createStackOf(EnumElement.Be, 1) });
GameRegistry.addRecipe(MinechemItems.projectorLens, new Object[] { "ABA", Character.valueOf('A'), MinechemItems.concaveLens, Character.valueOf('B'), MinechemItems.convexLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.blueprintProjector), new Object[] { " I ", "GPL", " I ", Character.valueOf('I'), ingotIron, Character.valueOf('P'), var7, Character.valueOf('L'), MinechemItems.projectorLens, Character.valueOf('G'), new ItemStack(Block.redstoneLampIdle) });
ItemStack var20 = new ItemStack(MinechemItems.molecule, 1, EnumMolecule.polyvinylChloride.ordinal());
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatFeet), new Object[] { " ", "P P", "P P", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatLegs), new Object[] { "PPP", "P P", "P P", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatTorso), new Object[] { " P ", "PPP", "PPP", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatHead), new Object[] { "PPP", "P P", " ", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.chemicalStorage), new Object[] { "LLL", "LCL", "LLL", Character.valueOf('L'), new ItemStack(MinechemItems.element, 1, EnumElement.Pb.ordinal()), Character.valueOf('C'), new ItemStack(Block.chest) });
GameRegistry.addRecipe(new ItemStack(MinechemItems.IAintAvinit), new Object[] { "ZZZ", "ZSZ", " S ", Character.valueOf('Z'), new ItemStack(Item.ingotIron), Character.valueOf('S'), new ItemStack(Item.stick) });
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.journal), new Object[] { new ItemStack(Item.book), new ItemStack(MinechemItems.testTube) });
for (EnumElement element : EnumElement.values()) {
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.testTube), new Object[] { new ItemStack(MinechemItems.element, element.ordinal()) });
}
GameRegistry.addRecipe(new RecipeJournalCloning());
Element var21 = this.element(EnumElement.C, 64);
// DecomposerRecipe.add(new DecomposerRecipe(var8, new
// Chemical[]{this.element(EnumElement.Fe, 4)}));
DecomposerRecipe.add(new DecomposerRecipe(oreIron, new Chemical[] { this.element(EnumElement.Fe, 32) }));
// DecomposerRecipe.add(new DecomposerRecipe(var9, new
// Chemical[]{this.element(EnumElement.Au, 4)}));
DecomposerRecipe.add(new DecomposerRecipe(oreGold, new Chemical[] { this.element(EnumElement.Au, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(var10, new Chemical[] { this.molecule(EnumMolecule.fullrene, 6) }));
DecomposerRecipe.add(new DecomposerRecipe(oreCoal, new Chemical[] { this.element(EnumElement.C, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(var11, new Chemical[] { this.molecule(EnumMolecule.beryl, 4), this.element(EnumElement.Cr, 4), this.element(EnumElement.V, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var14, new Chemical[] { this.molecule(EnumMolecule.lazurite, 4), this.molecule(EnumMolecule.sodalite), this.molecule(EnumMolecule.noselite), this.molecule(EnumMolecule.calcite), this.molecule(EnumMolecule.pyrite) }));
ItemStack ingotGold = new ItemStack(Item.ingotGold);
ItemStack var23 = new ItemStack(Item.diamond);
ItemStack var24 = new ItemStack(Item.emerald);
ItemStack chunkCoal = new ItemStack(Item.coal);
ItemStack fusionblue = new ItemStack(MinechemItems.blueprint, 1, MinechemBlueprint.fusion.id);
ItemStack fusionBlock1 = new ItemStack(MinechemBlocks.fusion, 0);
ItemStack fusionBlock2 = new ItemStack(MinechemBlocks.fusion, 1);
// DecomposerRecipe.add(new DecomposerRecipe(var15, new
// Chemical[]{this.element(EnumElement.Fe, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(ingotIron, new Chemical[] { this.element(EnumElement.Fe, 16) }));
// DecomposerRecipe.add(new DecomposerRecipe(var22, new
// Chemical[]{this.element(EnumElement.Au, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(ingotGold, new Chemical[] { this.element(EnumElement.Au, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var23, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var24, new Chemical[] { this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.Cr, 2), this.element(EnumElement.V, 2) }));
// DecomposerRecipe.add(new DecomposerRecipe(var25, new
// Chemical[]{this.element(EnumElement.C, 8)}));
DecomposerRecipe.add(new DecomposerRecipe(chunkCoal, new Chemical[] { this.element(EnumElement.C, 16) }));
// SynthesisRecipe.add(new SynthesisRecipe(var15, false, 1000, new
// Chemical[]{this.element(EnumElement.Fe, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(var22, false, 1000, new
// Chemical[]{this.element(EnumElement.Au, 2)}));
this.recipeIron = new SynthesisRecipe(ingotIron, false, 1000, new Chemical[] { this.element(EnumElement.Fe, 16) });
this.recipeGold = new SynthesisRecipe(ingotGold, false, 1000, new Chemical[] { this.element(EnumElement.Au, 16) });
SynthesisRecipe.add(recipeIron);
SynthesisRecipe.add(recipeGold);
SynthesisRecipe.add(new SynthesisRecipe(var23, true, '\uea60', new Chemical[] { null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null }));
SynthesisRecipe.add(new SynthesisRecipe(var24, true, 80000, new Chemical[] { null, this.element(EnumElement.Cr), null, this.element(EnumElement.V), this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.V), null, this.element(EnumElement.Cr), null }));
// DecomposerRecipe.add(new DecomposerRecipe(new
// ItemStack(Block.blockSteel), new
// Chemical[]{this.element(EnumElement.Fe, 18)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockIron), new Chemical[] { this.element(EnumElement.Fe, 144) }));
// DecomposerRecipe.add(new DecomposerRecipe(new
// ItemStack(Block.blockGold), new
// Chemical[]{this.element(EnumElement.Au, 18)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockGold), new Chemical[] { this.element(EnumElement.Au, 144) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockDiamond), new Chemical[] { this.molecule(EnumMolecule.fullrene, 36) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockEmerald), new Chemical[] { this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.Cr, 18), this.element(EnumElement.V, 18) }));
// SynthesisRecipe.add(new SynthesisRecipe(new
// ItemStack(Block.blockSteel), true, 5000, new
// Chemical[]{this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(new
// ItemStack(Block.blockGold), true, 5000, new
// Chemical[]{this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockDiamond), true, 120000, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockEmerald), true, 150000, new Chemical[] { this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.V, 9), this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.V, 9), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3) }));
ItemStack var26 = new ItemStack(Block.sandStone);
ItemStack var27 = new ItemStack(Item.flint);
DecomposerRecipe.add(new DecomposerRecipe(var26, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var4, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var6, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var7, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 1) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var5, 0.35F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var27, 0.5F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
Molecule var28 = this.molecule(EnumMolecule.siliconDioxide, 4);
Molecule var29 = this.molecule(EnumMolecule.siliconDioxide, 4);
SynthesisRecipe.add(new SynthesisRecipe(var6, true, 500, new Chemical[] { var28, null, var28, null, null, null, var28, null, var28 }));
SynthesisRecipe.add(new SynthesisRecipe(var4, true, 200, new Chemical[] { var28, var28, var28, var28 }));
SynthesisRecipe.add(new SynthesisRecipe(var27, true, 100, new Chemical[] { null, var29, null, var29, var29, var29, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var7, true, 50, new Chemical[] { null, null, null, this.molecule(EnumMolecule.siliconDioxide), null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var5, true, 30, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.siliconDioxide) }));
ItemStack var30 = new ItemStack(Item.feather);
DecomposerRecipe.add(new DecomposerRecipe(var30, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.N, 6) }));
SynthesisRecipe.add(new SynthesisRecipe(var30, true, 800, new Chemical[] { this.element(EnumElement.N), this.molecule(EnumMolecule.water, 2), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 1), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 5), this.element(EnumElement.N) }));
ItemStack var31 = new ItemStack(Item.arrow);
ItemStack var32 = new ItemStack(Item.paper);
ItemStack var33 = new ItemStack(Item.leather);
ItemStack var34 = new ItemStack(Item.snowball);
ItemStack var35 = new ItemStack(Item.brick);
ItemStack var36 = new ItemStack(Item.clay);
ItemStack var37 = new ItemStack(Block.mycelium);
ItemStack var38 = new ItemStack(Block.sapling, 1, -1);
DecomposerRecipe.add(new DecomposerRecipe(var31, new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O, 2), this.element(EnumElement.N, 6) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var36, 0.3F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var35, 0.5F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
DecomposerRecipe.add(new DecomposerRecipe(var34, new Chemical[] { this.molecule(EnumMolecule.water) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var37, 0.09F, new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var33, 0.5F, new Chemical[] { this.molecule(EnumMolecule.arginine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.keratin) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var38, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 1), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 2), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 3), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var32, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.clay, 12), false, 100, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.brick, 8), true, 400, new Chemical[] { this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null, this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.snowball, 5), true, 20, new Chemical[] { this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.mycelium, 16), false, 300, new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.leather, 5), true, 700, new Chemical[] { this.molecule(EnumMolecule.arginine), null, null, null, this.molecule(EnumMolecule.keratin), null, null, null, this.molecule(EnumMolecule.glycine) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 0), true, 20, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 1), true, 20, new Chemical[] { null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 2), true, 20, new Chemical[] { null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 3), true, 20, new Chemical[] { null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.paper, 16), true, 150, new Chemical[] { null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null }));
ItemStack var39 = new ItemStack(Item.slimeBall);
ItemStack var40 = new ItemStack(Item.blazeRod);
ItemStack var41 = new ItemStack(Item.blazePowder);
ItemStack var42 = new ItemStack(Item.magmaCream);
ItemStack var43 = new ItemStack(Item.ghastTear);
ItemStack var44 = new ItemStack(Item.netherStar);
ItemStack var45 = new ItemStack(Item.spiderEye);
ItemStack var46 = new ItemStack(Item.fermentedSpiderEye);
ItemStack var47 = new ItemStack(Item.netherStalkSeeds);
ItemStack var48 = new ItemStack(Block.glowStone);
ItemStack var49 = new ItemStack(Item.lightStoneDust);
ItemStack var50 = new ItemStack(Item.potion, 1, 0);
ItemStack var51 = new ItemStack(Item.bucketWater);
DecomposerRecipe.add(new DecomposerRecipeSelect(var39, 0.9F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.polycyanoacrylate) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Hg) }), new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.water, 10) }) }));
DecomposerRecipe.add(new DecomposerRecipe(var40, new Chemical[] { this.element(EnumElement.Pu, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(var41, new Chemical[] { this.element(EnumElement.Pu) }));
DecomposerRecipe.add(new DecomposerRecipe(var42, new Chemical[] { this.element(EnumElement.Hg), this.element(EnumElement.Pu), this.molecule(EnumMolecule.polycyanoacrylate, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(var43, new Chemical[] { this.element(EnumElement.Yb, 4), this.element(EnumElement.No, 4) }));
Element var52 = this.element(EnumElement.H, 64);
Element var53 = this.element(EnumElement.He, 64);
DecomposerRecipe.add(new DecomposerRecipe(var44, new Chemical[] { this.element(EnumElement.Cn, 16), var52, var52, var52, var53, var53, var53, var21, var21 }));
DecomposerRecipe.add(new DecomposerRecipeChance(var45, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ttx) }));
DecomposerRecipe.add(new DecomposerRecipe(var46, new Chemical[] { this.element(EnumElement.Po), this.molecule(EnumMolecule.ethanol) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var47, 0.5F, new Chemical[] { this.molecule(EnumMolecule.amphetamine) }));
DecomposerRecipe.add(new DecomposerRecipe(var48, new Chemical[] { this.element(EnumElement.P, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var49, new Chemical[] { this.element(EnumElement.P) }));
DecomposerRecipe.add(new DecomposerRecipe(var50, new Chemical[] { this.molecule(EnumMolecule.water, 8) }));
DecomposerRecipe.add(new DecomposerRecipe(var51, new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(var40, true, 15000, new Chemical[] { this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var42, true, 5000, new Chemical[] { null, this.element(EnumElement.Pu), null, this.molecule(EnumMolecule.polycyanoacrylate), this.element(EnumElement.Hg), this.molecule(EnumMolecule.polycyanoacrylate), null, this.molecule(EnumMolecule.polycyanoacrylate), null }));
SynthesisRecipe.add(new SynthesisRecipe(var43, true, 15000, new Chemical[] { this.element(EnumElement.Yb), this.element(EnumElement.Yb), this.element(EnumElement.No), null, this.element(EnumElement.Yb, 2), this.element(EnumElement.No, 2), null, this.element(EnumElement.No), null }));
SynthesisRecipe.add(new SynthesisRecipe(var44, true, 500000, new Chemical[] { var53, var53, var53, var21, this.element(EnumElement.Cn, 16), var53, var52, var52, var52 }));
SynthesisRecipe.add(new SynthesisRecipe(var45, true, 2000, new Chemical[] { this.element(EnumElement.C), null, null, null, this.molecule(EnumMolecule.ttx), null, null, null, this.element(EnumElement.C) }));
SynthesisRecipe.add(new SynthesisRecipe(var48, true, 500, new Chemical[] { this.element(EnumElement.P), null, this.element(EnumElement.P), this.element(EnumElement.P), null, this.element(EnumElement.P), null, null, null }));
ItemStack var54 = new ItemStack(Item.sugar);
ItemStack var55 = new ItemStack(Item.reed);
ItemStack var56 = new ItemStack(Block.pumpkin);
ItemStack var57 = new ItemStack(Block.melon);
ItemStack var58 = new ItemStack(Item.speckledMelon);
ItemStack var59 = new ItemStack(Item.melon);
ItemStack var60 = new ItemStack(Item.carrot);
ItemStack var61 = new ItemStack(Item.goldenCarrot);
ItemStack var62 = new ItemStack(Item.dyePowder, 1, 3);
ItemStack var63 = new ItemStack(Item.potato);
ItemStack var64 = new ItemStack(Item.bread);
ItemStack var65 = new ItemStack(Item.appleRed);
ItemStack var66 = new ItemStack(Item.appleGold, 1, 0);
// new ItemStack(Item.appleGold, 1, 1);
ItemStack var68 = new ItemStack(Item.chickenCooked);
DecomposerRecipe.add(new DecomposerRecipeChance(var54, 0.75F, new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var55, 0.65F, new Chemical[] { this.molecule(EnumMolecule.sucrose), this.element(EnumElement.H, 2), this.element(EnumElement.O) }));
DecomposerRecipe.add(new DecomposerRecipe(var62, new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
DecomposerRecipe.add(new DecomposerRecipe(var56, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
DecomposerRecipe.add(new DecomposerRecipe(var57, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin), this.molecule(EnumMolecule.asparticAcid), this.molecule(EnumMolecule.water, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var58, new Chemical[] { this.molecule(EnumMolecule.water, 4), this.molecule(EnumMolecule.whitePigment), this.element(EnumElement.Au, 1) }));
DecomposerRecipe.add(new DecomposerRecipe(var59, new Chemical[] { this.molecule(EnumMolecule.water) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var60, 0.05F, new Chemical[] { this.molecule(EnumMolecule.ret) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var61, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ret), this.element(EnumElement.Au, 4) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var63, 0.4F, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.K, 2), this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var64, 0.1F, new Chemical[] { this.molecule(EnumMolecule.starch), this.molecule(EnumMolecule.sucrose) }));
DecomposerRecipe.add(new DecomposerRecipe(var65, new Chemical[] { this.molecule(EnumMolecule.malicAcid) }));
DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 8) }));
DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 64), this.element(EnumElement.Np) }));
DecomposerRecipe.add(new DecomposerRecipe(var68, new Chemical[] { this.element(EnumElement.K), this.element(EnumElement.Na), this.element(EnumElement.C, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var54, false, 400, new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
SynthesisRecipe.add(new SynthesisRecipe(var65, false, 400, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.molecule(EnumMolecule.water, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var62, false, 400, new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
SynthesisRecipe.add(new SynthesisRecipe(var56, false, 400, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
SynthesisRecipe.add(new SynthesisRecipe(var68, true, 5000, new Chemical[] { this.element(EnumElement.K, 16), this.element(EnumElement.Na, 16), this.element(EnumElement.C, 16) }));
ItemStack var69 = new ItemStack(Item.gunpowder);
ItemStack var70 = new ItemStack(Block.tnt);
DecomposerRecipe.add(new DecomposerRecipe(var69, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.S, 2), this.element(EnumElement.C) }));
DecomposerRecipe.add(new DecomposerRecipe(var70, new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(var70, false, 1000, new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(var69, true, 600, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.C), null, this.element(EnumElement.S, 2), null, null, null, null, null }));
ItemStack var71 = new ItemStack(Block.wood, 1, -1);
ItemStack var72 = new ItemStack(Block.planks, 1, -1);
ItemStack var140 = new ItemStack(Block.planks, 1, 0);
ItemStack var141 = new ItemStack(Block.planks, 1, 1);
ItemStack var142 = new ItemStack(Block.planks, 1, 2);
ItemStack var143 = new ItemStack(Block.planks, 1, 3);
ItemStack var73 = new ItemStack(Item.stick);
ItemStack var74 = new ItemStack(Block.wood, 1, 0);
ItemStack var75 = new ItemStack(Block.wood, 1, 1);
ItemStack var76 = new ItemStack(Block.wood, 1, 2);
ItemStack var77 = new ItemStack(Block.wood, 1, 3);
ItemStack var78 = new ItemStack(Item.doorWood);
ItemStack var79 = new ItemStack(Block.pressurePlatePlanks, 1, -1);
DecomposerRecipe.add(new DecomposerRecipeChance(var71, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var74, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var75, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var76, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var77, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var72, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var140, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var141, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var142, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var143, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var73, 0.3F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var78, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 12) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var79, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 4) }));
Molecule var81 = this.molecule(EnumMolecule.cellulose, 1);
SynthesisRecipe.add(new SynthesisRecipe(var74, true, 100, new Chemical[] { var81, var81, var81, null, var81, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var75, true, 100, new Chemical[] { null, null, null, null, var81, null, var81, var81, var81 }));
SynthesisRecipe.add(new SynthesisRecipe(var76, true, 100, new Chemical[] { var81, null, var81, null, null, null, var81, null, var81 }));
SynthesisRecipe.add(new SynthesisRecipe(var77, true, 100, new Chemical[] { var81, null, null, var81, var81, null, var81, null, null }));
ItemStack var82 = new ItemStack(Item.dyePowder, 1, 0);
ItemStack var83 = new ItemStack(Item.dyePowder, 1, 1);
ItemStack var84 = new ItemStack(Item.dyePowder, 1, 2);
ItemStack var85 = new ItemStack(Item.dyePowder, 1, 4);
ItemStack var86 = new ItemStack(Item.dyePowder, 1, 5);
ItemStack var87 = new ItemStack(Item.dyePowder, 1, 6);
ItemStack var88 = new ItemStack(Item.dyePowder, 1, 7);
ItemStack var89 = new ItemStack(Item.dyePowder, 1, 8);
ItemStack var90 = new ItemStack(Item.dyePowder, 1, 9);
ItemStack var91 = new ItemStack(Item.dyePowder, 1, 10);
ItemStack var92 = new ItemStack(Item.dyePowder, 1, 11);
ItemStack var93 = new ItemStack(Item.dyePowder, 1, 12);
ItemStack var94 = new ItemStack(Item.dyePowder, 1, 13);
ItemStack var95 = new ItemStack(Item.dyePowder, 1, 14);
ItemStack var96 = new ItemStack(Item.dyePowder, 1, 15);
DecomposerRecipe.add(new DecomposerRecipe(var82, new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var83, new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var84, new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var85, new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipe(var86, new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var87, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var88, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var89, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(var90, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var91, new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var92, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var93, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var94, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var95, new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var96, new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var82, false, 50, new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var83, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var84, false, 50, new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var85, false, 50, new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(var86, false, 50, new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var87, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var88, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var89, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var90, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var91, false, 50, new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var92, false, 50, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var93, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var94, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var95, false, 50, new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var96, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
ItemStack var97 = new ItemStack(Block.cloth, 1, 0);
ItemStack var98 = new ItemStack(Block.cloth, 1, 1);
ItemStack var99 = new ItemStack(Block.cloth, 1, 2);
ItemStack var100 = new ItemStack(Block.cloth, 1, 3);
ItemStack var101 = new ItemStack(Block.cloth, 1, 4);
ItemStack var102 = new ItemStack(Block.cloth, 1, 5);
ItemStack var103 = new ItemStack(Block.cloth, 1, 6);
ItemStack var104 = new ItemStack(Block.cloth, 1, 7);
ItemStack var105 = new ItemStack(Block.cloth, 1, 8);
ItemStack var106 = new ItemStack(Block.cloth, 1, 9);
ItemStack var107 = new ItemStack(Block.cloth, 1, 10);
ItemStack var108 = new ItemStack(Block.cloth, 1, 11);
ItemStack var109 = new ItemStack(Block.cloth, 1, 12);
ItemStack var110 = new ItemStack(Block.cloth, 1, 13);
ItemStack var111 = new ItemStack(Block.cloth, 1, 14);
ItemStack var112 = new ItemStack(Block.cloth, 1, 15);
DecomposerRecipe.add(new DecomposerRecipeChance(var111, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var110, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var108, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var107, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var106, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var105, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var104, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var103, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var102, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var101, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var100, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var99, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var98, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var97, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var112, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var111, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var110, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var108, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(var107, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var106, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var105, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var104, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var103, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var102, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var101, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var100, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var99, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var98, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var97, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var112, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) }));
Molecule var113 = this.molecule(EnumMolecule.polyvinylChloride);
ItemStack var114 = new ItemStack(Item.record13);
ItemStack var115 = new ItemStack(Item.recordCat);
ItemStack var116 = new ItemStack(Item.recordFar);
ItemStack var117 = new ItemStack(Item.recordMall);
ItemStack var118 = new ItemStack(Item.recordMellohi);
ItemStack var119 = new ItemStack(Item.recordStal);
ItemStack var120 = new ItemStack(Item.recordStrad);
ItemStack var121 = new ItemStack(Item.recordWard);
ItemStack var122 = new ItemStack(Item.recordChirp);
DecomposerRecipe.add(new DecomposerRecipe(var114, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var115, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var116, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var117, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var118, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var119, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var120, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var121, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var122, new Chemical[] { var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var114, false, 1000, new Chemical[] { var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var115, false, 1000, new Chemical[] { null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var116, false, 1000, new Chemical[] { null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var117, false, 1000, new Chemical[] { null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var118, false, 1000, new Chemical[] { null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var119, false, 1000, new Chemical[] { null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var120, false, 1000, new Chemical[] { null, null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var121, false, 1000, new Chemical[] { null, null, null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var122, false, 1000, new Chemical[] { null, null, null, null, null, null, null, null, var113 }));
ItemStack var123 = new ItemStack(Block.mushroomBrown);
ItemStack var124 = new ItemStack(Block.mushroomRed);
ItemStack var125 = new ItemStack(Block.cactus);
DecomposerRecipe.add(new DecomposerRecipe(var123, new Chemical[] { this.molecule(EnumMolecule.psilocybin), this.molecule(EnumMolecule.water, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(var124, new Chemical[] { this.molecule(EnumMolecule.pantherine), this.molecule(EnumMolecule.water, 2), this.molecule(EnumMolecule.nicotine)}));
DecomposerRecipe.add(new DecomposerRecipe(var125, new Chemical[] { this.molecule(EnumMolecule.mescaline), this.molecule(EnumMolecule.water, 20) }));
SynthesisRecipe.add(new SynthesisRecipe(var125, true, 200, new Chemical[] { this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.mescaline), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var13, 0.8F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide, 6), this.molecule(EnumMolecule.strontiumNitrate, 6) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var18, 0.42F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide), this.molecule(EnumMolecule.strontiumNitrate) }));
SynthesisRecipe.add(new SynthesisRecipe(var18, true, 100, new Chemical[] { null, null, this.molecule(EnumMolecule.iron3oxide), null, this.molecule(EnumMolecule.strontiumNitrate), null, null, null, null }));
ItemStack var126 = new ItemStack(Item.enderPearl);
DecomposerRecipe.add(new DecomposerRecipe(var126, new Chemical[] { this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var126, true, 5000, new Chemical[] { this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate) }));
ItemStack var127 = new ItemStack(Block.obsidian);
DecomposerRecipe.add(new DecomposerRecipe(var127, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16), this.molecule(EnumMolecule.magnesiumOxide, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var127, true, 1000, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), null, this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2) }));
ItemStack var128 = new ItemStack(Item.bone);
ItemStack var129 = new ItemStack(Item.silk);
// new ItemStack(Block.cloth, 1, -1);
// new ItemStack(Block.cloth, 1, 0);
DecomposerRecipe.add(new DecomposerRecipe(var128, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var129, 0.45F, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) }));
SynthesisRecipe.add(new SynthesisRecipe(var128, false, 100, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) }));
SynthesisRecipe.add(new SynthesisRecipe(var129, true, 150, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) }));
ItemStack var132 = new ItemStack(Block.cobblestone);
DecomposerRecipe.add(new DecomposerRecipeSelect(var1, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var132, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na), this.element(EnumElement.Cl) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var3, 0.07F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.cobblestone, 8), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, null, this.element(EnumElement.O, 2), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.stone, 7), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, this.element(EnumElement.O, 2), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.dirt, 16), true, 50, new Chemical[] { null, null, null, null, this.element(EnumElement.O, 2), this.element(EnumElement.Si) }));
ItemStack var133 = new ItemStack(Block.netherrack);
ItemStack var134 = new ItemStack(Block.slowSand);
ItemStack var135 = new ItemStack(Block.whiteStone);
DecomposerRecipe.add(new DecomposerRecipeSelect(var133, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.Ni), this.element(EnumElement.Tc) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 3), this.element(EnumElement.Ti), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 1), this.element(EnumElement.W, 4), this.element(EnumElement.Cr, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 10), this.element(EnumElement.W, 1), this.element(EnumElement.Zn, 8), this.element(EnumElement.Be, 4) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var134, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 3), this.element(EnumElement.Be, 1), this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 1), this.element(EnumElement.Si, 5), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 6), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es, 1), this.element(EnumElement.O, 2) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var135, 0.8F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.H, 4), this.element(EnumElement.Li) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pu) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Nd) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.H, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Be, 8) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Li, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Rb) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) }));
ItemStack var136 = new ItemStack(Block.plantYellow);
DecomposerRecipe.add(new DecomposerRecipeChance(var136, 0.3F, new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2) }));
ItemStack var137 = new ItemStack(Item.rottenFlesh);
DecomposerRecipe.add(new DecomposerRecipeChance(var137, 0.05F, new Chemical[] { new Molecule(EnumMolecule.nod, 1) }));
ItemStack var138 = new ItemStack(Block.tallGrass, 1, 2);
DecomposerRecipe.add(new DecomposerRecipeChance(var138, 0.07F, new Chemical[] { new Molecule(EnumMolecule.biocide, 2) }));
ItemStack var139 = new ItemStack(Block.tallGrass, 1, 1);
DecomposerRecipe.add(new DecomposerRecipeChance(var139, 0.1F, new Chemical[] { new Molecule(EnumMolecule.afroman, 2) }));
if ( !isbop ) {
System.out.println("This is just a debug message! Move along!");
}
else {
System.out.println("Minechem: BOP support loaded");
ItemStack Algae = BlockReferences.getBlockItemStack("algae");
- DecomposerRecipe.add(new DecomposerRecipeChance(Algae, 0.1F, new Chemical[] { new Molecule(EnumMolecule.nod) }));
+ DecomposerRecipe.add(new DecomposerRecipeChance(Algae, 0.08F, new Chemical[] { new Molecule(EnumMolecule.nod) }));
ItemStack IndigoCap = BlockReferences.getBlockItemStack("bluemilk"); // THE BLUE ONES FUCK YOU UP BAD!
DecomposerRecipe.add(new DecomposerRecipe(IndigoCap, new Chemical[] { new Molecule(EnumMolecule.pantherine), new Molecule(EnumMolecule.psilocybin), new Molecule(EnumMolecule.blueorgodye) }));
ItemStack MagicShroom = BlockReferences.getBlockItemStack("toadstool");
DecomposerRecipe.add(new DecomposerRecipeChance(MagicShroom, 0.4F, new Chemical[] { new Molecule(EnumMolecule.psilocybin) }));
ItemStack Willowasprin = BlockReferences.getBlockItemStack("willowLog");
DecomposerRecipe.add(new DecomposerRecipeChance(Willowasprin, 0.4F, new Chemical[] { new Molecule(EnumMolecule.asprin, 2) }));
ItemStack FoxFire = BlockReferences.getBlockItemStack("glowshroom");
DecomposerRecipe.add(new DecomposerRecipeChance(FoxFire, 0.8F, new Chemical[] { new Molecule(EnumMolecule.psilocybin, 2), new Element(EnumElement.P, 4) }));
ItemStack Daisy1 = BlockReferences.getBlockItemStack("daisy");
DecomposerRecipe.add(new DecomposerRecipeChance(Daisy1, 0.3F, new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2), new Molecule(EnumMolecule.water, 2) }));
ItemStack WitherFlower = BlockReferences.getBlockItemStack("deathbloom");
DecomposerRecipe.add(new DecomposerRecipe(WitherFlower, new Chemical[] { new Molecule(EnumMolecule.poison, 4), new Molecule(EnumMolecule.water, 2) }));
}
this.addDecomposerRecipesFromMolecules();
this.addSynthesisRecipesFromMolecules();
this.addUnusedSynthesisRecipes();
this.registerPoisonRecipes(EnumMolecule.poison);
this.registerPoisonRecipes(EnumMolecule.sucrose);
this.registerPoisonRecipes(EnumMolecule.psilocybin);
this.registerPoisonRecipes(EnumMolecule.methamphetamine);
this.registerPoisonRecipes(EnumMolecule.amphetamine);
this.registerPoisonRecipes(EnumMolecule.pantherine);
this.registerPoisonRecipes(EnumMolecule.ethanol);
this.registerPoisonRecipes(EnumMolecule.penicillin);
this.registerPoisonRecipes(EnumMolecule.testosterone);
this.registerPoisonRecipes(EnumMolecule.xanax);
this.registerPoisonRecipes(EnumMolecule.mescaline);
this.registerPoisonRecipes(EnumMolecule.asprin);
this.registerPoisonRecipes(EnumMolecule.sulfuricAcid);
this.registerPoisonRecipes(EnumMolecule.ttx);
this.registerPoisonRecipes(EnumMolecule.pal2);
this.registerPoisonRecipes(EnumMolecule.nod);
this.registerPoisonRecipes(EnumMolecule.afroman);
}
private void addDecomposerRecipesFromMolecules() {
EnumMolecule[] var1 = EnumMolecule.molecules;
int var2 = var1.length;
for (int var3 = 0; var3 < var2; ++var3) {
EnumMolecule var4 = var1[var3];
ArrayList var5 = var4.components();
Chemical[] var6 = (Chemical[]) var5.toArray(new Chemical[var5.size()]);
ItemStack var7 = new ItemStack(MinechemItems.molecule, 1, var4.id());
DecomposerRecipe.add(new DecomposerRecipe(var7, var6));
}
}
private void addSynthesisRecipesFromMolecules() {
EnumMolecule[] var1 = EnumMolecule.molecules;
int var2 = var1.length;
for (int var3 = 0; var3 < var2; ++var3) {
EnumMolecule var4 = var1[var3];
ArrayList var5 = var4.components();
ItemStack var6 = new ItemStack(MinechemItems.molecule, 1, var4.id());
SynthesisRecipe.add(new SynthesisRecipe(var6, false, 50, var5));
}
}
private void addUnusedSynthesisRecipes() {
Iterator var1 = DecomposerRecipe.recipes.iterator();
while (var1.hasNext()) {
DecomposerRecipe var2 = (DecomposerRecipe) var1.next();
if (var2.getInput().getItemDamage() != -1) {
boolean var3 = false;
Iterator var4 = SynthesisRecipe.recipes.iterator();
while (true) {
if (var4.hasNext()) {
SynthesisRecipe var5 = (SynthesisRecipe) var4.next();
if (!Util.stacksAreSameKind(var5.getOutput(), var2.getInput())) {
continue;
}
var3 = true;
}
if (!var3) {
ArrayList var6 = var2.getOutputRaw();
if (var6 != null) {
SynthesisRecipe.add(new SynthesisRecipe(var2.getInput(), false, 100, var6));
}
}
break;
}
}
}
}
private ItemStack createPoisonedItemStack(Item var1, int var2, EnumMolecule var3) {
ItemStack var4 = new ItemStack(MinechemItems.molecule, 1, var3.id());
ItemStack var5 = new ItemStack(var1, 1, var2);
ItemStack var6 = new ItemStack(var1, 1, var2);
NBTTagCompound var7 = new NBTTagCompound();
var7.setBoolean("minechem.isPoisoned", true);
var7.setInteger("minechem.effectType", var3.id());
var6.setTagCompound(var7);
GameRegistry.addShapelessRecipe(var6, new Object[]{var4, var5});
return var6;
}
private void registerPoisonRecipes(EnumMolecule var1) {
this.createPoisonedItemStack(Item.appleRed, 0, var1);
this.createPoisonedItemStack(Item.porkCooked, 0, var1);
this.createPoisonedItemStack(Item.beefCooked, 0, var1);
this.createPoisonedItemStack(Item.carrot, 0, var1);
this.createPoisonedItemStack(Item.bakedPotato, 0, var1);
this.createPoisonedItemStack(Item.bread, 0, var1);
this.createPoisonedItemStack(Item.potato, 0, var1);
this.createPoisonedItemStack(Item.bucketMilk, 0, var1);
this.createPoisonedItemStack(Item.fishCooked, 0, var1);
this.createPoisonedItemStack(Item.cookie, 0, var1);
this.createPoisonedItemStack(Item.pumpkinPie, 0, var1);
}
@ForgeSubscribe
public void oreEvent(OreDictionary.OreRegisterEvent var1) {
String[] compounds = {"Aluminium","Titanium","Chrome",
"Tungsten", "Lead", "Zinc",
"Platinum", "Nickel", "Osmium",
"Iron", "Gold", "Coal",
"Copper", "Tin", "Silver",
"RefinedIron",
"Steel",
"Bronze", "Brass", "Electrum",
"Invar"};//,"Iridium"};
EnumElement[][] elements = {{EnumElement.Al}, {EnumElement.Ti}, {EnumElement.Cr},
{EnumElement.W}, {EnumElement.Pb}, {EnumElement.Zn},
{EnumElement.Pt}, {EnumElement.Ni}, {EnumElement.Os},
{EnumElement.Fe}, {EnumElement.Au}, {EnumElement.C},
{EnumElement.Cu}, {EnumElement.Sn}, {EnumElement.Ag},
{EnumElement.Fe},
{EnumElement.Fe, EnumElement.C}, //Steel
{EnumElement.Sn, EnumElement.Cu},
{EnumElement.Cu},//Bronze
{EnumElement.Zn, EnumElement.Cu}, //Brass
{EnumElement.Ag, EnumElement.Au}, //Electrum
{EnumElement.Fe, EnumElement.Ni} //Invar
};//, EnumElement.Ir
int[][] proportions = {{4},{4},{4},
{4},{4},{4},
{4},{4},{4},
{4},{4},{4},
{4},{4},{4},
{4},
{4,4},
{1,3},{1,3},{2,2},{2,1}};
String[] itemTypes = {"dustSmall", "dust", "ore" , "ingot", "block", "gear", "plate"}; //"nugget", "plate"
boolean[] craftable = {true, true, false, false, false, false, false};
int[] sizeCoeff = {1, 4, 8, 4, 36, 16, 4};
for (int i=0; i<compounds.length; i++){
for (int j=0; j<itemTypes.length; j++){
if(var1.Name.equals(itemTypes[j]+compounds[i])){
System.out.print("Adding recipe for " + itemTypes[j] + compounds[i]);
List<Chemical> _elems = new ArrayList<Chemical>();
for (int k=0; k<elements[i].length; k++){
_elems.add(this.element(elements[i][k], proportions[i][k]*sizeCoeff[j]));
}
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, _elems.toArray(new Chemical[_elems.size()])));
if(compounds[i].equals("Iron") && itemTypes[j].equals("dust")){
SynthesisRecipe.recipes.remove(recipeIron);
}
if(compounds[i].equals("Gold") && itemTypes[j].equals("dust")){
SynthesisRecipe.recipes.remove(recipeGold);
}
if(compounds[i].equals("Coal") && itemTypes[j].equals("dust")){
SynthesisRecipe.remove(new ItemStack(Item.coal));
SynthesisRecipe.remove(new ItemStack(Block.oreCoal));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.coal), true, 2000, new Chemical[]{this.element(EnumElement.C,4), null, this.element(EnumElement.C,4),
null, null, null,
this.element(EnumElement.C,4), null, this.element(EnumElement.C,4)}));
}
if (craftable[j]){
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000*sizeCoeff[j], _elems.toArray(new Chemical[_elems.size()])));
}
return;
}
}
}
// BEGIN ORE DICTONARY BULLSHIT
if(var1.Name.contains("uraniumOre")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.U, 4)}));
} else if(var1.Name.contains("uraniumIngot")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.U, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.U, 2)}));
} else if(var1.Name.contains("itemDropUranium")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.U, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.U, 2)}));
} else if(var1.Name.contains("gemApatite")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Ca, 5), this.molecule(EnumMolecule.phosphate, 4), this.element(EnumElement.Cl)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Ca, 5), this.molecule(EnumMolecule.phosphate, 4), this.element(EnumElement.Cl)}));
// } else if(var1.Name.contains("Iridium")) {
// DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Ir, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Ir, 2)}));
} else if(var1.Name.contains("Ruby")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr)}));
} else if(var1.Name.contains("Sapphire")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide, 2)}));
} else if(var1.Name.contains("plateSilicon")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Si, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Si, 2)}));
} else if(var1.Name.contains("xychoriumBlue")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Cu, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Cu, 1)}));
} else if(var1.Name.contains("xychoriumRed")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Fe, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Fe, 1)}));
} else if(var1.Name.contains("xychoriumGreen")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.V, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.V, 1)}));
} else if(var1.Name.contains("xychoriumDark")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Si, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Si, 1)}));
} else if(var1.Name.contains("xychoriumLight")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Ti, 1)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Ti, 1)}));
} else if(var1.Name.contains("ingotCobalt")) { // Tungsten - Cobalt Alloy
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Co, 2), this.element(EnumElement.W, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.Co, 2), this.element(EnumElement.W, 2)}));
} else if(var1.Name.contains("ingotArdite")) { // Tungsten - Iron - Silicon Alloy
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2)}));
} else if(var1.Name.contains("ingotManyullyn")) { // Tungsten - Iron - Silicon - Cobalt Alloy
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2), this.element(EnumElement.Co, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 7000, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2), this.element(EnumElement.Co, 2)}));
}
else if(var1.Name.contains("gemRuby")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr)}));
}
else if(var1.Name.contains("gemSapphire")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide)}));
}
else if(var1.Name.contains("gemPeridot")) {
DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.olivine)}));
SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.olivine)}));
}
// cropStingberry
}
// END
// BEGIN MISC FUNCTIONS
private Element element(EnumElement var1, int var2) {
return new Element(var1, var2);
}
private Element element(EnumElement var1) {
return new Element(var1, 1);
}
private Molecule molecule(EnumMolecule var1, int var2) {
return new Molecule(var1, var2);
}
private Molecule molecule(EnumMolecule var1) {
return new Molecule(var1, 1);
}
// END
} // EOF
| true | true | public void RegisterRecipes() {
boolean isbop = Loader.isModLoaded("BiomesOPlenty");
ItemStack var1 = new ItemStack(Block.stone);
new ItemStack(Block.cobblestone);
ItemStack var3 = new ItemStack(Block.dirt);
ItemStack var4 = new ItemStack(Block.sand);
ItemStack var5 = new ItemStack(Block.gravel);
ItemStack var6 = new ItemStack(Block.glass);
ItemStack var7 = new ItemStack(Block.thinGlass);
ItemStack oreIron = new ItemStack(Block.oreIron);
ItemStack oreGold = new ItemStack(Block.oreGold);
ItemStack var10 = new ItemStack(Block.oreDiamond);
ItemStack var11 = new ItemStack(Block.oreEmerald);
ItemStack oreCoal = new ItemStack(Block.oreCoal);
ItemStack var13 = new ItemStack(Block.oreRedstone);
ItemStack var14 = new ItemStack(Block.oreLapis);
ItemStack ingotIron = new ItemStack(Item.ingotIron);
ItemStack blockIron = new ItemStack(Block.blockIron);
ItemStack var17 = new ItemStack(MinechemItems.atomicManipulator);
ItemStack var18 = new ItemStack(Item.redstone);
ItemStack var19 = new ItemStack(MinechemItems.testTube, 16);
GameRegistry.addRecipe(var19, new Object[] { " G ", " G ", " G ", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.concaveLens, new Object[] { "G G", "GGG", "G G", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.convexLens, new Object[] { " G ", "GGG", " G ", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.microscopeLens, new Object[] { "A", "B", "A", Character.valueOf('A'), MinechemItems.convexLens, Character.valueOf('B'), MinechemItems.concaveLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.microscope), new Object[] { " LI", " PI", "III", Character.valueOf('L'), MinechemItems.microscopeLens, Character.valueOf('P'), var7, Character.valueOf('I'), ingotIron });
GameRegistry.addRecipe(new ItemStack(MinechemItems.atomicManipulator), new Object[] { "PPP", "PIP", "PPP", Character.valueOf('P'), new ItemStack(Block.pistonBase), Character.valueOf('I'), blockIron });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.decomposer), new Object[] { "III", "IAI", "IRI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18 });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.synthesis), new Object[] { "IRI", "IAI", "IDI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18, Character.valueOf('D'), new ItemStack(Item.diamond) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 0), new Object[] { "ILI", "ILI", "ILI", Character.valueOf('I'), ingotIron, Character.valueOf('L'), ItemElement.createStackOf(EnumElement.Pb, 1) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 1), new Object[] { "IWI", "IBI", "IWI", Character.valueOf('I'), ingotIron, Character.valueOf('W'), ItemElement.createStackOf(EnumElement.W, 1), Character.valueOf('B'), ItemElement.createStackOf(EnumElement.Be, 1) });
GameRegistry.addRecipe(MinechemItems.projectorLens, new Object[] { "ABA", Character.valueOf('A'), MinechemItems.concaveLens, Character.valueOf('B'), MinechemItems.convexLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.blueprintProjector), new Object[] { " I ", "GPL", " I ", Character.valueOf('I'), ingotIron, Character.valueOf('P'), var7, Character.valueOf('L'), MinechemItems.projectorLens, Character.valueOf('G'), new ItemStack(Block.redstoneLampIdle) });
ItemStack var20 = new ItemStack(MinechemItems.molecule, 1, EnumMolecule.polyvinylChloride.ordinal());
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatFeet), new Object[] { " ", "P P", "P P", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatLegs), new Object[] { "PPP", "P P", "P P", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatTorso), new Object[] { " P ", "PPP", "PPP", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatHead), new Object[] { "PPP", "P P", " ", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.chemicalStorage), new Object[] { "LLL", "LCL", "LLL", Character.valueOf('L'), new ItemStack(MinechemItems.element, 1, EnumElement.Pb.ordinal()), Character.valueOf('C'), new ItemStack(Block.chest) });
GameRegistry.addRecipe(new ItemStack(MinechemItems.IAintAvinit), new Object[] { "ZZZ", "ZSZ", " S ", Character.valueOf('Z'), new ItemStack(Item.ingotIron), Character.valueOf('S'), new ItemStack(Item.stick) });
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.journal), new Object[] { new ItemStack(Item.book), new ItemStack(MinechemItems.testTube) });
for (EnumElement element : EnumElement.values()) {
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.testTube), new Object[] { new ItemStack(MinechemItems.element, element.ordinal()) });
}
GameRegistry.addRecipe(new RecipeJournalCloning());
Element var21 = this.element(EnumElement.C, 64);
// DecomposerRecipe.add(new DecomposerRecipe(var8, new
// Chemical[]{this.element(EnumElement.Fe, 4)}));
DecomposerRecipe.add(new DecomposerRecipe(oreIron, new Chemical[] { this.element(EnumElement.Fe, 32) }));
// DecomposerRecipe.add(new DecomposerRecipe(var9, new
// Chemical[]{this.element(EnumElement.Au, 4)}));
DecomposerRecipe.add(new DecomposerRecipe(oreGold, new Chemical[] { this.element(EnumElement.Au, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(var10, new Chemical[] { this.molecule(EnumMolecule.fullrene, 6) }));
DecomposerRecipe.add(new DecomposerRecipe(oreCoal, new Chemical[] { this.element(EnumElement.C, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(var11, new Chemical[] { this.molecule(EnumMolecule.beryl, 4), this.element(EnumElement.Cr, 4), this.element(EnumElement.V, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var14, new Chemical[] { this.molecule(EnumMolecule.lazurite, 4), this.molecule(EnumMolecule.sodalite), this.molecule(EnumMolecule.noselite), this.molecule(EnumMolecule.calcite), this.molecule(EnumMolecule.pyrite) }));
ItemStack ingotGold = new ItemStack(Item.ingotGold);
ItemStack var23 = new ItemStack(Item.diamond);
ItemStack var24 = new ItemStack(Item.emerald);
ItemStack chunkCoal = new ItemStack(Item.coal);
ItemStack fusionblue = new ItemStack(MinechemItems.blueprint, 1, MinechemBlueprint.fusion.id);
ItemStack fusionBlock1 = new ItemStack(MinechemBlocks.fusion, 0);
ItemStack fusionBlock2 = new ItemStack(MinechemBlocks.fusion, 1);
// DecomposerRecipe.add(new DecomposerRecipe(var15, new
// Chemical[]{this.element(EnumElement.Fe, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(ingotIron, new Chemical[] { this.element(EnumElement.Fe, 16) }));
// DecomposerRecipe.add(new DecomposerRecipe(var22, new
// Chemical[]{this.element(EnumElement.Au, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(ingotGold, new Chemical[] { this.element(EnumElement.Au, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var23, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var24, new Chemical[] { this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.Cr, 2), this.element(EnumElement.V, 2) }));
// DecomposerRecipe.add(new DecomposerRecipe(var25, new
// Chemical[]{this.element(EnumElement.C, 8)}));
DecomposerRecipe.add(new DecomposerRecipe(chunkCoal, new Chemical[] { this.element(EnumElement.C, 16) }));
// SynthesisRecipe.add(new SynthesisRecipe(var15, false, 1000, new
// Chemical[]{this.element(EnumElement.Fe, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(var22, false, 1000, new
// Chemical[]{this.element(EnumElement.Au, 2)}));
this.recipeIron = new SynthesisRecipe(ingotIron, false, 1000, new Chemical[] { this.element(EnumElement.Fe, 16) });
this.recipeGold = new SynthesisRecipe(ingotGold, false, 1000, new Chemical[] { this.element(EnumElement.Au, 16) });
SynthesisRecipe.add(recipeIron);
SynthesisRecipe.add(recipeGold);
SynthesisRecipe.add(new SynthesisRecipe(var23, true, '\uea60', new Chemical[] { null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null }));
SynthesisRecipe.add(new SynthesisRecipe(var24, true, 80000, new Chemical[] { null, this.element(EnumElement.Cr), null, this.element(EnumElement.V), this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.V), null, this.element(EnumElement.Cr), null }));
// DecomposerRecipe.add(new DecomposerRecipe(new
// ItemStack(Block.blockSteel), new
// Chemical[]{this.element(EnumElement.Fe, 18)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockIron), new Chemical[] { this.element(EnumElement.Fe, 144) }));
// DecomposerRecipe.add(new DecomposerRecipe(new
// ItemStack(Block.blockGold), new
// Chemical[]{this.element(EnumElement.Au, 18)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockGold), new Chemical[] { this.element(EnumElement.Au, 144) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockDiamond), new Chemical[] { this.molecule(EnumMolecule.fullrene, 36) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockEmerald), new Chemical[] { this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.Cr, 18), this.element(EnumElement.V, 18) }));
// SynthesisRecipe.add(new SynthesisRecipe(new
// ItemStack(Block.blockSteel), true, 5000, new
// Chemical[]{this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(new
// ItemStack(Block.blockGold), true, 5000, new
// Chemical[]{this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockDiamond), true, 120000, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockEmerald), true, 150000, new Chemical[] { this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.V, 9), this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.V, 9), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3) }));
ItemStack var26 = new ItemStack(Block.sandStone);
ItemStack var27 = new ItemStack(Item.flint);
DecomposerRecipe.add(new DecomposerRecipe(var26, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var4, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var6, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var7, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 1) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var5, 0.35F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var27, 0.5F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
Molecule var28 = this.molecule(EnumMolecule.siliconDioxide, 4);
Molecule var29 = this.molecule(EnumMolecule.siliconDioxide, 4);
SynthesisRecipe.add(new SynthesisRecipe(var6, true, 500, new Chemical[] { var28, null, var28, null, null, null, var28, null, var28 }));
SynthesisRecipe.add(new SynthesisRecipe(var4, true, 200, new Chemical[] { var28, var28, var28, var28 }));
SynthesisRecipe.add(new SynthesisRecipe(var27, true, 100, new Chemical[] { null, var29, null, var29, var29, var29, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var7, true, 50, new Chemical[] { null, null, null, this.molecule(EnumMolecule.siliconDioxide), null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var5, true, 30, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.siliconDioxide) }));
ItemStack var30 = new ItemStack(Item.feather);
DecomposerRecipe.add(new DecomposerRecipe(var30, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.N, 6) }));
SynthesisRecipe.add(new SynthesisRecipe(var30, true, 800, new Chemical[] { this.element(EnumElement.N), this.molecule(EnumMolecule.water, 2), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 1), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 5), this.element(EnumElement.N) }));
ItemStack var31 = new ItemStack(Item.arrow);
ItemStack var32 = new ItemStack(Item.paper);
ItemStack var33 = new ItemStack(Item.leather);
ItemStack var34 = new ItemStack(Item.snowball);
ItemStack var35 = new ItemStack(Item.brick);
ItemStack var36 = new ItemStack(Item.clay);
ItemStack var37 = new ItemStack(Block.mycelium);
ItemStack var38 = new ItemStack(Block.sapling, 1, -1);
DecomposerRecipe.add(new DecomposerRecipe(var31, new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O, 2), this.element(EnumElement.N, 6) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var36, 0.3F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var35, 0.5F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
DecomposerRecipe.add(new DecomposerRecipe(var34, new Chemical[] { this.molecule(EnumMolecule.water) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var37, 0.09F, new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var33, 0.5F, new Chemical[] { this.molecule(EnumMolecule.arginine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.keratin) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var38, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 1), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 2), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 3), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var32, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.clay, 12), false, 100, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.brick, 8), true, 400, new Chemical[] { this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null, this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.snowball, 5), true, 20, new Chemical[] { this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.mycelium, 16), false, 300, new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.leather, 5), true, 700, new Chemical[] { this.molecule(EnumMolecule.arginine), null, null, null, this.molecule(EnumMolecule.keratin), null, null, null, this.molecule(EnumMolecule.glycine) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 0), true, 20, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 1), true, 20, new Chemical[] { null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 2), true, 20, new Chemical[] { null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 3), true, 20, new Chemical[] { null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.paper, 16), true, 150, new Chemical[] { null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null }));
ItemStack var39 = new ItemStack(Item.slimeBall);
ItemStack var40 = new ItemStack(Item.blazeRod);
ItemStack var41 = new ItemStack(Item.blazePowder);
ItemStack var42 = new ItemStack(Item.magmaCream);
ItemStack var43 = new ItemStack(Item.ghastTear);
ItemStack var44 = new ItemStack(Item.netherStar);
ItemStack var45 = new ItemStack(Item.spiderEye);
ItemStack var46 = new ItemStack(Item.fermentedSpiderEye);
ItemStack var47 = new ItemStack(Item.netherStalkSeeds);
ItemStack var48 = new ItemStack(Block.glowStone);
ItemStack var49 = new ItemStack(Item.lightStoneDust);
ItemStack var50 = new ItemStack(Item.potion, 1, 0);
ItemStack var51 = new ItemStack(Item.bucketWater);
DecomposerRecipe.add(new DecomposerRecipeSelect(var39, 0.9F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.polycyanoacrylate) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Hg) }), new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.water, 10) }) }));
DecomposerRecipe.add(new DecomposerRecipe(var40, new Chemical[] { this.element(EnumElement.Pu, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(var41, new Chemical[] { this.element(EnumElement.Pu) }));
DecomposerRecipe.add(new DecomposerRecipe(var42, new Chemical[] { this.element(EnumElement.Hg), this.element(EnumElement.Pu), this.molecule(EnumMolecule.polycyanoacrylate, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(var43, new Chemical[] { this.element(EnumElement.Yb, 4), this.element(EnumElement.No, 4) }));
Element var52 = this.element(EnumElement.H, 64);
Element var53 = this.element(EnumElement.He, 64);
DecomposerRecipe.add(new DecomposerRecipe(var44, new Chemical[] { this.element(EnumElement.Cn, 16), var52, var52, var52, var53, var53, var53, var21, var21 }));
DecomposerRecipe.add(new DecomposerRecipeChance(var45, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ttx) }));
DecomposerRecipe.add(new DecomposerRecipe(var46, new Chemical[] { this.element(EnumElement.Po), this.molecule(EnumMolecule.ethanol) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var47, 0.5F, new Chemical[] { this.molecule(EnumMolecule.amphetamine) }));
DecomposerRecipe.add(new DecomposerRecipe(var48, new Chemical[] { this.element(EnumElement.P, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var49, new Chemical[] { this.element(EnumElement.P) }));
DecomposerRecipe.add(new DecomposerRecipe(var50, new Chemical[] { this.molecule(EnumMolecule.water, 8) }));
DecomposerRecipe.add(new DecomposerRecipe(var51, new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(var40, true, 15000, new Chemical[] { this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var42, true, 5000, new Chemical[] { null, this.element(EnumElement.Pu), null, this.molecule(EnumMolecule.polycyanoacrylate), this.element(EnumElement.Hg), this.molecule(EnumMolecule.polycyanoacrylate), null, this.molecule(EnumMolecule.polycyanoacrylate), null }));
SynthesisRecipe.add(new SynthesisRecipe(var43, true, 15000, new Chemical[] { this.element(EnumElement.Yb), this.element(EnumElement.Yb), this.element(EnumElement.No), null, this.element(EnumElement.Yb, 2), this.element(EnumElement.No, 2), null, this.element(EnumElement.No), null }));
SynthesisRecipe.add(new SynthesisRecipe(var44, true, 500000, new Chemical[] { var53, var53, var53, var21, this.element(EnumElement.Cn, 16), var53, var52, var52, var52 }));
SynthesisRecipe.add(new SynthesisRecipe(var45, true, 2000, new Chemical[] { this.element(EnumElement.C), null, null, null, this.molecule(EnumMolecule.ttx), null, null, null, this.element(EnumElement.C) }));
SynthesisRecipe.add(new SynthesisRecipe(var48, true, 500, new Chemical[] { this.element(EnumElement.P), null, this.element(EnumElement.P), this.element(EnumElement.P), null, this.element(EnumElement.P), null, null, null }));
ItemStack var54 = new ItemStack(Item.sugar);
ItemStack var55 = new ItemStack(Item.reed);
ItemStack var56 = new ItemStack(Block.pumpkin);
ItemStack var57 = new ItemStack(Block.melon);
ItemStack var58 = new ItemStack(Item.speckledMelon);
ItemStack var59 = new ItemStack(Item.melon);
ItemStack var60 = new ItemStack(Item.carrot);
ItemStack var61 = new ItemStack(Item.goldenCarrot);
ItemStack var62 = new ItemStack(Item.dyePowder, 1, 3);
ItemStack var63 = new ItemStack(Item.potato);
ItemStack var64 = new ItemStack(Item.bread);
ItemStack var65 = new ItemStack(Item.appleRed);
ItemStack var66 = new ItemStack(Item.appleGold, 1, 0);
// new ItemStack(Item.appleGold, 1, 1);
ItemStack var68 = new ItemStack(Item.chickenCooked);
DecomposerRecipe.add(new DecomposerRecipeChance(var54, 0.75F, new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var55, 0.65F, new Chemical[] { this.molecule(EnumMolecule.sucrose), this.element(EnumElement.H, 2), this.element(EnumElement.O) }));
DecomposerRecipe.add(new DecomposerRecipe(var62, new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
DecomposerRecipe.add(new DecomposerRecipe(var56, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
DecomposerRecipe.add(new DecomposerRecipe(var57, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin), this.molecule(EnumMolecule.asparticAcid), this.molecule(EnumMolecule.water, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var58, new Chemical[] { this.molecule(EnumMolecule.water, 4), this.molecule(EnumMolecule.whitePigment), this.element(EnumElement.Au, 1) }));
DecomposerRecipe.add(new DecomposerRecipe(var59, new Chemical[] { this.molecule(EnumMolecule.water) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var60, 0.05F, new Chemical[] { this.molecule(EnumMolecule.ret) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var61, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ret), this.element(EnumElement.Au, 4) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var63, 0.4F, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.K, 2), this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var64, 0.1F, new Chemical[] { this.molecule(EnumMolecule.starch), this.molecule(EnumMolecule.sucrose) }));
DecomposerRecipe.add(new DecomposerRecipe(var65, new Chemical[] { this.molecule(EnumMolecule.malicAcid) }));
DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 8) }));
DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 64), this.element(EnumElement.Np) }));
DecomposerRecipe.add(new DecomposerRecipe(var68, new Chemical[] { this.element(EnumElement.K), this.element(EnumElement.Na), this.element(EnumElement.C, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var54, false, 400, new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
SynthesisRecipe.add(new SynthesisRecipe(var65, false, 400, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.molecule(EnumMolecule.water, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var62, false, 400, new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
SynthesisRecipe.add(new SynthesisRecipe(var56, false, 400, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
SynthesisRecipe.add(new SynthesisRecipe(var68, true, 5000, new Chemical[] { this.element(EnumElement.K, 16), this.element(EnumElement.Na, 16), this.element(EnumElement.C, 16) }));
ItemStack var69 = new ItemStack(Item.gunpowder);
ItemStack var70 = new ItemStack(Block.tnt);
DecomposerRecipe.add(new DecomposerRecipe(var69, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.S, 2), this.element(EnumElement.C) }));
DecomposerRecipe.add(new DecomposerRecipe(var70, new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(var70, false, 1000, new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(var69, true, 600, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.C), null, this.element(EnumElement.S, 2), null, null, null, null, null }));
ItemStack var71 = new ItemStack(Block.wood, 1, -1);
ItemStack var72 = new ItemStack(Block.planks, 1, -1);
ItemStack var140 = new ItemStack(Block.planks, 1, 0);
ItemStack var141 = new ItemStack(Block.planks, 1, 1);
ItemStack var142 = new ItemStack(Block.planks, 1, 2);
ItemStack var143 = new ItemStack(Block.planks, 1, 3);
ItemStack var73 = new ItemStack(Item.stick);
ItemStack var74 = new ItemStack(Block.wood, 1, 0);
ItemStack var75 = new ItemStack(Block.wood, 1, 1);
ItemStack var76 = new ItemStack(Block.wood, 1, 2);
ItemStack var77 = new ItemStack(Block.wood, 1, 3);
ItemStack var78 = new ItemStack(Item.doorWood);
ItemStack var79 = new ItemStack(Block.pressurePlatePlanks, 1, -1);
DecomposerRecipe.add(new DecomposerRecipeChance(var71, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var74, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var75, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var76, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var77, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var72, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var140, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var141, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var142, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var143, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var73, 0.3F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var78, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 12) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var79, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 4) }));
Molecule var81 = this.molecule(EnumMolecule.cellulose, 1);
SynthesisRecipe.add(new SynthesisRecipe(var74, true, 100, new Chemical[] { var81, var81, var81, null, var81, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var75, true, 100, new Chemical[] { null, null, null, null, var81, null, var81, var81, var81 }));
SynthesisRecipe.add(new SynthesisRecipe(var76, true, 100, new Chemical[] { var81, null, var81, null, null, null, var81, null, var81 }));
SynthesisRecipe.add(new SynthesisRecipe(var77, true, 100, new Chemical[] { var81, null, null, var81, var81, null, var81, null, null }));
ItemStack var82 = new ItemStack(Item.dyePowder, 1, 0);
ItemStack var83 = new ItemStack(Item.dyePowder, 1, 1);
ItemStack var84 = new ItemStack(Item.dyePowder, 1, 2);
ItemStack var85 = new ItemStack(Item.dyePowder, 1, 4);
ItemStack var86 = new ItemStack(Item.dyePowder, 1, 5);
ItemStack var87 = new ItemStack(Item.dyePowder, 1, 6);
ItemStack var88 = new ItemStack(Item.dyePowder, 1, 7);
ItemStack var89 = new ItemStack(Item.dyePowder, 1, 8);
ItemStack var90 = new ItemStack(Item.dyePowder, 1, 9);
ItemStack var91 = new ItemStack(Item.dyePowder, 1, 10);
ItemStack var92 = new ItemStack(Item.dyePowder, 1, 11);
ItemStack var93 = new ItemStack(Item.dyePowder, 1, 12);
ItemStack var94 = new ItemStack(Item.dyePowder, 1, 13);
ItemStack var95 = new ItemStack(Item.dyePowder, 1, 14);
ItemStack var96 = new ItemStack(Item.dyePowder, 1, 15);
DecomposerRecipe.add(new DecomposerRecipe(var82, new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var83, new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var84, new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var85, new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipe(var86, new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var87, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var88, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var89, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(var90, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var91, new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var92, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var93, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var94, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var95, new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var96, new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var82, false, 50, new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var83, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var84, false, 50, new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var85, false, 50, new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(var86, false, 50, new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var87, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var88, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var89, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var90, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var91, false, 50, new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var92, false, 50, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var93, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var94, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var95, false, 50, new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var96, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
ItemStack var97 = new ItemStack(Block.cloth, 1, 0);
ItemStack var98 = new ItemStack(Block.cloth, 1, 1);
ItemStack var99 = new ItemStack(Block.cloth, 1, 2);
ItemStack var100 = new ItemStack(Block.cloth, 1, 3);
ItemStack var101 = new ItemStack(Block.cloth, 1, 4);
ItemStack var102 = new ItemStack(Block.cloth, 1, 5);
ItemStack var103 = new ItemStack(Block.cloth, 1, 6);
ItemStack var104 = new ItemStack(Block.cloth, 1, 7);
ItemStack var105 = new ItemStack(Block.cloth, 1, 8);
ItemStack var106 = new ItemStack(Block.cloth, 1, 9);
ItemStack var107 = new ItemStack(Block.cloth, 1, 10);
ItemStack var108 = new ItemStack(Block.cloth, 1, 11);
ItemStack var109 = new ItemStack(Block.cloth, 1, 12);
ItemStack var110 = new ItemStack(Block.cloth, 1, 13);
ItemStack var111 = new ItemStack(Block.cloth, 1, 14);
ItemStack var112 = new ItemStack(Block.cloth, 1, 15);
DecomposerRecipe.add(new DecomposerRecipeChance(var111, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var110, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var108, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var107, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var106, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var105, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var104, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var103, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var102, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var101, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var100, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var99, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var98, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var97, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var112, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var111, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var110, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var108, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(var107, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var106, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var105, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var104, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var103, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var102, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var101, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var100, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var99, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var98, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var97, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var112, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) }));
Molecule var113 = this.molecule(EnumMolecule.polyvinylChloride);
ItemStack var114 = new ItemStack(Item.record13);
ItemStack var115 = new ItemStack(Item.recordCat);
ItemStack var116 = new ItemStack(Item.recordFar);
ItemStack var117 = new ItemStack(Item.recordMall);
ItemStack var118 = new ItemStack(Item.recordMellohi);
ItemStack var119 = new ItemStack(Item.recordStal);
ItemStack var120 = new ItemStack(Item.recordStrad);
ItemStack var121 = new ItemStack(Item.recordWard);
ItemStack var122 = new ItemStack(Item.recordChirp);
DecomposerRecipe.add(new DecomposerRecipe(var114, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var115, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var116, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var117, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var118, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var119, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var120, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var121, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var122, new Chemical[] { var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var114, false, 1000, new Chemical[] { var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var115, false, 1000, new Chemical[] { null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var116, false, 1000, new Chemical[] { null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var117, false, 1000, new Chemical[] { null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var118, false, 1000, new Chemical[] { null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var119, false, 1000, new Chemical[] { null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var120, false, 1000, new Chemical[] { null, null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var121, false, 1000, new Chemical[] { null, null, null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var122, false, 1000, new Chemical[] { null, null, null, null, null, null, null, null, var113 }));
ItemStack var123 = new ItemStack(Block.mushroomBrown);
ItemStack var124 = new ItemStack(Block.mushroomRed);
ItemStack var125 = new ItemStack(Block.cactus);
DecomposerRecipe.add(new DecomposerRecipe(var123, new Chemical[] { this.molecule(EnumMolecule.psilocybin), this.molecule(EnumMolecule.water, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(var124, new Chemical[] { this.molecule(EnumMolecule.pantherine), this.molecule(EnumMolecule.water, 2), this.molecule(EnumMolecule.nicotine)}));
DecomposerRecipe.add(new DecomposerRecipe(var125, new Chemical[] { this.molecule(EnumMolecule.mescaline), this.molecule(EnumMolecule.water, 20) }));
SynthesisRecipe.add(new SynthesisRecipe(var125, true, 200, new Chemical[] { this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.mescaline), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var13, 0.8F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide, 6), this.molecule(EnumMolecule.strontiumNitrate, 6) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var18, 0.42F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide), this.molecule(EnumMolecule.strontiumNitrate) }));
SynthesisRecipe.add(new SynthesisRecipe(var18, true, 100, new Chemical[] { null, null, this.molecule(EnumMolecule.iron3oxide), null, this.molecule(EnumMolecule.strontiumNitrate), null, null, null, null }));
ItemStack var126 = new ItemStack(Item.enderPearl);
DecomposerRecipe.add(new DecomposerRecipe(var126, new Chemical[] { this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var126, true, 5000, new Chemical[] { this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate) }));
ItemStack var127 = new ItemStack(Block.obsidian);
DecomposerRecipe.add(new DecomposerRecipe(var127, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16), this.molecule(EnumMolecule.magnesiumOxide, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var127, true, 1000, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), null, this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2) }));
ItemStack var128 = new ItemStack(Item.bone);
ItemStack var129 = new ItemStack(Item.silk);
// new ItemStack(Block.cloth, 1, -1);
// new ItemStack(Block.cloth, 1, 0);
DecomposerRecipe.add(new DecomposerRecipe(var128, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var129, 0.45F, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) }));
SynthesisRecipe.add(new SynthesisRecipe(var128, false, 100, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) }));
SynthesisRecipe.add(new SynthesisRecipe(var129, true, 150, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) }));
ItemStack var132 = new ItemStack(Block.cobblestone);
DecomposerRecipe.add(new DecomposerRecipeSelect(var1, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var132, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na), this.element(EnumElement.Cl) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var3, 0.07F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.cobblestone, 8), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, null, this.element(EnumElement.O, 2), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.stone, 7), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, this.element(EnumElement.O, 2), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.dirt, 16), true, 50, new Chemical[] { null, null, null, null, this.element(EnumElement.O, 2), this.element(EnumElement.Si) }));
ItemStack var133 = new ItemStack(Block.netherrack);
ItemStack var134 = new ItemStack(Block.slowSand);
ItemStack var135 = new ItemStack(Block.whiteStone);
DecomposerRecipe.add(new DecomposerRecipeSelect(var133, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.Ni), this.element(EnumElement.Tc) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 3), this.element(EnumElement.Ti), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 1), this.element(EnumElement.W, 4), this.element(EnumElement.Cr, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 10), this.element(EnumElement.W, 1), this.element(EnumElement.Zn, 8), this.element(EnumElement.Be, 4) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var134, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 3), this.element(EnumElement.Be, 1), this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 1), this.element(EnumElement.Si, 5), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 6), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es, 1), this.element(EnumElement.O, 2) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var135, 0.8F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.H, 4), this.element(EnumElement.Li) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pu) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Nd) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.H, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Be, 8) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Li, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Rb) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) }));
ItemStack var136 = new ItemStack(Block.plantYellow);
DecomposerRecipe.add(new DecomposerRecipeChance(var136, 0.3F, new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2) }));
ItemStack var137 = new ItemStack(Item.rottenFlesh);
DecomposerRecipe.add(new DecomposerRecipeChance(var137, 0.05F, new Chemical[] { new Molecule(EnumMolecule.nod, 1) }));
ItemStack var138 = new ItemStack(Block.tallGrass, 1, 2);
DecomposerRecipe.add(new DecomposerRecipeChance(var138, 0.07F, new Chemical[] { new Molecule(EnumMolecule.biocide, 2) }));
ItemStack var139 = new ItemStack(Block.tallGrass, 1, 1);
DecomposerRecipe.add(new DecomposerRecipeChance(var139, 0.1F, new Chemical[] { new Molecule(EnumMolecule.afroman, 2) }));
if ( !isbop ) {
System.out.println("This is just a debug message! Move along!");
}
else {
System.out.println("Minechem: BOP support loaded");
ItemStack Algae = BlockReferences.getBlockItemStack("algae");
DecomposerRecipe.add(new DecomposerRecipeChance(Algae, 0.1F, new Chemical[] { new Molecule(EnumMolecule.nod) }));
ItemStack IndigoCap = BlockReferences.getBlockItemStack("bluemilk"); // THE BLUE ONES FUCK YOU UP BAD!
DecomposerRecipe.add(new DecomposerRecipe(IndigoCap, new Chemical[] { new Molecule(EnumMolecule.pantherine), new Molecule(EnumMolecule.psilocybin), new Molecule(EnumMolecule.blueorgodye) }));
ItemStack MagicShroom = BlockReferences.getBlockItemStack("toadstool");
DecomposerRecipe.add(new DecomposerRecipeChance(MagicShroom, 0.4F, new Chemical[] { new Molecule(EnumMolecule.psilocybin) }));
ItemStack Willowasprin = BlockReferences.getBlockItemStack("willowLog");
DecomposerRecipe.add(new DecomposerRecipeChance(Willowasprin, 0.4F, new Chemical[] { new Molecule(EnumMolecule.asprin, 2) }));
ItemStack FoxFire = BlockReferences.getBlockItemStack("glowshroom");
DecomposerRecipe.add(new DecomposerRecipeChance(FoxFire, 0.8F, new Chemical[] { new Molecule(EnumMolecule.psilocybin, 2), new Element(EnumElement.P, 4) }));
ItemStack Daisy1 = BlockReferences.getBlockItemStack("daisy");
DecomposerRecipe.add(new DecomposerRecipeChance(Daisy1, 0.3F, new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2), new Molecule(EnumMolecule.water, 2) }));
ItemStack WitherFlower = BlockReferences.getBlockItemStack("deathbloom");
DecomposerRecipe.add(new DecomposerRecipe(WitherFlower, new Chemical[] { new Molecule(EnumMolecule.poison, 4), new Molecule(EnumMolecule.water, 2) }));
}
this.addDecomposerRecipesFromMolecules();
this.addSynthesisRecipesFromMolecules();
this.addUnusedSynthesisRecipes();
this.registerPoisonRecipes(EnumMolecule.poison);
this.registerPoisonRecipes(EnumMolecule.sucrose);
this.registerPoisonRecipes(EnumMolecule.psilocybin);
this.registerPoisonRecipes(EnumMolecule.methamphetamine);
this.registerPoisonRecipes(EnumMolecule.amphetamine);
this.registerPoisonRecipes(EnumMolecule.pantherine);
this.registerPoisonRecipes(EnumMolecule.ethanol);
this.registerPoisonRecipes(EnumMolecule.penicillin);
this.registerPoisonRecipes(EnumMolecule.testosterone);
this.registerPoisonRecipes(EnumMolecule.xanax);
this.registerPoisonRecipes(EnumMolecule.mescaline);
this.registerPoisonRecipes(EnumMolecule.asprin);
this.registerPoisonRecipes(EnumMolecule.sulfuricAcid);
this.registerPoisonRecipes(EnumMolecule.ttx);
this.registerPoisonRecipes(EnumMolecule.pal2);
this.registerPoisonRecipes(EnumMolecule.nod);
this.registerPoisonRecipes(EnumMolecule.afroman);
}
| public void RegisterRecipes() {
boolean isbop = Loader.isModLoaded("BiomesOPlenty");
ItemStack var1 = new ItemStack(Block.stone);
new ItemStack(Block.cobblestone);
ItemStack var3 = new ItemStack(Block.dirt);
ItemStack var4 = new ItemStack(Block.sand);
ItemStack var5 = new ItemStack(Block.gravel);
ItemStack var6 = new ItemStack(Block.glass);
ItemStack var7 = new ItemStack(Block.thinGlass);
ItemStack oreIron = new ItemStack(Block.oreIron);
ItemStack oreGold = new ItemStack(Block.oreGold);
ItemStack var10 = new ItemStack(Block.oreDiamond);
ItemStack var11 = new ItemStack(Block.oreEmerald);
ItemStack oreCoal = new ItemStack(Block.oreCoal);
ItemStack var13 = new ItemStack(Block.oreRedstone);
ItemStack var14 = new ItemStack(Block.oreLapis);
ItemStack ingotIron = new ItemStack(Item.ingotIron);
ItemStack blockIron = new ItemStack(Block.blockIron);
ItemStack var17 = new ItemStack(MinechemItems.atomicManipulator);
ItemStack var18 = new ItemStack(Item.redstone);
ItemStack var19 = new ItemStack(MinechemItems.testTube, 16);
GameRegistry.addRecipe(var19, new Object[] { " G ", " G ", " G ", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.concaveLens, new Object[] { "G G", "GGG", "G G", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.convexLens, new Object[] { " G ", "GGG", " G ", Character.valueOf('G'), var6 });
GameRegistry.addRecipe(MinechemItems.microscopeLens, new Object[] { "A", "B", "A", Character.valueOf('A'), MinechemItems.convexLens, Character.valueOf('B'), MinechemItems.concaveLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.microscope), new Object[] { " LI", " PI", "III", Character.valueOf('L'), MinechemItems.microscopeLens, Character.valueOf('P'), var7, Character.valueOf('I'), ingotIron });
GameRegistry.addRecipe(new ItemStack(MinechemItems.atomicManipulator), new Object[] { "PPP", "PIP", "PPP", Character.valueOf('P'), new ItemStack(Block.pistonBase), Character.valueOf('I'), blockIron });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.decomposer), new Object[] { "III", "IAI", "IRI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18 });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.synthesis), new Object[] { "IRI", "IAI", "IDI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18, Character.valueOf('D'), new ItemStack(Item.diamond) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 0), new Object[] { "ILI", "ILI", "ILI", Character.valueOf('I'), ingotIron, Character.valueOf('L'), ItemElement.createStackOf(EnumElement.Pb, 1) });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 1), new Object[] { "IWI", "IBI", "IWI", Character.valueOf('I'), ingotIron, Character.valueOf('W'), ItemElement.createStackOf(EnumElement.W, 1), Character.valueOf('B'), ItemElement.createStackOf(EnumElement.Be, 1) });
GameRegistry.addRecipe(MinechemItems.projectorLens, new Object[] { "ABA", Character.valueOf('A'), MinechemItems.concaveLens, Character.valueOf('B'), MinechemItems.convexLens });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.blueprintProjector), new Object[] { " I ", "GPL", " I ", Character.valueOf('I'), ingotIron, Character.valueOf('P'), var7, Character.valueOf('L'), MinechemItems.projectorLens, Character.valueOf('G'), new ItemStack(Block.redstoneLampIdle) });
ItemStack var20 = new ItemStack(MinechemItems.molecule, 1, EnumMolecule.polyvinylChloride.ordinal());
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatFeet), new Object[] { " ", "P P", "P P", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatLegs), new Object[] { "PPP", "P P", "P P", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatTorso), new Object[] { " P ", "PPP", "PPP", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatHead), new Object[] { "PPP", "P P", " ", Character.valueOf('P'), var20 });
GameRegistry.addRecipe(new ItemStack(MinechemBlocks.chemicalStorage), new Object[] { "LLL", "LCL", "LLL", Character.valueOf('L'), new ItemStack(MinechemItems.element, 1, EnumElement.Pb.ordinal()), Character.valueOf('C'), new ItemStack(Block.chest) });
GameRegistry.addRecipe(new ItemStack(MinechemItems.IAintAvinit), new Object[] { "ZZZ", "ZSZ", " S ", Character.valueOf('Z'), new ItemStack(Item.ingotIron), Character.valueOf('S'), new ItemStack(Item.stick) });
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.journal), new Object[] { new ItemStack(Item.book), new ItemStack(MinechemItems.testTube) });
for (EnumElement element : EnumElement.values()) {
GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.testTube), new Object[] { new ItemStack(MinechemItems.element, element.ordinal()) });
}
GameRegistry.addRecipe(new RecipeJournalCloning());
Element var21 = this.element(EnumElement.C, 64);
// DecomposerRecipe.add(new DecomposerRecipe(var8, new
// Chemical[]{this.element(EnumElement.Fe, 4)}));
DecomposerRecipe.add(new DecomposerRecipe(oreIron, new Chemical[] { this.element(EnumElement.Fe, 32) }));
// DecomposerRecipe.add(new DecomposerRecipe(var9, new
// Chemical[]{this.element(EnumElement.Au, 4)}));
DecomposerRecipe.add(new DecomposerRecipe(oreGold, new Chemical[] { this.element(EnumElement.Au, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(var10, new Chemical[] { this.molecule(EnumMolecule.fullrene, 6) }));
DecomposerRecipe.add(new DecomposerRecipe(oreCoal, new Chemical[] { this.element(EnumElement.C, 32) }));
DecomposerRecipe.add(new DecomposerRecipe(var11, new Chemical[] { this.molecule(EnumMolecule.beryl, 4), this.element(EnumElement.Cr, 4), this.element(EnumElement.V, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var14, new Chemical[] { this.molecule(EnumMolecule.lazurite, 4), this.molecule(EnumMolecule.sodalite), this.molecule(EnumMolecule.noselite), this.molecule(EnumMolecule.calcite), this.molecule(EnumMolecule.pyrite) }));
ItemStack ingotGold = new ItemStack(Item.ingotGold);
ItemStack var23 = new ItemStack(Item.diamond);
ItemStack var24 = new ItemStack(Item.emerald);
ItemStack chunkCoal = new ItemStack(Item.coal);
ItemStack fusionblue = new ItemStack(MinechemItems.blueprint, 1, MinechemBlueprint.fusion.id);
ItemStack fusionBlock1 = new ItemStack(MinechemBlocks.fusion, 0);
ItemStack fusionBlock2 = new ItemStack(MinechemBlocks.fusion, 1);
// DecomposerRecipe.add(new DecomposerRecipe(var15, new
// Chemical[]{this.element(EnumElement.Fe, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(ingotIron, new Chemical[] { this.element(EnumElement.Fe, 16) }));
// DecomposerRecipe.add(new DecomposerRecipe(var22, new
// Chemical[]{this.element(EnumElement.Au, 2)}));
DecomposerRecipe.add(new DecomposerRecipe(ingotGold, new Chemical[] { this.element(EnumElement.Au, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var23, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var24, new Chemical[] { this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.Cr, 2), this.element(EnumElement.V, 2) }));
// DecomposerRecipe.add(new DecomposerRecipe(var25, new
// Chemical[]{this.element(EnumElement.C, 8)}));
DecomposerRecipe.add(new DecomposerRecipe(chunkCoal, new Chemical[] { this.element(EnumElement.C, 16) }));
// SynthesisRecipe.add(new SynthesisRecipe(var15, false, 1000, new
// Chemical[]{this.element(EnumElement.Fe, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(var22, false, 1000, new
// Chemical[]{this.element(EnumElement.Au, 2)}));
this.recipeIron = new SynthesisRecipe(ingotIron, false, 1000, new Chemical[] { this.element(EnumElement.Fe, 16) });
this.recipeGold = new SynthesisRecipe(ingotGold, false, 1000, new Chemical[] { this.element(EnumElement.Au, 16) });
SynthesisRecipe.add(recipeIron);
SynthesisRecipe.add(recipeGold);
SynthesisRecipe.add(new SynthesisRecipe(var23, true, '\uea60', new Chemical[] { null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null }));
SynthesisRecipe.add(new SynthesisRecipe(var24, true, 80000, new Chemical[] { null, this.element(EnumElement.Cr), null, this.element(EnumElement.V), this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.V), null, this.element(EnumElement.Cr), null }));
// DecomposerRecipe.add(new DecomposerRecipe(new
// ItemStack(Block.blockSteel), new
// Chemical[]{this.element(EnumElement.Fe, 18)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockIron), new Chemical[] { this.element(EnumElement.Fe, 144) }));
// DecomposerRecipe.add(new DecomposerRecipe(new
// ItemStack(Block.blockGold), new
// Chemical[]{this.element(EnumElement.Au, 18)}));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockGold), new Chemical[] { this.element(EnumElement.Au, 144) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockDiamond), new Chemical[] { this.molecule(EnumMolecule.fullrene, 36) }));
DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockEmerald), new Chemical[] { this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.Cr, 18), this.element(EnumElement.V, 18) }));
// SynthesisRecipe.add(new SynthesisRecipe(new
// ItemStack(Block.blockSteel), true, 5000, new
// Chemical[]{this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2),
// this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2)}));
// SynthesisRecipe.add(new SynthesisRecipe(new
// ItemStack(Block.blockGold), true, 5000, new
// Chemical[]{this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2),
// this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2)}));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockDiamond), true, 120000, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockEmerald), true, 150000, new Chemical[] { this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.V, 9), this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.V, 9), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3) }));
ItemStack var26 = new ItemStack(Block.sandStone);
ItemStack var27 = new ItemStack(Item.flint);
DecomposerRecipe.add(new DecomposerRecipe(var26, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var4, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var6, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var7, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 1) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var5, 0.35F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var27, 0.5F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) }));
Molecule var28 = this.molecule(EnumMolecule.siliconDioxide, 4);
Molecule var29 = this.molecule(EnumMolecule.siliconDioxide, 4);
SynthesisRecipe.add(new SynthesisRecipe(var6, true, 500, new Chemical[] { var28, null, var28, null, null, null, var28, null, var28 }));
SynthesisRecipe.add(new SynthesisRecipe(var4, true, 200, new Chemical[] { var28, var28, var28, var28 }));
SynthesisRecipe.add(new SynthesisRecipe(var27, true, 100, new Chemical[] { null, var29, null, var29, var29, var29, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var7, true, 50, new Chemical[] { null, null, null, this.molecule(EnumMolecule.siliconDioxide), null, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var5, true, 30, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.siliconDioxide) }));
ItemStack var30 = new ItemStack(Item.feather);
DecomposerRecipe.add(new DecomposerRecipe(var30, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.N, 6) }));
SynthesisRecipe.add(new SynthesisRecipe(var30, true, 800, new Chemical[] { this.element(EnumElement.N), this.molecule(EnumMolecule.water, 2), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 1), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 5), this.element(EnumElement.N) }));
ItemStack var31 = new ItemStack(Item.arrow);
ItemStack var32 = new ItemStack(Item.paper);
ItemStack var33 = new ItemStack(Item.leather);
ItemStack var34 = new ItemStack(Item.snowball);
ItemStack var35 = new ItemStack(Item.brick);
ItemStack var36 = new ItemStack(Item.clay);
ItemStack var37 = new ItemStack(Block.mycelium);
ItemStack var38 = new ItemStack(Block.sapling, 1, -1);
DecomposerRecipe.add(new DecomposerRecipe(var31, new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O, 2), this.element(EnumElement.N, 6) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var36, 0.3F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var35, 0.5F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
DecomposerRecipe.add(new DecomposerRecipe(var34, new Chemical[] { this.molecule(EnumMolecule.water) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var37, 0.09F, new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var33, 0.5F, new Chemical[] { this.molecule(EnumMolecule.arginine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.keratin) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var38, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 1), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 2), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 3), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var32, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.clay, 12), false, 100, new Chemical[] { this.molecule(EnumMolecule.kaolinite) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.brick, 8), true, 400, new Chemical[] { this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null, this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.snowball, 5), true, 20, new Chemical[] { this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.mycelium, 16), false, 300, new Chemical[] { this.molecule(EnumMolecule.fingolimod) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.leather, 5), true, 700, new Chemical[] { this.molecule(EnumMolecule.arginine), null, null, null, this.molecule(EnumMolecule.keratin), null, null, null, this.molecule(EnumMolecule.glycine) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 0), true, 20, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 1), true, 20, new Chemical[] { null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 2), true, 20, new Chemical[] { null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 3), true, 20, new Chemical[] { null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.paper, 16), true, 150, new Chemical[] { null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null }));
ItemStack var39 = new ItemStack(Item.slimeBall);
ItemStack var40 = new ItemStack(Item.blazeRod);
ItemStack var41 = new ItemStack(Item.blazePowder);
ItemStack var42 = new ItemStack(Item.magmaCream);
ItemStack var43 = new ItemStack(Item.ghastTear);
ItemStack var44 = new ItemStack(Item.netherStar);
ItemStack var45 = new ItemStack(Item.spiderEye);
ItemStack var46 = new ItemStack(Item.fermentedSpiderEye);
ItemStack var47 = new ItemStack(Item.netherStalkSeeds);
ItemStack var48 = new ItemStack(Block.glowStone);
ItemStack var49 = new ItemStack(Item.lightStoneDust);
ItemStack var50 = new ItemStack(Item.potion, 1, 0);
ItemStack var51 = new ItemStack(Item.bucketWater);
DecomposerRecipe.add(new DecomposerRecipeSelect(var39, 0.9F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.polycyanoacrylate) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Hg) }), new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.water, 10) }) }));
DecomposerRecipe.add(new DecomposerRecipe(var40, new Chemical[] { this.element(EnumElement.Pu, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(var41, new Chemical[] { this.element(EnumElement.Pu) }));
DecomposerRecipe.add(new DecomposerRecipe(var42, new Chemical[] { this.element(EnumElement.Hg), this.element(EnumElement.Pu), this.molecule(EnumMolecule.polycyanoacrylate, 3) }));
DecomposerRecipe.add(new DecomposerRecipe(var43, new Chemical[] { this.element(EnumElement.Yb, 4), this.element(EnumElement.No, 4) }));
Element var52 = this.element(EnumElement.H, 64);
Element var53 = this.element(EnumElement.He, 64);
DecomposerRecipe.add(new DecomposerRecipe(var44, new Chemical[] { this.element(EnumElement.Cn, 16), var52, var52, var52, var53, var53, var53, var21, var21 }));
DecomposerRecipe.add(new DecomposerRecipeChance(var45, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ttx) }));
DecomposerRecipe.add(new DecomposerRecipe(var46, new Chemical[] { this.element(EnumElement.Po), this.molecule(EnumMolecule.ethanol) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var47, 0.5F, new Chemical[] { this.molecule(EnumMolecule.amphetamine) }));
DecomposerRecipe.add(new DecomposerRecipe(var48, new Chemical[] { this.element(EnumElement.P, 4) }));
DecomposerRecipe.add(new DecomposerRecipe(var49, new Chemical[] { this.element(EnumElement.P) }));
DecomposerRecipe.add(new DecomposerRecipe(var50, new Chemical[] { this.molecule(EnumMolecule.water, 8) }));
DecomposerRecipe.add(new DecomposerRecipe(var51, new Chemical[] { this.molecule(EnumMolecule.water, 16) }));
SynthesisRecipe.add(new SynthesisRecipe(var40, true, 15000, new Chemical[] { this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var42, true, 5000, new Chemical[] { null, this.element(EnumElement.Pu), null, this.molecule(EnumMolecule.polycyanoacrylate), this.element(EnumElement.Hg), this.molecule(EnumMolecule.polycyanoacrylate), null, this.molecule(EnumMolecule.polycyanoacrylate), null }));
SynthesisRecipe.add(new SynthesisRecipe(var43, true, 15000, new Chemical[] { this.element(EnumElement.Yb), this.element(EnumElement.Yb), this.element(EnumElement.No), null, this.element(EnumElement.Yb, 2), this.element(EnumElement.No, 2), null, this.element(EnumElement.No), null }));
SynthesisRecipe.add(new SynthesisRecipe(var44, true, 500000, new Chemical[] { var53, var53, var53, var21, this.element(EnumElement.Cn, 16), var53, var52, var52, var52 }));
SynthesisRecipe.add(new SynthesisRecipe(var45, true, 2000, new Chemical[] { this.element(EnumElement.C), null, null, null, this.molecule(EnumMolecule.ttx), null, null, null, this.element(EnumElement.C) }));
SynthesisRecipe.add(new SynthesisRecipe(var48, true, 500, new Chemical[] { this.element(EnumElement.P), null, this.element(EnumElement.P), this.element(EnumElement.P), null, this.element(EnumElement.P), null, null, null }));
ItemStack var54 = new ItemStack(Item.sugar);
ItemStack var55 = new ItemStack(Item.reed);
ItemStack var56 = new ItemStack(Block.pumpkin);
ItemStack var57 = new ItemStack(Block.melon);
ItemStack var58 = new ItemStack(Item.speckledMelon);
ItemStack var59 = new ItemStack(Item.melon);
ItemStack var60 = new ItemStack(Item.carrot);
ItemStack var61 = new ItemStack(Item.goldenCarrot);
ItemStack var62 = new ItemStack(Item.dyePowder, 1, 3);
ItemStack var63 = new ItemStack(Item.potato);
ItemStack var64 = new ItemStack(Item.bread);
ItemStack var65 = new ItemStack(Item.appleRed);
ItemStack var66 = new ItemStack(Item.appleGold, 1, 0);
// new ItemStack(Item.appleGold, 1, 1);
ItemStack var68 = new ItemStack(Item.chickenCooked);
DecomposerRecipe.add(new DecomposerRecipeChance(var54, 0.75F, new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var55, 0.65F, new Chemical[] { this.molecule(EnumMolecule.sucrose), this.element(EnumElement.H, 2), this.element(EnumElement.O) }));
DecomposerRecipe.add(new DecomposerRecipe(var62, new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
DecomposerRecipe.add(new DecomposerRecipe(var56, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
DecomposerRecipe.add(new DecomposerRecipe(var57, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin), this.molecule(EnumMolecule.asparticAcid), this.molecule(EnumMolecule.water, 16) }));
DecomposerRecipe.add(new DecomposerRecipe(var58, new Chemical[] { this.molecule(EnumMolecule.water, 4), this.molecule(EnumMolecule.whitePigment), this.element(EnumElement.Au, 1) }));
DecomposerRecipe.add(new DecomposerRecipe(var59, new Chemical[] { this.molecule(EnumMolecule.water) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var60, 0.05F, new Chemical[] { this.molecule(EnumMolecule.ret) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var61, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ret), this.element(EnumElement.Au, 4) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var63, 0.4F, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.K, 2), this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var64, 0.1F, new Chemical[] { this.molecule(EnumMolecule.starch), this.molecule(EnumMolecule.sucrose) }));
DecomposerRecipe.add(new DecomposerRecipe(var65, new Chemical[] { this.molecule(EnumMolecule.malicAcid) }));
DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 8) }));
DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 64), this.element(EnumElement.Np) }));
DecomposerRecipe.add(new DecomposerRecipe(var68, new Chemical[] { this.element(EnumElement.K), this.element(EnumElement.Na), this.element(EnumElement.C, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var54, false, 400, new Chemical[] { this.molecule(EnumMolecule.sucrose) }));
SynthesisRecipe.add(new SynthesisRecipe(var65, false, 400, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.molecule(EnumMolecule.water, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var62, false, 400, new Chemical[] { this.molecule(EnumMolecule.theobromine) }));
SynthesisRecipe.add(new SynthesisRecipe(var56, false, 400, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) }));
SynthesisRecipe.add(new SynthesisRecipe(var68, true, 5000, new Chemical[] { this.element(EnumElement.K, 16), this.element(EnumElement.Na, 16), this.element(EnumElement.C, 16) }));
ItemStack var69 = new ItemStack(Item.gunpowder);
ItemStack var70 = new ItemStack(Block.tnt);
DecomposerRecipe.add(new DecomposerRecipe(var69, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.S, 2), this.element(EnumElement.C) }));
DecomposerRecipe.add(new DecomposerRecipe(var70, new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(var70, false, 1000, new Chemical[] { this.molecule(EnumMolecule.tnt) }));
SynthesisRecipe.add(new SynthesisRecipe(var69, true, 600, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.C), null, this.element(EnumElement.S, 2), null, null, null, null, null }));
ItemStack var71 = new ItemStack(Block.wood, 1, -1);
ItemStack var72 = new ItemStack(Block.planks, 1, -1);
ItemStack var140 = new ItemStack(Block.planks, 1, 0);
ItemStack var141 = new ItemStack(Block.planks, 1, 1);
ItemStack var142 = new ItemStack(Block.planks, 1, 2);
ItemStack var143 = new ItemStack(Block.planks, 1, 3);
ItemStack var73 = new ItemStack(Item.stick);
ItemStack var74 = new ItemStack(Block.wood, 1, 0);
ItemStack var75 = new ItemStack(Block.wood, 1, 1);
ItemStack var76 = new ItemStack(Block.wood, 1, 2);
ItemStack var77 = new ItemStack(Block.wood, 1, 3);
ItemStack var78 = new ItemStack(Item.doorWood);
ItemStack var79 = new ItemStack(Block.pressurePlatePlanks, 1, -1);
DecomposerRecipe.add(new DecomposerRecipeChance(var71, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var74, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var75, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var76, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var77, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var72, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var140, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var141, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var142, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var143, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var73, 0.3F, new Chemical[] { this.molecule(EnumMolecule.cellulose) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var78, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 12) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var79, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 4) }));
Molecule var81 = this.molecule(EnumMolecule.cellulose, 1);
SynthesisRecipe.add(new SynthesisRecipe(var74, true, 100, new Chemical[] { var81, var81, var81, null, var81, null, null, null, null }));
SynthesisRecipe.add(new SynthesisRecipe(var75, true, 100, new Chemical[] { null, null, null, null, var81, null, var81, var81, var81 }));
SynthesisRecipe.add(new SynthesisRecipe(var76, true, 100, new Chemical[] { var81, null, var81, null, null, null, var81, null, var81 }));
SynthesisRecipe.add(new SynthesisRecipe(var77, true, 100, new Chemical[] { var81, null, null, var81, var81, null, var81, null, null }));
ItemStack var82 = new ItemStack(Item.dyePowder, 1, 0);
ItemStack var83 = new ItemStack(Item.dyePowder, 1, 1);
ItemStack var84 = new ItemStack(Item.dyePowder, 1, 2);
ItemStack var85 = new ItemStack(Item.dyePowder, 1, 4);
ItemStack var86 = new ItemStack(Item.dyePowder, 1, 5);
ItemStack var87 = new ItemStack(Item.dyePowder, 1, 6);
ItemStack var88 = new ItemStack(Item.dyePowder, 1, 7);
ItemStack var89 = new ItemStack(Item.dyePowder, 1, 8);
ItemStack var90 = new ItemStack(Item.dyePowder, 1, 9);
ItemStack var91 = new ItemStack(Item.dyePowder, 1, 10);
ItemStack var92 = new ItemStack(Item.dyePowder, 1, 11);
ItemStack var93 = new ItemStack(Item.dyePowder, 1, 12);
ItemStack var94 = new ItemStack(Item.dyePowder, 1, 13);
ItemStack var95 = new ItemStack(Item.dyePowder, 1, 14);
ItemStack var96 = new ItemStack(Item.dyePowder, 1, 15);
DecomposerRecipe.add(new DecomposerRecipe(var82, new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var83, new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var84, new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var85, new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipe(var86, new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var87, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var88, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var89, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(var90, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var91, new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var92, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var93, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var94, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var95, new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipe(var96, new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var82, false, 50, new Chemical[] { this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var83, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var84, false, 50, new Chemical[] { this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var85, false, 50, new Chemical[] { this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(var86, false, 50, new Chemical[] { this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var87, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var88, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var89, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var90, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var91, false, 50, new Chemical[] { this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var92, false, 50, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var93, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var94, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var95, false, 50, new Chemical[] { this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var96, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment) }));
ItemStack var97 = new ItemStack(Block.cloth, 1, 0);
ItemStack var98 = new ItemStack(Block.cloth, 1, 1);
ItemStack var99 = new ItemStack(Block.cloth, 1, 2);
ItemStack var100 = new ItemStack(Block.cloth, 1, 3);
ItemStack var101 = new ItemStack(Block.cloth, 1, 4);
ItemStack var102 = new ItemStack(Block.cloth, 1, 5);
ItemStack var103 = new ItemStack(Block.cloth, 1, 6);
ItemStack var104 = new ItemStack(Block.cloth, 1, 7);
ItemStack var105 = new ItemStack(Block.cloth, 1, 8);
ItemStack var106 = new ItemStack(Block.cloth, 1, 9);
ItemStack var107 = new ItemStack(Block.cloth, 1, 10);
ItemStack var108 = new ItemStack(Block.cloth, 1, 11);
ItemStack var109 = new ItemStack(Block.cloth, 1, 12);
ItemStack var110 = new ItemStack(Block.cloth, 1, 13);
ItemStack var111 = new ItemStack(Block.cloth, 1, 14);
ItemStack var112 = new ItemStack(Block.cloth, 1, 15);
DecomposerRecipe.add(new DecomposerRecipeChance(var111, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var110, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var108, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var107, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var106, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var105, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var104, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var103, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var102, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var101, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var100, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var99, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var98, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var97, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var112, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var111, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var110, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var108, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) }));
SynthesisRecipe.add(new SynthesisRecipe(var107, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var106, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var105, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var104, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) }));
SynthesisRecipe.add(new SynthesisRecipe(var103, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var102, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var101, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var100, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var99, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var98, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var97, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) }));
SynthesisRecipe.add(new SynthesisRecipe(var112, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) }));
Molecule var113 = this.molecule(EnumMolecule.polyvinylChloride);
ItemStack var114 = new ItemStack(Item.record13);
ItemStack var115 = new ItemStack(Item.recordCat);
ItemStack var116 = new ItemStack(Item.recordFar);
ItemStack var117 = new ItemStack(Item.recordMall);
ItemStack var118 = new ItemStack(Item.recordMellohi);
ItemStack var119 = new ItemStack(Item.recordStal);
ItemStack var120 = new ItemStack(Item.recordStrad);
ItemStack var121 = new ItemStack(Item.recordWard);
ItemStack var122 = new ItemStack(Item.recordChirp);
DecomposerRecipe.add(new DecomposerRecipe(var114, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var115, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var116, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var117, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var118, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var119, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var120, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var121, new Chemical[] { var113 }));
DecomposerRecipe.add(new DecomposerRecipe(var122, new Chemical[] { var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var114, false, 1000, new Chemical[] { var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var115, false, 1000, new Chemical[] { null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var116, false, 1000, new Chemical[] { null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var117, false, 1000, new Chemical[] { null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var118, false, 1000, new Chemical[] { null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var119, false, 1000, new Chemical[] { null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var120, false, 1000, new Chemical[] { null, null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var121, false, 1000, new Chemical[] { null, null, null, null, null, null, null, var113 }));
SynthesisRecipe.add(new SynthesisRecipe(var122, false, 1000, new Chemical[] { null, null, null, null, null, null, null, null, var113 }));
ItemStack var123 = new ItemStack(Block.mushroomBrown);
ItemStack var124 = new ItemStack(Block.mushroomRed);
ItemStack var125 = new ItemStack(Block.cactus);
DecomposerRecipe.add(new DecomposerRecipe(var123, new Chemical[] { this.molecule(EnumMolecule.psilocybin), this.molecule(EnumMolecule.water, 2) }));
DecomposerRecipe.add(new DecomposerRecipe(var124, new Chemical[] { this.molecule(EnumMolecule.pantherine), this.molecule(EnumMolecule.water, 2), this.molecule(EnumMolecule.nicotine)}));
DecomposerRecipe.add(new DecomposerRecipe(var125, new Chemical[] { this.molecule(EnumMolecule.mescaline), this.molecule(EnumMolecule.water, 20) }));
SynthesisRecipe.add(new SynthesisRecipe(var125, true, 200, new Chemical[] { this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.mescaline), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var13, 0.8F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide, 6), this.molecule(EnumMolecule.strontiumNitrate, 6) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var18, 0.42F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide), this.molecule(EnumMolecule.strontiumNitrate) }));
SynthesisRecipe.add(new SynthesisRecipe(var18, true, 100, new Chemical[] { null, null, this.molecule(EnumMolecule.iron3oxide), null, this.molecule(EnumMolecule.strontiumNitrate), null, null, null, null }));
ItemStack var126 = new ItemStack(Item.enderPearl);
DecomposerRecipe.add(new DecomposerRecipe(var126, new Chemical[] { this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var126, true, 5000, new Chemical[] { this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate) }));
ItemStack var127 = new ItemStack(Block.obsidian);
DecomposerRecipe.add(new DecomposerRecipe(var127, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16), this.molecule(EnumMolecule.magnesiumOxide, 8) }));
SynthesisRecipe.add(new SynthesisRecipe(var127, true, 1000, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), null, this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2) }));
ItemStack var128 = new ItemStack(Item.bone);
ItemStack var129 = new ItemStack(Item.silk);
// new ItemStack(Block.cloth, 1, -1);
// new ItemStack(Block.cloth, 1, 0);
DecomposerRecipe.add(new DecomposerRecipe(var128, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) }));
DecomposerRecipe.add(new DecomposerRecipeChance(var129, 0.45F, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) }));
SynthesisRecipe.add(new SynthesisRecipe(var128, false, 100, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) }));
SynthesisRecipe.add(new SynthesisRecipe(var129, true, 150, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) }));
ItemStack var132 = new ItemStack(Block.cobblestone);
DecomposerRecipe.add(new DecomposerRecipeSelect(var1, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var132, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na), this.element(EnumElement.Cl) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var3, 0.07F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.cobblestone, 8), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, null, this.element(EnumElement.O, 2), null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.stone, 7), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, this.element(EnumElement.O, 2), null, null }));
SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.dirt, 16), true, 50, new Chemical[] { null, null, null, null, this.element(EnumElement.O, 2), this.element(EnumElement.Si) }));
ItemStack var133 = new ItemStack(Block.netherrack);
ItemStack var134 = new ItemStack(Block.slowSand);
ItemStack var135 = new ItemStack(Block.whiteStone);
DecomposerRecipe.add(new DecomposerRecipeSelect(var133, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.Ni), this.element(EnumElement.Tc) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 3), this.element(EnumElement.Ti), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 1), this.element(EnumElement.W, 4), this.element(EnumElement.Cr, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 10), this.element(EnumElement.W, 1), this.element(EnumElement.Zn, 8), this.element(EnumElement.Be, 4) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var134, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 3), this.element(EnumElement.Be, 1), this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 1), this.element(EnumElement.Si, 5), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 6), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es, 1), this.element(EnumElement.O, 2) }) }));
DecomposerRecipe.add(new DecomposerRecipeSelect(var135, 0.8F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.H, 4), this.element(EnumElement.Li) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pu) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Nd) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.H, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Be, 8) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Li, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Rb) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) }));
ItemStack var136 = new ItemStack(Block.plantYellow);
DecomposerRecipe.add(new DecomposerRecipeChance(var136, 0.3F, new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2) }));
ItemStack var137 = new ItemStack(Item.rottenFlesh);
DecomposerRecipe.add(new DecomposerRecipeChance(var137, 0.05F, new Chemical[] { new Molecule(EnumMolecule.nod, 1) }));
ItemStack var138 = new ItemStack(Block.tallGrass, 1, 2);
DecomposerRecipe.add(new DecomposerRecipeChance(var138, 0.07F, new Chemical[] { new Molecule(EnumMolecule.biocide, 2) }));
ItemStack var139 = new ItemStack(Block.tallGrass, 1, 1);
DecomposerRecipe.add(new DecomposerRecipeChance(var139, 0.1F, new Chemical[] { new Molecule(EnumMolecule.afroman, 2) }));
if ( !isbop ) {
System.out.println("This is just a debug message! Move along!");
}
else {
System.out.println("Minechem: BOP support loaded");
ItemStack Algae = BlockReferences.getBlockItemStack("algae");
DecomposerRecipe.add(new DecomposerRecipeChance(Algae, 0.08F, new Chemical[] { new Molecule(EnumMolecule.nod) }));
ItemStack IndigoCap = BlockReferences.getBlockItemStack("bluemilk"); // THE BLUE ONES FUCK YOU UP BAD!
DecomposerRecipe.add(new DecomposerRecipe(IndigoCap, new Chemical[] { new Molecule(EnumMolecule.pantherine), new Molecule(EnumMolecule.psilocybin), new Molecule(EnumMolecule.blueorgodye) }));
ItemStack MagicShroom = BlockReferences.getBlockItemStack("toadstool");
DecomposerRecipe.add(new DecomposerRecipeChance(MagicShroom, 0.4F, new Chemical[] { new Molecule(EnumMolecule.psilocybin) }));
ItemStack Willowasprin = BlockReferences.getBlockItemStack("willowLog");
DecomposerRecipe.add(new DecomposerRecipeChance(Willowasprin, 0.4F, new Chemical[] { new Molecule(EnumMolecule.asprin, 2) }));
ItemStack FoxFire = BlockReferences.getBlockItemStack("glowshroom");
DecomposerRecipe.add(new DecomposerRecipeChance(FoxFire, 0.8F, new Chemical[] { new Molecule(EnumMolecule.psilocybin, 2), new Element(EnumElement.P, 4) }));
ItemStack Daisy1 = BlockReferences.getBlockItemStack("daisy");
DecomposerRecipe.add(new DecomposerRecipeChance(Daisy1, 0.3F, new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2), new Molecule(EnumMolecule.water, 2) }));
ItemStack WitherFlower = BlockReferences.getBlockItemStack("deathbloom");
DecomposerRecipe.add(new DecomposerRecipe(WitherFlower, new Chemical[] { new Molecule(EnumMolecule.poison, 4), new Molecule(EnumMolecule.water, 2) }));
}
this.addDecomposerRecipesFromMolecules();
this.addSynthesisRecipesFromMolecules();
this.addUnusedSynthesisRecipes();
this.registerPoisonRecipes(EnumMolecule.poison);
this.registerPoisonRecipes(EnumMolecule.sucrose);
this.registerPoisonRecipes(EnumMolecule.psilocybin);
this.registerPoisonRecipes(EnumMolecule.methamphetamine);
this.registerPoisonRecipes(EnumMolecule.amphetamine);
this.registerPoisonRecipes(EnumMolecule.pantherine);
this.registerPoisonRecipes(EnumMolecule.ethanol);
this.registerPoisonRecipes(EnumMolecule.penicillin);
this.registerPoisonRecipes(EnumMolecule.testosterone);
this.registerPoisonRecipes(EnumMolecule.xanax);
this.registerPoisonRecipes(EnumMolecule.mescaline);
this.registerPoisonRecipes(EnumMolecule.asprin);
this.registerPoisonRecipes(EnumMolecule.sulfuricAcid);
this.registerPoisonRecipes(EnumMolecule.ttx);
this.registerPoisonRecipes(EnumMolecule.pal2);
this.registerPoisonRecipes(EnumMolecule.nod);
this.registerPoisonRecipes(EnumMolecule.afroman);
}
|
diff --git a/core/src/main/java/org/springframework/batch/core/domain/Entity.java b/core/src/main/java/org/springframework/batch/core/domain/Entity.java
index d6c539912..8a4d34aad 100644
--- a/core/src/main/java/org/springframework/batch/core/domain/Entity.java
+++ b/core/src/main/java/org/springframework/batch/core/domain/Entity.java
@@ -1,106 +1,109 @@
/*
* Copyright 2006-2007 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.batch.core.domain;
import java.io.Serializable;
import org.springframework.util.ClassUtils;
/**
* Batch Domain Entity class. Any class that should be uniquely identifiable
* from another should subclass from Entity. More information on this pattern
* and the difference between Entities and Value Objects can be found in Domain
* Driven Design by Eric Evans.
*
* @author Lucas Ward
* @author Dave Syer
*
*/
public class Entity implements Serializable {
private Long id;
private Integer version;
public Entity() {
super();
}
public Entity(Long id) {
super();
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* @return the version
*/
public Integer getVersion() {
return version;
}
// @Override
public String toString() {
return ClassUtils.getShortName(getClass()) + ": id=" + getId();
}
/**
* Attempt to establish identity based on id if both exist. If either id
* does not exist use Object.equals().
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object other) {
+ if (other == this) {
+ return true;
+ }
if (other == null) {
return false;
}
if (!(other instanceof Entity)) {
return false;
}
Entity step = (Entity) other;
if (id == null || step.getId() == null) {
return step == this;
}
return id.equals(step.getId());
}
/**
* Use ID if it exists to establish hash code, otherwise fall back to
* Object.hashCode(). Based on the same information as equals, so if that
* changes, this will. N.B. this follows the contract of Object.hashCode(),
* but will cause problems for anyone adding an unsaved {@link Entity} to a
* Set because Set.contains() will almost certainly return false for the
* {@link Entity} after it is saved. Spring Batch does not store any of its
* entities in Sets as a matter of course, so internally this is consistent.
* Clients should not be exposed to unsaved entities.
*
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
if (id == null) {
return super.hashCode();
}
return 39 + 87 * id.hashCode();
}
}
| true | true | public boolean equals(Object other) {
if (other == null) {
return false;
}
if (!(other instanceof Entity)) {
return false;
}
Entity step = (Entity) other;
if (id == null || step.getId() == null) {
return step == this;
}
return id.equals(step.getId());
}
| public boolean equals(Object other) {
if (other == this) {
return true;
}
if (other == null) {
return false;
}
if (!(other instanceof Entity)) {
return false;
}
Entity step = (Entity) other;
if (id == null || step.getId() == null) {
return step == this;
}
return id.equals(step.getId());
}
|
diff --git a/src/main/java/ssh/TunnelPoller.java b/src/main/java/ssh/TunnelPoller.java
index 9953482..02a8f82 100644
--- a/src/main/java/ssh/TunnelPoller.java
+++ b/src/main/java/ssh/TunnelPoller.java
@@ -1,46 +1,46 @@
package ssh;
import com.testingbot.tunnel.Api;
import com.testingbot.tunnel.App;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.json.JSONObject;
/**
*
* @author TestingBot
*/
public class TunnelPoller {
private App app;
private Timer timer;
private String tunnelID;
public TunnelPoller(App app, String tunnelID) {
this.app = app;
this.tunnelID = tunnelID;
timer = new Timer();
timer.schedule(new PollTask(), 5000, 5000);
}
class PollTask extends TimerTask {
public void run() {
Api api = app.getApi();
JSONObject response;
try {
response = api.pollTunnel(tunnelID);
if (response.getString("state").equals("READY")) {
timer.cancel();
app.tunnelReady(response);
} else {
Logger.getLogger(TunnelPoller.class.getName()).log(Level.INFO, "Current tunnel status: {0}", response.getString("state"));
}
} catch (Exception ex) {
Logger.getLogger(TunnelPoller.class.getName()).log(Level.SEVERE, "Unable to poll for tunnel status.");
- Logger.getLogger(TunnelPoller.class.getName()).log(Level.SEVERE, null, ex);
+ Logger.getLogger(TunnelPoller.class.getName()).log(Level.SEVERE, ex.toString());
}
}
}
}
| true | true | public void run() {
Api api = app.getApi();
JSONObject response;
try {
response = api.pollTunnel(tunnelID);
if (response.getString("state").equals("READY")) {
timer.cancel();
app.tunnelReady(response);
} else {
Logger.getLogger(TunnelPoller.class.getName()).log(Level.INFO, "Current tunnel status: {0}", response.getString("state"));
}
} catch (Exception ex) {
Logger.getLogger(TunnelPoller.class.getName()).log(Level.SEVERE, "Unable to poll for tunnel status.");
Logger.getLogger(TunnelPoller.class.getName()).log(Level.SEVERE, null, ex);
}
}
| public void run() {
Api api = app.getApi();
JSONObject response;
try {
response = api.pollTunnel(tunnelID);
if (response.getString("state").equals("READY")) {
timer.cancel();
app.tunnelReady(response);
} else {
Logger.getLogger(TunnelPoller.class.getName()).log(Level.INFO, "Current tunnel status: {0}", response.getString("state"));
}
} catch (Exception ex) {
Logger.getLogger(TunnelPoller.class.getName()).log(Level.SEVERE, "Unable to poll for tunnel status.");
Logger.getLogger(TunnelPoller.class.getName()).log(Level.SEVERE, ex.toString());
}
}
|
diff --git a/common/net/minecraftforge/liquids/LiquidStack.java b/common/net/minecraftforge/liquids/LiquidStack.java
index 27504b518..30f93f679 100644
--- a/common/net/minecraftforge/liquids/LiquidStack.java
+++ b/common/net/minecraftforge/liquids/LiquidStack.java
@@ -1,165 +1,164 @@
package net.minecraftforge.liquids;
import static cpw.mods.fml.relauncher.Side.CLIENT;
import com.google.common.base.Objects;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFluid;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.Icon;
/**
* ItemStack substitute for liquids
* @author SirSengir
*/
public class LiquidStack
{
public int itemID;
public int amount;
public int itemMeta;
private LiquidStack(){}
public LiquidStack(int itemID, int amount) { this(itemID, amount, 0); }
public LiquidStack(Item item, int amount) { this(item.itemID, amount, 0); }
public LiquidStack(Block block, int amount) { this(block.blockID, amount, 0); }
public LiquidStack(int itemID, int amount, int itemDamage)
{
this.itemID = itemID;
this.amount = amount;
this.itemMeta = itemDamage;
}
public NBTTagCompound writeToNBT(NBTTagCompound nbt)
{
nbt.setShort("Id", (short)itemID);
nbt.setInteger("Amount", amount);
nbt.setShort("Meta", (short)itemMeta);
nbt.setString("LiquidName", LiquidDictionary.findLiquidName(this));
return nbt;
}
public void readFromNBT(NBTTagCompound nbt)
{
String liquidName = nbt.getString("LiquidName");
+ itemID = nbt.getShort("Id");
+ itemMeta = nbt.getShort("Meta");
if (liquidName != null)
{
LiquidStack liquid = LiquidDictionary.getCanonicalLiquid(liquidName);
- itemID = liquid.itemID;
- itemMeta = liquid.itemMeta;
- }
- else
- {
- itemID = nbt.getShort("Id");
- itemMeta = nbt.getShort("Meta");
+ if(liquid != null) {
+ itemID = liquid.itemID;
+ itemMeta = liquid.itemMeta;
+ }
}
amount = nbt.getInteger("Amount");
}
/**
* @return A copy of this LiquidStack
*/
public LiquidStack copy()
{
return new LiquidStack(itemID, amount, itemMeta);
}
/**
* @param other
* @return true if this LiquidStack contains the same liquid as the one passed in.
*/
public boolean isLiquidEqual(LiquidStack other)
{
return other != null && itemID == other.itemID && itemMeta == other.itemMeta;
}
/**
* @param other
* @return true if this LiquidStack contains the other liquid (liquids are equal and amount >= other.amount).
*/
public boolean containsLiquid(LiquidStack other)
{
return isLiquidEqual(other) && amount >= other.amount;
}
/**
* @param other ItemStack containing liquids.
* @return true if this LiquidStack contains the same liquid as the one passed in.
*/
public boolean isLiquidEqual(ItemStack other)
{
if (other == null)
{
return false;
}
if (itemID == other.itemID && itemMeta == other.getItemDamage())
{
return true;
}
return isLiquidEqual(LiquidContainerRegistry.getLiquidForFilledItem(other));
}
/**
* @return ItemStack representation of this LiquidStack
*/
public ItemStack asItemStack()
{
return new ItemStack(itemID, 1, itemMeta);
}
/**
* Reads a liquid stack from the passed nbttagcompound and returns it.
*
* @param nbt
* @return the liquid stack
*/
public static LiquidStack loadLiquidStackFromNBT(NBTTagCompound nbt)
{
LiquidStack liquidstack = new LiquidStack();
liquidstack.readFromNBT(nbt);
return liquidstack.itemID == 0 ? null : liquidstack;
}
@SideOnly(CLIENT)
private Icon renderingIcon;
@SideOnly(CLIENT)
public Icon getRenderingIcon()
{
if (itemID == Block.waterStill.blockID)
{
return BlockFluid.func_94424_b("water");
}
else if (itemID == Block.lavaStill.blockID)
{
return BlockFluid.func_94424_b("lava");
}
return renderingIcon;
}
@SideOnly(CLIENT)
public void setRenderingIcon(Icon icon)
{
this.renderingIcon = icon;
}
@Override
public final int hashCode()
{
return 31 * itemID + itemMeta;
}
@Override
public final boolean equals(Object ob)
{
return ob instanceof LiquidStack && Objects.equal(((LiquidStack)ob).itemID, itemID) && Objects.equal(((LiquidStack)ob).itemMeta, itemMeta);
}
}
| false | true | public void readFromNBT(NBTTagCompound nbt)
{
String liquidName = nbt.getString("LiquidName");
if (liquidName != null)
{
LiquidStack liquid = LiquidDictionary.getCanonicalLiquid(liquidName);
itemID = liquid.itemID;
itemMeta = liquid.itemMeta;
}
else
{
itemID = nbt.getShort("Id");
itemMeta = nbt.getShort("Meta");
}
amount = nbt.getInteger("Amount");
}
| public void readFromNBT(NBTTagCompound nbt)
{
String liquidName = nbt.getString("LiquidName");
itemID = nbt.getShort("Id");
itemMeta = nbt.getShort("Meta");
if (liquidName != null)
{
LiquidStack liquid = LiquidDictionary.getCanonicalLiquid(liquidName);
if(liquid != null) {
itemID = liquid.itemID;
itemMeta = liquid.itemMeta;
}
}
amount = nbt.getInteger("Amount");
}
|
diff --git a/chouette-validation/src/main/java/fr/certu/chouette/validation/test/ValidationConnectionLink.java b/chouette-validation/src/main/java/fr/certu/chouette/validation/test/ValidationConnectionLink.java
index 9d3952bc..de3eefc0 100644
--- a/chouette-validation/src/main/java/fr/certu/chouette/validation/test/ValidationConnectionLink.java
+++ b/chouette-validation/src/main/java/fr/certu/chouette/validation/test/ValidationConnectionLink.java
@@ -1,149 +1,150 @@
package fr.certu.chouette.validation.test;
import java.util.ArrayList;
import java.util.List;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.PrecisionModel;
import com.vividsolutions.jts.operation.distance.DistanceOp;
import fr.certu.chouette.model.neptune.AreaCentroid;
import fr.certu.chouette.model.neptune.ConnectionLink;
import fr.certu.chouette.model.neptune.StopArea;
import fr.certu.chouette.plugin.report.Report;
import fr.certu.chouette.plugin.report.ReportItem;
import fr.certu.chouette.plugin.validation.IValidationPlugin;
import fr.certu.chouette.plugin.validation.ValidationClassReportItem;
import fr.certu.chouette.plugin.validation.ValidationParameters;
import fr.certu.chouette.plugin.validation.ValidationStepDescription;
import fr.certu.chouette.validation.report.DetailReportItem;
import fr.certu.chouette.validation.report.SheetReportItem;
/**
*
* @author mamadou keira
*
*/
public class ValidationConnectionLink implements IValidationPlugin<ConnectionLink>{
ValidationStepDescription validationStepDescription;
private final long DIVIDER = 1000 * 3600;;
public void init(){
validationStepDescription = new ValidationStepDescription("", ValidationClassReportItem.CLASS.TWO.ordinal());
}
@Override
public ValidationStepDescription getDescription() {
return validationStepDescription;
}
@Override
public List<ValidationClassReportItem> doValidate(List<ConnectionLink> beans,ValidationParameters parameters) {
System.out.println("ConnectionLinkValidation");
return validate(beans,parameters);
}
private List<ValidationClassReportItem> validate(List<ConnectionLink> connectionLinks, ValidationParameters parameters){
List<ValidationClassReportItem> res = new ArrayList<ValidationClassReportItem>();
ValidationClassReportItem category2 = new ValidationClassReportItem(ValidationClassReportItem.CLASS.TWO);
ValidationClassReportItem category3 = new ValidationClassReportItem(ValidationClassReportItem.CLASS.THREE);
ReportItem sheet4 = new SheetReportItem("Test2_Sheet4",4);
ReportItem sheet3_8 = new SheetReportItem("Test3_Sheet8",8);
SheetReportItem report2_4 = new SheetReportItem("Test2_Sheet4_Step1",1);
SheetReportItem report3_8 = new SheetReportItem("Test3_Sheet8_Step1",1);
for(ConnectionLink connectionLink : connectionLinks){
String startOfLinkId = connectionLink.getStartOfLinkId();
String endOfLinkId = connectionLink.getEndOfLinkId();
//Test 2.4.1
if(startOfLinkId == null || endOfLinkId == null){
ReportItem detailReportItem = new DetailReportItem("Test2_Sheet4_Step1_error_a",Report.STATE.ERROR);
report2_4.addItem(detailReportItem);
- }else if(!startOfLinkId.equals(connectionLink.getStartOfLink().getObjectId()) || !endOfLinkId.equals(connectionLink.getEndOfLink().getObjectId())){
+ //}else if(!startOfLinkId.equals(connectionLink.getStartOfLink().getObjectId()) || !endOfLinkId.equals(connectionLink.getEndOfLink().getObjectId())){
+ }else if(connectionLink.getStartOfLink() == null || connectionLink.getEndOfLink() == null){
ReportItem detailReportItem = new DetailReportItem("Test2_Sheet4_Step1_error_b",Report.STATE.ERROR);
report2_4.addItem(detailReportItem);
}else {
report2_4.updateStatus(Report.STATE.OK);
}
//Test 3.8.1
StopArea startOfLink = connectionLink.getStartOfLink();
StopArea endOfLink = connectionLink.getEndOfLink();
AreaCentroid areaCentroidStart = (startOfLink != null) ? startOfLink.getAreaCentroid() : null;
AreaCentroid areaCentroidEnd = (endOfLink != null) ? endOfLink.getAreaCentroid() : null;
PrecisionModel precisionModel = new PrecisionModel(PrecisionModel.maximumPreciseValue);
double yStart = (areaCentroidStart != null && areaCentroidStart.getLatitude() != null) ? areaCentroidStart.getLatitude().doubleValue() : 0;
double xStart = (areaCentroidStart != null && areaCentroidStart.getLongitude() != null) ? areaCentroidStart.getLongitude().doubleValue() : 0;
int SRIDstart = (areaCentroidStart != null && areaCentroidStart.getLongLatType()!= null) ? areaCentroidStart.getLongLatType().epsgCode() : 0;
GeometryFactory factoryStart = new GeometryFactory(precisionModel, SRIDstart);
Point pointStart = factoryStart.createPoint(new Coordinate(xStart, yStart));
double yEnd = (areaCentroidEnd != null && areaCentroidEnd.getLatitude() != null) ? areaCentroidEnd.getLatitude().doubleValue() : 0;
double xEnd = (areaCentroidEnd != null && areaCentroidEnd.getLongitude() != null) ? areaCentroidEnd.getLongitude().doubleValue() : 0;
int SRIDend = (areaCentroidEnd != null && areaCentroidEnd.getLongLatType()!= null) ? areaCentroidEnd.getLongLatType().epsgCode() : 0;
GeometryFactory factoryEnd = new GeometryFactory(precisionModel, SRIDend);
Point pointEnd = factoryEnd.createPoint(new Coordinate(xEnd, yEnd));
DistanceOp distanceOp = new DistanceOp(pointStart, pointEnd);
double distance = distanceOp.distance();
//Test 3.8.1 a
long timeA = (connectionLink.getDefaultDuration() != null) ? connectionLink.getDefaultDuration().getTime() / DIVIDER : 0 ;
double speedA = distance /timeA;
double minA = parameters.getTest3_8a_MinimalSpeed();
double maxA = parameters.getTest3_8a_MaximalSpeed();
if(speedA < minA && speedA > maxA){
ReportItem detailReportItem = new DetailReportItem("Test3_Sheet8_Step1_error_a",Report.STATE.ERROR,
String.valueOf(minA),String.valueOf(maxA),connectionLink.getObjectId());
report3_8.addItem(detailReportItem);
}
//Test 3.8.1 b
long timeB = (connectionLink.getFrequentTravellerDuration() != null) ? connectionLink.getFrequentTravellerDuration().getTime() / DIVIDER : 0;
double speedB = distance/timeB;
double minB = parameters.getTest3_8b_MinimalSpeed();
double maxB = parameters.getTest3_8b_MaximalSpeed();
if(speedB < minB && speedB > maxB){
ReportItem detailReportItem = new DetailReportItem("Test3_Sheet8_Step1_error_b",Report.STATE.ERROR,
String.valueOf(minB),String.valueOf(maxB),connectionLink.getObjectId());
report3_8.addItem(detailReportItem);
}
//Test 3.8.1 c
long timeC = (connectionLink.getOccasionalTravellerDuration() != null) ? connectionLink.getOccasionalTravellerDuration().getTime() / DIVIDER: 0;
double speedC = distance/timeC;
double minC = parameters.getTest3_8c_MinimalSpeed();
double maxC = parameters.getTest3_8c_MaximalSpeed();
if(speedC < minC && speedC > maxC){
ReportItem detailReportItem = new DetailReportItem("Test3_Sheet8_Step1_error_c",Report.STATE.ERROR,
String.valueOf(minC),String.valueOf(maxC),connectionLink.getObjectId());
report3_8.addItem(detailReportItem);
}
//Test 3.8.1 d
if(connectionLink.getMobilityRestrictedTravellerDuration() == null)
report3_8.updateStatus(Report.STATE.OK);
else {
long timeD = connectionLink.getMobilityRestrictedTravellerDuration().getTime() / DIVIDER;
double speedD = distance/timeD;
double minD = parameters.getTest3_8d_MinimalSpeed();
double maxD = parameters.getTest3_8d_MaximalSpeed();
if(speedD < minD && speedD > maxD){
ReportItem detailReportItem = new DetailReportItem("Test3_Sheet8_Step1_error_d",Report.STATE.ERROR,
String.valueOf(minD),String.valueOf(maxD),connectionLink.getObjectId());
report3_8.addItem(detailReportItem);
}else
report3_8.updateStatus(Report.STATE.OK);
}
}
report2_4.computeDetailItemCount();
report3_8.computeDetailItemCount();
sheet4.addItem(report2_4);
sheet3_8.addItem(report3_8);
category2.addItem(sheet4);
category3.addItem(sheet3_8);
res.add(category2);
res.add(category3);
return res;
}
}
| true | true | private List<ValidationClassReportItem> validate(List<ConnectionLink> connectionLinks, ValidationParameters parameters){
List<ValidationClassReportItem> res = new ArrayList<ValidationClassReportItem>();
ValidationClassReportItem category2 = new ValidationClassReportItem(ValidationClassReportItem.CLASS.TWO);
ValidationClassReportItem category3 = new ValidationClassReportItem(ValidationClassReportItem.CLASS.THREE);
ReportItem sheet4 = new SheetReportItem("Test2_Sheet4",4);
ReportItem sheet3_8 = new SheetReportItem("Test3_Sheet8",8);
SheetReportItem report2_4 = new SheetReportItem("Test2_Sheet4_Step1",1);
SheetReportItem report3_8 = new SheetReportItem("Test3_Sheet8_Step1",1);
for(ConnectionLink connectionLink : connectionLinks){
String startOfLinkId = connectionLink.getStartOfLinkId();
String endOfLinkId = connectionLink.getEndOfLinkId();
//Test 2.4.1
if(startOfLinkId == null || endOfLinkId == null){
ReportItem detailReportItem = new DetailReportItem("Test2_Sheet4_Step1_error_a",Report.STATE.ERROR);
report2_4.addItem(detailReportItem);
}else if(!startOfLinkId.equals(connectionLink.getStartOfLink().getObjectId()) || !endOfLinkId.equals(connectionLink.getEndOfLink().getObjectId())){
ReportItem detailReportItem = new DetailReportItem("Test2_Sheet4_Step1_error_b",Report.STATE.ERROR);
report2_4.addItem(detailReportItem);
}else {
report2_4.updateStatus(Report.STATE.OK);
}
//Test 3.8.1
StopArea startOfLink = connectionLink.getStartOfLink();
StopArea endOfLink = connectionLink.getEndOfLink();
AreaCentroid areaCentroidStart = (startOfLink != null) ? startOfLink.getAreaCentroid() : null;
AreaCentroid areaCentroidEnd = (endOfLink != null) ? endOfLink.getAreaCentroid() : null;
PrecisionModel precisionModel = new PrecisionModel(PrecisionModel.maximumPreciseValue);
double yStart = (areaCentroidStart != null && areaCentroidStart.getLatitude() != null) ? areaCentroidStart.getLatitude().doubleValue() : 0;
double xStart = (areaCentroidStart != null && areaCentroidStart.getLongitude() != null) ? areaCentroidStart.getLongitude().doubleValue() : 0;
int SRIDstart = (areaCentroidStart != null && areaCentroidStart.getLongLatType()!= null) ? areaCentroidStart.getLongLatType().epsgCode() : 0;
GeometryFactory factoryStart = new GeometryFactory(precisionModel, SRIDstart);
Point pointStart = factoryStart.createPoint(new Coordinate(xStart, yStart));
double yEnd = (areaCentroidEnd != null && areaCentroidEnd.getLatitude() != null) ? areaCentroidEnd.getLatitude().doubleValue() : 0;
double xEnd = (areaCentroidEnd != null && areaCentroidEnd.getLongitude() != null) ? areaCentroidEnd.getLongitude().doubleValue() : 0;
int SRIDend = (areaCentroidEnd != null && areaCentroidEnd.getLongLatType()!= null) ? areaCentroidEnd.getLongLatType().epsgCode() : 0;
GeometryFactory factoryEnd = new GeometryFactory(precisionModel, SRIDend);
Point pointEnd = factoryEnd.createPoint(new Coordinate(xEnd, yEnd));
DistanceOp distanceOp = new DistanceOp(pointStart, pointEnd);
double distance = distanceOp.distance();
//Test 3.8.1 a
long timeA = (connectionLink.getDefaultDuration() != null) ? connectionLink.getDefaultDuration().getTime() / DIVIDER : 0 ;
double speedA = distance /timeA;
double minA = parameters.getTest3_8a_MinimalSpeed();
double maxA = parameters.getTest3_8a_MaximalSpeed();
if(speedA < minA && speedA > maxA){
ReportItem detailReportItem = new DetailReportItem("Test3_Sheet8_Step1_error_a",Report.STATE.ERROR,
String.valueOf(minA),String.valueOf(maxA),connectionLink.getObjectId());
report3_8.addItem(detailReportItem);
}
//Test 3.8.1 b
long timeB = (connectionLink.getFrequentTravellerDuration() != null) ? connectionLink.getFrequentTravellerDuration().getTime() / DIVIDER : 0;
double speedB = distance/timeB;
double minB = parameters.getTest3_8b_MinimalSpeed();
double maxB = parameters.getTest3_8b_MaximalSpeed();
if(speedB < minB && speedB > maxB){
ReportItem detailReportItem = new DetailReportItem("Test3_Sheet8_Step1_error_b",Report.STATE.ERROR,
String.valueOf(minB),String.valueOf(maxB),connectionLink.getObjectId());
report3_8.addItem(detailReportItem);
}
//Test 3.8.1 c
long timeC = (connectionLink.getOccasionalTravellerDuration() != null) ? connectionLink.getOccasionalTravellerDuration().getTime() / DIVIDER: 0;
double speedC = distance/timeC;
double minC = parameters.getTest3_8c_MinimalSpeed();
double maxC = parameters.getTest3_8c_MaximalSpeed();
if(speedC < minC && speedC > maxC){
ReportItem detailReportItem = new DetailReportItem("Test3_Sheet8_Step1_error_c",Report.STATE.ERROR,
String.valueOf(minC),String.valueOf(maxC),connectionLink.getObjectId());
report3_8.addItem(detailReportItem);
}
//Test 3.8.1 d
if(connectionLink.getMobilityRestrictedTravellerDuration() == null)
report3_8.updateStatus(Report.STATE.OK);
else {
long timeD = connectionLink.getMobilityRestrictedTravellerDuration().getTime() / DIVIDER;
double speedD = distance/timeD;
double minD = parameters.getTest3_8d_MinimalSpeed();
double maxD = parameters.getTest3_8d_MaximalSpeed();
if(speedD < minD && speedD > maxD){
ReportItem detailReportItem = new DetailReportItem("Test3_Sheet8_Step1_error_d",Report.STATE.ERROR,
String.valueOf(minD),String.valueOf(maxD),connectionLink.getObjectId());
report3_8.addItem(detailReportItem);
}else
report3_8.updateStatus(Report.STATE.OK);
}
}
report2_4.computeDetailItemCount();
report3_8.computeDetailItemCount();
sheet4.addItem(report2_4);
sheet3_8.addItem(report3_8);
category2.addItem(sheet4);
category3.addItem(sheet3_8);
res.add(category2);
res.add(category3);
return res;
}
| private List<ValidationClassReportItem> validate(List<ConnectionLink> connectionLinks, ValidationParameters parameters){
List<ValidationClassReportItem> res = new ArrayList<ValidationClassReportItem>();
ValidationClassReportItem category2 = new ValidationClassReportItem(ValidationClassReportItem.CLASS.TWO);
ValidationClassReportItem category3 = new ValidationClassReportItem(ValidationClassReportItem.CLASS.THREE);
ReportItem sheet4 = new SheetReportItem("Test2_Sheet4",4);
ReportItem sheet3_8 = new SheetReportItem("Test3_Sheet8",8);
SheetReportItem report2_4 = new SheetReportItem("Test2_Sheet4_Step1",1);
SheetReportItem report3_8 = new SheetReportItem("Test3_Sheet8_Step1",1);
for(ConnectionLink connectionLink : connectionLinks){
String startOfLinkId = connectionLink.getStartOfLinkId();
String endOfLinkId = connectionLink.getEndOfLinkId();
//Test 2.4.1
if(startOfLinkId == null || endOfLinkId == null){
ReportItem detailReportItem = new DetailReportItem("Test2_Sheet4_Step1_error_a",Report.STATE.ERROR);
report2_4.addItem(detailReportItem);
//}else if(!startOfLinkId.equals(connectionLink.getStartOfLink().getObjectId()) || !endOfLinkId.equals(connectionLink.getEndOfLink().getObjectId())){
}else if(connectionLink.getStartOfLink() == null || connectionLink.getEndOfLink() == null){
ReportItem detailReportItem = new DetailReportItem("Test2_Sheet4_Step1_error_b",Report.STATE.ERROR);
report2_4.addItem(detailReportItem);
}else {
report2_4.updateStatus(Report.STATE.OK);
}
//Test 3.8.1
StopArea startOfLink = connectionLink.getStartOfLink();
StopArea endOfLink = connectionLink.getEndOfLink();
AreaCentroid areaCentroidStart = (startOfLink != null) ? startOfLink.getAreaCentroid() : null;
AreaCentroid areaCentroidEnd = (endOfLink != null) ? endOfLink.getAreaCentroid() : null;
PrecisionModel precisionModel = new PrecisionModel(PrecisionModel.maximumPreciseValue);
double yStart = (areaCentroidStart != null && areaCentroidStart.getLatitude() != null) ? areaCentroidStart.getLatitude().doubleValue() : 0;
double xStart = (areaCentroidStart != null && areaCentroidStart.getLongitude() != null) ? areaCentroidStart.getLongitude().doubleValue() : 0;
int SRIDstart = (areaCentroidStart != null && areaCentroidStart.getLongLatType()!= null) ? areaCentroidStart.getLongLatType().epsgCode() : 0;
GeometryFactory factoryStart = new GeometryFactory(precisionModel, SRIDstart);
Point pointStart = factoryStart.createPoint(new Coordinate(xStart, yStart));
double yEnd = (areaCentroidEnd != null && areaCentroidEnd.getLatitude() != null) ? areaCentroidEnd.getLatitude().doubleValue() : 0;
double xEnd = (areaCentroidEnd != null && areaCentroidEnd.getLongitude() != null) ? areaCentroidEnd.getLongitude().doubleValue() : 0;
int SRIDend = (areaCentroidEnd != null && areaCentroidEnd.getLongLatType()!= null) ? areaCentroidEnd.getLongLatType().epsgCode() : 0;
GeometryFactory factoryEnd = new GeometryFactory(precisionModel, SRIDend);
Point pointEnd = factoryEnd.createPoint(new Coordinate(xEnd, yEnd));
DistanceOp distanceOp = new DistanceOp(pointStart, pointEnd);
double distance = distanceOp.distance();
//Test 3.8.1 a
long timeA = (connectionLink.getDefaultDuration() != null) ? connectionLink.getDefaultDuration().getTime() / DIVIDER : 0 ;
double speedA = distance /timeA;
double minA = parameters.getTest3_8a_MinimalSpeed();
double maxA = parameters.getTest3_8a_MaximalSpeed();
if(speedA < minA && speedA > maxA){
ReportItem detailReportItem = new DetailReportItem("Test3_Sheet8_Step1_error_a",Report.STATE.ERROR,
String.valueOf(minA),String.valueOf(maxA),connectionLink.getObjectId());
report3_8.addItem(detailReportItem);
}
//Test 3.8.1 b
long timeB = (connectionLink.getFrequentTravellerDuration() != null) ? connectionLink.getFrequentTravellerDuration().getTime() / DIVIDER : 0;
double speedB = distance/timeB;
double minB = parameters.getTest3_8b_MinimalSpeed();
double maxB = parameters.getTest3_8b_MaximalSpeed();
if(speedB < minB && speedB > maxB){
ReportItem detailReportItem = new DetailReportItem("Test3_Sheet8_Step1_error_b",Report.STATE.ERROR,
String.valueOf(minB),String.valueOf(maxB),connectionLink.getObjectId());
report3_8.addItem(detailReportItem);
}
//Test 3.8.1 c
long timeC = (connectionLink.getOccasionalTravellerDuration() != null) ? connectionLink.getOccasionalTravellerDuration().getTime() / DIVIDER: 0;
double speedC = distance/timeC;
double minC = parameters.getTest3_8c_MinimalSpeed();
double maxC = parameters.getTest3_8c_MaximalSpeed();
if(speedC < minC && speedC > maxC){
ReportItem detailReportItem = new DetailReportItem("Test3_Sheet8_Step1_error_c",Report.STATE.ERROR,
String.valueOf(minC),String.valueOf(maxC),connectionLink.getObjectId());
report3_8.addItem(detailReportItem);
}
//Test 3.8.1 d
if(connectionLink.getMobilityRestrictedTravellerDuration() == null)
report3_8.updateStatus(Report.STATE.OK);
else {
long timeD = connectionLink.getMobilityRestrictedTravellerDuration().getTime() / DIVIDER;
double speedD = distance/timeD;
double minD = parameters.getTest3_8d_MinimalSpeed();
double maxD = parameters.getTest3_8d_MaximalSpeed();
if(speedD < minD && speedD > maxD){
ReportItem detailReportItem = new DetailReportItem("Test3_Sheet8_Step1_error_d",Report.STATE.ERROR,
String.valueOf(minD),String.valueOf(maxD),connectionLink.getObjectId());
report3_8.addItem(detailReportItem);
}else
report3_8.updateStatus(Report.STATE.OK);
}
}
report2_4.computeDetailItemCount();
report3_8.computeDetailItemCount();
sheet4.addItem(report2_4);
sheet3_8.addItem(report3_8);
category2.addItem(sheet4);
category3.addItem(sheet3_8);
res.add(category2);
res.add(category3);
return res;
}
|
diff --git a/src/JPlotGraph.java b/src/JPlotGraph.java
index a4ca610..7b65860 100644
--- a/src/JPlotGraph.java
+++ b/src/JPlotGraph.java
@@ -1,133 +1,134 @@
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.JFreeChart;
import org.apache.batik.dom.GenericDOMImplementation;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import java.awt.geom.Rectangle2D;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.svggen.SVGGraphics2DIOException;
/**
* A line graph generator
* input(command line argument): a file with all path+names of data files
* output corresponding svg graph in the same directory
* @author JJ
*
*/
public class JPlotGraph {
/**
* a simple java application to display graphs
*
* @param arg
* [0] the file contains all the file path and name of datasets
*/
public static void main(String[] args) {
ArrayList<String> filePath = new ArrayList<String>();
BufferedReader br = null;
// read in the list of files for generating graphs
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(args[0]));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
filePath.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
for (String fileS : filePath) {
// if not empty or null,then create a plot file
if (!((fileS == null) || (fileS.isEmpty()))) {
File dataFile = new File(fileS);
// the whole dataset from file
ArrayList<float[]> dataSet = new ArrayList<float[]>();
// read the file into dataset
Scanner mScanner=null;
try {
mScanner= new Scanner(dataFile);
while (mScanner.hasNextLine()) {
// only read in lines starting with a float number
if (mScanner.hasNextFloat()) {
// data Entry for each line
float[] dataEntry = new float[3];
dataEntry[0] = mScanner.nextFloat();
dataEntry[1] = mScanner.nextFloat();
dataEntry[2] = mScanner.nextFloat();
dataSet.add(dataEntry);
//inc to next line
mScanner.nextLine();
} else
mScanner.nextLine();
}
} catch (FileNotFoundException e) {
System.out.println("dataFile doesn't exist!");
} finally{
if (mScanner != null)
mScanner.close();
}
// create data sample series
XYSeries x_data = new XYSeries("X axis");
XYSeries y_data = new XYSeries("Y axis");
XYSeries z_data = new XYSeries("Z axis");
/* Define some XY Data series for the SVG chart */
for (int index = 0; index < dataSet.size(); index++) {
x_data.add(index, dataSet.get(index)[0]);
y_data.add(index, dataSet.get(index)[1]);
z_data.add(index, dataSet.get(index)[2]);
}
/* Add all XYSeries to XYSeriesCollection */
// XYSeriesCollection implements XYDataset
XYSeriesCollection svgXYDataSeries = new XYSeriesCollection();
// add series using addSeries method
svgXYDataSeries.addSeries(x_data);
svgXYDataSeries.addSeries(y_data);
svgXYDataSeries.addSeries(z_data);
+ String chartTitle=fileS+"readings";
// Use createXYLineChart to create the chart
JFreeChart XYLineChart = ChartFactory.createXYLineChart(
- "Accelerometer Readings", "time", "m/s^2",
+ chartTitle, "time", "m/s^2",
svgXYDataSeries, PlotOrientation.VERTICAL, true, true,
false);
/* Write Chart output as SVG */
/* Get DOM Implementation */
DOMImplementation mySVGDOM = GenericDOMImplementation
.getDOMImplementation();
/* create Document object */
Document document = mySVGDOM.createDocument(null, "svg", null);
/* Create SVG Generator */
SVGGraphics2D my_svg_generator = new SVGGraphics2D(document);
/* Render chart as SVG 2D Graphics object */
XYLineChart.draw(my_svg_generator, new Rectangle2D.Double(0, 0,
1200, 600), null);
/* Write output to file */
try {
String outputFileName =fileS+"_graph"+".svg";
my_svg_generator.stream(outputFileName);
} catch (SVGGraphics2DIOException e) {
System.out.println("fail to create svg file");
}
}
}
}
}
| false | true | public static void main(String[] args) {
ArrayList<String> filePath = new ArrayList<String>();
BufferedReader br = null;
// read in the list of files for generating graphs
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(args[0]));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
filePath.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
for (String fileS : filePath) {
// if not empty or null,then create a plot file
if (!((fileS == null) || (fileS.isEmpty()))) {
File dataFile = new File(fileS);
// the whole dataset from file
ArrayList<float[]> dataSet = new ArrayList<float[]>();
// read the file into dataset
Scanner mScanner=null;
try {
mScanner= new Scanner(dataFile);
while (mScanner.hasNextLine()) {
// only read in lines starting with a float number
if (mScanner.hasNextFloat()) {
// data Entry for each line
float[] dataEntry = new float[3];
dataEntry[0] = mScanner.nextFloat();
dataEntry[1] = mScanner.nextFloat();
dataEntry[2] = mScanner.nextFloat();
dataSet.add(dataEntry);
//inc to next line
mScanner.nextLine();
} else
mScanner.nextLine();
}
} catch (FileNotFoundException e) {
System.out.println("dataFile doesn't exist!");
} finally{
if (mScanner != null)
mScanner.close();
}
// create data sample series
XYSeries x_data = new XYSeries("X axis");
XYSeries y_data = new XYSeries("Y axis");
XYSeries z_data = new XYSeries("Z axis");
/* Define some XY Data series for the SVG chart */
for (int index = 0; index < dataSet.size(); index++) {
x_data.add(index, dataSet.get(index)[0]);
y_data.add(index, dataSet.get(index)[1]);
z_data.add(index, dataSet.get(index)[2]);
}
/* Add all XYSeries to XYSeriesCollection */
// XYSeriesCollection implements XYDataset
XYSeriesCollection svgXYDataSeries = new XYSeriesCollection();
// add series using addSeries method
svgXYDataSeries.addSeries(x_data);
svgXYDataSeries.addSeries(y_data);
svgXYDataSeries.addSeries(z_data);
// Use createXYLineChart to create the chart
JFreeChart XYLineChart = ChartFactory.createXYLineChart(
"Accelerometer Readings", "time", "m/s^2",
svgXYDataSeries, PlotOrientation.VERTICAL, true, true,
false);
/* Write Chart output as SVG */
/* Get DOM Implementation */
DOMImplementation mySVGDOM = GenericDOMImplementation
.getDOMImplementation();
/* create Document object */
Document document = mySVGDOM.createDocument(null, "svg", null);
/* Create SVG Generator */
SVGGraphics2D my_svg_generator = new SVGGraphics2D(document);
/* Render chart as SVG 2D Graphics object */
XYLineChart.draw(my_svg_generator, new Rectangle2D.Double(0, 0,
1200, 600), null);
/* Write output to file */
try {
String outputFileName =fileS+"_graph"+".svg";
my_svg_generator.stream(outputFileName);
} catch (SVGGraphics2DIOException e) {
System.out.println("fail to create svg file");
}
}
}
}
| public static void main(String[] args) {
ArrayList<String> filePath = new ArrayList<String>();
BufferedReader br = null;
// read in the list of files for generating graphs
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(args[0]));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
filePath.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
for (String fileS : filePath) {
// if not empty or null,then create a plot file
if (!((fileS == null) || (fileS.isEmpty()))) {
File dataFile = new File(fileS);
// the whole dataset from file
ArrayList<float[]> dataSet = new ArrayList<float[]>();
// read the file into dataset
Scanner mScanner=null;
try {
mScanner= new Scanner(dataFile);
while (mScanner.hasNextLine()) {
// only read in lines starting with a float number
if (mScanner.hasNextFloat()) {
// data Entry for each line
float[] dataEntry = new float[3];
dataEntry[0] = mScanner.nextFloat();
dataEntry[1] = mScanner.nextFloat();
dataEntry[2] = mScanner.nextFloat();
dataSet.add(dataEntry);
//inc to next line
mScanner.nextLine();
} else
mScanner.nextLine();
}
} catch (FileNotFoundException e) {
System.out.println("dataFile doesn't exist!");
} finally{
if (mScanner != null)
mScanner.close();
}
// create data sample series
XYSeries x_data = new XYSeries("X axis");
XYSeries y_data = new XYSeries("Y axis");
XYSeries z_data = new XYSeries("Z axis");
/* Define some XY Data series for the SVG chart */
for (int index = 0; index < dataSet.size(); index++) {
x_data.add(index, dataSet.get(index)[0]);
y_data.add(index, dataSet.get(index)[1]);
z_data.add(index, dataSet.get(index)[2]);
}
/* Add all XYSeries to XYSeriesCollection */
// XYSeriesCollection implements XYDataset
XYSeriesCollection svgXYDataSeries = new XYSeriesCollection();
// add series using addSeries method
svgXYDataSeries.addSeries(x_data);
svgXYDataSeries.addSeries(y_data);
svgXYDataSeries.addSeries(z_data);
String chartTitle=fileS+"readings";
// Use createXYLineChart to create the chart
JFreeChart XYLineChart = ChartFactory.createXYLineChart(
chartTitle, "time", "m/s^2",
svgXYDataSeries, PlotOrientation.VERTICAL, true, true,
false);
/* Write Chart output as SVG */
/* Get DOM Implementation */
DOMImplementation mySVGDOM = GenericDOMImplementation
.getDOMImplementation();
/* create Document object */
Document document = mySVGDOM.createDocument(null, "svg", null);
/* Create SVG Generator */
SVGGraphics2D my_svg_generator = new SVGGraphics2D(document);
/* Render chart as SVG 2D Graphics object */
XYLineChart.draw(my_svg_generator, new Rectangle2D.Double(0, 0,
1200, 600), null);
/* Write output to file */
try {
String outputFileName =fileS+"_graph"+".svg";
my_svg_generator.stream(outputFileName);
} catch (SVGGraphics2DIOException e) {
System.out.println("fail to create svg file");
}
}
}
}
|
diff --git a/src/main/java/net/minecraft/src/GameWindowListener.java b/src/main/java/net/minecraft/src/GameWindowListener.java
index 8107552d..ffaf5c0d 100644
--- a/src/main/java/net/minecraft/src/GameWindowListener.java
+++ b/src/main/java/net/minecraft/src/GameWindowListener.java
@@ -1,19 +1,19 @@
package net.minecraft.src;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import net.minecraft.client.Minecraft;
import org.spoutcraft.client.SpoutClient;
public final class GameWindowListener extends WindowAdapter {
public void windowClosing(WindowEvent par1WindowEvent) {
- SpoutClient.getHandle().shutdownMinecraftApplet();
+ SpoutClient.getHandle().shutdown();
try {
SpoutClient.getHandle().mainThread.join(10000L);
} catch (InterruptedException var4) {
}
System.exit(0);
}
}
| true | true | public void windowClosing(WindowEvent par1WindowEvent) {
SpoutClient.getHandle().shutdownMinecraftApplet();
try {
SpoutClient.getHandle().mainThread.join(10000L);
} catch (InterruptedException var4) {
}
System.exit(0);
}
| public void windowClosing(WindowEvent par1WindowEvent) {
SpoutClient.getHandle().shutdown();
try {
SpoutClient.getHandle().mainThread.join(10000L);
} catch (InterruptedException var4) {
}
System.exit(0);
}
|
diff --git a/img2unisay.java b/img2unisay.java
index e6502ea..3929c6f 100755
--- a/img2unisay.java
+++ b/img2unisay.java
@@ -1,639 +1,639 @@
/**
* image2unisay — ponysay to unisay pony convertion tool
*
* Copyright © 2012 Mattias Andrée ([email protected])
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
import javax.imageio.*;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import java.io.*;
/**
* The main class of the img2unisay program
*
* @author Mattias Andrée, <a href="mailto:[email protected]">[email protected]</a>
*/
public class img2unisay
{
/**
* Non-constructor
*/
private img2unisay()
{
assert false : "This class [img2unisay] is not meant to be instansiated.";
}
private static final ArrayList<int[]> pre = new ArrayList<int[]>();
private static int[] prebuf = null;
private static int preptr = 0;
/**
* This is the main entry point of the program
*
* @param args Startup arguments, start the program with </code>--help</code> for details
*
* @throws IOException On I/O exception
*/
public static void main(final String... args) throws IOException
{
if (args.length == 0)
{
System.out.println("Image to unisay convertion tool");
System.out.println();
System.out.println("USAGE: img2unisay [-2] [--] SOURCE > TARGET");
System.out.println();
System.out.println("Source: Image file");
System.out.println("Target (STDOUT): File name for new unisay pony");
System.out.println();
System.out.println("-2 Input image have double dimensioned pixels.");
System.out.println();
System.out.println("Known supported input formats:");
System.out.println(" ⋅ PNG (non-animated)");
System.out.println(" ⋅ GIF (first frame)");
System.out.println();
System.out.println();
System.out.println("Copyright (C) 2012 Mattias Andrée <[email protected]>");
System.out.println();
System.out.println("This program is free software: you can redistribute it and/or modify");
System.out.println("it under the terms of the GNU General Public License as published by");
System.out.println("the Free Software Foundation, either version 3 of the License, or");
System.out.println("(at your option) any later version.");
System.out.println();
System.out.println("This program is distributed in the hope that it will be useful,");
System.out.println("but WITHOUT ANY WARRANTY; without even the implied warranty of");
System.out.println("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the");
System.out.println("GNU General Public License for more details.");
System.out.println();
System.out.println("You should have received a copy of the GNU General Public License");
System.out.println("along with this library. If not, see <http://www.gnu.org/licenses/>.");
System.out.println();
System.out.println();
return;
}
int ai = 0;
int ps = 1;
if (args[ai].equals("-2"))
{
ai++;
ps = 2;
}
if (args[ai].equals("--"))
ai++;
String file = args[ai++];
final PrintStream out = System.out;
final BufferedImage img = ImageIO.read(new File(file));
int w = img.getWidth() / ps;
int h = img.getHeight() / ps;
int maxx = 0;
int minx = w;
int[][] pony = new int[h + 1][w];
final int[] emptyset = new int[w];
for (int x = 0; x < w; x++)
emptyset[x] = -1;
for (int y = 0; y < h; y++)
{
boolean empty = true;
for (int x = 0; x < w; x++)
{
final int argb = img.getRGB(x * ps, y * ps);
int a = (argb >> 24) & 0xFF;
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
if ((0 < a) && (a < 255))
{
r = r * a / 255 + 255 - a;
g = g * a / 255 + 255 - a;
b = b * a / 255 + 255 - a;
}
if (a != 0)
{
pony[y][x] = (new Colour((byte)r, (byte)g, (byte)b)).index;
empty = false;
if (maxx < x) maxx = x;
if (minx > x) minx = x;
}
else
pony[y][x] = -1;
}
if (empty)
pony[y] = null;
}
int yoff = 0;
while (pony[yoff] == null)
yoff++;
for (int y = yoff; y < h; y++)
pony[y - yoff] = pony[y];
h -= yoff;
while (pony[h - 1] == null)
h--;
for (int y = 0; y < h; y++)
if (pony[y] == null)
pony[y] = emptyset;
pony[h] = emptyset;
int fore = -1;
int back = -1;
minx = (minx -= 1) < 0 ? 0 : minx;
int bw = 0;
String offl = new String();
for (int x = minx; x <= maxx; x++)
{
if (pony[0][x] >= 0)
break;
if (x - minx > 3)
{
offl += ' ';
bw++;
}
}
System.out.println("$baloon" + (bw + 3) + "$\033[0m");
System.out.println(offl + "$\\$");
System.out.println(offl + " $\\$");
System.out.println(offl + " $\\$");
for (int y = 0; y < h; y += 2)
{
for (int x = minx; x <= maxx; x++)
{
final int upper = pony[y][x];
final int lower = pony[y + 1][x];
if ((upper < 0) && (lower < 0))
{
if (fore >= 0) System.out.print("\033[39m");
if (back >= 0) System.out.print("\033[49m");
fore = back = -1;
System.out.print(' ');
}
else if (upper < 0)
{
if (back >= 0) System.out.print("\033[49m");
back = -1;
if (fore != lower)
System.out.print("\033[38;5;" + (fore = lower) + "m");
System.out.print('▄');
}
else if (lower < 0)
{
if (back >= 0) System.out.print("\033[49m");
back = -1;
- if (fore != lower)
+ if (fore != upper)
System.out.print("\033[38;5;" + (fore = upper) + "m");
System.out.print('▀');
}
else if ((back == lower) || (fore == upper))
{
if (fore != upper) System.out.print("\033[38;5;" + (fore = upper) + "m");
if (back != lower) System.out.print("\033[48;5;" + (back = lower) + "m");
System.out.print('▀');
}
else
{
if (back != upper) System.out.print("\033[48;5;" + (back = upper) + "m");
if (fore != lower) System.out.print("\033[38;5;" + (fore = lower) + "m");
System.out.print('▄');
}
}
fore = back = -1;
System.out.println("\033[0m");
}
}
}
//####################################################################################
//## The following code is pasted from TWT, but the class is made package private ##
//####################################################################################
/**
* TWT — Terminal Window Toolkit, a free pure Java terminal toolkit.
* Copyright (C) 2011 Mattias Andrée <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Terminal colour class.
*
* @author Mattias Andrée, <a href="mailto:[email protected]">[email protected]</a>
*/
class Colour
{
/**
* Possible colour intensitivities on mixed colours
*/
public static final int[] COLOUR_INTENSITIVITY = {0, 95, 135, 175, 215, 255};
/**
* Possible intensitivities on grey colours, excluding the mixed colours' intensitivities
*/
public static final int[] GREY_EXTRA_INTENSITIVITY = {8, 18, 28, 38, 48, 58, 68, 78, 88, 98, 108, 118, 128,
138, 148, 158, 168, 178, 188, 198, 208, 218, 228, 238};
/**
* Possible intensitivities on mixed colours, including the mixed colours' intensitivities
*/
public static final int[] GREY_FULL_INTENSITIVITY = {0, 8, 18, 28, 38, 48, 58, 68, 78, 88, 95, 98, 108, 118, 128, 135,
138, 148, 158, 168, 175, 178, 188, 198, 208, 218, 215, 228, 238, 255};
/**
* <p>Constructor</p>
* <p>
* Selects the colour by index.
* </p>
*
* @param index The colour's index [0–255].
*/
@SuppressWarnings("hiding")
public Colour(final byte index)
{
final int[] I = COLOUR_INTENSITIVITY;
int i = index; if (i < 0) i += 1 << 8;
if ((this.index = i) < 16)
{
this.systemColour = true;
this.red = new int[] { 0, 128, 0, 128, 0, 128, 0, 192,
128, 255, 0, 255, 0, 255, 0, 255} [i];
this.green = new int[] { 0, 0, 128, 128, 0, 0, 128, 192,
128, 0, 255, 255, 0, 0, 255, 255} [i];
this.blue = new int[] { 0, 0, 0, 0, 128, 128, 128, 192,
128, 0, 0, 0, 255, 255, 255, 255} [i];
}
else
{
this.systemColour = false;
if (i < 232)
{
final int j = i - 16, b, g;
this.blue = b = j % 6;
this.green = g = ((j - b) / 6) % 6;
this.red = (j - b - g * 6) / (6 * 6);
}
else
this.red = this.green = this.blue = (index - 232) * 10 + 8;
}
}
/**
* <p>Constructor</p>
* <p>
* Selects the colour the closest the a proper terminal colour.
* </p>
*
* @param red The red intensity [0–255].
* @param green The green intensity [0–255].
* @param blue The blue intensity [0–255].
*/
@SuppressWarnings("hiding")
public Colour(final byte red, final byte green, final byte blue)
{
final int[] I = COLOUR_INTENSITIVITY;
int r = red ; if (r < 0) r += 1 << 8;
int g = green; if (g < 0) g += 1 << 8;
int b = blue ; if (b < 0) b += 1 << 8;
int d, ð, dr, db, dg; dr = db = dg = 0;
int ir = -1, ig = -1, ib = -1, ii = -1;
d = 500; for (int cr : I) if (d > (ð = Math.abs(cr - r))) {d = ð; dr = cr; ir++;} else break;
d = 500; for (int cg : I) if (d > (ð = Math.abs(cg - g))) {d = ð; dg = cg; ig++;} else break;
d = 500; for (int cb : I) if (d > (ð = Math.abs(cb - b))) {d = ð; db = cb; ib++;} else break;
d = (dr - r)*(dr - r) + (dg - g)*(dg - g) + (db - b)*(db - b);
for (int gr = 8; gr <= 238; gr += 10)
{
int ðr = Math.abs(gr - r);
int ðg = Math.abs(gr - g);
int ðb = Math.abs(gr - b);
ð = ðr*ðr + ðg*ðg + ðb*ðb;
if (d > ð)
{
d = ð;
dr = gr;
dg = gr;
db = gr;
ii = (gr - 8) / 10;
}
}
this.systemColour = false;
this.red = dr;
this.green = dg;
this.blue = db;
this.index = ii < 0 ? (16 + (ir * 6 + ig) * 6 + ib) : ii + 232;
}
/**
* <p>Constructor</p>
* <p>
* Selects the colour by index.
* </p>
*
* @param index The colour's index [0–255].
*/
@SuppressWarnings("hiding")
public Colour(final int index)
{
this((byte)index);
}
/**
* <p>Constructor</p>
* <p>
* Selects the colour the closest the a proper terminal colour.
* </p>
*
* @param red The red intensity [0–255].
* @param green The green intensity [0–255].
* @param blue The blue intensity [0–255].
*/
@SuppressWarnings("hiding")
public Colour(final int red, final int green, final int blue)
{
this((byte)red, (byte)green, (byte)blue);
}
/**
* The red intensity [0–255].
*/
public final int red;
/**
* The green intensity [0–255].
*/
public final int green;
/**
* The blue intensity [0–255].
*/
public final int blue;
/**
* The colour's index [0–255].
*/
public final int index;
/**
* Whether the colour is a system colour.
*/
public final boolean systemColour;
/**
* {@inheritDoc}
*/
@Override
public int hashCode()
{
return this.index;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object o)
{
if ((o == null) || !(o instanceof Colour))
return false;
return ((Colour)o).index == this.index;
}
/**
* System colour initialisation index counter.
*/
private static byte sciic = 0;
/**
* System colour: black
*/
public static final Colour SYSTEM_BLACK = new Colour(sciic++);
/**
* System colour: medium red
*/
public static final Colour SYSTEM_RED = new Colour(sciic++);
/**
* System colour: medium green
*/
public static final Colour SYSTEM_GREEN = new Colour(sciic++);
/**
* System colour: medium yellow, dark orange or brown
*/
public static final Colour SYSTEM_YELLOW = new Colour(sciic++);
/**
* System colour: medium blue
*/
public static final Colour SYSTEM_BLUE = new Colour(sciic++);
/**
* System colour: medium magenta or medium lilac
*/
public static final Colour SYSTEM_MAGENTA = new Colour(sciic++);
/**
* System colour: medium cyan or medium turquoise
*/
public static final Colour SYSTEM_CYAN = new Colour(sciic++);
/**
* System colour: dark grey
*/
public static final Colour SYSTEM_GREY = new Colour(sciic++);
/**
* System colour: light grey
*/
public static final Colour SYSTEM_INTENSIVE_BLACK = new Colour(sciic++);
/**
* System colour: light red
*/
public static final Colour SYSTEM_INTENSIVE_RED = new Colour(sciic++);
/**
* System colour: light green
*/
public static final Colour SYSTEM_INTENSIVE_GREEN = new Colour(sciic++);
/**
* System colour: light yellow or medium orange
*/
public static final Colour SYSTEM_INTENSIVE_YELLOW = new Colour(sciic++);
/**
* System colour: light blue
*/
public static final Colour SYSTEM_INTENSIVE_BLUE = new Colour(sciic++);
/**
* System colour: light magenta or light lilac
*/
public static final Colour SYSTEM_INTENSIVE_MAGENTA = new Colour(sciic++);
/**
* System colour: light cyan or light turquoise
*/
public static final Colour SYSTEM_INTENSIVE_CYAN = new Colour(sciic++);
/**
* System colour: white
*/
public static final Colour SYSTEM_INTENSIVE_GREY = new Colour(sciic++);
/**
* System independent colour: pitch black
*/
public static final Colour PURE_BLACK = new Colour(0, 0, 0);
/**
* System independent colour: medium red
*/
public static final Colour PURE_RED = new Colour(175, 0, 0);
/**
* System independent colour: medium green
*/
public static final Colour PURE_GREEN = new Colour(0, 175, 0);
/**
* System independent colour: medium yellow
*/
public static final Colour PURE_YELLOW = new Colour(175, 175, 0);
/**
* System independent colour: medium blue
*/
public static final Colour PURE_BLUE = new Colour(0, 0, 175);
/**
* System independent colour: medium magenta
*/
public static final Colour PURE_MAGENTA = new Colour(175, 0, 175);
/**
* System independent colour: medium cyan
*/
public static final Colour PURE_CYAN = new Colour(0, 175, 175);
/**
* System independent colour: dark grey
*/
public static final Colour PURE_GREY = new Colour(198, 192, 192);
/**
* System independent colour: light grey
*/
public static final Colour PURE_INTENSIVE_BLACK = new Colour(127, 128, 128);
/**
* System independent colour: light red
*/
public static final Colour PURE_INTENSIVE_RED = new Colour(255, 0, 0);
/**
* System independent colour: light green
*/
public static final Colour PURE_INTENSIVE_GREEN = new Colour(0, 255, 0);
/**
* System independent colour: light yellow
*/
public static final Colour PURE_INTENSIVE_YELLOW = new Colour(255, 255, 0);
/**
* System independent colour: light blue
*/
public static final Colour PURE_INTENSIVE_BLUE = new Colour(0, 0, 255);
/**
* System independent colour: light magenta
*/
public static final Colour PURE_INTENSIVE_MAGENTA = new Colour(255, 0, 255);
/**
* System independent colour: light cyan
*/
public static final Colour PURE_INTENSIVE_CYAN = new Colour(0, 255, 255);
/**
* System independent colour: pure white
*/
public static final Colour PURE_INTENSIVE_GREY = new Colour(0, 255, 255);
}
| true | true | public static void main(final String... args) throws IOException
{
if (args.length == 0)
{
System.out.println("Image to unisay convertion tool");
System.out.println();
System.out.println("USAGE: img2unisay [-2] [--] SOURCE > TARGET");
System.out.println();
System.out.println("Source: Image file");
System.out.println("Target (STDOUT): File name for new unisay pony");
System.out.println();
System.out.println("-2 Input image have double dimensioned pixels.");
System.out.println();
System.out.println("Known supported input formats:");
System.out.println(" ⋅ PNG (non-animated)");
System.out.println(" ⋅ GIF (first frame)");
System.out.println();
System.out.println();
System.out.println("Copyright (C) 2012 Mattias Andrée <[email protected]>");
System.out.println();
System.out.println("This program is free software: you can redistribute it and/or modify");
System.out.println("it under the terms of the GNU General Public License as published by");
System.out.println("the Free Software Foundation, either version 3 of the License, or");
System.out.println("(at your option) any later version.");
System.out.println();
System.out.println("This program is distributed in the hope that it will be useful,");
System.out.println("but WITHOUT ANY WARRANTY; without even the implied warranty of");
System.out.println("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the");
System.out.println("GNU General Public License for more details.");
System.out.println();
System.out.println("You should have received a copy of the GNU General Public License");
System.out.println("along with this library. If not, see <http://www.gnu.org/licenses/>.");
System.out.println();
System.out.println();
return;
}
int ai = 0;
int ps = 1;
if (args[ai].equals("-2"))
{
ai++;
ps = 2;
}
if (args[ai].equals("--"))
ai++;
String file = args[ai++];
final PrintStream out = System.out;
final BufferedImage img = ImageIO.read(new File(file));
int w = img.getWidth() / ps;
int h = img.getHeight() / ps;
int maxx = 0;
int minx = w;
int[][] pony = new int[h + 1][w];
final int[] emptyset = new int[w];
for (int x = 0; x < w; x++)
emptyset[x] = -1;
for (int y = 0; y < h; y++)
{
boolean empty = true;
for (int x = 0; x < w; x++)
{
final int argb = img.getRGB(x * ps, y * ps);
int a = (argb >> 24) & 0xFF;
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
if ((0 < a) && (a < 255))
{
r = r * a / 255 + 255 - a;
g = g * a / 255 + 255 - a;
b = b * a / 255 + 255 - a;
}
if (a != 0)
{
pony[y][x] = (new Colour((byte)r, (byte)g, (byte)b)).index;
empty = false;
if (maxx < x) maxx = x;
if (minx > x) minx = x;
}
else
pony[y][x] = -1;
}
if (empty)
pony[y] = null;
}
int yoff = 0;
while (pony[yoff] == null)
yoff++;
for (int y = yoff; y < h; y++)
pony[y - yoff] = pony[y];
h -= yoff;
while (pony[h - 1] == null)
h--;
for (int y = 0; y < h; y++)
if (pony[y] == null)
pony[y] = emptyset;
pony[h] = emptyset;
int fore = -1;
int back = -1;
minx = (minx -= 1) < 0 ? 0 : minx;
int bw = 0;
String offl = new String();
for (int x = minx; x <= maxx; x++)
{
if (pony[0][x] >= 0)
break;
if (x - minx > 3)
{
offl += ' ';
bw++;
}
}
System.out.println("$baloon" + (bw + 3) + "$\033[0m");
System.out.println(offl + "$\\$");
System.out.println(offl + " $\\$");
System.out.println(offl + " $\\$");
for (int y = 0; y < h; y += 2)
{
for (int x = minx; x <= maxx; x++)
{
final int upper = pony[y][x];
final int lower = pony[y + 1][x];
if ((upper < 0) && (lower < 0))
{
if (fore >= 0) System.out.print("\033[39m");
if (back >= 0) System.out.print("\033[49m");
fore = back = -1;
System.out.print(' ');
}
else if (upper < 0)
{
if (back >= 0) System.out.print("\033[49m");
back = -1;
if (fore != lower)
System.out.print("\033[38;5;" + (fore = lower) + "m");
System.out.print('▄');
}
else if (lower < 0)
{
if (back >= 0) System.out.print("\033[49m");
back = -1;
if (fore != lower)
System.out.print("\033[38;5;" + (fore = upper) + "m");
System.out.print('▀');
}
else if ((back == lower) || (fore == upper))
{
if (fore != upper) System.out.print("\033[38;5;" + (fore = upper) + "m");
if (back != lower) System.out.print("\033[48;5;" + (back = lower) + "m");
System.out.print('▀');
}
else
{
if (back != upper) System.out.print("\033[48;5;" + (back = upper) + "m");
if (fore != lower) System.out.print("\033[38;5;" + (fore = lower) + "m");
System.out.print('▄');
}
}
fore = back = -1;
System.out.println("\033[0m");
}
}
| public static void main(final String... args) throws IOException
{
if (args.length == 0)
{
System.out.println("Image to unisay convertion tool");
System.out.println();
System.out.println("USAGE: img2unisay [-2] [--] SOURCE > TARGET");
System.out.println();
System.out.println("Source: Image file");
System.out.println("Target (STDOUT): File name for new unisay pony");
System.out.println();
System.out.println("-2 Input image have double dimensioned pixels.");
System.out.println();
System.out.println("Known supported input formats:");
System.out.println(" ⋅ PNG (non-animated)");
System.out.println(" ⋅ GIF (first frame)");
System.out.println();
System.out.println();
System.out.println("Copyright (C) 2012 Mattias Andrée <[email protected]>");
System.out.println();
System.out.println("This program is free software: you can redistribute it and/or modify");
System.out.println("it under the terms of the GNU General Public License as published by");
System.out.println("the Free Software Foundation, either version 3 of the License, or");
System.out.println("(at your option) any later version.");
System.out.println();
System.out.println("This program is distributed in the hope that it will be useful,");
System.out.println("but WITHOUT ANY WARRANTY; without even the implied warranty of");
System.out.println("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the");
System.out.println("GNU General Public License for more details.");
System.out.println();
System.out.println("You should have received a copy of the GNU General Public License");
System.out.println("along with this library. If not, see <http://www.gnu.org/licenses/>.");
System.out.println();
System.out.println();
return;
}
int ai = 0;
int ps = 1;
if (args[ai].equals("-2"))
{
ai++;
ps = 2;
}
if (args[ai].equals("--"))
ai++;
String file = args[ai++];
final PrintStream out = System.out;
final BufferedImage img = ImageIO.read(new File(file));
int w = img.getWidth() / ps;
int h = img.getHeight() / ps;
int maxx = 0;
int minx = w;
int[][] pony = new int[h + 1][w];
final int[] emptyset = new int[w];
for (int x = 0; x < w; x++)
emptyset[x] = -1;
for (int y = 0; y < h; y++)
{
boolean empty = true;
for (int x = 0; x < w; x++)
{
final int argb = img.getRGB(x * ps, y * ps);
int a = (argb >> 24) & 0xFF;
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
if ((0 < a) && (a < 255))
{
r = r * a / 255 + 255 - a;
g = g * a / 255 + 255 - a;
b = b * a / 255 + 255 - a;
}
if (a != 0)
{
pony[y][x] = (new Colour((byte)r, (byte)g, (byte)b)).index;
empty = false;
if (maxx < x) maxx = x;
if (minx > x) minx = x;
}
else
pony[y][x] = -1;
}
if (empty)
pony[y] = null;
}
int yoff = 0;
while (pony[yoff] == null)
yoff++;
for (int y = yoff; y < h; y++)
pony[y - yoff] = pony[y];
h -= yoff;
while (pony[h - 1] == null)
h--;
for (int y = 0; y < h; y++)
if (pony[y] == null)
pony[y] = emptyset;
pony[h] = emptyset;
int fore = -1;
int back = -1;
minx = (minx -= 1) < 0 ? 0 : minx;
int bw = 0;
String offl = new String();
for (int x = minx; x <= maxx; x++)
{
if (pony[0][x] >= 0)
break;
if (x - minx > 3)
{
offl += ' ';
bw++;
}
}
System.out.println("$baloon" + (bw + 3) + "$\033[0m");
System.out.println(offl + "$\\$");
System.out.println(offl + " $\\$");
System.out.println(offl + " $\\$");
for (int y = 0; y < h; y += 2)
{
for (int x = minx; x <= maxx; x++)
{
final int upper = pony[y][x];
final int lower = pony[y + 1][x];
if ((upper < 0) && (lower < 0))
{
if (fore >= 0) System.out.print("\033[39m");
if (back >= 0) System.out.print("\033[49m");
fore = back = -1;
System.out.print(' ');
}
else if (upper < 0)
{
if (back >= 0) System.out.print("\033[49m");
back = -1;
if (fore != lower)
System.out.print("\033[38;5;" + (fore = lower) + "m");
System.out.print('▄');
}
else if (lower < 0)
{
if (back >= 0) System.out.print("\033[49m");
back = -1;
if (fore != upper)
System.out.print("\033[38;5;" + (fore = upper) + "m");
System.out.print('▀');
}
else if ((back == lower) || (fore == upper))
{
if (fore != upper) System.out.print("\033[38;5;" + (fore = upper) + "m");
if (back != lower) System.out.print("\033[48;5;" + (back = lower) + "m");
System.out.print('▀');
}
else
{
if (back != upper) System.out.print("\033[48;5;" + (back = upper) + "m");
if (fore != lower) System.out.print("\033[38;5;" + (fore = lower) + "m");
System.out.print('▄');
}
}
fore = back = -1;
System.out.println("\033[0m");
}
}
|
diff --git a/pmd/regress/test/net/sourceforge/pmd/rules/strictexception/ExceptionAsFlowControlTest.java b/pmd/regress/test/net/sourceforge/pmd/rules/strictexception/ExceptionAsFlowControlTest.java
index 03f76c976..c80fe006d 100644
--- a/pmd/regress/test/net/sourceforge/pmd/rules/strictexception/ExceptionAsFlowControlTest.java
+++ b/pmd/regress/test/net/sourceforge/pmd/rules/strictexception/ExceptionAsFlowControlTest.java
@@ -1,60 +1,60 @@
package test.net.sourceforge.pmd.rules.strictexception;
import net.sourceforge.pmd.PMD;
import net.sourceforge.pmd.Rule;
import test.net.sourceforge.pmd.testframework.SimpleAggregatorTst;
import test.net.sourceforge.pmd.testframework.TestDescriptor;
public class ExceptionAsFlowControlTest extends SimpleAggregatorTst {
private Rule rule;
public void setUp() throws Exception {
rule = findRule("rulesets/strictexception.xml", "ExceptionAsFlowControl");
rule.setMessage("Avoid this stuff -> ''{0}''");
}
public void testAll() {
runTests(new TestDescriptor[] {
new TestDescriptor(TEST1, "failure case", 1, rule),
new TestDescriptor(TEST2, "normal throw catch", 0, rule),
- //new TestDescriptor(TEST3, "BUG 996007", 0, rule)
+ new TestDescriptor(TEST3, "BUG 996007", 0, rule)
});
}
private static final String TEST1 =
"public class Foo {" + PMD.EOL +
" void bar() {" + PMD.EOL +
" try {" + PMD.EOL +
" try {" + PMD.EOL +
" } catch (Exception e) {" + PMD.EOL +
" throw new WrapperException(e);" + PMD.EOL +
" // this is essentially a GOTO to the WrapperException catch block" + PMD.EOL +
" }" + PMD.EOL +
" } catch (WrapperException e) {" + PMD.EOL +
" // do some more stuff " + PMD.EOL +
" }" + PMD.EOL +
" }" + PMD.EOL +
"}";
private static final String TEST2 =
"public class Foo {" + PMD.EOL +
" void bar() {" + PMD.EOL +
" try {} catch (Exception e) {}" + PMD.EOL +
" }" + PMD.EOL +
"}";
private static final String TEST3 =
"public class Foo {" + PMD.EOL +
" void bar() {" + PMD.EOL +
" try {} catch (IOException e) {" + PMD.EOL +
" if (foo!=null) " + PMD.EOL +
" throw new IOException(foo.getResponseMessage()); " + PMD.EOL +
" else " + PMD.EOL +
" throw e; " + PMD.EOL +
" " + PMD.EOL +
" }" + PMD.EOL +
" }" + PMD.EOL +
"}";
}
| true | true | public void testAll() {
runTests(new TestDescriptor[] {
new TestDescriptor(TEST1, "failure case", 1, rule),
new TestDescriptor(TEST2, "normal throw catch", 0, rule),
//new TestDescriptor(TEST3, "BUG 996007", 0, rule)
});
}
| public void testAll() {
runTests(new TestDescriptor[] {
new TestDescriptor(TEST1, "failure case", 1, rule),
new TestDescriptor(TEST2, "normal throw catch", 0, rule),
new TestDescriptor(TEST3, "BUG 996007", 0, rule)
});
}
|
diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/ChangeEncodingAction.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/ChangeEncodingAction.java
index 3a2e33aa4..c61fd20d2 100644
--- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/ChangeEncodingAction.java
+++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/ChangeEncodingAction.java
@@ -1,243 +1,240 @@
/*******************************************************************************
* Copyright (c) 2000, 2009 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.ui.texteditor;
import java.util.ResourceBundle;
import org.eclipse.swt.SWT;
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.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.DialogPage;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceStore;
import org.eclipse.ui.ide.dialogs.AbstractEncodingFieldEditor;
import org.eclipse.ui.ide.dialogs.EncodingFieldEditor;
import org.eclipse.ui.ide.dialogs.ResourceEncodingFieldEditor;
import org.eclipse.ui.editors.text.IEncodingSupport;
/**
* Action for changing the encoding of the editor's
* input element.
* <p>
* The following keys, prepended by the given option prefix,
* are used for retrieving resources from the given bundle:
* <ul>
* <li><code>"dialog.title"</code> - the input dialog's title</li>
* </ul>
* This class may be instantiated but is not intended to be subclassed.
* </p>
*
* @since 3.1
* @noextend This class is not intended to be subclassed by clients.
*/
public class ChangeEncodingAction extends TextEditorAction {
private static final int APPLY_ID= IDialogConstants.OK_ID + IDialogConstants.CANCEL_ID + 1;
private String fDialogTitle;
private static final String ENCODING_PREF_KEY= "encoding"; //$NON-NLS-1$
/**
* Creates a new action for the given text editor.
*
* @param editor the text editor
* @see TextEditorAction#TextEditorAction(ResourceBundle, String, ITextEditor)
* @since 3.5
*/
public ChangeEncodingAction(ITextEditor editor) {
this(TextEditorMessages.getBundleForConstructedKeys(), "Editor.ChangeEncodingAction.", editor); //$NON-NLS-1$
}
/**
* Creates a new action for the given text editor. The action configures its visual
* representation from the given resource bundle.
*
* @param bundle the resource bundle
* @param prefix a prefix to be prepended to the various resource keys (described in
* <code>ResourceAction</code> constructor), or <code>null</code> if none
* @param editor the text editor
* @see TextEditorAction#TextEditorAction(ResourceBundle, String, ITextEditor)
*/
public ChangeEncodingAction(ResourceBundle bundle, String prefix, ITextEditor editor) {
super(bundle, prefix, editor);
String key= "dialog.title"; //$NON-NLS-1$;
if (prefix != null && prefix.length() > 0)
key= prefix + key;
fDialogTitle= getString(bundle, key, null);
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
final IResource resource= getResource();
final Shell parentShell= getTextEditor().getSite().getShell();
final IEncodingSupport encodingSupport= getEncodingSupport();
if (resource == null && encodingSupport == null) {
MessageDialog.openInformation(parentShell, fDialogTitle, TextEditorMessages.ChangeEncodingAction_message_noEncodingSupport);
return;
}
Dialog dialog= new Dialog(parentShell) {
private AbstractEncodingFieldEditor fEncodingEditor;
private IPreferenceStore store= null;
/*
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(fDialogTitle);
}
/*
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
protected Control createDialogArea(Composite parent) {
- Control composite= super.createDialogArea(parent);
- if (!(composite instanceof Composite)) {
- composite.dispose();
- composite= new Composite(parent, SWT.NONE);
- }
+ Composite composite= (Composite)super.createDialogArea(parent);
+ composite= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- parent.setLayout(layout);
+ composite.setLayout(layout);
GridData data = new GridData(GridData.FILL_BOTH);
composite.setLayoutData(data);
composite.setFont(parent.getFont());
- DialogPage page= new MessageDialogPage((Composite)composite) {
+ DialogPage page= new MessageDialogPage(composite) {
public void setErrorMessage(String newMessage) {
super.setErrorMessage(newMessage);
setButtonEnabledState(IDialogConstants.OK_ID, newMessage == null);
setButtonEnabledState(APPLY_ID, newMessage == null);
}
private void setButtonEnabledState(int id, boolean state) {
Button button= getButton(id);
if (button != null)
button.setEnabled(state);
}
};
if (resource != null) {
- fEncodingEditor= new ResourceEncodingFieldEditor("", (Composite)composite, resource, null); //$NON-NLS-1$
+ fEncodingEditor= new ResourceEncodingFieldEditor("", composite, resource, null); //$NON-NLS-1$
fEncodingEditor.setPage(page);
fEncodingEditor.load();
} else {
- fEncodingEditor= new EncodingFieldEditor(ENCODING_PREF_KEY, "", null, (Composite)composite); //$NON-NLS-1$
+ fEncodingEditor= new EncodingFieldEditor(ENCODING_PREF_KEY, "", null, composite); //$NON-NLS-1$
store= new PreferenceStore();
String defaultEncoding= encodingSupport.getDefaultEncoding();
store.setDefault(ENCODING_PREF_KEY, defaultEncoding);
String encoding= encodingSupport.getEncoding();
if (encoding != null)
store.setValue(ENCODING_PREF_KEY, encoding);
fEncodingEditor.setPreferenceStore(store);
fEncodingEditor.setPage(page);
fEncodingEditor.load();
if (encoding == null || encoding.equals(defaultEncoding) || encoding.length() == 0)
fEncodingEditor.loadDefault();
}
return composite;
}
/*
* @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite)
*/
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, APPLY_ID, TextEditorMessages.ChangeEncodingAction_button_apply_label, false);
super.createButtonsForButtonBar(parent);
}
/*
* @see org.eclipse.jface.dialogs.Dialog#buttonPressed(int)
*/
protected void buttonPressed(int buttonId) {
if (buttonId == APPLY_ID)
apply();
else
super.buttonPressed(buttonId);
}
/*
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
protected void okPressed() {
apply();
super.okPressed();
}
private void apply() {
fEncodingEditor.store();
if (resource == null) {
String encoding= fEncodingEditor.getPreferenceStore().getString(fEncodingEditor.getPreferenceName());
encodingSupport.setEncoding(encoding);
}
}
};
dialog.open();
}
/*
* @see org.eclipse.ui.texteditor.IUpdate#update()
*/
public void update() {
setEnabled((getResource() != null || getEncodingSupport() != null) && !getTextEditor().isDirty());
}
/**
* Gets the resource which is being edited in the editor.
*
* @return the resource being edited or <code>null</code>s
*/
private IResource getResource() {
if (getTextEditor() != null && getTextEditor().getEditorInput() != null)
return (IResource)getTextEditor().getEditorInput().getAdapter(IResource.class);
return null;
}
/**
* Gets the editor's encoding support.
*
* @return the resource being edited or <code>null</code>s
*/
private IEncodingSupport getEncodingSupport() {
if (getTextEditor() != null)
return (IEncodingSupport)getTextEditor().getAdapter(IEncodingSupport.class);
return null;
}
}
| false | true | public void run() {
final IResource resource= getResource();
final Shell parentShell= getTextEditor().getSite().getShell();
final IEncodingSupport encodingSupport= getEncodingSupport();
if (resource == null && encodingSupport == null) {
MessageDialog.openInformation(parentShell, fDialogTitle, TextEditorMessages.ChangeEncodingAction_message_noEncodingSupport);
return;
}
Dialog dialog= new Dialog(parentShell) {
private AbstractEncodingFieldEditor fEncodingEditor;
private IPreferenceStore store= null;
/*
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(fDialogTitle);
}
/*
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
protected Control createDialogArea(Composite parent) {
Control composite= super.createDialogArea(parent);
if (!(composite instanceof Composite)) {
composite.dispose();
composite= new Composite(parent, SWT.NONE);
}
GridLayout layout= new GridLayout();
layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
parent.setLayout(layout);
GridData data = new GridData(GridData.FILL_BOTH);
composite.setLayoutData(data);
composite.setFont(parent.getFont());
DialogPage page= new MessageDialogPage((Composite)composite) {
public void setErrorMessage(String newMessage) {
super.setErrorMessage(newMessage);
setButtonEnabledState(IDialogConstants.OK_ID, newMessage == null);
setButtonEnabledState(APPLY_ID, newMessage == null);
}
private void setButtonEnabledState(int id, boolean state) {
Button button= getButton(id);
if (button != null)
button.setEnabled(state);
}
};
if (resource != null) {
fEncodingEditor= new ResourceEncodingFieldEditor("", (Composite)composite, resource, null); //$NON-NLS-1$
fEncodingEditor.setPage(page);
fEncodingEditor.load();
} else {
fEncodingEditor= new EncodingFieldEditor(ENCODING_PREF_KEY, "", null, (Composite)composite); //$NON-NLS-1$
store= new PreferenceStore();
String defaultEncoding= encodingSupport.getDefaultEncoding();
store.setDefault(ENCODING_PREF_KEY, defaultEncoding);
String encoding= encodingSupport.getEncoding();
if (encoding != null)
store.setValue(ENCODING_PREF_KEY, encoding);
fEncodingEditor.setPreferenceStore(store);
fEncodingEditor.setPage(page);
fEncodingEditor.load();
if (encoding == null || encoding.equals(defaultEncoding) || encoding.length() == 0)
fEncodingEditor.loadDefault();
}
return composite;
}
/*
* @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite)
*/
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, APPLY_ID, TextEditorMessages.ChangeEncodingAction_button_apply_label, false);
super.createButtonsForButtonBar(parent);
}
/*
* @see org.eclipse.jface.dialogs.Dialog#buttonPressed(int)
*/
protected void buttonPressed(int buttonId) {
if (buttonId == APPLY_ID)
apply();
else
super.buttonPressed(buttonId);
}
/*
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
protected void okPressed() {
apply();
super.okPressed();
}
private void apply() {
fEncodingEditor.store();
if (resource == null) {
String encoding= fEncodingEditor.getPreferenceStore().getString(fEncodingEditor.getPreferenceName());
encodingSupport.setEncoding(encoding);
}
}
};
dialog.open();
}
| public void run() {
final IResource resource= getResource();
final Shell parentShell= getTextEditor().getSite().getShell();
final IEncodingSupport encodingSupport= getEncodingSupport();
if (resource == null && encodingSupport == null) {
MessageDialog.openInformation(parentShell, fDialogTitle, TextEditorMessages.ChangeEncodingAction_message_noEncodingSupport);
return;
}
Dialog dialog= new Dialog(parentShell) {
private AbstractEncodingFieldEditor fEncodingEditor;
private IPreferenceStore store= null;
/*
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(fDialogTitle);
}
/*
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite)super.createDialogArea(parent);
composite= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
composite.setLayout(layout);
GridData data = new GridData(GridData.FILL_BOTH);
composite.setLayoutData(data);
composite.setFont(parent.getFont());
DialogPage page= new MessageDialogPage(composite) {
public void setErrorMessage(String newMessage) {
super.setErrorMessage(newMessage);
setButtonEnabledState(IDialogConstants.OK_ID, newMessage == null);
setButtonEnabledState(APPLY_ID, newMessage == null);
}
private void setButtonEnabledState(int id, boolean state) {
Button button= getButton(id);
if (button != null)
button.setEnabled(state);
}
};
if (resource != null) {
fEncodingEditor= new ResourceEncodingFieldEditor("", composite, resource, null); //$NON-NLS-1$
fEncodingEditor.setPage(page);
fEncodingEditor.load();
} else {
fEncodingEditor= new EncodingFieldEditor(ENCODING_PREF_KEY, "", null, composite); //$NON-NLS-1$
store= new PreferenceStore();
String defaultEncoding= encodingSupport.getDefaultEncoding();
store.setDefault(ENCODING_PREF_KEY, defaultEncoding);
String encoding= encodingSupport.getEncoding();
if (encoding != null)
store.setValue(ENCODING_PREF_KEY, encoding);
fEncodingEditor.setPreferenceStore(store);
fEncodingEditor.setPage(page);
fEncodingEditor.load();
if (encoding == null || encoding.equals(defaultEncoding) || encoding.length() == 0)
fEncodingEditor.loadDefault();
}
return composite;
}
/*
* @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite)
*/
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, APPLY_ID, TextEditorMessages.ChangeEncodingAction_button_apply_label, false);
super.createButtonsForButtonBar(parent);
}
/*
* @see org.eclipse.jface.dialogs.Dialog#buttonPressed(int)
*/
protected void buttonPressed(int buttonId) {
if (buttonId == APPLY_ID)
apply();
else
super.buttonPressed(buttonId);
}
/*
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
protected void okPressed() {
apply();
super.okPressed();
}
private void apply() {
fEncodingEditor.store();
if (resource == null) {
String encoding= fEncodingEditor.getPreferenceStore().getString(fEncodingEditor.getPreferenceName());
encodingSupport.setEncoding(encoding);
}
}
};
dialog.open();
}
|
diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/cmd/DeleteTaskCmd.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/cmd/DeleteTaskCmd.java
index 1c5c91b40..37fd2ea14 100644
--- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/cmd/DeleteTaskCmd.java
+++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/cmd/DeleteTaskCmd.java
@@ -1,86 +1,86 @@
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.impl.cmd;
import java.util.Collection;
import java.util.List;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.history.HistoricDetail;
import org.activiti.engine.impl.HistoricDetailQueryImpl;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.db.DbSqlSession;
import org.activiti.engine.impl.history.HistoricDetailEntity;
import org.activiti.engine.impl.history.HistoricTaskInstanceEntity;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.task.TaskEntity;
/**
* @author Joram Barrez
*/
public class DeleteTaskCmd implements Command<Void> {
protected String taskId;
protected Collection<String> taskIds;
protected boolean cascade;
public DeleteTaskCmd(String taskId, boolean cascade) {
this.taskId = taskId;
this.cascade = cascade;
}
public DeleteTaskCmd(Collection<String> taskIds, boolean cascade) {
this.taskIds = taskIds;
this.cascade = cascade;
}
public Void execute(CommandContext commandContext) {
if (taskId != null) {
deleteTask(commandContext, taskId);
} else if (taskIds != null) {
for (String taskId : taskIds) {
deleteTask(commandContext, taskId);
}
} else {
throw new ActivitiException("taskId and taskIds are null");
}
return null;
}
protected void deleteTask(CommandContext commandContext, String taskId) {
TaskEntity task = commandContext
.getTaskSession()
.findTaskById(taskId);
if (task!=null) {
task.delete(TaskEntity.DELETE_REASON_DELETED);
}
if (cascade) {
int historyLevel = Context.getProcessEngineContext().getHistoryLevel();
DbSqlSession dbSqlSession = commandContext.getDbSqlSession();
if (historyLevel>=ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) {
dbSqlSession.delete(HistoricTaskInstanceEntity.class, taskId);
- }
- List<HistoricDetail> historicTaskDetails = new HistoricDetailQueryImpl(commandContext)
- .taskId(taskId)
- .list();
- for (HistoricDetail historicTaskDetail: historicTaskDetails) {
- dbSqlSession.delete(HistoricDetailEntity.class, historicTaskDetail.getId());
+ List<HistoricDetail> historicTaskDetails = new HistoricDetailQueryImpl(commandContext)
+ .taskId(taskId)
+ .list();
+ for (HistoricDetail historicTaskDetail: historicTaskDetails) {
+ dbSqlSession.delete(HistoricDetailEntity.class, historicTaskDetail.getId());
+ }
}
}
}
}
| true | true | protected void deleteTask(CommandContext commandContext, String taskId) {
TaskEntity task = commandContext
.getTaskSession()
.findTaskById(taskId);
if (task!=null) {
task.delete(TaskEntity.DELETE_REASON_DELETED);
}
if (cascade) {
int historyLevel = Context.getProcessEngineContext().getHistoryLevel();
DbSqlSession dbSqlSession = commandContext.getDbSqlSession();
if (historyLevel>=ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) {
dbSqlSession.delete(HistoricTaskInstanceEntity.class, taskId);
}
List<HistoricDetail> historicTaskDetails = new HistoricDetailQueryImpl(commandContext)
.taskId(taskId)
.list();
for (HistoricDetail historicTaskDetail: historicTaskDetails) {
dbSqlSession.delete(HistoricDetailEntity.class, historicTaskDetail.getId());
}
}
}
| protected void deleteTask(CommandContext commandContext, String taskId) {
TaskEntity task = commandContext
.getTaskSession()
.findTaskById(taskId);
if (task!=null) {
task.delete(TaskEntity.DELETE_REASON_DELETED);
}
if (cascade) {
int historyLevel = Context.getProcessEngineContext().getHistoryLevel();
DbSqlSession dbSqlSession = commandContext.getDbSqlSession();
if (historyLevel>=ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) {
dbSqlSession.delete(HistoricTaskInstanceEntity.class, taskId);
List<HistoricDetail> historicTaskDetails = new HistoricDetailQueryImpl(commandContext)
.taskId(taskId)
.list();
for (HistoricDetail historicTaskDetail: historicTaskDetails) {
dbSqlSession.delete(HistoricDetailEntity.class, historicTaskDetail.getId());
}
}
}
}
|
diff --git a/src/com/yahoo/platform/yui/compressor/CssCompressor.java b/src/com/yahoo/platform/yui/compressor/CssCompressor.java
index c8c560f..be387a2 100644
--- a/src/com/yahoo/platform/yui/compressor/CssCompressor.java
+++ b/src/com/yahoo/platform/yui/compressor/CssCompressor.java
@@ -1,382 +1,384 @@
/*
* YUI Compressor
* http://developer.yahoo.com/yui/compressor/
* Author: Julien Lecomte - http://www.julienlecomte.net/
* Author: Isaac Schlueter - http://foohack.com/
* Author: Stoyan Stefanov - http://phpied.com/
* Copyright (c) 2011 Yahoo! Inc. All rights reserved.
* The copyrights embodied in the content of this file are licensed
* by Yahoo! Inc. under the BSD (revised) open source license.
*/
package com.yahoo.platform.yui.compressor;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
public class CssCompressor {
private StringBuffer srcsb = new StringBuffer();
public CssCompressor(Reader in) throws IOException {
// Read the stream...
int c;
while ((c = in.read()) != -1) {
srcsb.append((char) c);
}
}
// Leave data urls alone to increase parse performance.
protected String extractDataUrls(String css, ArrayList preservedTokens) {
int maxIndex = css.length() - 1;
int appendIndex = 0;
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("url\\(\\s*([\"']?)data\\:");
Matcher m = p.matcher(css);
/*
* Since we need to account for non-base64 data urls, we need to handle
* ' and ) being part of the data string. Hence switching to indexOf,
* to determine whether or not we have matching string terminators and
* handling sb appends directly, instead of using matcher.append* methods.
*/
while (m.find()) {
int startIndex = m.start() + 4; // "url(".length()
String terminator = m.group(1); // ', " or empty (not quoted)
if (terminator.length() == 0) {
terminator = ")";
}
boolean foundTerminator = false;
int endIndex = m.end() - 1;
while(foundTerminator == false && endIndex+1 <= maxIndex) {
endIndex = css.indexOf(terminator, endIndex+1);
if ((endIndex > 0) && (css.charAt(endIndex-1) != '\\')) {
foundTerminator = true;
if (!")".equals(terminator)) {
endIndex = css.indexOf(")", endIndex);
}
}
}
// Enough searching, start moving stuff over to the buffer
sb.append(css.substring(appendIndex, m.start()));
if (foundTerminator) {
String token = css.substring(startIndex, endIndex);
token = token.replaceAll("\\s+", "");
preservedTokens.add(token);
String preserver = "url(___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___)";
sb.append(preserver);
appendIndex = endIndex + 1;
} else {
// No end terminator found, re-add the whole match. Should we throw/warn here?
sb.append(css.substring(m.start(), m.end()));
appendIndex = m.end();
}
}
sb.append(css.substring(appendIndex));
return sb.toString();
}
public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
css = this.extractDataUrls(css, preservedTokens);
StringBuffer sb = new StringBuffer(css);
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
+ // Restore spaces for !important
+ css = css.replaceAll("!important", " !important");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
// We also want to make sure we're only compressing #AABBCC patterns inside { }, not id selectors ( #FAABAC {} )
// We also want to avoid compressing invalid values (e.g. #AABBCCD to #ABCD)
p = Pattern.compile("(\\=\\s*?[\"']?)?" + "#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])" + "(:?\\}|[^0-9a-fA-F{][^{]*?\\})");
m = p.matcher(css);
sb = new StringBuffer();
int index = 0;
while (m.find(index)) {
sb.append(css.substring(index, m.start()));
boolean isFilter = (m.group(1) != null && !"".equals(m.group(1)));
if (isFilter) {
// Restore, as is. Compression will break filters
sb.append(m.group(1) + "#" + m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7));
} else {
if( m.group(2).equalsIgnoreCase(m.group(3)) &&
m.group(4).equalsIgnoreCase(m.group(5)) &&
m.group(6).equalsIgnoreCase(m.group(7))) {
// #AABBCC pattern
sb.append("#" + (m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
// Non-compressible color, restore, but lower case.
sb.append("#" + (m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)).toLowerCase());
}
}
index = m.end(7);
}
sb.append(css.substring(index));
css = sb.toString();
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-left|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
// TODO: Should this be after we re-insert tokens. These could alter the break points. However then
// we'd need to make sure we don't break in the middle of a string etc.
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
}
| true | true | public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
css = this.extractDataUrls(css, preservedTokens);
StringBuffer sb = new StringBuffer(css);
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
// We also want to make sure we're only compressing #AABBCC patterns inside { }, not id selectors ( #FAABAC {} )
// We also want to avoid compressing invalid values (e.g. #AABBCCD to #ABCD)
p = Pattern.compile("(\\=\\s*?[\"']?)?" + "#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])" + "(:?\\}|[^0-9a-fA-F{][^{]*?\\})");
m = p.matcher(css);
sb = new StringBuffer();
int index = 0;
while (m.find(index)) {
sb.append(css.substring(index, m.start()));
boolean isFilter = (m.group(1) != null && !"".equals(m.group(1)));
if (isFilter) {
// Restore, as is. Compression will break filters
sb.append(m.group(1) + "#" + m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7));
} else {
if( m.group(2).equalsIgnoreCase(m.group(3)) &&
m.group(4).equalsIgnoreCase(m.group(5)) &&
m.group(6).equalsIgnoreCase(m.group(7))) {
// #AABBCC pattern
sb.append("#" + (m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
// Non-compressible color, restore, but lower case.
sb.append("#" + (m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)).toLowerCase());
}
}
index = m.end(7);
}
sb.append(css.substring(index));
css = sb.toString();
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-left|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
// TODO: Should this be after we re-insert tokens. These could alter the break points. However then
// we'd need to make sure we don't break in the middle of a string etc.
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
| public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
css = this.extractDataUrls(css, preservedTokens);
StringBuffer sb = new StringBuffer(css);
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
// Restore spaces for !important
css = css.replaceAll("!important", " !important");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
// We also want to make sure we're only compressing #AABBCC patterns inside { }, not id selectors ( #FAABAC {} )
// We also want to avoid compressing invalid values (e.g. #AABBCCD to #ABCD)
p = Pattern.compile("(\\=\\s*?[\"']?)?" + "#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])" + "(:?\\}|[^0-9a-fA-F{][^{]*?\\})");
m = p.matcher(css);
sb = new StringBuffer();
int index = 0;
while (m.find(index)) {
sb.append(css.substring(index, m.start()));
boolean isFilter = (m.group(1) != null && !"".equals(m.group(1)));
if (isFilter) {
// Restore, as is. Compression will break filters
sb.append(m.group(1) + "#" + m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7));
} else {
if( m.group(2).equalsIgnoreCase(m.group(3)) &&
m.group(4).equalsIgnoreCase(m.group(5)) &&
m.group(6).equalsIgnoreCase(m.group(7))) {
// #AABBCC pattern
sb.append("#" + (m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
// Non-compressible color, restore, but lower case.
sb.append("#" + (m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)).toLowerCase());
}
}
index = m.end(7);
}
sb.append(css.substring(index));
css = sb.toString();
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-left|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
// TODO: Should this be after we re-insert tokens. These could alter the break points. However then
// we'd need to make sure we don't break in the middle of a string etc.
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
|
diff --git a/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactResolver.java b/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactResolver.java
index 8963069..eec243d 100644
--- a/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactResolver.java
+++ b/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactResolver.java
@@ -1,299 +1,299 @@
package org.apache.maven.artifact.resolver;
import org.apache.maven.artifact.AbstractArtifactComponent;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.handler.manager.ArtifactHandlerNotFoundException;
import org.apache.maven.artifact.manager.WagonManager;
import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.wagon.TransferFailedException;
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;
public class DefaultArtifactResolver
extends AbstractArtifactComponent
implements ArtifactResolver
{
private WagonManager wagonManager;
public Artifact resolve( Artifact artifact,
Set remoteRepositories,
ArtifactRepository localRepository )
throws ArtifactResolutionException
{
// ----------------------------------------------------------------------
// Perform any transformation on the artifacts
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// Check for the existence of the artifact in the specified local
// ArtifactRepository. If it is present then simply return as the request
// for resolution has been satisfied.
// ----------------------------------------------------------------------
try
{
setLocalRepositoryPath( artifact, localRepository );
if ( artifact.exists() )
{
return artifact;
}
wagonManager.get( artifact, remoteRepositories, localRepository );
}
catch ( ArtifactHandlerNotFoundException e )
{
throw new ArtifactResolutionException( "Error resolving artifact: ", e );
}
catch ( TransferFailedException e )
{
throw new ArtifactResolutionException( artifactNotFound( artifact, remoteRepositories ), e );
}
return artifact;
}
private String LS = System.getProperty( "line.separator" );
private String artifactNotFound( Artifact artifact, Set remoteRepositories )
{
StringBuffer sb = new StringBuffer();
sb.append( "The artifact is not present locally as:" )
.append( LS )
.append( LS )
.append( artifact.getPath() )
.append( LS )
.append( LS )
.append( "or in any of the specified remote repositories:" )
.append( LS )
.append( LS );
for ( Iterator i = remoteRepositories.iterator(); i.hasNext(); )
{
ArtifactRepository remoteRepository = (ArtifactRepository) i.next();
sb.append( remoteRepository.getUrl() );
if ( i.hasNext() )
{
sb.append( ", " );
}
}
return sb.toString();
}
public Set resolve( Set artifacts,
Set remoteRepositories,
ArtifactRepository localRepository )
throws ArtifactResolutionException
{
Set resolvedArtifacts = new HashSet();
for ( Iterator i = artifacts.iterator(); i.hasNext(); )
{
Artifact artifact = (Artifact) i.next();
Artifact resolvedArtifact = resolve( artifact, remoteRepositories, localRepository );
resolvedArtifacts.add( resolvedArtifact );
}
return resolvedArtifacts;
}
// ----------------------------------------------------------------------
// Transitive modes
// ----------------------------------------------------------------------
public ArtifactResolutionResult resolveTransitively( Set artifacts,
Set remoteRepositories,
ArtifactRepository localRepository,
ArtifactMetadataSource source,
ArtifactFilter filter )
throws ArtifactResolutionException
{
ArtifactResolutionResult artifactResolutionResult;
try
{
artifactResolutionResult = collect( artifacts,
localRepository,
remoteRepositories,
source,
filter );
}
catch ( TransitiveArtifactResolutionException e )
{
throw new ArtifactResolutionException( "Error transitively resolving artifacts: ", e );
}
for ( Iterator i = artifactResolutionResult.getArtifacts().values().iterator(); i.hasNext(); )
{
resolve( (Artifact) i.next(), remoteRepositories, localRepository );
}
return artifactResolutionResult;
}
public ArtifactResolutionResult resolveTransitively( Set artifacts,
Set remoteRepositories,
ArtifactRepository localRepository,
ArtifactMetadataSource source )
throws ArtifactResolutionException
{
return resolveTransitively( artifacts, remoteRepositories, localRepository, source, null );
}
public ArtifactResolutionResult resolveTransitively( Artifact artifact,
Set remoteRepositories,
ArtifactRepository localRepository,
ArtifactMetadataSource source )
throws ArtifactResolutionException
{
Set s = new HashSet();
s.add( artifact );
return resolveTransitively( s, remoteRepositories, localRepository, source );
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
protected ArtifactResolutionResult collect( Set artifacts,
ArtifactRepository localRepository,
Set remoteRepositories,
ArtifactMetadataSource source,
ArtifactFilter filter )
throws TransitiveArtifactResolutionException
{
ArtifactResolutionResult result = new ArtifactResolutionResult();
Map resolvedArtifacts = new HashMap();
List queue = new LinkedList();
queue.add( artifacts );
while ( !queue.isEmpty() )
{
Set currentArtifacts = (Set) queue.remove( 0 );
for ( Iterator i = currentArtifacts.iterator(); i.hasNext(); )
{
Artifact newArtifact = (Artifact) i.next();
String id = newArtifact.getConflictId();
if ( resolvedArtifacts.containsKey( id ) )
{
Artifact knownArtifact = (Artifact) resolvedArtifacts.get( id );
String newVersion = newArtifact.getVersion();
String knownVersion = knownArtifact.getVersion();
if ( !newVersion.equals( knownVersion ) )
{
addConflict( result, knownArtifact, newArtifact );
}
}
else
{
// ----------------------------------------------------------------------
// It's the first time we have encountered this artifact
// ----------------------------------------------------------------------
if ( filter != null && !filter.include( newArtifact.getArtifactId() ) )
{
continue;
}
resolvedArtifacts.put( id, newArtifact );
Set referencedDependencies = null;
try
{
referencedDependencies = source.retrieve( newArtifact );
}
catch ( ArtifactMetadataRetrievalException e )
{
- throw new TransitiveArtifactResolutionException( "Error retrieving metadata: ", e );
+ throw new TransitiveArtifactResolutionException( "Error retrieving metadata [" + newArtifact + "] : ", e );
}
// the pom for given dependency exisit we will add it to the queue
queue.add( referencedDependencies );
}
}
}
// ----------------------------------------------------------------------
// the dependencies list is keyed by groupId+artifactId+type
// so it must be 'rekeyed' to the complete id: groupId+artifactId+type+version
// ----------------------------------------------------------------------
Map artifactResult = result.getArtifacts();
for ( Iterator it = resolvedArtifacts.values().iterator(); it.hasNext(); )
{
Artifact artifact = (Artifact) it.next();
try
{
setLocalRepositoryPath( artifact, localRepository );
}
catch ( ArtifactHandlerNotFoundException e )
{
throw new TransitiveArtifactResolutionException( "Error collecting artifact: ", e );
}
artifactResult.put( artifact.getId(), artifact );
}
return result;
}
private void addConflict( ArtifactResolutionResult result, Artifact knownArtifact, Artifact newArtifact )
{
List conflicts;
conflicts = (List) result.getConflicts().get( newArtifact.getConflictId() );
if ( conflicts == null )
{
conflicts = new LinkedList();
conflicts.add( knownArtifact );
result.getConflicts().put( newArtifact.getConflictId(), conflicts );
}
conflicts.add( newArtifact );
}
protected boolean includeArtifact( String artifactId, String[] artifactExcludes )
{
for ( int b = 0; b < artifactExcludes.length; b++ )
{
if ( artifactId.equals( artifactExcludes[b] ) )
{
return false;
}
}
return true;
}
}
| true | true | protected ArtifactResolutionResult collect( Set artifacts,
ArtifactRepository localRepository,
Set remoteRepositories,
ArtifactMetadataSource source,
ArtifactFilter filter )
throws TransitiveArtifactResolutionException
{
ArtifactResolutionResult result = new ArtifactResolutionResult();
Map resolvedArtifacts = new HashMap();
List queue = new LinkedList();
queue.add( artifacts );
while ( !queue.isEmpty() )
{
Set currentArtifacts = (Set) queue.remove( 0 );
for ( Iterator i = currentArtifacts.iterator(); i.hasNext(); )
{
Artifact newArtifact = (Artifact) i.next();
String id = newArtifact.getConflictId();
if ( resolvedArtifacts.containsKey( id ) )
{
Artifact knownArtifact = (Artifact) resolvedArtifacts.get( id );
String newVersion = newArtifact.getVersion();
String knownVersion = knownArtifact.getVersion();
if ( !newVersion.equals( knownVersion ) )
{
addConflict( result, knownArtifact, newArtifact );
}
}
else
{
// ----------------------------------------------------------------------
// It's the first time we have encountered this artifact
// ----------------------------------------------------------------------
if ( filter != null && !filter.include( newArtifact.getArtifactId() ) )
{
continue;
}
resolvedArtifacts.put( id, newArtifact );
Set referencedDependencies = null;
try
{
referencedDependencies = source.retrieve( newArtifact );
}
catch ( ArtifactMetadataRetrievalException e )
{
throw new TransitiveArtifactResolutionException( "Error retrieving metadata: ", e );
}
// the pom for given dependency exisit we will add it to the queue
queue.add( referencedDependencies );
}
}
}
// ----------------------------------------------------------------------
// the dependencies list is keyed by groupId+artifactId+type
// so it must be 'rekeyed' to the complete id: groupId+artifactId+type+version
// ----------------------------------------------------------------------
Map artifactResult = result.getArtifacts();
for ( Iterator it = resolvedArtifacts.values().iterator(); it.hasNext(); )
{
Artifact artifact = (Artifact) it.next();
try
{
setLocalRepositoryPath( artifact, localRepository );
}
catch ( ArtifactHandlerNotFoundException e )
{
throw new TransitiveArtifactResolutionException( "Error collecting artifact: ", e );
}
artifactResult.put( artifact.getId(), artifact );
}
return result;
}
| protected ArtifactResolutionResult collect( Set artifacts,
ArtifactRepository localRepository,
Set remoteRepositories,
ArtifactMetadataSource source,
ArtifactFilter filter )
throws TransitiveArtifactResolutionException
{
ArtifactResolutionResult result = new ArtifactResolutionResult();
Map resolvedArtifacts = new HashMap();
List queue = new LinkedList();
queue.add( artifacts );
while ( !queue.isEmpty() )
{
Set currentArtifacts = (Set) queue.remove( 0 );
for ( Iterator i = currentArtifacts.iterator(); i.hasNext(); )
{
Artifact newArtifact = (Artifact) i.next();
String id = newArtifact.getConflictId();
if ( resolvedArtifacts.containsKey( id ) )
{
Artifact knownArtifact = (Artifact) resolvedArtifacts.get( id );
String newVersion = newArtifact.getVersion();
String knownVersion = knownArtifact.getVersion();
if ( !newVersion.equals( knownVersion ) )
{
addConflict( result, knownArtifact, newArtifact );
}
}
else
{
// ----------------------------------------------------------------------
// It's the first time we have encountered this artifact
// ----------------------------------------------------------------------
if ( filter != null && !filter.include( newArtifact.getArtifactId() ) )
{
continue;
}
resolvedArtifacts.put( id, newArtifact );
Set referencedDependencies = null;
try
{
referencedDependencies = source.retrieve( newArtifact );
}
catch ( ArtifactMetadataRetrievalException e )
{
throw new TransitiveArtifactResolutionException( "Error retrieving metadata [" + newArtifact + "] : ", e );
}
// the pom for given dependency exisit we will add it to the queue
queue.add( referencedDependencies );
}
}
}
// ----------------------------------------------------------------------
// the dependencies list is keyed by groupId+artifactId+type
// so it must be 'rekeyed' to the complete id: groupId+artifactId+type+version
// ----------------------------------------------------------------------
Map artifactResult = result.getArtifacts();
for ( Iterator it = resolvedArtifacts.values().iterator(); it.hasNext(); )
{
Artifact artifact = (Artifact) it.next();
try
{
setLocalRepositoryPath( artifact, localRepository );
}
catch ( ArtifactHandlerNotFoundException e )
{
throw new TransitiveArtifactResolutionException( "Error collecting artifact: ", e );
}
artifactResult.put( artifact.getId(), artifact );
}
return result;
}
|
diff --git a/kovu/teamstats/api/TeamStatsAPI.java b/kovu/teamstats/api/TeamStatsAPI.java
index 7d3d4ba..7e5f110 100644
--- a/kovu/teamstats/api/TeamStatsAPI.java
+++ b/kovu/teamstats/api/TeamStatsAPI.java
@@ -1,621 +1,621 @@
package kovu.teamstats.api;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import kovu.teamstats.api.exception.CreationNotCompleteException;
import kovu.teamstats.api.exception.ServerConnectionLostException;
import kovu.teamstats.api.exception.ServerOutdatedException;
import kovu.teamstats.api.exception.ServerRejectionException;
import kovu.teamstats.api.list.TSAList;
import net.ae97.teamstats.ClientRequest;
import net.ae97.teamstats.networking.Packet;
import net.ae97.teamstats.networking.PacketListener;
import net.ae97.teamstats.networking.PacketSender;
import net.minecraft.client.Minecraft;
/**
* The TeamStats API class. This handles all the server-related requests. This
* should be used to get info from the server.
*
* @author Lord_Ralex
* @version 0.3
* @since 0.1
*/
public final class TeamStatsAPI {
private static TeamStatsAPI api;
private static final String MAIN_SERVER_URL;
private static final int SERVER_PORT;
private final String name;
private String session;
private Socket connection;
private final PacketListener packetListener;
private final PacketSender packetSender;
private final List<String> friendList = new TSAList<String>();
private final Map<String, Map<String, Object>> friendStats = new ConcurrentHashMap<String, Map<String, Object>>();
private final List<String> friendRequests = new TSAList<String>();
private final UpdaterThread updaterThread = new UpdaterThread();
private final Map<String, Object> stats = new ConcurrentHashMap<String, Object>();
private final List<String> newFriends = new TSAList<String>();
private final List<String> newRequests = new TSAList<String>();
private final List<String> newlyRemovedFriends = new TSAList<String>();
private final List<String> onlineFriends = new TSAList<String>();
private final int UPDATE_TIMER = 60; //time this means is set when sent to executor service
private boolean online = false;
private static final short API_VERSION = 3;
private boolean was_set_up = false;
private final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
private final ScheduledFuture task;
static {
//enter the server url here where the main bouncer is
MAIN_SERVER_URL = "teamstats.ae97.net";
//enter the port the bouncer runs off of here
SERVER_PORT = 19325;
}
public TeamStatsAPI(String aName, String aSession) throws ServerRejectionException, IOException, ClassNotFoundException {
name = aName;
session = aSession;
connection = new Socket(MAIN_SERVER_URL, SERVER_PORT);
PacketSender tempSender = new PacketSender(connection.getOutputStream());
PacketListener tempListener = new PacketListener(connection.getInputStream());
tempListener.start();
Packet getServer = new Packet(ClientRequest.GETSERVER);
tempSender.sendPacket(getServer);
Packet p = tempListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
tempListener.interrupt();
String SERVER_URL = null;
Object o = p.getData("ip");
if (o instanceof String) {
SERVER_URL = (String) o;
}
connection.close();
if (SERVER_URL == null || SERVER_URL.equalsIgnoreCase("NONODE")) {
throw new ServerRejectionException("There is no node open");
}
String link = (String) p.getData("ip");
int port = (Integer) p.getData("port");
short server_version = (Short) p.getData("version");
if (server_version != API_VERSION) {
throw new ServerOutdatedException();
}
connection = new Socket(link, port);
packetListener = new PacketListener(connection.getInputStream());
packetSender = new PacketSender(connection.getOutputStream());
packetListener.start();
Packet pac = new Packet(ClientRequest.OPENCONNECTION);
pac.addData("name", name).addData("session", session);
packetSender.sendPacket(pac);
Packet response = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
boolean isAccepted = (Boolean) response.getData("reply");
if (!isAccepted) {
throw new ServerRejectionException();
}
task = service.scheduleAtFixedRate(updaterThread, UPDATE_TIMER, UPDATE_TIMER, TimeUnit.SECONDS);
online = true;
was_set_up = true;
}
/**
* Gets the stats for each friend that is registered by the server. This can
* throw an IOException if the server rejects the client communication or an
* issue occurs when reading the data.
*
* @return Mapping of friends and their stats
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public Map<String, Map<String, Object>> getFriendStats() throws IOException {
wasSetup();
return friendStats;
}
/**
* Returns the map's toString form of the friend's stats. THIS IS
* DEPRECATED, REFER TO NOTES FOR NEW METHOD
*
* @param friendName Name of friend
* @return String version of the stats
* @throws IOException
*/
public String getFriendState(String friendName) throws IOException {
wasSetup();
return friendStats.get(friendName).toString();
}
/**
* Gets the stats for a single friend. If the friend requested is not an
* actual friend, this will return null.
*
* @param friendName The friend to get the stats for
* @return The stats in a map
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public Map<String, Object> getFriendStat(String friendName) throws IOException {
wasSetup();
return friendStats.get(friendName);
}
/**
* Gets the specific value for a certain stat for a friend. The key is the
* stat name.
*
* @param friendName Name of friend
* @param key Key of stat
* @return Value of the friend's key, or null if not one
* @throws IOException
*/
public Object getFriendStat(String friendName, String key) throws IOException {
wasSetup();
key = key.toLowerCase();
Map<String, Object> stat = friendStats.get(friendName);
if (stat == null) {
return null;
} else {
return stat.get(key);
}
}
/**
* Gets all accepted friends.
*
* @return An array of all friends accepted
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public String[] getFriends() throws IOException {
wasSetup();
return friendList.toArray(new String[0]);
}
/**
* Sends the stats to the server. This will never return false. If the
* connection is rejected, this will throw an IOException.
*
* @param key Key to set
* @param value The value for this key
* @return True if connection was successful.
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public boolean updateStats(String key, Object value) throws IOException {
wasSetup();
stats.put(key.toLowerCase().trim(), value);
return true;
}
/**
* Sends the stats to the server. This will never return false. If the
* connection is rejected, this will throw an IOException.
*
* @param map Map of values to set
* @return True if connection was successful.
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public boolean updateStats(Map<String, ? extends Object> map) throws IOException {
for (String key : map.keySet()) {
updateStats(key, map.get(key));
}
return true;
}
/**
* Gets a list of friend requests the user has. This will return names of
* those that want to friend this user.
*
* @return Array of friend requests to the user
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public String[] getFriendRequests() throws IOException {
wasSetup();
return friendRequests.toArray(new String[0]);
}
/**
* Requests a friend addition. This will not add them, just request that the
* person add them. The return is just for the connection, not for the
* friend request.
*
* @param name Name of friend to add/request
* @return True if request was successful
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public boolean addFriend(String name) throws IOException {
wasSetup();
return friendList.add(name);
}
/**
* Removes a friend. This will take place once used and any friend list will
* be updated.
*
* @param name Name of friend to remove
* @return True if connection was successful
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public boolean removeFriend(String name) throws IOException {
wasSetup();
return friendList.remove(name);
}
/**
* Gets the list of new requests to this user. This will also clear the list
* if true is passed.
*
* @param reset Whether to clear the list. True will remove the list after
* returning it.
* @return Names of new friend requests
*/
public String[] getNewFriendRequests(boolean reset) throws IOException {
wasSetup();
String[] newFriendsToReturn = newRequests.toArray(new String[0]);
if (reset) {
newRequests.clear();
}
return newFriendsToReturn;
}
/**
* Gets the list of removed friends to this user. This will also clear the
* list if true is passed.
*
* @param reset Whether to clear the list. True will remove the list after
* returning it.
* @return Names of newly removed friends
*/
public String[] getRemovedFriends(boolean reset) throws IOException {
wasSetup();
String[] newFriendsToReturn = newlyRemovedFriends.toArray(new String[0]);
if (reset) {
newlyRemovedFriends.clear();
}
return newFriendsToReturn;
}
/**
* Gets the list of new friends to this user. This will also clear the list
* if true is passed.
*
* @param reset Whether to clear the list. True will remove the list after
* returning it.
* @return Names of new friends
*/
public String[] getNewFriends(boolean reset) throws IOException {
wasSetup();
String[] newFriendsToReturn = newFriends.toArray(new String[0]);
if (reset) {
newFriends.clear();
}
return newFriendsToReturn;
}
/**
* Gets the list of new requests to this user. This will also clear the
* list.
*
* @return Names of new friend requests
*/
public String[] getNewFriendRequests() throws IOException {
wasSetup();
return getNewFriendRequests(true);
}
/**
* Gets the list of removed friends to this user. This will also clear the
* list.
*
* @return Names of newly removed friends
*/
public String[] getRemovedFriends() throws IOException {
wasSetup();
return getRemovedFriends(true);
}
/**
* Gets the list of new friends to this user. This will also clear the list.
*
* @return Names of new friends
*/
public String[] getNewFriends() throws IOException {
wasSetup();
return getNewFriends(true);
}
/**
* Returns an array of friends that are online based on the cache.
*
* @return Array of friends who are online
*/
public String[] getOnlineFriends() throws IOException {
wasSetup();
return onlineFriends.toArray(new String[0]);
}
/**
* Checks to see if a particular friend is online.
*
* @param name Name of friend
* @return True if they are online, false otherwise
*/
public boolean isFriendOnline(String name) throws IOException {
wasSetup();
return onlineFriends.contains(name);
}
/**
* Forces the client to update the stats and such. This forces the update
* thread to run.
*
* @throws IOException
*/
public void forceUpdate() throws IOException {
wasSetup();
synchronized (task) {
if (!task.isDone()) {
task.notify();
} else {
throw new ServerConnectionLostException();
}
}
}
/**
* Checks to see if the client is still connected to the server and if the
* update thread is running.
*
* @return True if the update thread is alive, false otherwise.
* @throws IOException
*/
public boolean isChecking() throws IOException {
wasSetup();
boolean done;
synchronized (task) {
done = task.isDone();
}
return !done;
}
/**
* Changes the online status of the client. This is instant to the server
* and tells the server to turn the client offline.
*
* @param newStatus New online status
* @return The new online status
* @throws IOException
*/
public boolean changeOnlineStatus(boolean newStatus) throws IOException {
wasSetup();
online = newStatus;
Packet packet = new Packet(ClientRequest.CHANGEONLINE);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("online", online);
packetSender.sendPacket(packet);
Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if ((Boolean) reply.getData("reply")) {
return online;
} else {
throw new ServerRejectionException();
}
}
/**
* Changes the online status of the client. This is instant to the server
* and tells the server to turn the client offline.
*
* @return The new online status
* @throws IOException
*/
public boolean changeOnlineStatus() throws IOException {
wasSetup();
return changeOnlineStatus(!online);
}
/**
* Returns a boolean where true means the API was completely setup and
* connections were successful, otherwise an exception is thrown. This only
* checks the initial connection, not the later connections. Use
* isChecking() for that.
*
* @return True if API was set up.
* @throws IOException If api was not created right, exception thrown
*/
public boolean wasSetup() throws IOException {
if (was_set_up) {
return true;
} else {
throw new CreationNotCompleteException();
}
}
public static void setAPI(TeamStatsAPI apiTemp) throws IllegalAccessException {
if (apiTemp == null) {
throw new IllegalAccessException("The API instance cannot be null");
}
if (api != null) {
if (api == apiTemp) {
return;
} else {
throw new IllegalAccessException("Cannot change the API once it is set");
}
}
api = apiTemp;
}
public static TeamStatsAPI getAPI() {
return api;
}
private class UpdaterThread implements Runnable {
@Override
public void run() {
if (online) {
try {
Packet packet = new Packet(ClientRequest.GETFRIENDS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
String[] friends;
Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException((String) reply.getData("reason"));
}
friends = ((String) packet.getData("names")).split(" ");
//check current friend list, removing and adding name differences
List<String> addFriend = new TSAList<String>();
addFriend.addAll(friendList);
for (String existing : friends) {
addFriend.remove(existing);
}
for (String name : addFriend) {
packet = new Packet(ClientRequest.ADDFRIEND);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
List<String> removeFriend = new ArrayList<String>();
removeFriend.addAll(Arrays.asList(friends));
for (String existing : friendList) {
removeFriend.remove(existing);
}
for (String name : removeFriend) {
packet = new Packet(ClientRequest.REMOVEFRIEND);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
//send new stats for this person
String pStats = "";
for (String key : stats.keySet()) {
pStats += key + ":" + stats.get(key) + " ";
}
pStats = pStats.trim();
packet = new Packet(ClientRequest.UPDATESTATS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("stats", pStats);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
//check friend requests
packet = new Packet(ClientRequest.GETREQUESTS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String names = (String) reply.getData("names");
String[] old = friendRequests.toArray(new String[0]);
friendRequests.clear();
friendRequests.addAll(Arrays.asList(names.split(" ")));
if (newRequests.containsAll(Arrays.asList(old))) {
}
for (String name : old) {
if (!newRequests.contains(name)) {
newRequests.add(name);
}
}
packet = new Packet(ClientRequest.GETFRIENDS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
List<String> updateFriends = Arrays.asList(((String) reply.getData("names")).split(" "));
for (String name : updateFriends) {
if (friendList.contains(name)) {
continue;
}
newFriends.add(name);
}
for (String name : friendList) {
if (updateFriends.contains(name)) {
continue;
}
newlyRemovedFriends.add(name);
}
friendList.clear();
friendList.addAll(updateFriends);
//get stats for friends in list
friendStats.clear();
onlineFriends.clear();
for (String friendName : friendList) {
Packet send = new Packet(ClientRequest.GETSTATS);
send.addData("session", Minecraft.getMinecraft().session.sessionId);
send.addData("name", friendName);
packetSender.sendPacket(send);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String stat = (String) reply.getData("stats");
Map<String, Object> friendS = new HashMap<String, Object>();
String[] parts = stat.split(" ");
for (String string : parts) {
friendS.put(string.split(":")[0].toLowerCase().trim(), string.split(":")[1]);
}
friendStats.put(friendName, friendS);
Packet send2 = new Packet(ClientRequest.GETONLINESTATUS);
send2.addData("session", Minecraft.getMinecraft().session.sessionId);
send2.addData("name", friendName);
packetSender.sendPacket(send2);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
boolean isOnline = (Boolean) reply.getData("online");
if (isOnline) {
onlineFriends.add(friendName);
}
}
} catch (IOException ex) {
- ex.printStackTrace(System.err);
+ ex.printStackTrace(System.out);
online = false;
}
} else {
- new ServerConnectionLostException().printStackTrace(System.err);
+ new ServerConnectionLostException().printStackTrace(System.out);
online = false;
}
}
}
}
| false | true | public void run() {
if (online) {
try {
Packet packet = new Packet(ClientRequest.GETFRIENDS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
String[] friends;
Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException((String) reply.getData("reason"));
}
friends = ((String) packet.getData("names")).split(" ");
//check current friend list, removing and adding name differences
List<String> addFriend = new TSAList<String>();
addFriend.addAll(friendList);
for (String existing : friends) {
addFriend.remove(existing);
}
for (String name : addFriend) {
packet = new Packet(ClientRequest.ADDFRIEND);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
List<String> removeFriend = new ArrayList<String>();
removeFriend.addAll(Arrays.asList(friends));
for (String existing : friendList) {
removeFriend.remove(existing);
}
for (String name : removeFriend) {
packet = new Packet(ClientRequest.REMOVEFRIEND);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
//send new stats for this person
String pStats = "";
for (String key : stats.keySet()) {
pStats += key + ":" + stats.get(key) + " ";
}
pStats = pStats.trim();
packet = new Packet(ClientRequest.UPDATESTATS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("stats", pStats);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
//check friend requests
packet = new Packet(ClientRequest.GETREQUESTS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String names = (String) reply.getData("names");
String[] old = friendRequests.toArray(new String[0]);
friendRequests.clear();
friendRequests.addAll(Arrays.asList(names.split(" ")));
if (newRequests.containsAll(Arrays.asList(old))) {
}
for (String name : old) {
if (!newRequests.contains(name)) {
newRequests.add(name);
}
}
packet = new Packet(ClientRequest.GETFRIENDS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
List<String> updateFriends = Arrays.asList(((String) reply.getData("names")).split(" "));
for (String name : updateFriends) {
if (friendList.contains(name)) {
continue;
}
newFriends.add(name);
}
for (String name : friendList) {
if (updateFriends.contains(name)) {
continue;
}
newlyRemovedFriends.add(name);
}
friendList.clear();
friendList.addAll(updateFriends);
//get stats for friends in list
friendStats.clear();
onlineFriends.clear();
for (String friendName : friendList) {
Packet send = new Packet(ClientRequest.GETSTATS);
send.addData("session", Minecraft.getMinecraft().session.sessionId);
send.addData("name", friendName);
packetSender.sendPacket(send);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String stat = (String) reply.getData("stats");
Map<String, Object> friendS = new HashMap<String, Object>();
String[] parts = stat.split(" ");
for (String string : parts) {
friendS.put(string.split(":")[0].toLowerCase().trim(), string.split(":")[1]);
}
friendStats.put(friendName, friendS);
Packet send2 = new Packet(ClientRequest.GETONLINESTATUS);
send2.addData("session", Minecraft.getMinecraft().session.sessionId);
send2.addData("name", friendName);
packetSender.sendPacket(send2);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
boolean isOnline = (Boolean) reply.getData("online");
if (isOnline) {
onlineFriends.add(friendName);
}
}
} catch (IOException ex) {
ex.printStackTrace(System.err);
online = false;
}
} else {
new ServerConnectionLostException().printStackTrace(System.err);
online = false;
}
}
| public void run() {
if (online) {
try {
Packet packet = new Packet(ClientRequest.GETFRIENDS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
String[] friends;
Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException((String) reply.getData("reason"));
}
friends = ((String) packet.getData("names")).split(" ");
//check current friend list, removing and adding name differences
List<String> addFriend = new TSAList<String>();
addFriend.addAll(friendList);
for (String existing : friends) {
addFriend.remove(existing);
}
for (String name : addFriend) {
packet = new Packet(ClientRequest.ADDFRIEND);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
List<String> removeFriend = new ArrayList<String>();
removeFriend.addAll(Arrays.asList(friends));
for (String existing : friendList) {
removeFriend.remove(existing);
}
for (String name : removeFriend) {
packet = new Packet(ClientRequest.REMOVEFRIEND);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
//send new stats for this person
String pStats = "";
for (String key : stats.keySet()) {
pStats += key + ":" + stats.get(key) + " ";
}
pStats = pStats.trim();
packet = new Packet(ClientRequest.UPDATESTATS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("stats", pStats);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
//check friend requests
packet = new Packet(ClientRequest.GETREQUESTS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String names = (String) reply.getData("names");
String[] old = friendRequests.toArray(new String[0]);
friendRequests.clear();
friendRequests.addAll(Arrays.asList(names.split(" ")));
if (newRequests.containsAll(Arrays.asList(old))) {
}
for (String name : old) {
if (!newRequests.contains(name)) {
newRequests.add(name);
}
}
packet = new Packet(ClientRequest.GETFRIENDS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
List<String> updateFriends = Arrays.asList(((String) reply.getData("names")).split(" "));
for (String name : updateFriends) {
if (friendList.contains(name)) {
continue;
}
newFriends.add(name);
}
for (String name : friendList) {
if (updateFriends.contains(name)) {
continue;
}
newlyRemovedFriends.add(name);
}
friendList.clear();
friendList.addAll(updateFriends);
//get stats for friends in list
friendStats.clear();
onlineFriends.clear();
for (String friendName : friendList) {
Packet send = new Packet(ClientRequest.GETSTATS);
send.addData("session", Minecraft.getMinecraft().session.sessionId);
send.addData("name", friendName);
packetSender.sendPacket(send);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String stat = (String) reply.getData("stats");
Map<String, Object> friendS = new HashMap<String, Object>();
String[] parts = stat.split(" ");
for (String string : parts) {
friendS.put(string.split(":")[0].toLowerCase().trim(), string.split(":")[1]);
}
friendStats.put(friendName, friendS);
Packet send2 = new Packet(ClientRequest.GETONLINESTATUS);
send2.addData("session", Minecraft.getMinecraft().session.sessionId);
send2.addData("name", friendName);
packetSender.sendPacket(send2);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
boolean isOnline = (Boolean) reply.getData("online");
if (isOnline) {
onlineFriends.add(friendName);
}
}
} catch (IOException ex) {
ex.printStackTrace(System.out);
online = false;
}
} else {
new ServerConnectionLostException().printStackTrace(System.out);
online = false;
}
}
|
diff --git a/cobertura/src/main/java/net/sourceforge/cobertura/instrument/CoberturaClassWriter.java b/cobertura/src/main/java/net/sourceforge/cobertura/instrument/CoberturaClassWriter.java
index 8b77d4e..2e20bde 100644
--- a/cobertura/src/main/java/net/sourceforge/cobertura/instrument/CoberturaClassWriter.java
+++ b/cobertura/src/main/java/net/sourceforge/cobertura/instrument/CoberturaClassWriter.java
@@ -1,67 +1,67 @@
/**
*
*/
package net.sourceforge.cobertura.instrument;
import org.objectweb.asm.ClassWriter;
/**
* @author schristou88
*
*/
public class CoberturaClassWriter extends ClassWriter {
public CoberturaClassWriter(final int flags) {
super(flags);
}
@Override
protected String getCommonSuperClass(final String type1, final String type2) {
try {
return super.getCommonSuperClass(type1, type2);
} catch (RuntimeException e) {
// Since the default super construction failed we need to dig further.
}
Class<?> c, d;
// If system class fails to load, then let's use the auxClasspath url instead.
try {
c = Class.forName(type1.replace('/', '.'), false, ClassLoader
.getSystemClassLoader());
} catch (Exception e) {
try {
- c = Class.forName(type1.replace('/', '.'), true,
+ c = Class.forName(type1.replace('/', '.'), false,
Main.urlClassLoader);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
}
// If system class fails to load, then let's use the auxClasspath url instead.
try {
d = Class.forName(type2.replace('/', '.'), false, ClassLoader
.getSystemClassLoader());
} catch (Exception e) {
try {
d = Class.forName(type2.replace('/', '.'), false,
Main.urlClassLoader);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
}
if (c.isAssignableFrom(d)) {
return type1;
}
if (d.isAssignableFrom(c)) {
return type2;
}
if (c.isInterface() || d.isInterface()) {
return "java/lang/Object";
} else {
do {
c = c.getSuperclass();
} while (!c.isAssignableFrom(d));
return c.getName().replace('.', '/');
}
}
}
| true | true | protected String getCommonSuperClass(final String type1, final String type2) {
try {
return super.getCommonSuperClass(type1, type2);
} catch (RuntimeException e) {
// Since the default super construction failed we need to dig further.
}
Class<?> c, d;
// If system class fails to load, then let's use the auxClasspath url instead.
try {
c = Class.forName(type1.replace('/', '.'), false, ClassLoader
.getSystemClassLoader());
} catch (Exception e) {
try {
c = Class.forName(type1.replace('/', '.'), true,
Main.urlClassLoader);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
}
// If system class fails to load, then let's use the auxClasspath url instead.
try {
d = Class.forName(type2.replace('/', '.'), false, ClassLoader
.getSystemClassLoader());
} catch (Exception e) {
try {
d = Class.forName(type2.replace('/', '.'), false,
Main.urlClassLoader);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
}
if (c.isAssignableFrom(d)) {
return type1;
}
if (d.isAssignableFrom(c)) {
return type2;
}
if (c.isInterface() || d.isInterface()) {
return "java/lang/Object";
} else {
do {
c = c.getSuperclass();
} while (!c.isAssignableFrom(d));
return c.getName().replace('.', '/');
}
}
| protected String getCommonSuperClass(final String type1, final String type2) {
try {
return super.getCommonSuperClass(type1, type2);
} catch (RuntimeException e) {
// Since the default super construction failed we need to dig further.
}
Class<?> c, d;
// If system class fails to load, then let's use the auxClasspath url instead.
try {
c = Class.forName(type1.replace('/', '.'), false, ClassLoader
.getSystemClassLoader());
} catch (Exception e) {
try {
c = Class.forName(type1.replace('/', '.'), false,
Main.urlClassLoader);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
}
// If system class fails to load, then let's use the auxClasspath url instead.
try {
d = Class.forName(type2.replace('/', '.'), false, ClassLoader
.getSystemClassLoader());
} catch (Exception e) {
try {
d = Class.forName(type2.replace('/', '.'), false,
Main.urlClassLoader);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
}
if (c.isAssignableFrom(d)) {
return type1;
}
if (d.isAssignableFrom(c)) {
return type2;
}
if (c.isInterface() || d.isInterface()) {
return "java/lang/Object";
} else {
do {
c = c.getSuperclass();
} while (!c.isAssignableFrom(d));
return c.getName().replace('.', '/');
}
}
|
diff --git a/core/src/visad/trunk/Gridded3DSet.java b/core/src/visad/trunk/Gridded3DSet.java
index 500b3485b..9d78d15fd 100644
--- a/core/src/visad/trunk/Gridded3DSet.java
+++ b/core/src/visad/trunk/Gridded3DSet.java
@@ -1,4782 +1,4787 @@
//
// Gridded3DSet.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.io.*;
/**
Gridded3DSet represents a finite set of samples of R^3.<P>
*/
public class Gridded3DSet extends GriddedSet {
int LengthX, LengthY, LengthZ;
float LowX, HiX, LowY, HiY, LowZ, HiZ;
/** a 3-D set whose topology is a lengthX x lengthY x lengthZ
grid, with null errors, CoordinateSystem and Units are
defaults from type */
public Gridded3DSet(MathType type, float[][] samples, int lengthX,
int lengthY, int lengthZ) throws VisADException {
this(type, samples, lengthX, lengthY, lengthZ, null, null, null);
}
/** a 3-D set whose topology is a lengthX x lengthY x lengthZ
grid; samples array is organized float[3][number_of_samples]
where lengthX * lengthY * lengthZ = number_of_samples;
samples must form a non-degenerate 3-D grid (no bow-tie-shaped
grid cubes); the X component increases fastest and the Z
component slowest in the second index of samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded3DSet(MathType type, float[][] samples,
int lengthX, int lengthY, int lengthZ,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, samples, lengthX, lengthY, lengthZ, coord_sys,
units, errors, true, true);
}
public Gridded3DSet(MathType type, float[][] samples,
int lengthX, int lengthY, int lengthZ,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
this(type, samples, lengthX, lengthY, lengthZ, coord_sys,
units, errors, copy, true);
}
public Gridded3DSet(MathType type, float[][] samples,
int lengthX, int lengthY, int lengthZ,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy,
boolean test) throws VisADException {
super(type, samples, make_lengths(lengthX, lengthY, lengthZ),
coord_sys, units, errors, copy);
LowX = Low[0];
HiX = Hi[0];
LengthX = Lengths[0];
LowY = Low[1];
HiY = Hi[1];
LengthY = Lengths[1];
LowZ = Low[2];
HiZ = Hi[2];
LengthZ = Lengths[2];
if (Samples != null &&
Lengths[0] > 1 && Lengths[1] > 1 && Lengths[2] > 1) {
for (int i=0; i<Length; i++) {
if (Samples[0][i] != Samples[0][i]) {
throw new SetException(
"Gridded3DSet: samples values may not be missing");
}
}
if (test) {
// Samples consistency test
float[] t000 = new float[3];
float[] t100 = new float[3];
float[] t010 = new float[3];
float[] t001 = new float[3];
float[] t110 = new float[3];
float[] t101 = new float[3];
float[] t011 = new float[3];
float[] t111 = new float[3];
for (int v=0; v<3; v++) {
t000[v] = Samples[v][0];
t100[v] = Samples[v][1];
t010[v] = Samples[v][LengthX];
t001[v] = Samples[v][LengthY*LengthX];
t110[v] = Samples[v][LengthX+1];
t101[v] = Samples[v][LengthY*LengthX+1];
t011[v] = Samples[v][(LengthY+1)*LengthX];
t111[v] = Samples[v][(LengthY+1)*LengthX+1];
}
Pos = ( ( (t100[1]-t000[1])*(t101[2]-t100[2])
- (t100[2]-t000[2])*(t101[1]-t100[1]) )
*(t110[0]-t100[0]) )
+ ( ( (t100[2]-t000[2])*(t101[0]-t100[0])
- (t100[0]-t000[0])*(t101[2]-t100[2]) )
*(t110[1]-t100[1]) )
+ ( ( (t100[0]-t000[0])*(t101[1]-t100[1])
- (t100[1]-t000[1])*(t101[0]-t100[0]) )
*(t110[2]-t100[2]) ) > 0;
for (int k=0; k<LengthZ-1; k++) {
for (int j=0; j<LengthY-1; j++) {
for (int i=0; i<LengthX-1; i++) {
float[] v000 = new float[3];
float[] v100 = new float[3];
float[] v010 = new float[3];
float[] v001 = new float[3];
float[] v110 = new float[3];
float[] v101 = new float[3];
float[] v011 = new float[3];
float[] v111 = new float[3];
for (int v=0; v<3; v++) {
int zadd = LengthY*LengthX;
int base = k*zadd + j*LengthX + i;
v000[v] = Samples[v][base];
v100[v] = Samples[v][base+1];
v010[v] = Samples[v][base+LengthX];
v001[v] = Samples[v][base+zadd];
v110[v] = Samples[v][base+LengthX+1];
v101[v] = Samples[v][base+zadd+1];
v011[v] = Samples[v][base+zadd+LengthX];
v111[v] = Samples[v][base+zadd+LengthX+1];
}
if ((( ( (v100[1]-v000[1])*(v101[2]-v100[2]) // test 1
- (v100[2]-v000[2])*(v101[1]-v100[1]) )
*(v110[0]-v100[0]) )
+ ( ( (v100[2]-v000[2])*(v101[0]-v100[0])
- (v100[0]-v000[0])*(v101[2]-v100[2]) )
*(v110[1]-v100[1]) )
+ ( ( (v100[0]-v000[0])*(v101[1]-v100[1])
- (v100[1]-v000[1])*(v101[0]-v100[0]) )
*(v110[2]-v100[2]) ) > 0 != Pos)
|| (( ( (v101[1]-v100[1])*(v001[2]-v101[2]) // test 2
- (v101[2]-v100[2])*(v001[1]-v101[1]) )
*(v111[0]-v101[0]) )
+ ( ( (v101[2]-v100[2])*(v001[0]-v101[0])
- (v101[0]-v100[0])*(v001[2]-v101[2]) )
*(v111[1]-v101[1]) )
+ ( ( (v101[0]-v100[0])*(v001[1]-v101[1])
- (v101[1]-v100[1])*(v001[0]-v101[0]) )
*(v111[2]-v101[2]) ) > 0 != Pos)
|| (( ( (v001[1]-v101[1])*(v000[2]-v001[2]) // test 3
- (v001[2]-v101[2])*(v000[1]-v001[1]) )
*(v011[0]-v001[0]) )
+ ( ( (v001[2]-v101[2])*(v000[0]-v001[0])
- (v001[0]-v101[0])*(v000[2]-v001[2]) )
*(v011[1]-v001[1]) )
+ ( ( (v001[0]-v101[0])*(v000[1]-v001[1])
- (v001[1]-v101[1])*(v000[0]-v001[0]) )
*(v011[2]-v001[2]) ) > 0 != Pos)
|| (( ( (v000[1]-v001[1])*(v100[2]-v000[2]) // test 4
- (v000[2]-v001[2])*(v100[1]-v000[1]) )
*(v010[0]-v000[0]) )
+ ( ( (v000[2]-v001[2])*(v100[0]-v000[0])
- (v000[0]-v001[0])*(v100[2]-v000[2]) )
*(v010[1]-v000[1]) )
+ ( ( (v000[0]-v001[0])*(v100[1]-v000[1])
- (v000[1]-v001[1])*(v100[0]-v000[0]) )
*(v010[2]-v000[2]) ) > 0 != Pos)
|| (( ( (v110[1]-v111[1])*(v010[2]-v110[2]) // test 5
- (v110[2]-v111[2])*(v010[1]-v110[1]) )
*(v100[0]-v110[0]) )
+ ( ( (v110[2]-v111[2])*(v010[0]-v110[0])
- (v110[0]-v111[0])*(v010[2]-v110[2]) )
*(v100[1]-v110[1]) )
+ ( ( (v110[0]-v111[0])*(v010[1]-v110[1])
- (v110[1]-v111[1])*(v010[0]-v110[0]) )
*(v100[2]-v110[2]) ) > 0 != Pos)
|| (( ( (v111[1]-v011[1])*(v110[2]-v111[2]) // test 6
- (v111[2]-v011[2])*(v110[1]-v111[1]) )
*(v101[0]-v111[0]) )
+ ( ( (v111[2]-v011[2])*(v110[0]-v111[0])
- (v111[0]-v011[0])*(v110[2]-v111[2]) )
*(v101[1]-v111[1]) )
+ ( ( (v111[0]-v011[0])*(v110[1]-v111[1])
- (v111[1]-v011[1])*(v110[0]-v111[0]) )
*(v101[2]-v111[2]) ) > 0 != Pos)
|| (( ( (v011[1]-v010[1])*(v111[2]-v011[2]) // test 7
- (v011[2]-v010[2])*(v111[1]-v011[1]) )
*(v001[0]-v011[0]) )
+ ( ( (v011[2]-v010[2])*(v111[0]-v011[0])
- (v011[0]-v010[0])*(v111[2]-v011[2]) )
*(v001[1]-v011[1]) )
+ ( ( (v011[0]-v010[0])*(v111[1]-v011[1])
- (v011[1]-v010[1])*(v111[0]-v011[0]) )
*(v001[2]-v011[2]) ) > 0 != Pos)
|| (( ( (v010[1]-v110[1])*(v011[2]-v010[2]) // test 8
- (v010[2]-v110[2])*(v011[1]-v010[1]) )
*(v000[0]-v010[0]) )
+ ( ( (v010[2]-v110[2])*(v011[0]-v010[0])
- (v010[0]-v110[0])*(v011[2]-v010[2]) )
*(v000[1]-v010[1]) )
+ ( ( (v010[0]-v110[0])*(v011[1]-v010[1])
- (v010[1]-v110[1])*(v011[0]-v010[0]) )
*(v000[2]-v010[2]) ) > 0 != Pos)) {
throw new SetException("Gridded3DSet: samples do not form "
+"a valid grid ("+i+","+j+","+k+")");
}
}
}
}
} // end if (test)
}
}
/** a 3-D set with manifold dimension = 2, with null errors,
CoordinateSystem and Units are defaults from type */
public Gridded3DSet(MathType type, float[][] samples, int lengthX,
int lengthY) throws VisADException {
this(type, samples, lengthX, lengthY, null, null, null);
}
/** a 3-D set with manifold dimension = 2; samples array is
organized float[3][number_of_samples] where lengthX * lengthY
= number_of_samples; no geometric constraint on samples; the
X component increases fastest in the second index of samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded3DSet(MathType type, float[][] samples,
int lengthX, int lengthY,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, samples, lengthX, lengthY, coord_sys, units,
errors, true);
}
public Gridded3DSet(MathType type, float[][] samples,
int lengthX, int lengthY,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
super(type, samples, Gridded2DSet.make_lengths(lengthX, lengthY),
coord_sys, units, errors, copy);
LowX = Low[0];
HiX = Hi[0];
LengthX = Lengths[0];
LowY = Low[1];
HiY = Hi[1];
LengthY = Lengths[1];
LowZ = Low[2];
HiZ = Hi[2];
// no Samples consistency test
}
/** a 3-D set with manifold dimension = 1, with null errors,
CoordinateSystem and Units are defaults from type */
public Gridded3DSet(MathType type, float[][] samples, int lengthX)
throws VisADException {
this(type, samples, lengthX, null, null, null);
}
/** a 3-D set with manifold dimension = 1; samples array is
organized float[3][number_of_samples] where lengthX =
number_of_samples; no geometric constraint on samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded3DSet(MathType type, float[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, samples, lengthX, coord_sys, units, errors, true);
}
public Gridded3DSet(MathType type, float[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
super(type, samples, Gridded1DSet.make_lengths(lengthX),
coord_sys, units, errors, copy);
LowX = Low[0];
HiX = Hi[0];
LengthX = Lengths[0];
LowY = Low[1];
HiY = Hi[1];
LowZ = Low[2];
HiZ = Hi[2];
// no Samples consistency test
}
static int[] make_lengths(int lengthX, int lengthY, int lengthZ) {
int[] lens = new int[3];
lens[0] = lengthX;
lens[1] = lengthY;
lens[2] = lengthZ;
return lens;
}
/** convert an array of 1-D indices to an array of values in R^DomainDimension */
public float[][] indexToValue(int[] index) throws VisADException {
int length = index.length;
if (Samples == null) {
// not used - over-ridden by Linear3DSet.indexToValue
int indexX, indexY, indexZ;
int k;
float[][] grid = new float[ManifoldDimension][length];
for (int i=0; i<length; i++) {
if (0 <= index[i] && index[i] < Length) {
indexX = index[i] % LengthX;
k = index[i] / LengthX;
indexY = k % LengthY;
indexZ = k / LengthY;
}
else {
indexX = -1;
indexY = -1;
indexZ = -1;
}
grid[0][i] = (float) indexX;
grid[1][i] = (float) indexY;
grid[2][i] = (float) indexZ;
}
return gridToValue(grid);
}
else {
float[][] values = new float[3][length];
for (int i=0; i<length; i++) {
if (0 <= index[i] && index[i] < Length) {
values[0][i] = Samples[0][index[i]];
values[1][i] = Samples[1][index[i]];
values[2][i] = Samples[2][index[i]];
}
else {
values[0][i] = Float.NaN;
values[1][i] = Float.NaN;
values[2][i] = Float.NaN;
}
}
return values;
}
}
/** convert an array of values in R^DomainDimension to an array of 1-D indices */
public int[] valueToIndex(float[][] value) throws VisADException {
if (value.length != DomainDimension) {
throw new SetException("Gridded3DSet.valueToIndex: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int length = value[0].length;
int[] index = new int[length];
float[][] grid = valueToGrid(value);
float[] grid0 = grid[0];
float[] grid1 = grid[1];
float[] grid2 = grid[2];
float g0, g1, g2;
for (int i=0; i<length; i++) {
g0 = grid0[i];
g1 = grid1[i];
g2 = grid2[i];
/* WLH 24 Oct 97
index[i] = (Float.isNaN(g0)
|| Float.isNaN(g1)
|| Float.isNaN(g2)) ? -1 :
*/
// test for missing
/* WLH 2 April 99
index[i] = (g0 != g0 || g1 != g1 || g2 != g2) ? 1 :
*/
index[i] = (g0 != g0 || g1 != g1 || g2 != g2) ? -1 :
((int) (g0 + 0.5)) + LengthX*( ((int) (g1 + 0.5)) +
LengthY*((int) (g2 + 0.5)));
}
return index;
}
/** transform an array of non-integer grid coordinates to an array
of values in R^DomainDimension */
public float[][] gridToValue(float[][] grid) throws VisADException {
if (grid.length != ManifoldDimension) {
throw new SetException("Gridded3DSet.gridToValue: grid dimension " +
grid.length + " not equal to Manifold dimension " +
ManifoldDimension);
}
if (ManifoldDimension == 3) {
return gridToValue3D(grid);
}
else if (ManifoldDimension == 2) {
return gridToValue2D(grid);
}
else {
throw new SetException("Gridded3DSet.gridToValue: ManifoldDimension " +
"must be 2 or 3");
}
}
private float[][] gridToValue2D(float[][] grid) throws VisADException {
if (Lengths[0] < 2 || Lengths[1] < 2) {
throw new SetException("Gridded3DSet.gridToValue: requires all grid " +
"dimensions to be > 1");
}
// avoid any ArrayOutOfBounds exceptions by taking the shortest length
int length = Math.min(grid[0].length, grid[1].length);
float[][] value = new float[3][length];
for (int i=0; i<length; i++) {
// let gx and gy by the current grid values
float gx = grid[0][i];
float gy = grid[1][i];
if ( (gx < -0.5) || (gy < -0.5) ||
(gx > LengthX-0.5) || (gy > LengthY-0.5) ) {
value[0][i] = value[1][i] = value[2][i] = Float.NaN;
continue;
}
// calculate closest integer variables
int igx = (int) gx;
int igy = (int) gy;
if (igx < 0) igx = 0;
if (igx > LengthX-2) igx = LengthX-2;
if (igy < 0) igy = 0;
if (igy > LengthY-2) igy = LengthY-2;
// set up conversion to 1D Samples array
int[][] s = { {LengthX*igy+igx, // (0, 0)
LengthX*(igy+1)+igx}, // (0, 1)
{LengthX*igy+igx+1, // (1, 0)
LengthX*(igy+1)+igx+1} }; // (1, 1)
if (gx+gy-igx-igy-1 <= 0) {
// point is in LOWER triangle
for (int j=0; j<3; j++) {
value[j][i] = Samples[j][s[0][0]]
+ (gx-igx)*(Samples[j][s[1][0]]-Samples[j][s[0][0]])
+ (gy-igy)*(Samples[j][s[0][1]]-Samples[j][s[0][0]]);
}
}
else {
// point is in UPPER triangle
for (int j=0; j<3; j++) {
value[j][i] = Samples[j][s[1][1]]
+ (1+igx-gx)*(Samples[j][s[0][1]]-Samples[j][s[1][1]])
+ (1+igy-gy)*(Samples[j][s[1][0]]-Samples[j][s[1][1]]);
}
}
/*
for (int j=0; j<3; j++) {
if (value[j][i] != value[j][i]) {
System.out.println("gridToValue2D: bad Samples j = " + j + " gx, gy = " + gx +
" " + gy + " " + s[0][0] + " " + s[0][1] +
" " + s[1][0] + " " + s[1][1]);
}
}
*/
}
return value;
}
private float[][] gridToValue3D(float[][] grid) throws VisADException {
if (Lengths[0] < 2 || Lengths[1] < 2 || Lengths[2] < 2) {
throw new SetException("Gridded3DSet.gridToValue: requires all grid " +
"dimensions to be > 1");
}
// avoid any ArrayOutOfBounds exceptions by taking the shortest length
int length = Math.min(grid[0].length, grid[1].length);
length = Math.min(length, grid[2].length);
float[][] value = new float[3][length];
for (int i=0; i<length; i++) {
// let gx, gy, and gz be the current grid values
float gx = grid[0][i];
float gy = grid[1][i];
float gz = grid[2][i];
if ( (gx < -0.5) || (gy < -0.5) || (gz < -0.5) ||
(gx > LengthX-0.5) || (gy > LengthY-0.5) || (gz > LengthZ-0.5) ) {
value[0][i] = value[1][i] = value[2][i] = Float.NaN;
continue;
}
// calculate closest integer variables
int igx, igy, igz;
if (gx < 0) igx = 0;
else if (gx > LengthX-2) igx = LengthX - 2;
else igx = (int) gx;
if (gy < 0) igy = 0;
else if (gy > LengthY-2) igy = LengthY - 2;
else igy = (int) gy;
if (gz < 0) igz = 0;
else if (gz > LengthZ-2) igz = LengthZ - 2;
else igz = (int) gz;
// determine tetrahedralization type
boolean evencube = ((igx+igy+igz) % 2 == 0);
// calculate distances from integer grid point
float s, t, u;
if (evencube) {
s = gx - igx;
t = gy - igy;
u = gz - igz;
}
else {
s = 1 + igx - gx;
t = 1 + igy - gy;
u = 1 + igz - gz;
}
// Define vertices of grid box
int zadd = LengthY*LengthX;
int base = igz*zadd + igy*LengthX + igx;
int ai = base+zadd; // 0, 0, 1
int bi = base+zadd+1; // 1, 0, 1
int ci = base+zadd+LengthX+1; // 1, 1, 1
int di = base+zadd+LengthX; // 0, 1, 1
int ei = base; // 0, 0, 0
int fi = base+1; // 1, 0, 0
int gi = base+LengthX+1; // 1, 1, 0
int hi = base+LengthX; // 0, 1, 0
float[] A = new float[3];
float[] B = new float[3];
float[] C = new float[3];
float[] D = new float[3];
float[] E = new float[3];
float[] F = new float[3];
float[] G = new float[3];
float[] H = new float[3];
if (evencube) {
A[0] = Samples[0][ai];
A[1] = Samples[1][ai];
A[2] = Samples[2][ai];
B[0] = Samples[0][bi];
B[1] = Samples[1][bi];
B[2] = Samples[2][bi];
C[0] = Samples[0][ci];
C[1] = Samples[1][ci];
C[2] = Samples[2][ci];
D[0] = Samples[0][di];
D[1] = Samples[1][di];
D[2] = Samples[2][di];
E[0] = Samples[0][ei];
E[1] = Samples[1][ei];
E[2] = Samples[2][ei];
F[0] = Samples[0][fi];
F[1] = Samples[1][fi];
F[2] = Samples[2][fi];
G[0] = Samples[0][gi];
G[1] = Samples[1][gi];
G[2] = Samples[2][gi];
H[0] = Samples[0][hi];
H[1] = Samples[1][hi];
H[2] = Samples[2][hi];
}
else {
G[0] = Samples[0][ai];
G[1] = Samples[1][ai];
G[2] = Samples[2][ai];
H[0] = Samples[0][bi];
H[1] = Samples[1][bi];
H[2] = Samples[2][bi];
E[0] = Samples[0][ci];
E[1] = Samples[1][ci];
E[2] = Samples[2][ci];
F[0] = Samples[0][di];
F[1] = Samples[1][di];
F[2] = Samples[2][di];
C[0] = Samples[0][ei];
C[1] = Samples[1][ei];
C[2] = Samples[2][ei];
D[0] = Samples[0][fi];
D[1] = Samples[1][fi];
D[2] = Samples[2][fi];
A[0] = Samples[0][gi];
A[1] = Samples[1][gi];
A[2] = Samples[2][gi];
B[0] = Samples[0][hi];
B[1] = Samples[1][hi];
B[2] = Samples[2][hi];
}
// These tests determine which tetrahedron the point is in
boolean test1 = (1 - s - t - u >= 0);
boolean test2 = (s - t + u - 1 >= 0);
boolean test3 = (t - s + u - 1 >= 0);
boolean test4 = (s + t - u - 1 >= 0);
// These cases handle grid coordinates off the grid
// (Different tetrahedrons must be chosen accordingly)
if ( (gx < 0) || (gx > LengthX-1)
|| (gy < 0) || (gy > LengthY-1)
|| (gz < 0) || (gz > LengthZ-1) ) {
boolean OX, OY, OZ, MX, MY, MZ, LX, LY, LZ;
OX = OY = OZ = MX = MY = MZ = LX = LY = LZ = false;
if (igx == 0) OX = true;
if (igy == 0) OY = true;
if (igz == 0) OZ = true;
if (igx == LengthX-2) LX = true;
if (igy == LengthY-2) LY = true;
if (igz == LengthZ-2) LZ = true;
if (!OX && !LX) MX = true;
if (!OY && !LY) MY = true;
if (!OZ && !LZ) MZ = true;
test1 = test2 = test3 = test4 = false;
// 26 cases
if (evencube) {
if (!LX && !LY && !LZ) test1 = true;
else if ( (LX && OY && MZ) || (MX && OY && LZ)
|| (LX && MY && LZ) || (LX && OY && LZ)
|| (MX && MY && LZ) || (LX && MY && MZ) ) test2 = true;
else if ( (OX && LY && MZ) || (OX && MY && LZ)
|| (MX && LY && LZ) || (OX && LY && LZ)
|| (MX && LY && MZ) ) test3 = true;
else if ( (MX && LY && OZ) || (LX && MY && OZ)
|| (LX && LY && MZ) || (LX && LY && OZ) ) test4 = true;
}
else {
if (!OX && !OY && !OZ) test1 = true;
else if ( (OX && MY && OZ) || (MX && LY && OZ)
|| (OX && LY && MZ) || (OX && LY && OZ)
|| (MX && MY && OZ) || (OX && MY && MZ) ) test2 = true;
else if ( (LX && MY && OZ) || (MX && OY && OZ)
|| (LX && OY && MZ) || (LX && OY && OZ)
|| (MX && OY && MZ) ) test3 = true;
else if ( (OX && OY && MZ) || (OX && MY && OZ)
|| (MX && OY && LZ) || (OX && OY && LZ) ) test4 = true;
}
}
if (test1) {
for (int j=0; j<3; j++) {
value[j][i] = E[j] + s*(F[j]-E[j])
+ t*(H[j]-E[j])
+ u*(A[j]-E[j]);
}
}
else if (test2) {
for (int j=0; j<3; j++) {
value[j][i] = B[j] + (1-s)*(A[j]-B[j])
+ t*(C[j]-B[j])
+ (1-u)*(F[j]-B[j]);
}
}
else if (test3) {
for (int j=0; j<3; j++) {
value[j][i] = D[j] + s*(C[j]-D[j])
+ (1-t)*(A[j]-D[j])
+ (1-u)*(H[j]-D[j]);
}
}
else if (test4) {
for (int j=0; j<3; j++) {
value[j][i] = G[j] + (1-s)*(H[j]-G[j])
+ (1-t)*(F[j]-G[j])
+ u*(C[j]-G[j]);
}
}
else {
for (int j=0; j<3; j++) {
value[j][i] = (H[j]+F[j]+A[j]-C[j])/2 + s*(C[j]+F[j]-H[j]-A[j])/2
+ t*(C[j]-F[j]+H[j]-A[j])/2
+ u*(C[j]-F[j]-H[j]+A[j])/2;
}
}
}
return value;
}
// WLH 6 Dec 2001
private int gx = -1;
private int gy = -1;
private int gz = -1;
/** transform an array of values in R^DomainDimension to an array
of non-integer grid coordinates */
public float[][] valueToGrid(float[][] value) throws VisADException {
if (value.length < DomainDimension) {
throw new SetException("Gridded3DSet.valueToGrid: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
if (ManifoldDimension < 3) {
throw new SetException("Gridded3DSet.valueToGrid: ManifoldDimension " +
"must be 3");
}
if (Lengths[0] < 2 || Lengths[1] < 2 || Lengths[2] < 2) {
throw new SetException("Gridded3DSet.valueToGrid: requires all grid " +
"dimensions to be > 1");
}
// Avoid any ArrayOutOfBounds exceptions by taking the shortest length
int length = Math.min(value[0].length, value[1].length);
length = Math.min(length, value[2].length);
float[][] grid = new float[ManifoldDimension][length];
// (gx, gy, gz) is the current grid box guess
/* WLH 6 Dec 2001
int gx = (LengthX-1)/2;
int gy = (LengthY-1)/2;
int gz = (LengthZ-1)/2;
*/
// use value from last call as first guess, if reasonable
if (gx < 0 || gx >= LengthX || gy < 0 || gy >= LengthY ||
gz < 0 || gz >= LengthZ) {
gx = (LengthX-1)/2;
gy = (LengthY-1)/2;
gz = (LengthZ-1)/2;
}
for (int i=0; i<length; i++) {
// a flag indicating whether point is off the grid
boolean offgrid = false;
// the first guess should be the last box unless there was no solution
/* WLH 24 Oct 97
if ( (i != 0) && (Float.isNaN(grid[0][i-1])) )
*/
// test for missing
if ( (i != 0) && grid[0][i-1] != grid[0][i-1] ) {
gx = (LengthX-1)/2;
gy = (LengthY-1)/2;
gz = (LengthZ-1)/2;
}
int tetnum = 5; // Tetrahedron number in which to start search
// if the iteration loop fails, the result should be NaN
grid[0][i] = grid[1][i] = grid[2][i] = Float.NaN;
for (int itnum=0; itnum<2*(LengthX+LengthY+LengthZ); itnum++) {
// determine tetrahedralization type
boolean evencube = ((gx+gy+gz) % 2 == 0);
// Define vertices of grid box
int zadd = LengthY*LengthX;
int base = gz*zadd + gy*LengthX + gx;
int ai = base+zadd; // 0, 0, 1
int bi = base+zadd+1; // 1, 0, 1
int ci = base+zadd+LengthX+1; // 1, 1, 1
int di = base+zadd+LengthX; // 0, 1, 1
int ei = base; // 0, 0, 0
int fi = base+1; // 1, 0, 0
int gi = base+LengthX+1; // 1, 1, 0
int hi = base+LengthX; // 0, 1, 0
float[] A = new float[3];
float[] B = new float[3];
float[] C = new float[3];
float[] D = new float[3];
float[] E = new float[3];
float[] F = new float[3];
float[] G = new float[3];
float[] H = new float[3];
if (evencube) {
A[0] = Samples[0][ai];
A[1] = Samples[1][ai];
A[2] = Samples[2][ai];
B[0] = Samples[0][bi];
B[1] = Samples[1][bi];
B[2] = Samples[2][bi];
C[0] = Samples[0][ci];
C[1] = Samples[1][ci];
C[2] = Samples[2][ci];
D[0] = Samples[0][di];
D[1] = Samples[1][di];
D[2] = Samples[2][di];
E[0] = Samples[0][ei];
E[1] = Samples[1][ei];
E[2] = Samples[2][ei];
F[0] = Samples[0][fi];
F[1] = Samples[1][fi];
F[2] = Samples[2][fi];
G[0] = Samples[0][gi];
G[1] = Samples[1][gi];
G[2] = Samples[2][gi];
H[0] = Samples[0][hi];
H[1] = Samples[1][hi];
H[2] = Samples[2][hi];
}
else {
G[0] = Samples[0][ai];
G[1] = Samples[1][ai];
G[2] = Samples[2][ai];
H[0] = Samples[0][bi];
H[1] = Samples[1][bi];
H[2] = Samples[2][bi];
E[0] = Samples[0][ci];
E[1] = Samples[1][ci];
E[2] = Samples[2][ci];
F[0] = Samples[0][di];
F[1] = Samples[1][di];
F[2] = Samples[2][di];
C[0] = Samples[0][ei];
C[1] = Samples[1][ei];
C[2] = Samples[2][ei];
D[0] = Samples[0][fi];
D[1] = Samples[1][fi];
D[2] = Samples[2][fi];
A[0] = Samples[0][gi];
A[1] = Samples[1][gi];
A[2] = Samples[2][gi];
B[0] = Samples[0][hi];
B[1] = Samples[1][hi];
B[2] = Samples[2][hi];
}
// Compute tests and go to a new box depending on results
boolean test1, test2, test3, test4;
float tval1, tval2, tval3, tval4;
int ogx = gx;
int ogy = gy;
int ogz = gz;
if (tetnum==1) {
tval1 = ( (E[1]-A[1])*(F[2]-E[2]) - (E[2]-A[2])*(F[1]-E[1]) )
*(value[0][i]-E[0])
+ ( (E[2]-A[2])*(F[0]-E[0]) - (E[0]-A[0])*(F[2]-E[2]) )
*(value[1][i]-E[1])
+ ( (E[0]-A[0])*(F[1]-E[1]) - (E[1]-A[1])*(F[0]-E[0]) )
*(value[2][i]-E[2]);
tval2 = ( (E[1]-H[1])*(A[2]-E[2]) - (E[2]-H[2])*(A[1]-E[1]) )
*(value[0][i]-E[0])
+ ( (E[2]-H[2])*(A[0]-E[0]) - (E[0]-H[0])*(A[2]-E[2]) )
*(value[1][i]-E[1])
+ ( (E[0]-H[0])*(A[1]-E[1]) - (E[1]-H[1])*(A[0]-E[0]) )
*(value[2][i]-E[2]);
tval3 = ( (E[1]-F[1])*(H[2]-E[2]) - (E[2]-F[2])*(H[1]-E[1]) )
*(value[0][i]-E[0])
+ ( (E[2]-F[2])*(H[0]-E[0]) - (E[0]-F[0])*(H[2]-E[2]) )
*(value[1][i]-E[1])
+ ( (E[0]-F[0])*(H[1]-E[1]) - (E[1]-F[1])*(H[0]-E[0]) )
*(value[2][i]-E[2]);
test1 = (tval1 == 0) || ((tval1 > 0) == (!evencube)^Pos);
test2 = (tval2 == 0) || ((tval2 > 0) == (!evencube)^Pos);
test3 = (tval3 == 0) || ((tval3 > 0) == (!evencube)^Pos);
// if a test failed go to a new box
int updown = (evencube) ? -1 : 1;
if (!test1) gy += updown; // UP/DOWN
if (!test2) gx += updown; // LEFT/RIGHT
if (!test3) gz += updown; // BACK/FORWARD
tetnum = 5;
// Snap coordinates back onto grid in case they fell off.
if (gx < 0) gx = 0;
if (gy < 0) gy = 0;
if (gz < 0) gz = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy > LengthY-2) gy = LengthY-2;
if (gz > LengthZ-2) gz = LengthZ-2;
// Detect if the point is off the grid entirely
if ( (gx == ogx) && (gy == ogy) && (gz == ogz)
&& (!test1 || !test2 || !test3) && !offgrid ) {
offgrid = true;
continue;
}
// If all tests pass then this is the correct tetrahedron
if ( ( (gx == ogx) && (gy == ogy) && (gz == ogz) )
|| offgrid) {
// solve point
float[] M = new float[3];
float[] N = new float[3];
float[] O = new float[3];
float[] P = new float[3];
float[] X = new float[3];
float[] Y = new float[3];
for (int j=0; j<3; j++) {
M[j] = (F[j]-E[j])*(A[(j+1)%3]-E[(j+1)%3])
- (F[(j+1)%3]-E[(j+1)%3])*(A[j]-E[j]);
N[j] = (H[j]-E[j])*(A[(j+1)%3]-E[(j+1)%3])
- (H[(j+1)%3]-E[(j+1)%3])*(A[j]-E[j]);
O[j] = (F[(j+1)%3]-E[(j+1)%3])*(A[(j+2)%3]-E[(j+2)%3])
- (F[(j+2)%3]-E[(j+2)%3])*(A[(j+1)%3]-E[(j+1)%3]);
P[j] = (H[(j+1)%3]-E[(j+1)%3])*(A[(j+2)%3]-E[(j+2)%3])
- (H[(j+2)%3]-E[(j+2)%3])*(A[(j+1)%3]-E[(j+1)%3]);
X[j] = value[(j+2)%3][i]*(A[(j+1)%3]-E[(j+1)%3])
- value[(j+1)%3][i]*(A[(j+2)%3]-E[(j+2)%3])
+ E[(j+1)%3]*A[(j+2)%3] - E[(j+2)%3]*A[(j+1)%3];
Y[j] = value[j][i]*(A[(j+1)%3]-E[(j+1)%3])
- value[(j+1)%3][i]*(A[j]-E[j])
+ E[(j+1)%3]*A[j] - E[j]*A[(j+1)%3];
}
float s, t, u;
// these if statements handle skewed grids
float d0 = M[0]*P[0] - N[0]*O[0];
float d1 = M[1]*P[1] - N[1]*O[1];
float d2 = M[2]*P[2] - N[2]*O[2];
float ad0 = Math.abs(d0);
float ad1 = Math.abs(d1);
float ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
s = (N[0]*X[0] + P[0]*Y[0])/d0;
t = -(M[0]*X[0] + O[0]*Y[0])/d0;
}
else if (ad1 > ad2) {
s = (N[1]*X[1] + P[1]*Y[1])/d1;
t = -(M[1]*X[1] + O[1]*Y[1])/d1;
}
else {
s = (N[2]*X[2] + P[2]*Y[2])/d2;
t = -(M[2]*X[2] + O[2]*Y[2])/d2;
}
/* WLH 5 April 99
if (M[0]*P[0] != N[0]*O[0]) {
s = (N[0]*X[0] + P[0]*Y[0])/(M[0]*P[0] - N[0]*O[0]);
t = (M[0]*X[0] + O[0]*Y[0])/(N[0]*O[0] - M[0]*P[0]);
}
else if (M[1]*P[1] != N[1]*O[1]) {
s = (N[1]*X[1] + P[1]*Y[1])/(M[1]*P[1] - N[1]*O[1]);
t = (M[1]*X[1] + O[1]*Y[1])/(N[1]*O[1] - M[1]*P[1]);
}
else {
s = (N[2]*X[2] + P[2]*Y[2])/(M[2]*P[2] - N[2]*O[2]);
t = (M[2]*X[2] + O[2]*Y[2])/(N[2]*O[2] - M[2]*P[2]);
}
*/
d0 = A[0]-E[0];
d1 = A[1]-E[1];
d2 = A[2]-E[2];
ad0 = Math.abs(d0);
ad1 = Math.abs(d1);
ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
u = ( value[0][i] - E[0] - s*(F[0]-E[0])
- t*(H[0]-E[0]) ) / d0;
}
else if (ad1 > ad2) {
u = ( value[1][i] - E[1] - s*(F[1]-E[1])
- t*(H[1]-E[1]) ) / d1;
}
else {
u = ( value[2][i] - E[2] - s*(F[2]-E[2])
- t*(H[2]-E[2]) ) / d2;
}
/* WLH 5 April 99
if (A[0] != E[0]) {
u = ( value[0][i] - E[0] - s*(F[0]-E[0])
- t*(H[0]-E[0]) ) / (A[0]-E[0]);
}
else if (A[1] != E[1]) {
u = ( value[1][i] - E[1] - s*(F[1]-E[1])
- t*(H[1]-E[1]) ) / (A[1]-E[1]);
}
else {
u = ( value[2][i] - E[2] - s*(F[2]-E[2])
- t*(H[2]-E[2]) ) / (A[2]-E[2]);
}
*/
if (evencube) {
grid[0][i] = gx+s;
grid[1][i] = gy+t;
grid[2][i] = gz+u;
}
else {
grid[0][i] = gx+1-s;
grid[1][i] = gy+1-t;
grid[2][i] = gz+1-u;
}
break;
}
}
else if (tetnum==2) {
tval1 = ( (B[1]-C[1])*(F[2]-B[2]) - (B[2]-C[2])*(F[1]-B[1]) )
*(value[0][i]-B[0])
+ ( (B[2]-C[2])*(F[0]-B[0]) - (B[0]-C[0])*(F[2]-B[2]) )
*(value[1][i]-B[1])
+ ( (B[0]-C[0])*(F[1]-B[1]) - (B[1]-C[1])*(F[0]-B[0]) )
*(value[2][i]-B[2]);
tval2 = ( (B[1]-A[1])*(C[2]-B[2]) - (B[2]-A[2])*(C[1]-B[1]) )
*(value[0][i]-B[0])
+ ( (B[2]-A[2])*(C[0]-B[0]) - (B[0]-A[0])*(C[2]-B[2]) )
*(value[1][i]-B[1])
+ ( (B[0]-A[0])*(C[1]-B[1]) - (B[1]-A[1])*(C[0]-B[0]) )
*(value[2][i]-B[2]);
tval3 = ( (B[1]-F[1])*(A[2]-B[2]) - (B[2]-F[2])*(A[1]-B[1]) )
*(value[0][i]-B[0])
+ ( (B[2]-F[2])*(A[0]-B[0]) - (B[0]-F[0])*(A[2]-B[2]) )
*(value[1][i]-B[1])
+ ( (B[0]-F[0])*(A[1]-B[1]) - (B[1]-F[1])*(A[0]-B[0]) )
*(value[2][i]-B[2]);
test1 = (tval1 == 0) || ((tval1 > 0) == (!evencube)^Pos);
test2 = (tval2 == 0) || ((tval2 > 0) == (!evencube)^Pos);
test3 = (tval3 == 0) || ((tval3 > 0) == (!evencube)^Pos);
// if a test failed go to a new box
if (!test1 && evencube) gx++; // RIGHT
if (!test1 && !evencube) gx--; // LEFT
if (!test2 && evencube) gz++; // FORWARD
if (!test2 && !evencube) gz--; // BACK
if (!test3 && evencube) gy--; // UP
if (!test3 && !evencube) gy++; // DOWN
tetnum = 5;
// Snap coordinates back onto grid in case they fell off
if (gx < 0) gx = 0;
if (gy < 0) gy = 0;
if (gz < 0) gz = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy > LengthY-2) gy = LengthY-2;
if (gz > LengthZ-2) gz = LengthZ-2;
// Detect if the point is off the grid entirely
if ( (gx == ogx) && (gy == ogy) && (gz == ogz)
&& (!test1 || !test2 || !test3) && !offgrid ) {
offgrid = true;
continue;
}
// If all tests pass then this is the correct tetrahedron
if ( ( (gx == ogx) && (gy == ogy) && (gz == ogz) )
|| offgrid) {
// solve point
float[] M = new float[3];
float[] N = new float[3];
float[] O = new float[3];
float[] P = new float[3];
float[] X = new float[3];
float[] Y = new float[3];
for (int j=0; j<3; j++) {
M[j] = (A[j]-B[j])*(F[(j+1)%3]-B[(j+1)%3])
- (A[(j+1)%3]-B[(j+1)%3])*(F[j]-B[j]);
N[j] = (C[j]-B[j])*(F[(j+1)%3]-B[(j+1)%3])
- (C[(j+1)%3]-B[(j+1)%3])*(F[j]-B[j]);
O[j] = (A[(j+1)%3]-B[(j+1)%3])*(F[(j+2)%3]-B[(j+2)%3])
- (A[(j+2)%3]-B[(j+2)%3])*(F[(j+1)%3]-B[(j+1)%3]);
P[j] = (C[(j+1)%3]-B[(j+1)%3])*(F[(j+2)%3]-B[(j+2)%3])
- (C[(j+2)%3]-B[(j+2)%3])*(F[(j+1)%3]-B[(j+1)%3]);
X[j] = value[(j+2)%3][i]*(F[(j+1)%3]-B[(j+1)%3])
- value[(j+1)%3][i]*(F[(j+2)%3]-B[(j+2)%3])
+ B[(j+1)%3]*F[(j+2)%3] - B[(j+2)%3]*F[(j+1)%3];
Y[j] = value[j][i]*(F[(j+1)%3]-B[(j+1)%3])
- value[1][i]*(F[j]-B[j])
+ B[(j+1)%3]*F[j] - B[j]*F[(j+1)%3];
}
float s, t, u;
// these if statements handle skewed grids
float d0 = M[0]*P[0] - N[0]*O[0];
float d1 = M[1]*P[1] - N[1]*O[1];
float d2 = M[2]*P[2] - N[2]*O[2];
float ad0 = Math.abs(d0);
float ad1 = Math.abs(d1);
float ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
s = 1 - (N[0]*X[0] + P[0]*Y[0])/d0;
t = -(M[0]*X[0] + O[0]*Y[0])/d0;
}
else if (ad1 > ad2) {
s = 1 - (N[1]*X[1] + P[1]*Y[1])/d1;
t = -(M[1]*X[1] + O[1]*Y[1])/d1;
}
else {
s = 1 - (N[2]*X[2] + P[2]*Y[2])/d2;
t = -(M[2]*X[2] + O[2]*Y[2])/d2;
}
/* WLH 5 April 99
if (M[0]*P[0] != N[0]*O[0]) {
s = 1 - (N[0]*X[0] + P[0]*Y[0])/(M[0]*P[0] - N[0]*O[0]);
t = (M[0]*X[0] + O[0]*Y[0])/(N[0]*O[0] - M[0]*P[0]);
}
else if (M[1]*P[1] != N[1]*O[1]) {
s = 1 - (N[1]*X[1] + P[1]*Y[1])/(M[1]*P[1] - N[1]*O[1]);
t = (M[1]*X[1] + O[1]*Y[1])/(N[1]*O[1] - M[1]*P[1]);
}
else {
s = 1 - (N[2]*X[2] + P[2]*Y[2])/(M[2]*P[2] - N[2]*O[2]);
t = (M[2]*X[2] + O[2]*Y[2])/(N[2]*O[2] - M[2]*P[2]);
}
*/
d0 = F[0]-B[0];
d1 = F[1]-B[1];
d2 = F[2]-B[2];
ad0 = Math.abs(d0);
ad1 = Math.abs(d1);
ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
u = 1 - ( value[0][i] - B[0] - (1-s)*(A[0]-B[0])
- t*(C[0]-B[0]) ) / d0;
}
else if (ad1 > ad2) {
u = 1 - ( value[1][i] - B[1] - (1-s)*(A[1]-B[1])
- t*(C[1]-B[1]) ) / d1;
}
else {
u = 1 - ( value[2][i] - B[2] - (1-s)*(A[2]-B[2])
- t*(C[2]-B[2]) ) / d2;
}
/* WLH 5 April 99
if (F[0] != B[0]) {
u = 1 - ( value[0][i] - B[0] - (1-s)*(A[0]-B[0])
- t*(C[0]-B[0]) ) / (F[0]-B[0]);
}
else if (F[1] != B[1]) {
u = 1 - ( value[1][i] - B[1] - (1-s)*(A[1]-B[1])
- t*(C[1]-B[1]) ) / (F[1]-B[1]);
}
else {
u = 1 - ( value[2][i] - B[2] - (1-s)*(A[2]-B[2])
- t*(C[2]-B[2]) ) / (F[2]-B[2]);
}
*/
if (evencube) {
grid[0][i] = gx+s;
grid[1][i] = gy+t;
grid[2][i] = gz+u;
}
else {
grid[0][i] = gx+1-s;
grid[1][i] = gy+1-t;
grid[2][i] = gz+1-u;
}
break;
}
}
else if (tetnum==3) {
tval1 = ( (D[1]-A[1])*(H[2]-D[2]) - (D[2]-A[2])*(H[1]-D[1]) )
*(value[0][i]-D[0])
+ ( (D[2]-A[2])*(H[0]-D[0]) - (D[0]-A[0])*(H[2]-D[2]) )
*(value[1][i]-D[1])
+ ( (D[0]-A[0])*(H[1]-D[1]) - (D[1]-A[1])*(H[0]-D[0]) )
*(value[2][i]-D[2]);
tval2 = ( (D[1]-C[1])*(A[2]-D[2]) - (D[2]-C[2])*(A[1]-D[1]) )
*(value[0][i]-D[0])
+ ( (D[2]-C[2])*(A[0]-D[0]) - (D[0]-C[0])*(A[2]-D[2]) )
*(value[1][i]-D[1])
+ ( (D[0]-C[0])*(A[1]-D[1]) - (D[1]-C[1])*(A[0]-D[0]) )
*(value[2][i]-D[2]);
tval3 = ( (D[1]-H[1])*(C[2]-D[2]) - (D[2]-H[2])*(C[1]-D[1]) )
*(value[0][i]-D[0])
+ ( (D[2]-H[2])*(C[0]-D[0]) - (D[0]-H[0])*(C[2]-D[2]) )
*(value[1][i]-D[1])
+ ( (D[0]-H[0])*(C[1]-D[1]) - (D[1]-H[1])*(C[0]-D[0]) )
*(value[2][i]-D[2]);
test1 = (tval1 == 0) || ((tval1 > 0) == (!evencube)^Pos);
test2 = (tval2 == 0) || ((tval2 > 0) == (!evencube)^Pos);
test3 = (tval3 == 0) || ((tval3 > 0) == (!evencube)^Pos);
// if a test failed go to a new box
if (!test1 && evencube) gx--; // LEFT
if (!test1 && !evencube) gx++; // RIGHT
if (!test2 && evencube) gz++; // FORWARD
if (!test2 && !evencube) gz--; // BACK
if (!test3 && evencube) gy++; // DOWN
if (!test3 && !evencube) gy--; // UP
tetnum = 5;
// Snap coordinates back onto grid in case they fell off
if (gx < 0) gx = 0;
if (gy < 0) gy = 0;
if (gz < 0) gz = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy > LengthY-2) gy = LengthY-2;
if (gz > LengthZ-2) gz = LengthZ-2;
// Detect if the point is off the grid entirely
if ( (gx == ogx) && (gy == ogy) && (gz == ogz)
&& (!test1 || !test2 || !test3) && !offgrid ) {
offgrid = true;
continue;
}
// If all tests pass then this is the correct tetrahedron
if ( ( (gx == ogx) && (gy == ogy) && (gz == ogz) )
|| offgrid) {
// solve point
float[] M = new float[3];
float[] N = new float[3];
float[] O = new float[3];
float[] P = new float[3];
float[] X = new float[3];
float[] Y = new float[3];
for (int j=0; j<3; j++) {
M[j] = (C[j]-D[j])*(H[(j+1)%3]-D[(j+1)%3])
- (C[(j+1)%3]-D[(j+1)%3])*(H[j]-D[j]);
N[j] = (A[j]-D[j])*(H[(j+1)%3]-D[(j+1)%3])
- (A[(j+1)%3]-D[(j+1)%3])*(H[j]-D[j]);
O[j] = (C[(j+1)%3]-D[(j+1)%3])*(H[(j+2)%3]-D[(j+2)%3])
- (C[(j+2)%3]-D[(j+2)%3])*(H[(j+1)%3]-D[(j+1)%3]);
P[j] = (A[(j+1)%3]-D[(j+1)%3])*(H[(j+2)%3]-D[(j+2)%3])
- (A[(j+2)%3]-D[(j+2)%3])*(H[(j+1)%3]-D[(j+1)%3]);
X[j] = value[(j+2)%3][i]*(H[(j+1)%3]-D[(j+1)%3])
- value[(j+1)%3][i]*(H[(j+2)%3]-D[(j+2)%3])
+ D[(j+1)%3]*H[(j+2)%3] - D[(j+2)%3]*H[(j+1)%3];
Y[j] = value[j][i]*(H[(j+1)%3]-D[(j+1)%3])
- value[(j+1)%3][i]*(H[j]-D[j])
+ D[(j+1)%3]*H[j] - D[j]*H[(j+1)%3];
}
float s, t, u;
// these if statements handle skewed grids
float d0 = M[0]*P[0] - N[0]*O[0];
float d1 = M[1]*P[1] - N[1]*O[1];
float d2 = M[2]*P[2] - N[2]*O[2];
float ad0 = Math.abs(d0);
float ad1 = Math.abs(d1);
float ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
s = (N[0]*X[0] + P[0]*Y[0])/d0;
t = 1 + (M[0]*X[0] + O[0]*Y[0])/d0;
}
else if (ad1 > ad2) {
s = (N[1]*X[1] + P[1]*Y[1])/d1;
t = 1 + (M[1]*X[1] + O[1]*Y[1])/d1;
}
else {
s = (N[2]*X[2] + P[2]*Y[2])/d2;
t = 1 + (M[2]*X[2] + O[2]*Y[2])/d2;
}
/* WLH 5 April 99
if (M[0]*P[0] != N[0]*O[0]) {
s = (N[0]*X[0] + P[0]*Y[0])/(M[0]*P[0] - N[0]*O[0]);
t = 1 - (M[0]*X[0] + O[0]*Y[0])/(N[0]*O[0] - M[0]*P[0]);
}
else if (M[1]*P[1] != N[1]*O[1]) {
s = (N[1]*X[1] + P[1]*Y[1])/(M[1]*P[1] - N[1]*O[1]);
t = 1 - (M[1]*X[1] + O[1]*Y[1])/(N[1]*O[1] - M[1]*P[1]);
}
else {
s = (N[2]*X[2] + P[2]*Y[2])/(M[2]*P[2] - N[2]*O[2]);
t = 1 - (M[2]*X[2] + O[2]*Y[2])/(N[2]*O[2] - M[2]*P[2]);
}
*/
d0 = H[0]-D[0];
d1 = H[1]-D[1];
d2 = H[2]-D[2];
ad0 = Math.abs(d0);
ad1 = Math.abs(d1);
ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
u = 1 - ( value[0][i] - D[0] - s*(C[0]-D[0])
- (1-t)*(A[0]-D[0]) ) / d0;
}
else if (ad1 > ad2) {
u = 1 - ( value[1][i] - D[1] - s*(C[1]-D[1])
- (1-t)*(A[1]-D[1]) ) / d1;
}
else {
u = 1 - ( value[2][i] - D[2] - s*(C[2]-D[2])
- (1-t)*(A[2]-D[2]) ) / d2;
}
/* WLH 5 April 99
if (H[0] != D[0]) {
u = 1 - ( value[0][i] - D[0] - s*(C[0]-D[0])
- (1-t)*(A[0]-D[0]) ) / (H[0]-D[0]);
}
else if (H[1] != D[1]) {
u = 1 - ( value[1][i] - D[1] - s*(C[1]-D[1])
- (1-t)*(A[1]-D[1]) ) / (H[1]-D[1]);
}
else {
u = 1 - ( value[2][i] - D[2] - s*(C[2]-D[2])
- (1-t)*(A[2]-D[2]) ) / (H[2]-D[2]);
}
*/
if (evencube) {
grid[0][i] = gx+s;
grid[1][i] = gy+t;
grid[2][i] = gz+u;
}
else {
grid[0][i] = gx+1-s;
grid[1][i] = gy+1-t;
grid[2][i] = gz+1-u;
}
break;
}
}
else if (tetnum==4) {
tval1 = ( (G[1]-C[1])*(H[2]-G[2]) - (G[2]-C[2])*(H[1]-G[1]) )
*(value[0][i]-G[0])
+ ( (G[2]-C[2])*(H[0]-G[0]) - (G[0]-C[0])*(H[2]-G[2]) )
*(value[1][i]-G[1])
+ ( (G[0]-C[0])*(H[1]-G[1]) - (G[1]-C[1])*(H[0]-G[0]) )
*(value[2][i]-G[2]);
tval2 = ( (G[1]-F[1])*(C[2]-G[2]) - (G[2]-F[2])*(C[1]-G[1]) )
*(value[0][i]-G[0])
+ ( (G[2]-F[2])*(C[0]-G[0]) - (G[0]-F[0])*(C[2]-G[2]) )
*(value[1][i]-G[1])
+ ( (G[0]-F[0])*(C[1]-G[1]) - (G[1]-F[1])*(C[0]-G[0]) )
*(value[2][i]-G[2]);
tval3 = ( (G[1]-H[1])*(F[2]-G[2]) - (G[2]-H[2])*(F[1]-G[1]) )
*(value[0][i]-G[0])
+ ( (G[2]-H[2])*(F[0]-G[0]) - (G[0]-H[0])*(F[2]-G[2]) )
*(value[1][i]-G[1])
+ ( (G[0]-H[0])*(F[1]-G[1]) - (G[1]-H[1])*(F[0]-G[0]) )
*(value[2][i]-G[2]);
test1 = (tval1 == 0) || ((tval1 > 0) == (!evencube)^Pos);
test2 = (tval2 == 0) || ((tval2 > 0) == (!evencube)^Pos);
test3 = (tval3 == 0) || ((tval3 > 0) == (!evencube)^Pos);
// if a test failed go to a new box
if (!test1 && evencube) gy++; // DOWN
if (!test1 && !evencube) gy--; // UP
if (!test2 && evencube) gx++; // RIGHT
if (!test2 && !evencube) gx--; // LEFT
if (!test3 && evencube) gz--; // BACK
if (!test3 && !evencube) gz++; // FORWARD
tetnum = 5;
// Snap coordinates back onto grid in case they fell off
if (gx < 0) gx = 0;
if (gy < 0) gy = 0;
if (gz < 0) gz = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy > LengthY-2) gy = LengthY-2;
if (gz > LengthZ-2) gz = LengthZ-2;
// Detect if the point is off the grid entirely
if ( (gx == ogx) && (gy == ogy) && (gz == ogz)
&& (!test1 || !test2 || !test3) && !offgrid ) {
offgrid = true;
continue;
}
// If all tests pass then this is the correct tetrahedron
if ( ( (gx == ogx) && (gy == ogy) && (gz == ogz) )
|| offgrid) {
// solve point
float[] M = new float[3];
float[] N = new float[3];
float[] O = new float[3];
float[] P = new float[3];
float[] X = new float[3];
float[] Y = new float[3];
for (int j=0; j<3; j++) {
M[j] = (H[j]-G[j])*(C[(j+1)%3]-G[(j+1)%3])
- (H[(j+1)%3]-G[(j+1)%3])*(C[j]-G[j]);
N[j] = (F[j]-G[j])*(C[(j+1)%3]-G[(j+1)%3])
- (F[(j+1)%3]-G[(j+1)%3])*(C[j]-G[j]);
O[j] = (H[(j+1)%3]-G[(j+1)%3])*(C[(j+2)%3]-G[(j+2)%3])
- (H[(j+2)%3]-G[(j+2)%3])*(C[(j+1)%3]-G[(j+1)%3]);
P[j] = (F[(j+1)%3]-G[(j+1)%3])*(C[(j+2)%3]-G[(j+2)%3])
- (F[(j+2)%3]-G[(j+2)%3])*(C[(j+1)%3]-G[(j+1)%3]);
X[j] = value[(j+2)%3][i]*(C[(j+1)%3]-G[(j+1)%3])
- value[(j+1)%3][i]*(C[(j+2)%3]-G[(j+2)%3])
+ G[(j+1)%3]*C[(j+2)%3] - G[(j+2)%3]*C[(j+1)%3];
Y[j] = value[j][i]*(C[(j+1)%3]-G[(j+1)%3])
- value[(j+1)%3][i]*(C[j]-G[j])
+ G[(j+1)%3]*C[j] - G[j]*C[(j+1)%3];
}
float s, t, u;
// these if statements handle skewed grids
float d0 = M[0]*P[0] - N[0]*O[0];
float d1 = M[1]*P[1] - N[1]*O[1];
float d2 = M[2]*P[2] - N[2]*O[2];
float ad0 = Math.abs(d0);
float ad1 = Math.abs(d1);
float ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
s = 1 - (N[0]*X[0] + P[0]*Y[0])/d0;
t = 1 + (M[0]*X[0] + O[0]*Y[0])/d0;
}
else if (ad1 > ad2) {
s = 1 - (N[1]*X[1] + P[1]*Y[1])/d1;
t = 1 + (M[1]*X[1] + O[1]*Y[1])/d1;
}
else {
s = 1 - (N[2]*X[2] + P[2]*Y[2])/d2;
t = 1 + (M[2]*X[2] + O[2]*Y[2])/d2;
}
/* WLH 5 April 99
if (M[0]*P[0] != N[0]*O[0]) {
s = 1 - (N[0]*X[0] + P[0]*Y[0])/(M[0]*P[0] - N[0]*O[0]);
t = 1 - (M[0]*X[0] + O[0]*Y[0])/(N[0]*O[0] - M[0]*P[0]);
}
else if (M[1]*P[1] != N[1]*O[1]) {
s = 1 - (N[1]*X[1] + P[1]*Y[1])/(M[1]*P[1] - N[1]*O[1]);
t = 1 - (M[1]*X[1] + O[1]*Y[1])/(N[1]*O[1] - M[1]*P[1]);
}
else {
s = 1 - (N[2]*X[2] + P[2]*Y[2])/(M[2]*P[2] - N[2]*O[2]);
t = 1 - (M[2]*X[2] + O[2]*Y[2])/(N[2]*O[2] - M[2]*P[2]);
}
*/
d0 = C[0]-G[0];
d1 = C[1]-G[1];
d2 = C[2]-G[2];
ad0 = Math.abs(d0);
ad1 = Math.abs(d1);
ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
u = ( value[0][i] - G[0] - (1-s)*(H[0]-G[0])
- (1-t)*(F[0]-G[0]) ) / d0;
}
else if (ad1 > ad2) {
u = ( value[1][i] - G[1] - (1-s)*(H[1]-G[1])
- (1-t)*(F[1]-G[1]) ) / d1;
}
else {
u = ( value[2][i] - G[2] - (1-s)*(H[2]-G[2])
- (1-t)*(F[2]-G[2]) ) / d2;
}
/* WLH 5 April 99
if (C[0] != G[0]) {
u = ( value[0][i] - G[0] - (1-s)*(H[0]-G[0])
- (1-t)*(F[0]-G[0]) ) / (C[0]-G[0]);
}
else if (C[1] != G[1]) {
u = ( value[1][i] - G[1] - (1-s)*(H[1]-G[1])
- (1-t)*(F[1]-G[1]) ) / (C[1]-G[1]);
}
else {
u = ( value[2][i] - G[2] - (1-s)*(H[2]-G[2])
- (1-t)*(F[2]-G[2]) ) / (C[2]-G[2]);
}
*/
if (evencube) {
grid[0][i] = gx+s;
grid[1][i] = gy+t;
grid[2][i] = gz+u;
}
else {
grid[0][i] = gx+1-s;
grid[1][i] = gy+1-t;
grid[2][i] = gz+1-u;
}
break;
}
}
else { // tetnum==5
tval1 = ( (F[1]-H[1])*(A[2]-F[2]) - (F[2]-H[2])*(A[1]-F[1]) )
*(value[0][i]-F[0])
+ ( (F[2]-H[2])*(A[0]-F[0]) - (F[0]-H[0])*(A[2]-F[2]) )
*(value[1][i]-F[1])
+ ( (F[0]-H[0])*(A[1]-F[1]) - (F[1]-H[1])*(A[0]-F[0]) )
*(value[2][i]-F[2]);
tval2 = ( (C[1]-F[1])*(A[2]-C[2]) - (C[2]-F[2])*(A[1]-C[1]) )
*(value[0][i]-C[0])
+ ( (C[2]-F[2])*(A[0]-C[0]) - (C[0]-F[0])*(A[2]-C[2]) )
*(value[1][i]-C[1])
+ ( (C[0]-F[0])*(A[1]-C[1]) - (C[1]-F[1])*(A[0]-C[0]) )
*(value[2][i]-C[2]);
tval3 = ( (C[1]-A[1])*(H[2]-C[2]) - (C[2]-A[2])*(H[1]-C[1]) )
*(value[0][i]-C[0])
+ ( (C[2]-A[2])*(H[0]-C[0]) - (C[0]-A[0])*(H[2]-C[2]) )
*(value[1][i]-C[1])
+ ( (C[0]-A[0])*(H[1]-C[1]) - (C[1]-A[1])*(H[0]-C[0]) )
*(value[2][i]-C[2]);
tval4 = ( (F[1]-C[1])*(H[2]-F[2]) - (F[2]-C[2])*(H[1]-F[1]) )
*(value[0][i]-F[0])
+ ( (F[2]-C[2])*(H[0]-F[0]) - (F[0]-C[0])*(H[2]-F[2]) )
*(value[1][i]-F[1])
+ ( (F[0]-C[0])*(H[1]-F[1]) - (F[1]-C[1])*(H[0]-F[0]) )
*(value[2][i]-F[2]);
test1 = (tval1 == 0) || ((tval1 > 0) == (!evencube)^Pos);
test2 = (tval2 == 0) || ((tval2 > 0) == (!evencube)^Pos);
test3 = (tval3 == 0) || ((tval3 > 0) == (!evencube)^Pos);
test4 = (tval4 == 0) || ((tval4 > 0) == (!evencube)^Pos);
// if a test failed go to a new tetrahedron
if (!test1 && test2 && test3 && test4) tetnum = 1;
if (test1 && !test2 && test3 && test4) tetnum = 2;
if (test1 && test2 && !test3 && test4) tetnum = 3;
if (test1 && test2 && test3 && !test4) tetnum = 4;
if ( (!test1 && !test2 && evencube)
|| (!test3 && !test4 && !evencube) ) gy--; // GO UP
if ( (!test1 && !test3 && evencube)
|| (!test2 && !test4 && !evencube) ) gx--; // GO LEFT
if ( (!test1 && !test4 && evencube)
|| (!test2 && !test3 && !evencube) ) gz--; // GO BACK
if ( (!test2 && !test3 && evencube)
|| (!test1 && !test4 && !evencube) ) gz++; // GO FORWARD
if ( (!test2 && !test4 && evencube)
|| (!test1 && !test3 && !evencube) ) gx++; // GO RIGHT
if ( (!test3 && !test4 && evencube)
|| (!test1 && !test2 && !evencube) ) gy++; // GO DOWN
// Snap coordinates back onto grid in case they fell off
if (gx < 0) gx = 0;
if (gy < 0) gy = 0;
if (gz < 0) gz = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy > LengthY-2) gy = LengthY-2;
if (gz > LengthZ-2) gz = LengthZ-2;
// Detect if the point is off the grid entirely
if ( ( (gx == ogx) && (gy == ogy) && (gz == ogz)
&& (!test1 || !test2 || !test3 || !test4)
&& (tetnum == 5)) || offgrid) {
offgrid = true;
boolean OX, OY, OZ, MX, MY, MZ, LX, LY, LZ;
OX = OY = OZ = MX = MY = MZ = LX = LY = LZ = false;
if (gx == 0) OX = true;
if (gy == 0) OY = true;
if (gz == 0) OZ = true;
if (gx == LengthX-2) LX = true;
if (gy == LengthY-2) LY = true;
if (gz == LengthZ-2) LZ = true;
if (!OX && !LX) MX = true;
if (!OY && !LY) MY = true;
if (!OZ && !LZ) MZ = true;
test1 = test2 = test3 = test4 = false;
// 26 cases
if (evencube) {
if (!LX && !LY && !LZ) tetnum = 1;
else if ( (LX && OY && MZ) || (MX && OY && LZ)
|| (LX && MY && LZ) || (LX && OY && LZ)
|| (MX && MY && LZ) || (LX && MY && MZ) ) tetnum = 2;
else if ( (OX && LY && MZ) || (OX && MY && LZ)
|| (MX && LY && LZ) || (OX && LY && LZ)
|| (MX && LY && MZ) ) tetnum = 3;
else if ( (MX && LY && OZ) || (LX && MY && OZ)
|| (LX && LY && MZ) || (LX && LY && OZ) ) tetnum = 4;
}
else {
if (!OX && !OY && !OZ) tetnum = 1;
else if ( (OX && MY && OZ) || (MX && LY && OZ)
|| (OX && LY && MZ) || (OX && LY && OZ)
|| (MX && MY && OZ) || (OX && MY && MZ) ) tetnum = 2;
else if ( (LX && MY && OZ) || (MX && OY && OZ)
|| (LX && OY && MZ) || (LX && OY && OZ)
|| (MX && OY && MZ) ) tetnum = 3;
else if ( (OX && OY && MZ) || (OX && MY && OZ)
|| (MX && OY && LZ) || (OX && OY && LZ) ) tetnum = 4;
}
}
// If all tests pass then this is the correct tetrahedron
if ( (gx == ogx) && (gy == ogy) && (gz == ogz) && (tetnum == 5) ) {
// solve point
float[] Q = new float[3];
for (int j=0; j<3; j++) {
Q[j] = (H[j] + F[j] + A[j] - C[j])/2;
}
float[] M = new float[3];
float[] N = new float[3];
float[] O = new float[3];
float[] P = new float[3];
float[] X = new float[3];
float[] Y = new float[3];
for (int j=0; j<3; j++) {
M[j] = (F[j]-Q[j])*(A[(j+1)%3]-Q[(j+1)%3])
- (F[(j+1)%3]-Q[(j+1)%3])*(A[j]-Q[j]);
N[j] = (H[j]-Q[j])*(A[(j+1)%3]-Q[(j+1)%3])
- (H[(j+1)%3]-Q[(j+1)%3])*(A[j]-Q[j]);
O[j] = (F[(j+1)%3]-Q[(j+1)%3])*(A[(j+2)%3]-Q[(j+2)%3])
- (F[(j+2)%3]-Q[(j+2)%3])*(A[(j+1)%3]-Q[(j+1)%3]);
P[j] = (H[(j+1)%3]-Q[(j+1)%3])*(A[(j+2)%3]-Q[(j+2)%3])
- (H[(j+2)%3]-Q[(j+2)%3])*(A[(j+1)%3]-Q[(j+1)%3]);
X[j] = value[(j+2)%3][i]*(A[(j+1)%3]-Q[(j+1)%3])
- value[(j+1)%3][i]*(A[(j+2)%3]-Q[(j+2)%3])
+ Q[(j+1)%3]*A[(j+2)%3] - Q[(j+2)%3]*A[(j+1)%3];
Y[j] = value[j][i]*(A[(j+1)%3]-Q[(j+1)%3])
- value[(j+1)%3][i]*(A[j]-Q[j])
+ Q[(j+1)%3]*A[j] - Q[j]*A[(j+1)%3];
}
float s, t, u;
// these if statements handle skewed grids
float d0 = M[0]*P[0] - N[0]*O[0];
float d1 = M[1]*P[1] - N[1]*O[1];
float d2 = M[2]*P[2] - N[2]*O[2];
float ad0 = Math.abs(d0);
float ad1 = Math.abs(d1);
float ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
s = (N[0]*X[0] + P[0]*Y[0])/d0;
t = -(M[0]*X[0] + O[0]*Y[0])/d0;
}
else if (ad1 > ad2) {
s = (N[1]*X[1] + P[1]*Y[1])/d1;
t = -(M[1]*X[1] + O[1]*Y[1])/d1;
}
else {
s = (N[2]*X[2] + P[2]*Y[2])/d2;
t = -(M[2]*X[2] + O[2]*Y[2])/d2;
}
/* WLH 3 April 99
if (M[0]*P[0] != N[0]*O[0]) {
s = (N[0]*X[0] + P[0]*Y[0])/(M[0]*P[0] - N[0]*O[0]);
t = (M[0]*X[0] + O[0]*Y[0])/(N[0]*O[0] - M[0]*P[0]);
}
else if (M[1]*P[1] != N[1]*O[1]) {
s = (N[1]*X[1] + P[1]*Y[1])/(M[1]*P[1] - N[1]*O[1]);
t = (M[1]*X[1] + O[1]*Y[1])/(N[1]*O[1] - M[1]*P[1]);
}
else {
s = (N[2]*X[2] + P[2]*Y[2])/(M[2]*P[2] - N[2]*O[2]);
t = (M[2]*X[2] + O[2]*Y[2])/(N[2]*O[2] - M[2]*P[2]);
}
*/
d0 = A[0]-Q[0];
d1 = A[1]-Q[1];
d2 = A[2]-Q[2];
ad0 = Math.abs(d0);
ad1 = Math.abs(d1);
ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
u = ( value[0][i] - Q[0] - s*(F[0]-Q[0])
- t*(H[0]-Q[0]) ) / d0;
}
else if (ad1 > ad2) {
u = ( value[1][i] - Q[1] - s*(F[1]-Q[1])
- t*(H[1]-Q[1]) ) / d1;
}
else {
u = ( value[2][i] - Q[2] - s*(F[2]-Q[2])
- t*(H[2]-Q[2]) ) / d2;
}
/* WLH 3 April 99
if (A[0] != Q[0]) {
u = ( value[0][i] - Q[0] - s*(F[0]-Q[0])
- t*(H[0]-Q[0]) ) / (A[0]-Q[0]);
}
else if (A[1] != Q[1]) {
u = ( value[1][i] - Q[1] - s*(F[1]-Q[1])
- t*(H[1]-Q[1]) ) / (A[1]-Q[1]);
}
else {
u = ( value[2][i] - Q[2] - s*(F[2]-Q[2])
- t*(H[2]-Q[2]) ) / (A[2]-Q[2]);
}
*/
if (evencube) {
grid[0][i] = gx+s;
grid[1][i] = gy+t;
grid[2][i] = gz+u;
}
else {
grid[0][i] = gx+1-s;
grid[1][i] = gy+1-t;
grid[2][i] = gz+1-u;
}
break;
}
}
}
// allow estimations up to 0.5 boxes outside of defined samples
if ( (grid[0][i] <= -0.5) || (grid[0][i] >= LengthX-0.5)
|| (grid[1][i] <= -0.5) || (grid[1][i] >= LengthY-0.5)
|| (grid[2][i] <= -0.5) || (grid[2][i] >= LengthZ-0.5) ) {
grid[0][i] = grid[1][i] = grid[2][i] = Float.NaN;
}
}
return grid;
}
public VisADGeometryArray[][] makeIsoLines(float[] intervals,
float lowlimit, float highlimit, float base,
float[] fieldValues, byte[][] color_values,
boolean[] swap, boolean dash,
boolean fill, ScalarMap[] smap, double scale_ratio,
double label_size, float[][][] f_array)
throws VisADException {
int Length = getLength();
int ManifoldDimension = getManifoldDimension();
int[] Lengths = getLengths();
int LengthX = Lengths[0];
int LengthY = Lengths[1];
if (ManifoldDimension != 2) {
throw new DisplayException("Gridded3DSet.makeIsoLines: " +
"ManifoldDimension must be 2");
}
int nr = LengthX;
int nc = LengthY;
float[] g = fieldValues;
// these are just estimates
// int est = 2 * Length; WLH 14 April 2000
double dest = Math.sqrt((double) Length);
int est = (int) (dest * Math.sqrt(dest));
if (est < 1000) est = 1000;
int maxv2 = est;
int maxv1 = 2 * 2 * maxv2;
// maxv3 and maxv4 should be equal
int maxv3 = est;
int maxv4 = maxv3;
/* memory use for temporaries, in bytes (for est = 2 * Length):
12 * color_length * Length +
64 * Length +
48 * Length +
= (112 + 12 * color_length) * Length
for color_length = 3 this is 148 * Length
*/
int color_length = (color_values != null) ? color_values.length : 0;
byte[][] color_levels1 = null;
byte[][] color_levels2 = null;
byte[][] color_levels3 = null;
if (color_length > 0) {
color_levels1 = new byte[color_length][maxv1];
color_levels2 = new byte[color_length][maxv2];
color_levels3 = new byte[color_length][maxv3];
}
float[][] vx1 = new float[1][maxv1];
float[][] vy1 = new float[1][maxv1];
float[][] vz1 = new float[1][maxv1];
float[][] vx2 = new float[1][maxv2];
float[][] vy2 = new float[1][maxv2];
float[][] vz2 = new float[1][maxv2];
float[][] vx3 = new float[1][maxv3];
float[][] vy3 = new float[1][maxv3];
float[][] vz3 = new float[1][maxv3];
float[][] vx4 = new float[1][maxv4];
float[][] vy4 = new float[1][maxv4];
float[][] vz4 = new float[1][maxv4];
int[] numv1 = new int[1];
int[] numv2 = new int[1];
int[] numv3 = new int[1];
int[] numv4 = new int[1];
float[][] tri = new float[2][];
float[][] tri_normals = new float[1][];
byte[][] tri_color = new byte[color_length][];
float[][][] grd_normals = null;
if (intervals == null) {
return null;
}
byte[][] interval_colors = new byte[color_length][intervals.length];
if (fill) { //- compute normals at grid points
float[][] samples = getSamples(false);
grd_normals = new float[nc][nr][3];
// calculate normals
int k = 0;
int k3 = 0;
int ki, kj;
for (int i=0; i<LengthY; i++) {
for (int j=0; j<LengthX; j++) {
float c0 = samples[0][k3];
float c1 = samples[1][k3];
float c2 = samples[2][k3];
float n0 = 0.0f;
float n1 = 0.0f;
float n2 = 0.0f;
float n, m, m0, m1, m2;
for (int ip = -1; ip<=1; ip += 2) {
for (int jp = -1; jp<=1; jp += 2) {
int ii = i + ip;
int jj = j + jp;
if (0 <= ii && ii < LengthY && 0 <= jj && jj < LengthX) {
ki = k3 + ip * LengthX;
kj = k3 + jp;
m0 = (samples[2][kj] - c2) * (samples[1][ki] - c1) -
(samples[1][kj] - c1) * (samples[2][ki] - c2);
m1 = (samples[0][kj] - c0) * (samples[2][ki] - c2) -
(samples[2][kj] - c2) * (samples[0][ki] - c0);
m2 = (samples[1][kj] - c1) * (samples[0][ki] - c0) -
(samples[0][kj] - c0) * (samples[1][ki] - c1);
m = (float) Math.sqrt(m0 * m0 + m1 * m1 + m2 * m2);
if (ip == jp) {
n0 += m0 / m;
n1 += m1 / m;
n2 += m2 / m;
}
else {
n0 -= m0 / m;
n1 -= m1 / m;
n2 -= m2 / m;
}
}
}
}
n = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
grd_normals[i][j][0] = n0 / n;
grd_normals[i][j][1] = n1 / n;
grd_normals[i][j][2] = n2 / n;
k += 3;
k3++;
}
}
//-- compute color at field contour intervals
float[] default_intervals = null;
Unit ounit = smap[0].getOverrideUnit();
if (ounit != null) {
default_intervals =
(((RealType)smap[0].getScalar()).getDefaultUnit()).toThis(intervals, ounit);
}
else {
default_intervals = intervals;
}
float[] display_intervals = smap[0].scaleValues(default_intervals);
BaseColorControl color_control = (BaseColorControl)smap[0].getControl();
float[][] temp = null;
try {
temp = color_control.lookupValues(display_intervals);
}
catch (Exception e) {
}
for (int tt=0; tt<temp.length; tt++) {
for (int kk=0; kk<interval_colors[0].length; kk++) {
interval_colors[tt][kk] = ShadowType.floatToByte(temp[tt][kk]);
}
}
}
float[][][][] lbl_vv = new float[4][][][];
byte[][][][] lbl_cc = new byte[4][][][];
float[][][] lbl_loc = new float[3][][];
Contour2D.contour( g, nr, nc, intervals, lowlimit, highlimit, base, dash,
vx1, vy1, vz1, maxv1, numv1, vx2, vy2, vz2, maxv2, numv2,
vx3, vy3, vz3, maxv3, numv3, vx4, vy4, vz4, maxv4, numv4,
color_values, color_levels1, color_levels2,
color_levels3, swap,
fill, tri, tri_color, grd_normals, tri_normals,
interval_colors, lbl_vv, lbl_cc, lbl_loc, scale_ratio, label_size,
this);
if (fill) {
VisADGeometryArray[][] tri_array = new VisADGeometryArray[2][];
tri_array[0] = new VisADGeometryArray[1];
tri_array[0][0] = new VisADTriangleArray();
tri_array[0][0].normals = tri_normals[0];
setGeometryArray(tri_array[0][0], gridToValue(tri), 3, tri_color);
return tri_array;
}
float[][] grid1 = new float[3][numv1[0]];
System.arraycopy(vx1[0], 0, grid1[0], 0, numv1[0]);
vx1 = null;
System.arraycopy(vy1[0], 0, grid1[1], 0, numv1[0]);
vy1 = null;
System.arraycopy(vz1[0], 0, grid1[2], 0, numv1[0]);
vz1 = null;
if (color_length > 0) {
byte[][] a = new byte[color_length][numv1[0]];
for (int i=0; i<color_length; i++) {
System.arraycopy(color_levels1[i], 0, a[i], 0, numv1[0]);
}
color_levels1 = a;
}
float[][] grid2 = new float[3][numv2[0]];
System.arraycopy(vx2[0], 0, grid2[0], 0, numv2[0]);
vx2 = null;
System.arraycopy(vy2[0], 0, grid2[1], 0, numv2[0]);
vy2 = null;
System.arraycopy(vz2[0], 0, grid2[2], 0, numv2[0]);
vz2 = null;
if (color_length > 0) {
byte[][] a = new byte[color_length][numv2[0]];
for (int i=0; i<color_length; i++) {
System.arraycopy(color_levels2[i], 0, a[i], 0, numv2[0]);
}
color_levels2 = a;
}
int n_labels = lbl_loc[0].length;
f_array[0] = new float[n_labels][4];
VisADLineArray[][] arrays = new VisADLineArray[4][];
arrays[0] = new VisADLineArray[1];
arrays[1] = new VisADLineArray[1];
arrays[0][0] = new VisADLineArray();
setGeometryArray(arrays[0][0], grid1, 3, color_levels1);
grid1 = null;
arrays[1][0] = new VisADLineArray();
setGeometryArray(arrays[1][0], grid2, 3, color_levels2);
grid2 = null;
arrays[2] = new VisADLineArray[n_labels*2];
arrays[3] = new VisADLineArray[n_labels*4];
for (int kk = 0; kk < n_labels; kk++) {
f_array[0][kk][0] = lbl_loc[0][kk][3];
f_array[0][kk][1] = lbl_loc[0][kk][4];
f_array[0][kk][2] = lbl_loc[0][kk][5];
f_array[0][kk][3] = lbl_loc[0][kk][6];
// temporary label orientation hack
// TO_DO - eventually return all 4 label orientations
// and have ProjectionControl switch among them
boolean backwards = true;
boolean upsidedown = false;
float[] vx = null;
float[] vy = null;
if (backwards) {
//vy = vy4[0];
vy = lbl_vv[1][kk][1];
}
else {
//vy = vy3[0];
vy = lbl_vv[0][kk][1];
}
vy3 = null;
vy4 = null;
if (upsidedown) {
//vx = vx4[0];
vx = lbl_vv[1][kk][0];
}
else {
//vx = vx3[0];
vx = lbl_vv[0][kk][0];
}
//vx3 = null;
//vx4 = null;
int num = vx.length;
float[][] grid_label = new float[3][num];
System.arraycopy(vx, 0, grid_label[0], 0, num);
System.arraycopy(vy, 0, grid_label[1], 0, num);
System.arraycopy(lbl_vv[0][kk][2], 0, grid_label[2], 0, num);
// WLH 5 Nov 98
vx = null;
vy = null;
byte[][] segL_color = null;
byte[][] segR_color = null;
if (color_length > 0) {
byte[][] a = new byte[color_length][num];
segL_color = new byte[color_length][2];
segR_color = new byte[color_length][2];
for (int i=0; i<color_length; i++) {
System.arraycopy(lbl_cc[0][kk][i], 0, a[i], 0, num);
System.arraycopy(lbl_cc[2][kk][i], 0, segL_color[i], 0, 2);
System.arraycopy(lbl_cc[3][kk][i], 0, segR_color[i], 0, 2);
}
color_levels3 = a;
}
arrays[2][kk*2] = new VisADLineArray();
arrays[2][kk*2+1] = new VisADLineArray();
setGeometryArray(arrays[2][kk*2], grid_label, 3, color_levels3);
grid_label = null;
float[][] loc = new float[3][1];
loc[0][0] = lbl_loc[0][kk][0];
loc[1][0] = lbl_loc[0][kk][1];
loc[2][0] = lbl_loc[0][kk][2];
setGeometryArray(arrays[2][kk*2+1], loc, 3, null);
arrays[3][kk*4] = new VisADLineArray();
arrays[3][kk*4+1] = new VisADLineArray();
arrays[3][kk*4+2] = new VisADLineArray();
arrays[3][kk*4+3] = new VisADLineArray();
float[][] segL = new float[3][2];
segL[0][0] = lbl_vv[2][kk][0][0];
segL[1][0] = lbl_vv[2][kk][1][0];
segL[2][0] = lbl_vv[2][kk][2][0];
segL[0][1] = lbl_vv[2][kk][0][1];
segL[1][1] = lbl_vv[2][kk][1][1];
segL[2][1] = lbl_vv[2][kk][2][1];
setGeometryArray(arrays[3][kk*4], segL, 3, segL_color);
loc[0][0] = lbl_loc[1][kk][0];
loc[1][0] = lbl_loc[1][kk][1];
loc[2][0] = lbl_loc[1][kk][2];
setGeometryArray(arrays[3][kk*4+1], loc, 3, null);
float[][] segR = new float[3][2];
segR[0][0] = lbl_vv[3][kk][0][0];
segR[1][0] = lbl_vv[3][kk][1][0];
segR[2][0] = lbl_vv[3][kk][2][0];
segR[0][1] = lbl_vv[3][kk][0][1];
segR[1][1] = lbl_vv[3][kk][1][1];
segR[2][1] = lbl_vv[3][kk][2][1];
setGeometryArray(arrays[3][kk*4+2], segR, 3, segR_color);
loc[0][0] = lbl_loc[2][kk][0];
loc[1][0] = lbl_loc[2][kk][1];
loc[2][0] = lbl_loc[2][kk][2];
setGeometryArray(arrays[3][kk*4+3], loc, 3, null);
}
return arrays;
}
public float[][] getNormals(float[][] grid)
throws VisADException
{
int[] Lengths = getLengths();
int LengthX = Lengths[0];
int LengthY = Lengths[1];
float[][] samples = getSamples(false);
float[][] grd_normals = new float[3][grid[0].length];
// calculate normals
int k3 = 0;
int ki, kj;
for (int tt=0; tt<grid[0].length; tt++) {
k3 = ((int)grid[1][tt])*LengthX + (int)grid[0][tt];
int i = k3/LengthX;
int j = k3 - i*LengthX;
float c0 = samples[0][k3];
float c1 = samples[1][k3];
float c2 = samples[2][k3];
float n0 = 0.0f;
float n1 = 0.0f;
float n2 = 0.0f;
float n, m, m0, m1, m2;
for (int ip = -1; ip<=1; ip += 2) {
for (int jp = -1; jp<=1; jp += 2) {
int ii = i + ip;
int jj = j + jp;
if (0 <= ii && ii < LengthY && 0 <= jj && jj < LengthX) {
ki = k3 + ip * LengthX;
kj = k3 + jp;
m0 = (samples[2][kj] - c2) * (samples[1][ki] - c1) -
(samples[1][kj] - c1) * (samples[2][ki] - c2);
m1 = (samples[0][kj] - c0) * (samples[2][ki] - c2) -
(samples[2][kj] - c2) * (samples[0][ki] - c0);
m2 = (samples[1][kj] - c1) * (samples[0][ki] - c0) -
(samples[0][kj] - c0) * (samples[1][ki] - c1);
m = (float) Math.sqrt(m0 * m0 + m1 * m1 + m2 * m2);
if (ip == jp) {
n0 += m0 / m;
n1 += m1 / m;
n2 += m2 / m;
}
else {
n0 -= m0 / m;
n1 -= m1 / m;
n2 -= m2 / m;
}
}
}
}
n = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
grd_normals[0][tt] = n0 / n;
grd_normals[1][tt] = n1 / n;
grd_normals[2][tt] = n2 / n;
}
return grd_normals;
}
/** constants for isosurface, etc */
static final int BIG_NEG = (int) -2e+9;
static final float EPS_0 = (float) 1.0e-5;
static final boolean TRUE = true;
static final boolean FALSE = false;
static final int MASK = 0x0F;
static final int MAX_FLAG_NUM = 317;
static final int SF_6B = 0;
static final int SF_6D = 6;
static final int SF_79 = 12;
static final int SF_97 = 18;
static final int SF_9E = 24;
static final int SF_B6 = 30;
static final int SF_D6 = 36;
static final int SF_E9 = 42;
static final int Zp = 0;
static final int Zn = 1;
static final int Yp = 2;
static final int Yn = 3;
static final int Xp = 4;
static final int Xn = 5;
static final int incZn = 0;
static final int incYn = 8;
static final int incXn = 16;
static final int pol_edges[][] =
{
{ 0x0, 0, 0x0, 0x0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1, 1, 0x3, 0xe, 1, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1, 1, 0x3, 0x32, 4, 5, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x3, 1, 0x4, 0x3c, 2, 4, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1, 1, 0x3, 0xc4, 2, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x3, 1, 0x4, 0xca, 6, 1, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x6, 2, 0x33, 0xf6, 1, 4, 5, 2, 7, 6, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0xf8, 4, 5, 3, 7, 6, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1, 1, 0x3, 0x150, 6, 8, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x6, 2, 0x33, 0x15e, 4, 6, 8, 1, 3, 2, 0, 0, 0, 0, 0, 0 },
{ 0x3, 1, 0x4, 0x162, 1, 6, 8, 5, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x16c, 6, 8, 5, 3, 2, 0, 0, 0, 0, 0, 0, 0 },
{ 0x3, 1, 0x4, 0x194, 4, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x19a, 1, 3, 7, 8, 4, 0, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x1a6, 2, 7, 8, 5, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf, 1, 0x4, 0x1a8, 5, 3, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1, 1, 0x3, 0x608, 3, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x3, 1, 0x4, 0x606, 10, 2, 1, 9, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x6, 2, 0x33, 0x63a, 3, 9,10, 1, 4, 5, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x634, 9,10, 2, 4, 5, 0, 0, 0, 0, 0, 0, 0 },
{ 0x6, 2, 0x33, 0x6cc, 2, 7, 6, 3, 9,10, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x6c2, 7, 6, 1, 9,10, 0, 0, 0, 0, 0, 0, 0 },
{ 0x16, 3, 0x333, 0x6fe, 1, 4, 5, 2, 7, 6, 3, 9,10, 0, 0, 0 },
{ 0x17, 1, 0x6, 0x6f0, 5, 9,10, 7, 6, 4, 0, 0, 0, 0, 0, 0 },
{ 0x18, 2, 0x33, 0x758, 3, 9,10, 4, 6, 8, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x756, 1, 9,10, 2, 4, 6, 8, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x76a, 1, 6, 8, 5, 3, 9,10, 0, 0, 0, 0, 0 },
{ 0x1b, 1, 0x6, 0x764, 2, 6, 8, 5, 9,10, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x79c, 7, 8, 4, 2,10, 3, 9, 0, 0, 0, 0, 0 },
{ 0x1d, 1, 0x6, 0x792, 1, 9,10, 7, 8, 4, 0, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x7ae, 3, 9,10, 2, 7, 8, 5, 1, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x7a0, 10, 7, 8, 5, 9, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1, 1, 0x3, 0xa20, 9, 5,11, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x6, 2, 0x33, 0xa2e, 1, 3, 2, 5,11, 9, 0, 0, 0, 0, 0, 0 },
{ 0x3, 1, 0x4, 0xa12, 4,11, 9, 1, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0xa1c, 3, 2, 4,11, 9, 0, 0, 0, 0, 0, 0, 0 },
{ 0x18, 2, 0x33, 0xae4, 5,11, 9, 6, 2, 7, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0xaea, 3, 7, 6, 1, 9, 5,11, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0xad6, 4,11, 9, 1, 6, 2, 7, 0, 0, 0, 0, 0 },
{ 0x1d, 1, 0x6, 0xad8, 3, 7, 6, 4,11, 9, 0, 0, 0, 0, 0, 0 },
{ 0x6, 2, 0x33, 0xb70, 5,11, 9, 4, 6, 8, 0, 0, 0, 0, 0, 0 },
{ 0x16, 3, 0x333, 0xb7e, 4, 6, 8, 1, 3, 2, 5,11, 9, 0, 0, 0 },
{ 0x7, 1, 0x5, 0xb42, 11, 9, 1, 6, 8, 0, 0, 0, 0, 0, 0, 0 },
{ 0x17, 1, 0x6, 0xb4c, 8,11, 9, 3, 2, 6, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0xbb4, 4, 2, 7, 8, 5,11, 9, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0xbba, 5,11, 9, 1, 3, 7, 8, 4, 0, 0, 0, 0 },
{ 0x1b, 1, 0x6, 0xb86, 1, 2, 7, 8,11, 9, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0xb88, 9, 3, 7, 8,11, 0, 0, 0, 0, 0, 0, 0 },
{ 0x3, 1, 0x4, 0xc28, 11,10, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0xc26, 5,11,10, 2, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0xc1a, 1, 4,11,10, 3, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf, 1, 0x4, 0xc14, 2, 4,11,10, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0xcec, 3, 5,11,10, 2, 7, 6, 0, 0, 0, 0, 0 },
{ 0x1b, 1, 0x6, 0xce2, 10, 7, 6, 1, 5,11, 0, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0xcde, 2, 7, 6, 1, 4,11,10, 3, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0xcd0, 6, 4,11,10, 7, 0, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0xd78, 11,10, 3, 5, 8, 4, 6, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0xd76, 4, 6, 8, 5,11,10, 2, 1, 0, 0, 0, 0 },
{ 0x1d, 1, 0x6, 0xd4a, 1, 6, 8,11,10, 3, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0xd44, 8,11,10, 2, 6, 0, 0, 0, 0, 0, 0, 0 },
{ 0x3c, 2, 0x44, 0xdbc, 4, 2, 7, 8, 5,11,10, 3, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0xdb2, 8,11,10, 7, 4, 1, 5, 0, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0xd8e, 10, 7, 8,11, 3, 1, 2, 0, 0, 0, 0, 0 },
{ 0xfc, 1, 0x4, 0xd80, 10, 7, 8,11, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1, 1, 0x3, 0x1480, 10,12, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x6, 2, 0x33, 0x148e, 3, 2, 1,10,12, 7, 0, 0, 0, 0, 0, 0 },
{ 0x18, 2, 0x33, 0x14b2, 7,10,12, 1, 4, 5, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x14bc, 2, 4, 5, 3, 7,10,12, 0, 0, 0, 0, 0 },
{ 0x3, 1, 0x4, 0x1444, 2,10,12, 6, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x144a, 10,12, 6, 1, 3, 0, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x1476, 2,10,12, 6, 1, 4, 5, 0, 0, 0, 0, 0 },
{ 0x1b, 1, 0x6, 0x1478, 6, 4, 5, 3,10,12, 0, 0, 0, 0, 0, 0 },
{ 0x6, 2, 0x33, 0x15d0, 6, 8, 4, 7,10,12, 0, 0, 0, 0, 0, 0 },
{ 0x16, 3, 0x333, 0x15de, 2, 1, 3, 6, 8, 4, 7,10,12, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x15e2, 8, 5, 1, 6,12, 7,10, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x15ec, 7,10,12, 6, 8, 5, 3, 2, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x1514, 8, 4, 2,10,12, 0, 0, 0, 0, 0, 0, 0 },
{ 0x17, 1, 0x6, 0x151a, 3,10,12, 8, 4, 1, 0, 0, 0, 0, 0, 0 },
{ 0x1d, 1, 0x6, 0x1526, 2,10,12, 8, 5, 1, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x1528, 12, 8, 5, 3,10, 0, 0, 0, 0, 0, 0, 0 },
{ 0x3, 1, 0x4, 0x1288, 7, 3, 9,12, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x1286, 2, 1, 9,12, 7, 0, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x12ba, 9,12, 7, 3, 5, 1, 4, 0, 0, 0, 0, 0 },
{ 0x1d, 1, 0x6, 0x12b4, 9,12, 7, 2, 4, 5, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x124c, 3, 9,12, 6, 2, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf, 1, 0x4, 0x1242, 1, 9,12, 6, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x127e, 1, 4, 5, 3, 9,12, 6, 2, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x1270, 5, 9,12, 6, 4, 0, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x13d8, 7, 3, 9,12, 6, 8, 4, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x13d6, 6, 8, 4, 2, 1, 9,12, 7, 0, 0, 0, 0 },
{ 0x3c, 2, 0x44, 0x13ea, 1, 6, 8, 5, 3, 9,12, 7, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x13e4, 12, 8, 5, 9, 7, 2, 6, 0, 0, 0, 0, 0 },
{ 0x1b, 1, 0x6, 0x131c, 2, 3, 9,12, 8, 4, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x1312, 4, 1, 9,12, 8, 0, 0, 0, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x132e, 5, 9,12, 8, 1, 2, 3, 0, 0, 0, 0, 0 },
{ 0xfc, 1, 0x4, 0x1320, 5, 9,12, 8, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x6, 2, 0x33, 0x1ea0, 10,12, 7, 9, 5,11, 0, 0, 0, 0, 0, 0 },
{ 0x16, 3, 0x333, 0x1eae, 3, 2, 1,10,12, 7, 9, 5,11, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x1e92, 9, 1, 4,11,10,12, 7, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x1e9c, 10,12, 7, 3, 2, 4,11, 9, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x1e64, 12, 6, 2,10,11, 9, 5, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x1e6a, 9, 5,11,10,12, 6, 1, 3, 0, 0, 0, 0 },
{ 0x3c, 2, 0x44, 0x1e56, 2,10,12, 6, 1, 4,11, 9, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x1e58, 11,12, 6, 4, 9, 3,10, 0, 0, 0, 0, 0 },
{ 0x16, 3, 0x333, 0x1ff0, 11, 9, 5,12, 7,10, 8, 4, 6, 0, 0, 0 },
{ 0x69, 4, 0x3333,0x1ffe, 1, 3, 2, 6, 8, 4, 9, 5,11,10,12, 7 },
{ 0x1e, 2, 0x53, 0x1fc2, 12, 7,10,11, 9, 1, 6, 8, 0, 0, 0, 0 },
{ 0xe9, 3, 0x333, 0x1fcc, 12, 8,11,10, 9, 3, 7, 2, 6, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x1f34, 11, 9, 5, 8, 4, 2,10,12, 0, 0, 0, 0 },
{ 0xe9, 3, 0x333, 0x1f3a, 5, 4, 1, 9, 3,10,11,12, 8, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x1f06, 10, 9, 1, 2,12, 8,11, 0, 0, 0, 0, 0 },
{ 0xf9, 2, 0x33, 0x1f08, 9, 3,10,11,12, 8, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x18a8, 12, 7, 3, 5,11, 0, 0, 0, 0, 0, 0, 0 },
{ 0x17, 1, 0x6, 0x18a6, 1, 5,11,12, 7, 2, 0, 0, 0, 0, 0, 0 },
{ 0x1b, 1, 0x6, 0x189a, 11,12, 7, 3, 1, 4, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x1894, 7, 2, 4,11,12, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1d, 1, 0x6, 0x186c, 12, 6, 2, 3, 5,11, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x1862, 11,12, 6, 1, 5, 0, 0, 0, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x185e, 6, 4,11,12, 2, 3, 1, 0, 0, 0, 0, 0 },
{ 0xfc, 1, 0x4, 0x1850, 11,12, 6, 4, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x19f8, 8, 4, 6,12, 7, 3, 5,11, 0, 0, 0, 0 },
{ 0xe9, 3, 0x333, 0x19f6, 6, 7, 2, 4, 1, 5, 8,11,12, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x19ca, 6, 7, 3, 1, 8,11,12, 0, 0, 0, 0, 0 },
{ 0xf9, 2, 0x33, 0x19c4, 8,11,12, 6, 7, 2, 0, 0, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x193c, 5, 4, 2, 3,11,12, 8, 0, 0, 0, 0, 0 },
{ 0xf9, 2, 0x33, 0x1932, 11,12, 8, 5, 4, 1, 0, 0, 0, 0, 0, 0 },
{ 0xe7, 2, 0x33, 0x190e, 3, 1, 2,12, 8,11, 0, 0, 0, 0, 0, 0 },
{ 0xfe, 1, 0x3, 0x1900, 11,12, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1, 1, 0x3, 0x1900, 11, 8,12, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x18, 2, 0x33, 0x190e, 8,12,11, 2, 1, 3, 0, 0, 0, 0, 0, 0 },
{ 0x6, 2, 0x33, 0x1932, 11, 8,12, 5, 1, 4, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x193c, 5, 3, 2, 4,11, 8,12, 0, 0, 0, 0, 0 },
{ 0x6, 2, 0x33, 0x19c4, 8,12,11, 6, 2, 7, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x19ca, 6, 1, 3, 7, 8,12,11, 0, 0, 0, 0, 0 },
{ 0x16, 3, 0x333, 0x19f6, 6, 2, 7, 4, 5, 1, 8,12,11, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x19f8, 8,12,11, 4, 5, 3, 7, 6, 0, 0, 0, 0 },
{ 0x3, 1, 0x4, 0x1850, 11, 4, 6,12, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x185e, 6,12,11, 4, 2, 1, 3, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x1862, 5, 1, 6,12,11, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1d, 1, 0x6, 0x186c, 6,12,11, 5, 3, 2, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x1894, 12,11, 4, 2, 7, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1b, 1, 0x6, 0x189a, 4, 1, 3, 7,12,11, 0, 0, 0, 0, 0, 0 },
{ 0x17, 1, 0x6, 0x18a6, 7,12,11, 5, 1, 2, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x18a8, 11, 5, 3, 7,12, 0, 0, 0, 0, 0, 0, 0 },
{ 0x6, 2, 0x33, 0x1f08, 9,10, 3,11, 8,12, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x1f06, 10, 2, 1, 9,12,11, 8, 0, 0, 0, 0, 0 },
{ 0x16, 3, 0x333, 0x1f3a, 9,10, 3,11, 8,12, 5, 1, 4, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x1f34, 11, 8,12, 9,10, 2, 4, 5, 0, 0, 0, 0 },
{ 0x16, 3, 0x333, 0x1fcc, 10, 3, 9, 7, 6, 2,12,11, 8, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x1fc2, 12,11, 8, 7, 6, 1, 9,10, 0, 0, 0, 0 },
{ 0x69, 4, 0x3333,0x1ffe, 4, 5, 1, 2, 7, 6,11, 8,12, 9,10, 3 },
{ 0xe9, 3, 0x333, 0x1ff0, 11, 5, 9,12,10, 7, 8, 6, 4, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x1e58, 11, 4, 6,12, 9,10, 3, 0, 0, 0, 0, 0 },
{ 0x3c, 2, 0x44, 0x1e56, 10, 2, 1, 9,12,11, 4, 6, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x1e6a, 9,10, 3, 5, 1, 6,12,11, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x1e64, 12,10, 2, 6,11, 5, 9, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x1e9c, 10, 3, 9,12,11, 4, 2, 7, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x1e92, 9,11, 4, 1,10, 7,12, 0, 0, 0, 0, 0 },
{ 0xe9, 3, 0x333, 0x1eae, 10, 7,12, 9,11, 5, 3, 1, 2, 0, 0, 0 },
{ 0xf9, 2, 0x33, 0x1ea0, 11, 5, 9,12,10, 7, 0, 0, 0, 0, 0, 0 },
{ 0x3, 1, 0x4, 0x1320, 12, 9, 5, 8, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x132e, 5, 8,12, 9, 1, 3, 2, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x1312, 8,12, 9, 1, 4, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1b, 1, 0x6, 0x131c, 4, 8,12, 9, 3, 2, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0x13e4, 12, 9, 5, 8, 7, 6, 2, 0, 0, 0, 0, 0 },
{ 0x3c, 2, 0x44, 0x13ea, 6, 1, 3, 7, 8,12, 9, 5, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x13d6, 6, 2, 7, 8,12, 9, 1, 4, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x13d8, 7,12, 9, 3, 6, 4, 8, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x1270, 4, 6,12, 9, 5, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x127e, 1, 3, 2, 4, 6,12, 9, 5, 0, 0, 0, 0 },
{ 0xf, 1, 0x4, 0x1242, 9, 1, 6,12, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x124c, 2, 6,12, 9, 3, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1d, 1, 0x6, 0x12b4, 12, 9, 5, 4, 2, 7, 0, 0, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x12ba, 9, 3, 7,12, 5, 4, 1, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x1286, 7,12, 9, 1, 2, 0, 0, 0, 0, 0, 0, 0 },
{ 0xfc, 1, 0x4, 0x1288, 7,12, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x1528, 10, 3, 5, 8,12, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1d, 1, 0x6, 0x1526, 5, 8,12,10, 2, 1, 0, 0, 0, 0, 0, 0 },
{ 0x17, 1, 0x6, 0x151a, 3, 1, 4, 8,12,10, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x1514, 12,10, 2, 4, 8, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x15ec, 7, 6, 2,10, 3, 5, 8,12, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x15e2, 8, 6, 1, 5,12,10, 7, 0, 0, 0, 0, 0 },
{ 0xe9, 3, 0x333, 0x15de, 2, 3, 1, 6, 4, 8, 7,12,10, 0, 0, 0 },
{ 0xf9, 2, 0x33, 0x15d0, 6, 4, 8, 7,12,10, 0, 0, 0, 0, 0, 0 },
{ 0x1b, 1, 0x6, 0x1478, 12,10, 3, 5, 4, 6, 0, 0, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x1476, 2, 6,12,10, 1, 5, 4, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x144a, 3, 1, 6,12,10, 0, 0, 0, 0, 0, 0, 0 },
{ 0xfc, 1, 0x4, 0x1444, 2, 6,12,10, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x14bc, 2, 3, 5, 4, 7,12,10, 0, 0, 0, 0, 0 },
{ 0xe7, 2, 0x33, 0x14b2, 7,12,10, 1, 5, 4, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 2, 0x33, 0x148e, 3, 1, 2,10, 7,12, 0, 0, 0, 0, 0, 0 },
{ 0xfe, 1, 0x3, 0x1480, 10, 7,12, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x3, 1, 0x4, 0xd80, 10,11, 8, 7, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0xd8e, 10,11, 8, 7, 3, 2, 1, 0, 0, 0, 0, 0 },
{ 0x19, 2, 0x34, 0xdb2, 8, 7,10,11, 4, 5, 1, 0, 0, 0, 0, 0 },
{ 0x3c, 2, 0x44, 0xdbc, 2, 4, 5, 3, 7,10,11, 8, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0xd44, 6, 2,10,11, 8, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1d, 1, 0x6, 0xd4a, 10,11, 8, 6, 1, 3, 0, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0xd76, 4, 5, 1, 6, 2,10,11, 8, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0xd78, 11, 5, 3,10, 8, 6, 4, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0xcd0, 7,10,11, 4, 6, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0xcde, 2, 1, 3, 7,10,11, 4, 6, 0, 0, 0, 0 },
{ 0x1b, 1, 0x6, 0xce2, 11, 5, 1, 6, 7,10, 0, 0, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0xcec, 3,10,11, 5, 2, 6, 7, 0, 0, 0, 0, 0 },
{ 0xf, 1, 0x4, 0xc14, 4, 2,10,11, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0xc1a, 3,10,11, 4, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0xc26, 1, 2,10,11, 5, 0, 0, 0, 0, 0, 0, 0 },
{ 0xfc, 1, 0x4, 0xc28, 3,10,11, 5, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0xb88, 11, 8, 7, 3, 9, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1b, 1, 0x6, 0xb86, 7, 2, 1, 9,11, 8, 0, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0xbba, 5, 1, 4,11, 8, 7, 3, 9, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0xbb4, 4, 8, 7, 2, 5, 9,11, 0, 0, 0, 0, 0 },
{ 0x17, 1, 0x6, 0xb4c, 9,11, 8, 6, 2, 3, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0xb42, 8, 6, 1, 9,11, 0, 0, 0, 0, 0, 0, 0 },
{ 0xe9, 3, 0x333, 0xb7e, 4, 8, 6, 1, 2, 3, 5, 9,11, 0, 0, 0 },
{ 0xf9, 2, 0x33, 0xb70, 5, 9,11, 4, 8, 6, 0, 0, 0, 0, 0, 0 },
{ 0x1d, 1, 0x6, 0xad8, 7, 3, 9,11, 4, 6, 0, 0, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0xad6, 4, 1, 9,11, 6, 7, 2, 0, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0xaea, 3, 1, 6, 7, 9,11, 5, 0, 0, 0, 0, 0 },
{ 0xe7, 2, 0x33, 0xae4, 5, 9,11, 6, 7, 2, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0xa1c, 9,11, 4, 2, 3, 0, 0, 0, 0, 0, 0, 0 },
{ 0xfc, 1, 0x4, 0xa12, 4, 1, 9,11, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 2, 0x33, 0xa2e, 9,11, 5, 3, 1, 2, 0, 0, 0, 0, 0, 0 },
{ 0xfe, 1, 0x3, 0xa20, 9,11, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x7, 1, 0x5, 0x7a0, 9, 5, 8, 7,10, 0, 0, 0, 0, 0, 0, 0 },
{ 0x1e, 2, 0x53, 0x7ae, 3, 2, 1, 9, 5, 8, 7,10, 0, 0, 0, 0 },
{ 0x1d, 1, 0x6, 0x792, 9, 1, 4, 8, 7,10, 0, 0, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x79c, 7, 2, 4, 8,10, 9, 3, 0, 0, 0, 0, 0 },
{ 0x1b, 1, 0x6, 0x764, 8, 6, 2,10, 9, 5, 0, 0, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x76a, 1, 5, 8, 6, 3,10, 9, 0, 0, 0, 0, 0 },
{ 0xe6, 2, 0x34, 0x756, 1, 2,10, 9, 4, 8, 6, 0, 0, 0, 0, 0 },
{ 0xe7, 2, 0x33, 0x758, 3,10, 9, 4, 8, 6, 0, 0, 0, 0, 0, 0 },
{ 0x17, 1, 0x6, 0x6f0, 10, 9, 5, 4, 6, 7, 0, 0, 0, 0, 0, 0 },
{ 0xe9, 3, 0x333, 0x6fe, 1, 5, 4, 2, 6, 7, 3,10, 9, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x6c2, 10, 9, 1, 6, 7, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 2, 0x33, 0x6cc, 2, 6, 7, 3,10, 9, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x634, 5, 4, 2,10, 9, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 2, 0x33, 0x63a, 5, 4, 1, 9, 3,10, 0, 0, 0, 0, 0, 0 },
{ 0xfc, 1, 0x4, 0x606, 1, 2,10, 9, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xfe, 1, 0x3, 0x608, 9, 3,10, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf, 1, 0x4, 0x1a8, 8, 7, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x1a6, 1, 5, 8, 7, 2, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x19a, 4, 8, 7, 3, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 0xfc, 1, 0x4, 0x194, 4, 8, 7, 2, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0x16c, 2, 3, 5, 8, 6, 0, 0, 0, 0, 0, 0, 0 },
{ 0xfc, 1, 0x4, 0x162, 1, 5, 8, 6, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 2, 0x33, 0x15e, 4, 8, 6, 1, 2, 3, 0, 0, 0, 0, 0, 0 },
{ 0xfe, 1, 0x3, 0x150, 6, 4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf8, 1, 0x5, 0xf8, 6, 7, 3, 5, 4, 0, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 2, 0x33, 0xf6, 1, 5, 4, 2, 6, 7, 0, 0, 0, 0, 0, 0 },
{ 0xfc, 1, 0x4, 0xca, 6, 7, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xfe, 1, 0x3, 0xc4, 2, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xfc, 1, 0x4, 0x3c, 2, 3, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xfe, 1, 0x3, 0x32, 4, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xfe, 1, 0x3, 0xe, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0x0, 0, 0x0, 0x0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0xdb2, 8,11,10, 7, 4, 1, 5,11, 8, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0xd8e, 10, 7, 8,11, 3, 1, 2, 7,10, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x13e4, 12, 8, 5, 9, 7, 2, 6, 8,12, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x132e, 5, 9,12, 8, 1, 2, 3, 9, 5, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x1e58, 11,12, 6, 4, 9, 3,10,12,11, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x1f06, 10, 9, 1, 2,12, 8,11, 9,10, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x185e, 6, 4,11,12, 2, 3, 1, 4, 6, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x19ca, 6, 7, 3, 1, 8,11,12, 7, 6, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x193c, 5, 4, 2, 3,11,12, 8, 4, 5, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x1e64, 12,10, 2, 6,11, 5, 9,10,12, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x1e92, 9,11, 4, 1,10, 7,12,11, 9, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x13d8, 7,12, 9, 3, 6, 4, 8,12, 7, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x12ba, 9, 3, 7,12, 5, 4, 1, 3, 9, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x15e2, 8, 6, 1, 5,12,10, 7, 6, 8, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x1476, 2, 6,12,10, 1, 5, 4, 6, 2, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x14bc, 2, 3, 5, 4, 7,12,10, 3, 2, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0xd78, 11, 5, 3,10, 8, 6, 4, 5,11, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0xcec, 3,10,11, 5, 2, 6, 7,10, 3, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0xbb4, 4, 8, 7, 2, 5, 9,11, 8, 4, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0xad6, 4, 1, 9,11, 6, 7, 2, 1, 4, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0xaea, 3, 1, 6, 7, 9,11, 5, 1, 3, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x79c, 7, 2, 4, 8,10, 9, 3, 2, 7, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x76a, 1, 5, 8, 6, 3,10, 9, 5, 1, 0, 0, 0 },
{ 0xe6, 2, 0x54, 0x756, 1, 2,10, 9, 4, 8, 6, 2, 1, 0, 0, 0 },
{ 0xf9, 1, 0x6, 0x1f08, 9, 3,10,12, 8,11, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 1, 0x6, 0x19c4, 8,11,12, 7, 2, 6, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 1, 0x6, 0x1932, 11,12, 8, 4, 1, 5, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 1, 0x6, 0x1ea0, 11, 5, 9,10, 7,12, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 1, 0x6, 0x15d0, 6, 4, 8,12,10, 7, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 1, 0x6, 0x148e, 3, 1, 2, 7,12,10, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 1, 0x6, 0xb70, 5, 9,11, 8, 6, 4, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 1, 0x6, 0xa2e, 9,11, 5, 1, 2, 3, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 1, 0x6, 0x6cc, 2, 6, 7,10, 9, 3, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 1, 0x6, 0x63a, 5, 4, 1, 3,10, 9, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 1, 0x6, 0x15e, 4, 8, 6, 2, 3, 1, 0, 0, 0, 0, 0, 0 },
{ 0xf9, 1, 0x6, 0xf6, 1, 5, 4, 6, 7, 2, 0, 0, 0, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x1fcc, 12, 8,11, 9, 3,10, 7, 2, 6, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x1f3a, 5, 4, 1, 3,10, 9,11,12, 8, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x19f6, 6, 7, 2, 1, 5, 4, 8,11,12, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x1ff0, 11, 5, 9,10, 7,12, 8, 6, 4, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x1eae, 10, 7,12,11, 5, 9, 3, 1, 2, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x15de, 2, 3, 1, 4, 8, 6, 7,12,10, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0xb7e, 4, 8, 6, 2, 3, 1, 5, 9,11, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x6fe, 1, 5, 4, 6, 7, 2, 3,10, 9, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x1fcc, 8,11,12, 7, 2, 6, 9, 3,10, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x1f3a, 4, 1, 5,11,12, 8, 3,10, 9, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x19f6, 7, 2, 6, 8,11,12, 1, 5, 4, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x1ff0, 5, 9,11, 8, 6, 4,10, 7,12, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x1eae, 7,12,10, 3, 1, 2,11, 5, 9, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x15de, 3, 1, 2, 7,12,10, 4, 8, 6, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0xb7e, 8, 6, 4, 5, 9,11, 2, 3, 1, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x6fe, 5, 4, 1, 3,10, 9, 6, 7, 2, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x1fcc, 2, 6, 7,10, 9, 3,12, 8,11, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x1f3a, 12, 8,11, 9, 3,10, 5, 4, 1, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x19f6, 11,12, 8, 4, 1, 5, 6, 7, 2, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x1ff0, 6, 4, 8,12,10, 7,11, 5, 9, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x1eae, 1, 2, 3, 9,11, 5,10, 7,12, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x15de, 12,10, 7, 6, 4, 8, 2, 3, 1, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0xb7e, 9,11, 5, 1, 2, 3, 4, 8, 6, 0, 0, 0 },
{ 0xe9, 2, 0x36, 0x6fe, 10, 9, 3, 2, 6, 7, 1, 5, 4, 0, 0, 0 }
};
static final int sp_cases[] =
{
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 256, 257, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 258, 000, 000, 259, 000, 000, 000, 000, 000,
000, 000, 000, 260, 000, 000, 000, 292, 000, 293,
261, 280, 000, 000, 000, 000, 000, 000, 262, 000,
000, 294, 263, 281, 264, 282, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 295, 000, 000, 000, 265, 000, 266, 296, 283,
000, 000, 000, 000, 000, 000, 000, 267, 000, 000,
000, 000, 000, 268, 000, 000, 000, 000, 000, 000,
000, 269, 297, 284, 000, 270, 000, 000, 271, 000,
285, 000, 000, 000, 000, 000, 000, 000, 000, 272,
000, 000, 000, 273, 000, 000, 000, 000, 000, 000,
000, 274, 000, 000, 298, 286, 000, 275, 276, 000,
000, 000, 287, 000, 000, 000, 000, 277, 000, 278,
279, 000, 000, 299, 000, 288, 000, 289, 000, 000,
000, 000, 000, 000, 000, 000, 290, 000, 000, 291,
000, 000, 000, 000, 000, 000
};
static final int case_E9[] =
{
Xn, Yp, Zp, incXn, incYn, incZn,
Xp, Yn, Zp, incYn, incZn, incXn,
Xp, Yp, Zn, incXn, incYn, incZn,
Xp, Yp, Zp, incYn, incXn, incZn,
Xn, Yn, Zp, incYn, incXn, incZn,
Xn, Yp, Zp, incYn, incXn, incZn,
Xp, Yn, Zn, incYn, incXn, incZn,
Xn, Yn, Zn, incXn, incYn, incZn
};
static final int NTAB[] =
{ 0,1,2, 1,2,0, 2,0,1,
0,1,3,2, 1,2,0,3, 2,3,1,0, 3,0,2,1,
0,1,4,2,3, 1,2,0,3,4, 2,3,1,4,0, 3,4,2,0,1, 4,0,3,1,2,
0,1,5,2,4,3, 1,2,0,3,5,4, 2,3,1,4,0,5, 3,4,2,5,1,0, 4,5,3,0,2,1,
5,0,4,1,3,2
};
static final int ITAB[] =
{ 0,2,1, 1,0,2, 2,1,0,
0,3,1,2, 1,0,2,3, 2,1,3,0, 3,2,0,1,
0,4,1,3,2, 1,0,2,4,3, 2,1,3,0,4, 3,2,4,1,0, 4,3,0,2,1,
0,5,1,4,2,3, 1,0,2,5,3,4, 2,1,3,0,4,5, 3,2,4,1,5,0, 4,3,5,2,0,1,
5,4,0,3,1,2
};
static final int STAB[] = { 0, 9, 25, 50 };
public VisADGeometryArray makeIsoSurface(float isolevel,
float[] fieldValues, byte[][] color_values, boolean indexed)
throws VisADException {
boolean debug = false;
int i, NVT, cnt;
int size_stripe;
int xdim_x_ydim, xdim_x_ydim_x_zdim;
int num_cubes, nvertex, npolygons;
int ix, iy, ii;
int nvertex_estimate;
if (ManifoldDimension != 3) {
throw new DisplayException("Gridded3DSet.makeIsoSurface: " +
"ManifoldDimension must be 3");
}
/* adapt isosurf algorithm to Gridded3DSet variables */
// NOTE X & Y swap
int xdim = LengthY;
int ydim = LengthX;
int zdim = LengthZ;
float[] ptGRID = fieldValues;
xdim_x_ydim = xdim * ydim;
xdim_x_ydim_x_zdim = xdim_x_ydim * zdim;
num_cubes = (xdim-1) * (ydim-1) * (zdim-1);
int[] ptFLAG = new int[ num_cubes ];
int[] ptAUX = new int[ xdim_x_ydim_x_zdim ];
int[] pcube = new int[ num_cubes+1 ];
// System.out.println("pre-flags: isolevel = " + isolevel +
// " xdim, ydim, zdim = " + xdim + " " + ydim + " " + zdim);
npolygons = flags( isolevel, ptFLAG, ptAUX, pcube,
ptGRID, xdim, ydim, zdim );
if (debug) System.out.println("npolygons= "+npolygons);
if (npolygons == 0) return null;
// take the garbage out
pcube = null;
nvertex_estimate = 4 * npolygons + 100;
ix = 9 * (nvertex_estimate + 50);
iy = 7 * npolygons;
float[][] VX = new float[1][nvertex_estimate];
float[][] VY = new float[1][nvertex_estimate];
float[][] VZ = new float[1][nvertex_estimate];
byte[][] color_temps = null;
if (color_values != null) {
color_temps = new byte[color_values.length][];
}
int[] Pol_f_Vert = new int[ix];
int[] Vert_f_Pol = new int[iy];
int[][] arg_Pol_f_Vert = new int[][] {Pol_f_Vert};
nvertex = isosurf( isolevel, ptFLAG, nvertex_estimate, npolygons,
ptGRID, xdim, ydim, zdim, VX, VY, VZ,
color_values, color_temps, arg_Pol_f_Vert, Vert_f_Pol );
Pol_f_Vert = arg_Pol_f_Vert[0];
if (nvertex == 0) return null;
// take the garbage out
ptFLAG = null;
ptAUX = null;
/*
for (int j=0; j<nvertex; j++) {
System.out.println("iso vertex[" + j + "] " + VX[0][j] + " " + VY[0][j] +
" " + VZ[0][j]);
}
*/
float[][] fieldVertices = new float[3][nvertex];
// NOTE - NO X & Y swap
System.arraycopy(VX[0], 0, fieldVertices[0], 0, nvertex);
System.arraycopy(VY[0], 0, fieldVertices[1], 0, nvertex);
System.arraycopy(VZ[0], 0, fieldVertices[2], 0, nvertex);
// take the garbage out
VX = null;
VY = null;
VZ = null;
byte[][] color_levels = null;
if (color_values != null) {
color_levels = new byte[color_values.length][nvertex];
System.arraycopy(color_temps[0], 0, color_levels[0], 0, nvertex);
System.arraycopy(color_temps[1], 0, color_levels[1], 0, nvertex);
System.arraycopy(color_temps[2], 0, color_levels[2], 0, nvertex);
if (color_temps.length > 3) {
System.arraycopy(color_temps[3], 0, color_levels[3], 0, nvertex);
}
// take the garbage out
color_temps = null;
}
if (debug) System.out.println("nvertex= "+nvertex);
float[] NxA = new float[npolygons];
float[] NxB = new float[npolygons];
float[] NyA = new float[npolygons];
float[] NyB = new float[npolygons];
float[] NzA = new float[npolygons];
float[] NzB = new float[npolygons];
float[] Pnx = new float[npolygons];
float[] Pny = new float[npolygons];
float[] Pnz = new float[npolygons];
float[] NX = new float[nvertex];
float[] NY = new float[nvertex];
float[] NZ = new float[nvertex];
make_normals( fieldVertices[0], fieldVertices[1], fieldVertices[2],
NX, NY, NZ, nvertex, npolygons, Pnx, Pny, Pnz,
NxA, NxB, NyA, NyB, NzA, NzB, Pol_f_Vert, Vert_f_Pol);
// take the garbage out
NxA = NxB = NyA = NyB = NzA = NzB = Pnx = Pny = Pnz = null;
float[] normals = new float[3 * nvertex];
int j = 0;
for (i=0; i<nvertex; i++) {
normals[j++] = (float) NX[i];
normals[j++] = (float) NY[i];
normals[j++] = (float) NZ[i];
}
// take the garbage out
NX = NY = NZ = null;
/* ----- Find PolyTriangle Stripe */
// temporary array to hold maximum possible polytriangle strip
int[] stripe = new int[6 * npolygons];
int[] vet_pol = new int[npolygons];
size_stripe = poly_triangle_stripe( vet_pol, stripe, nvertex,
npolygons, Pol_f_Vert, Vert_f_Pol );
// take the garbage out
Pol_f_Vert = null;
Vert_f_Pol = null;
if (indexed) {
VisADIndexedTriangleStripArray array =
new VisADIndexedTriangleStripArray();
// set up indices
array.indexCount = size_stripe;
array.indices = new int[size_stripe];
System.arraycopy(stripe, 0, array.indices, 0, size_stripe);
array.stripVertexCounts = new int[1];
array.stripVertexCounts[0] = size_stripe;
// take the garbage out
stripe = null;
// set coordinates and colors
setGeometryArray(array, fieldVertices, 4, color_levels);
// take the garbage out
fieldVertices = null;
color_levels = null;
// array.vertexFormat |= NORMALS;
array.normals = normals;
if (debug) {
System.out.println("size_stripe= "+size_stripe);
for(ii=0;ii<size_stripe;ii++) System.out.println(+array.indices[ii]);
}
return array;
}
else { // if (!indexed)
VisADTriangleStripArray array = new VisADTriangleStripArray();
array.stripVertexCounts = new int[] {size_stripe};
array.vertexCount = size_stripe;
array.normals = new float[3 * size_stripe];
int k = 0;
for (i=0; i<3*size_stripe; i+=3) {
j = 3 * stripe[k];
array.normals[i] = normals[j];
array.normals[i+1] = normals[j+1];
array.normals[i+2] = normals[j+2];
k++;
}
normals = null;
array.coordinates = new float[3 * size_stripe];
k = 0;
for (i=0; i<3*size_stripe; i+=3) {
j = stripe[k];
array.coordinates[i] = fieldVertices[0][j];
array.coordinates[i+1] = fieldVertices[1][j];
array.coordinates[i+2] = fieldVertices[2][j];
k++;
}
fieldVertices = null;
if (color_levels != null) {
int color_length = color_levels.length;
array.colors = new byte[color_length * size_stripe];
k = 0;
if (color_length == 4) {
for (i=0; i<color_length*size_stripe; i+=color_length) {
j = stripe[k];
array.colors[i] = color_levels[0][j];
array.colors[i+1] = color_levels[1][j];
array.colors[i+2] = color_levels[2][j];
array.colors[i+3] = color_levels[3][j];
k++;
}
}
else { // if (color_length == 3)
for (i=0; i<color_length*size_stripe; i+=color_length) {
j = stripe[k];
array.colors[i] = color_levels[0][j];
array.colors[i+1] = color_levels[1][j];
array.colors[i+2] = color_levels[2][j];
k++;
}
}
}
color_levels = null;
stripe = null;
return array;
} // end if (!indexed)
}
public static int flags( float isovalue, int[] ptFLAG, int[] ptAUX, int[] pcube,
float[] ptGRID, int xdim, int ydim, int zdim ) {
int ii, jj, ix, iy, iz, cb, SF, bcase;
int num_cubes, num_cubes_xy, num_cubes_y;
int xdim_x_ydim = xdim*ydim;
int xdim_x_ydim_x_zdim = xdim_x_ydim*zdim;
int npolygons;
num_cubes_y = ydim-1;
num_cubes_xy = (xdim-1) * num_cubes_y;
num_cubes = (zdim-1) * num_cubes_xy;
/*
*************
Big Attention
*************
pcube must have the dimension "num_cubes+1" because in terms of
eficiency the best loop to calculate "pcube" will use more one
component to pcube.
*/
/* Calculate the Flag Value of each Cube */
/* In order to simplify the Flags calculations, "pcube" will
be used to store the number of the first vertex of each cube */
ii = 0; pcube[0] = 0; cb = 0;
for (iz=0; iz<(zdim-1); iz++)
{ for (ix=0; ix<(xdim-1); ix++)
{ cb = pcube[ii];
for (iy=1; iy<(ydim-1); iy++) /* Vectorized */
pcube[ii+iy] = cb+iy;
ii += ydim-1;
pcube[ii] = pcube[ii-1]+2;
}
pcube[ii] += ydim;
}
/* Vectorized */
for (ii = 0; ii < xdim_x_ydim_x_zdim; ii++) {
/* WLH 24 Oct 97
if (ptGRID[ii] >= INVALID_VALUE) ptAUX[ii] = 0x1001;
if (Float.isNaN(ptGRID[ii]) ptAUX[ii] = 0x1001;
*/
// test for missing
if (ptGRID[ii] != ptGRID[ii]) ptAUX[ii] = 0x1001;
else if (ptGRID[ii] >= isovalue) ptAUX[ii] = 1;
else ptAUX[ii] = 0;
}
/* Vectorized */
for (ii = 0; ii < num_cubes; ii++) {
ptFLAG[ii] = ((ptAUX[ pcube[ii] ] ) |
(ptAUX[ pcube[ii] + ydim ] << 1) |
(ptAUX[ pcube[ii] + 1 ] << 2) |
(ptAUX[ pcube[ii] + ydim + 1 ] << 3) |
(ptAUX[ pcube[ii] + xdim_x_ydim ] << 4) |
(ptAUX[ pcube[ii] + ydim + xdim_x_ydim ] << 5) |
(ptAUX[ pcube[ii] + 1 + xdim_x_ydim ] << 6) |
(ptAUX[ pcube[ii] + 1 + ydim + xdim_x_ydim ] << 7));
}
/* After this Point it is not more used pcube */
/* Analyse Special Cases in FLAG */
ii = npolygons = 0;
while ( TRUE )
{
for (; ii < num_cubes; ii++) {
if ( ((ptFLAG[ii] != 0) && (ptFLAG[ii] != 0xFF)) &&
ptFLAG[ii] < MAX_FLAG_NUM) break;
}
if ( ii == num_cubes ) break;
bcase = pol_edges[ptFLAG[ii]][0];
if (bcase == 0xE6 || bcase == 0xF9) {
iz = ii/num_cubes_xy;
ix = (int)((ii - (iz*num_cubes_xy))/num_cubes_y);
iy = ii - (iz*num_cubes_xy) - (ix*num_cubes_y);
/* == Z+ == */
if ((ptFLAG[ii] & 0xF0) == 0x90 ||
(ptFLAG[ii] & 0xF0) == 0x60) {
cb = (iz < (zdim - 1)) ? ii + num_cubes_xy : -1 ;
}
/* == Z- == */
else if ((ptFLAG[ii] & 0x0F) == 0x09 ||
(ptFLAG[ii] & 0x0F) == 0x06) {
cb = (iz > 0) ? ii - num_cubes_xy : -1 ;
}
/* == Y+ == */
else if ((ptFLAG[ii] & 0xCC) == 0x84 ||
(ptFLAG[ii] & 0xCC) == 0x48) {
cb = (iy < (ydim - 1)) ? ii + 1 : -1 ;
}
/* == Y- == */
else if ((ptFLAG[ii] & 0x33) == 0x21 ||
(ptFLAG[ii] & 0x33) == 0x12) {
cb = (iy > 0) ? ii - 1 : -1 ;
}
/* == X+ == */
else if ((ptFLAG[ii] & 0xAA) == 0x82 ||
(ptFLAG[ii] & 0xAA) == 0x28) {
cb = (ix < (xdim - 1)) ? ii + num_cubes_y : -1 ;
}
/* == X- == */
else if ((ptFLAG[ii] & 0x55) == 0x41 ||
(ptFLAG[ii] & 0x55) == 0x14) {
cb = (ix > 0) ? ii - num_cubes_y : -1 ;
}
/* == Map Special Case == */
if ((cb > -1 && cb < num_cubes) && ptFLAG[cb]<316) /*changed by BEP on 7-20-92*/
{ bcase = pol_edges[ptFLAG[cb]][0];
if (bcase == 0x06 || bcase == 0x16 ||
bcase == 0x19 || bcase == 0x1E ||
bcase == 0x3C || bcase == 0x69) {
ptFLAG[ii] = sp_cases[ptFLAG[ii]];
}
}
}
else if (bcase == 0xE9) {
iz = ii/num_cubes_xy;
ix = (int)((ii - (iz*num_cubes_xy))/num_cubes_y);
iy = ii - (iz*num_cubes_xy) - (ix*num_cubes_y);
SF = 0;
if (ptFLAG[ii] == 0x6B) SF = SF_6B;
else if (ptFLAG[ii] == 0x6D) SF = SF_6D;
else if (ptFLAG[ii] == 0x79) SF = SF_79;
else if (ptFLAG[ii] == 0x97) SF = SF_97;
else if (ptFLAG[ii] == 0x9E) SF = SF_9E;
else if (ptFLAG[ii] == 0xB6) SF = SF_B6;
else if (ptFLAG[ii] == 0xD6) SF = SF_D6;
else if (ptFLAG[ii] == 0xE9) SF = SF_E9;
for (jj=0; jj<3; jj++) {
if (case_E9[jj+SF] == Zp) {
cb = (iz < (zdim - 1)) ? ii + num_cubes_xy : -1 ;
}
else if (case_E9[jj+SF] == Zn) {
cb = (iz > 0) ? ii - num_cubes_xy : -1 ;
}
else if (case_E9[jj+SF] == Yp) {
cb = (iy < (ydim - 1)) ? ii + 1 : -1 ;
}
else if (case_E9[jj+SF] == Yn) {
cb = (iy > 0) ? ii - 1 : -1 ;
}
else if (case_E9[jj+SF] == Xp) {
cb = (ix < (xdim - 1)) ? ii + num_cubes_y : -1 ;
}
else if (case_E9[jj+SF] == Xn) {
cb = (ix > 0) ? ii - num_cubes_y : -1 ;
}
/* changed:
if ((cb > -1 && cb < num_cubes))
to: */
if ((cb > -1 && cb < num_cubes) && ptFLAG[cb]<316)
/* changed by BEP on 7-20-92*/
{ bcase = pol_edges[ptFLAG[cb]][0];
if (bcase == 0x06 || bcase == 0x16 ||
bcase == 0x19 || bcase == 0x1E ||
bcase == 0x3C || bcase == 0x69)
{
ptFLAG[ii] = sp_cases[ptFLAG[ii]] +
case_E9[jj+SF+3];
break;
}
}
}
}
/* Calculate the Number of Generated Triangles and Polygons */
npolygons += pol_edges[ptFLAG[ii]][1];
ii++;
}
/* npolygons2 = 2*npolygons; */
return npolygons;
}
private int isosurf( float isovalue, int[] ptFLAG, int nvertex_estimate,
int npolygons, float[] ptGRID, int xdim, int ydim,
int zdim, float[][] VX, float[][] VY, float[][] VZ,
byte[][] auxValues, byte[][] auxLevels,
int[][] Pol_f_Vert, int[] Vert_f_Pol )
throws VisADException {
int ix, iy, iz, caseA, above, bellow, front, rear, mm, nn;
int ii, jj, kk, ncube, cpl, pvp, pa, ve;
int[] calc_edge = new int[13];
int xx, yy, zz;
float cp;
float vnode0 = 0;
float vnode1 = 0;
float vnode2 = 0;
float vnode3 = 0;
float vnode4 = 0;
float vnode5 = 0;
float vnode6 = 0;
float vnode7 = 0;
int pt = 0;
int n_pol;
int aa;
int bb;
int temp;
float nodeDiff;
int xdim_x_ydim = xdim*ydim;
int nvet;
int t;
float[][] samples = getSamples(false);
int naux = (auxValues != null) ? auxValues.length : 0;
if (naux > 0) {
if (auxLevels == null || auxLevels.length != naux) {
throw new SetException("Gridded3DSet.isosurf: "
+"auxLevels length " + auxLevels.length +
" doesn't match expected " + naux);
}
for (int i=0; i<naux; i++) {
if (auxValues[i].length != Length) {
throw new SetException("Gridded3DSet.isosurf: expected auxValues " +
" length#" + i + " to be " + Length +
", not " + auxValues[i].length);
}
}
}
else {
if (auxLevels != null) {
throw new SetException("Gridded3DSet.isosurf: "
+"auxValues null but auxLevels not null");
}
}
// temporary storage of auxLevels structure
byte[][] tempaux = (naux > 0) ? new byte[naux][nvertex_estimate] : null;
bellow = rear = 0; above = front = 1;
/* Initialize the Auxiliar Arrays of Pointers */
/* WLH 25 Oct 97
ix = 9 * (npolygons*2 + 50);
iy = 7 * npolygons;
ii = ix + iy;
*/
for (jj=0; jj<Pol_f_Vert[0].length; jj++) {
Pol_f_Vert[0][jj] = BIG_NEG;
}
for (jj=8; jj<Pol_f_Vert[0].length; jj+=9) {
Pol_f_Vert[0][jj] = 0;
}
for (jj=0; jj<Vert_f_Pol.length; jj++) {
Vert_f_Pol[jj] = BIG_NEG;
}
for (jj=6; jj<Vert_f_Pol.length; jj+=7) {
Vert_f_Pol[jj] = 0;
}
/* Allocate the auxiliar edge vectors
size ixPlane = (xdim - 1) * ydim = xdim_x_ydim - ydim
size iyPlane = (ydim - 1) * xdim = xdim_x_ydim - xdim
size izPlane = xdim
*/
xx = xdim_x_ydim - ydim;
yy = xdim_x_ydim - xdim;
zz = ydim;
ii = 2 * (xx + yy + zz);
int[] P_array = new int[ii];
/* Calculate the Vertex of the Polygons which edges were
calculated above */
nvet = ncube = cpl = pvp = 0;
for ( iz = 0; iz < zdim - 1; iz++ ) {
for ( ix = 0; ix < xdim - 1; ix++ ) {
for ( iy = 0; iy < ydim - 1; iy++ ) {
if ( (ptFLAG[ncube] != 0 & ptFLAG[ncube] != 0xFF) ) {
if (nvet + 12 > nvertex_estimate) {
// allocate more space
nvertex_estimate = 2 * (nvet + 12);
if (naux > 0) {
for (int i=0; i<naux; i++) {
byte[] tt = tempaux[i];
tempaux[i] = new byte[nvertex_estimate];
System.arraycopy(tt, 0, tempaux[i], 0, nvet);
}
}
float[] tt = VX[0];
VX[0] = new float[nvertex_estimate];
System.arraycopy(tt, 0, VX[0], 0, tt.length);
tt = VY[0];
VY[0] = new float[nvertex_estimate];
System.arraycopy(tt, 0, VY[0], 0, tt.length);
tt = VZ[0];
VZ[0] = new float[nvertex_estimate];
System.arraycopy(tt, 0, VZ[0], 0, tt.length);
int big_ix = 9 * (nvertex_estimate + 50);
int[] it = Pol_f_Vert[0];
Pol_f_Vert[0] = new int[big_ix];
for (jj=0; jj<Pol_f_Vert[0].length; jj++) {
Pol_f_Vert[0][jj] = BIG_NEG;
}
for (jj=8; jj<Pol_f_Vert[0].length; jj+=9) {
Pol_f_Vert[0][jj] = 0;
}
System.arraycopy(it, 0, Pol_f_Vert[0], 0, it.length);
}
/* WLH 2 April 99 */
vnode0 = ptGRID[pt];
vnode1 = ptGRID[pt + ydim];
vnode2 = ptGRID[pt + 1];
vnode3 = ptGRID[pt + ydim + 1];
vnode4 = ptGRID[pt + xdim_x_ydim];
vnode5 = ptGRID[pt + ydim + xdim_x_ydim];
vnode6 = ptGRID[pt + 1 + xdim_x_ydim];
vnode7 = ptGRID[pt + 1 + ydim + xdim_x_ydim];
if ( (ptFLAG[ncube] < MAX_FLAG_NUM) ) {
/* fill_Vert_f_Pol(ncube); */
kk = pol_edges[ptFLAG[ncube]][2];
aa = ptFLAG[ncube];
bb = 4;
pa = pvp;
n_pol = pol_edges[ptFLAG[ncube]][1];
for (ii=0; ii < n_pol; ii++) {
Vert_f_Pol[pa+6] = ve = kk&MASK;
ve+=pa;
for (jj=pa; jj<ve && jj<pa+6; jj++) {
Vert_f_Pol[jj] = pol_edges[aa][bb];
bb++;
if (bb >= 16) {
aa++;
bb -= 16;
}
}
kk >>= 4; pa += 7;
}
/* end fill_Vert_f_Pol(ncube); */
/* */
/* find_vertex(); */
/* WLH 2 April 99
vnode0 = ptGRID[pt];
vnode1 = ptGRID[pt + ydim];
vnode2 = ptGRID[pt + 1];
vnode3 = ptGRID[pt + ydim + 1];
vnode4 = ptGRID[pt + xdim_x_ydim];
vnode5 = ptGRID[pt + ydim + xdim_x_ydim];
vnode6 = ptGRID[pt + 1 + xdim_x_ydim];
vnode7 = ptGRID[pt + 1 + ydim + xdim_x_ydim];
*/
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0002) != 0) ) { /* cube vertex 0-1 */
if ( (iz != 0) || (iy != 0) ) {
calc_edge[1] = P_array[ bellow*xx + ix*ydim + iy ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode1 - vnode0;
cp = ( ( isovalue - vnode0 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode0 ) / ( vnode1 - vnode0 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim] + (1.0f-cp) * samples[0][pt];
VY[0][nvet] = (float) cp * samples[1][pt + ydim] + (1.0f-cp) * samples[1][pt];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim] + (1.0f-cp) * samples[2][pt];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt] < 0) ?
((float) auxValues[j][pt]) + 256.0f :
((float) auxValues[j][pt]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim] +
(1.0f-cp) * auxValues[j][pt];
*/
}
calc_edge[1] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0004) != 0) ) { /* cube vertex 0-2 */
if ( (iz != 0) || (ix != 0) ) {
calc_edge[2] = P_array[ 2*xx + bellow*yy + iy*xdim + ix ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode2 - vnode0;
cp = ( ( isovalue - vnode0 ) / nodeDiff ) + iy;
VX[0][nvet] = ix;
VY[0][nvet] = cp;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode0 ) / ( vnode2 - vnode0 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1] + (1.0f-cp) * samples[0][pt];
VY[0][nvet] = (float) cp * samples[1][pt + 1] + (1.0f-cp) * samples[1][pt];
VZ[0][nvet] = (float) cp * samples[2][pt + 1] + (1.0f-cp) * samples[2][pt];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt] < 0) ?
((float) auxValues[j][pt]) + 256.0f :
((float) auxValues[j][pt]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1] +
(1.0f-cp) * auxValues[j][pt];
*/
}
calc_edge[2] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0008) != 0) ) { /* cube vertex 0-4 */
if ( (ix != 0) || (iy != 0) ) {
calc_edge[3] = P_array[ 2*xx + 2*yy + rear*zz + iy ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode4 - vnode0;
cp = ( ( isovalue - vnode0 ) / nodeDiff ) + iz;
VX[0][nvet] = ix;
VY[0][nvet] = iy;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode0 ) / ( vnode4 - vnode0 ) );
VX[0][nvet] = (float) cp * samples[0][pt + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt];
VY[0][nvet] = (float) cp * samples[1][pt + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt];
VZ[0][nvet] = (float) cp * samples[2][pt + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt] < 0) ?
((float) auxValues[j][pt]) + 256.0f :
((float) auxValues[j][pt]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt];
*/
}
calc_edge[3] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0010) != 0) ) { /* cube vertex 1-3 */
if ( (iz != 0) ) {
calc_edge[4] = P_array[ 2*xx + bellow*yy + iy*xdim + (ix+1) ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode3 - vnode1;
cp = ( ( isovalue - vnode1 ) / nodeDiff ) + iy;
VX[0][nvet] = ix+1;
VY[0][nvet] = cp;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode1 ) / ( vnode3 - vnode1 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + 1] +
(1.0f-cp) * samples[0][pt + ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + 1] +
(1.0f-cp) * samples[1][pt + ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + 1] +
(1.0f-cp) * samples[2][pt + ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + 1] +
(1.0f-cp) * auxValues[j][pt + ydim];
*/
}
calc_edge[4] = nvet;
P_array[ 2*xx + bellow*yy + iy*xdim + (ix+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0020) != 0) ) { /* cube vertex 1-5 */
if ( (iy != 0) ) {
calc_edge[5] = P_array[ 2*xx + 2*yy + front*zz + iy ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode5 - vnode1;
cp = ( ( isovalue - vnode1 ) / nodeDiff ) + iz;
VX[0][nvet] = ix+1;
VY[0][nvet] = iy;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode1 ) / ( vnode5 - vnode1 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim];
*/
}
calc_edge[5] = nvet;
P_array[ 2*xx + 2*yy + front*zz + iy ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0040) != 0) ) { /* cube vertex 2-3 */
if ( (iz != 0) ) {
calc_edge[6] = P_array[ bellow*xx + ix*ydim + (iy+1) ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode3 - vnode2;
cp = ( ( isovalue - vnode2 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy+1;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode2 ) / ( vnode3 - vnode2 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + 1] +
(1.0f-cp) * samples[0][pt + 1];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + 1] +
(1.0f-cp) * samples[1][pt + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + 1] +
(1.0f-cp) * samples[2][pt + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + 1] +
(1.0f-cp) * auxValues[j][pt + 1];
*/
}
calc_edge[6] = nvet;
P_array[ bellow*xx + ix*ydim + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0080) != 0) ) { /* cube vertex 2-6 */
if ( (ix != 0) ) {
calc_edge[7] = P_array[ 2*xx + 2*yy + rear*zz + (iy+1) ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode6 - vnode2;
cp = ( ( isovalue - vnode2 ) / nodeDiff ) + iz;
VX[0][nvet] = ix;
VY[0][nvet] = iy+1;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode2 ) / ( vnode6 - vnode2 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + 1];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + 1];
*/
}
calc_edge[7] = nvet;
P_array[ 2*xx + 2*yy + rear*zz + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0100) != 0) ) { /* cube vertex 3-7 */
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode3;
cp = ( ( isovalue - vnode3 ) / nodeDiff ) + iz;
VX[0][nvet] = ix+1;
VY[0][nvet] = iy+1;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode3 ) / ( vnode7 - vnode3 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim + 1];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim + 1];
*/
}
calc_edge[8] = nvet;
P_array[ 2*xx + 2*yy + front*zz + (iy+1) ] = nvet;
nvet++;
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0200) != 0) ) { /* cube vertex 4-5 */
if ( (iy != 0) ) {
calc_edge[9] = P_array[ above*xx + ix*ydim + iy ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode5 - vnode4;
cp = ( ( isovalue - vnode4 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode4 ) / ( vnode5 - vnode4 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + xdim_x_ydim];
*/
}
calc_edge[9] = nvet;
P_array[ above*xx + ix*ydim + iy ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0400) != 0) ) { /* cube vertex 4-6 */
if ( (ix != 0) ) {
calc_edge[10] = P_array[ 2*xx + above*yy + iy*xdim + ix ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode6 - vnode4;
cp = ( ( isovalue - vnode4 ) / nodeDiff ) + iy;
VX[0][nvet] = ix;
VY[0][nvet] = cp;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode4 ) / ( vnode6 - vnode4 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + xdim_x_ydim];
*/
}
calc_edge[10] = nvet;
P_array[ 2*xx + above*yy + iy*xdim + ix ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0800) != 0) ) { /* cube vertex 5-7 */
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode5;
cp = ( ( isovalue - vnode5 ) / nodeDiff ) + iy;
VX[0][nvet] = ix+1;
VY[0][nvet] = cp;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode5 ) / ( vnode7 - vnode5 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim + xdim_x_ydim];
*/
}
calc_edge[11] = nvet;
P_array[ 2*xx + above*yy + iy*xdim + (ix+1) ] = nvet;
nvet++;
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x1000) != 0) ) { /* cube vertex 6-7 */
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode6;
cp = ( ( isovalue - vnode6 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy+1;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode6 ) / ( vnode7 - vnode6 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + 1 + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + 1 + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + 1 + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + 1 + xdim_x_ydim];
*/
}
calc_edge[12] = nvet;
P_array[ above*xx + ix*ydim + (iy+1) ] = nvet;
nvet++;
}
/* end find_vertex(); */
/* update_data_structure(ncube); */
kk = pol_edges[ptFLAG[ncube]][2];
nn = pol_edges[ptFLAG[ncube]][1];
for (ii=0; ii<nn; ii++) {
mm = pvp+(kk&MASK);
for (jj=pvp; jj<mm; jj++) {
Vert_f_Pol [jj] = ve = calc_edge[Vert_f_Pol [jj]];
// Pol_f_Vert[0][ve*9 + (Pol_f_Vert[0][ve*9 + 8])++] = cpl;
temp = Pol_f_Vert[0][ve*9 + 8];
Pol_f_Vert[0][ve*9 + temp] = cpl;
Pol_f_Vert[0][ve*9 + 8] = temp + 1;
}
kk >>= 4; pvp += 7; cpl++;
}
/* end update_data_structure(ncube); */
}
else { // !(ptFLAG[ncube] < MAX_FLAG_NUM)
/* find_vertex_invalid_cube(ncube); */
ptFLAG[ncube] &= 0x1FF;
if ( (ptFLAG[ncube] != 0 & ptFLAG[ncube] != 0xFF) )
{ if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0010) != 0) ) /* cube vertex 1-3 */
/* WLH 24 Oct 97
{ if (!(iz != 0 ) && vnode3 < INV_VAL && vnode1 < INV_VAL)
{ if (!(iz != 0 ) && !Float.isNaN(vnode3) && !Float.isNaN(vnode1))
*/
// test for not missing
{ if (!(iz != 0 ) && vnode3 == vnode3 && vnode1 == vnode1)
{
/* WLH 26 Oct 97
nodeDiff = vnode3 - vnode1;
cp = ( ( isovalue - vnode1 ) / nodeDiff ) + iy;
VX[0][nvet] = ix+1;
VY[0][nvet] = cp;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode1 ) / ( vnode3 - vnode1 ) );
// WLH 4 Aug 2000 - replace Samples by samples
VX[0][nvet] = (float) cp * samples[0][pt + ydim + 1] +
(1.0f-cp) * samples[0][pt + ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + 1] +
(1.0f-cp) * samples[1][pt + ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + 1] +
(1.0f-cp) * samples[2][pt + ydim];
// end WLH 4 Aug 2000 - replace Samples by samples
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + 1] +
(1.0f-cp) * auxValues[j][pt + ydim];
*/
}
P_array[ 2*xx + bellow*yy + iy*xdim + (ix+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0020) != 0) ) /* cube vertex 1-5 */
/* WLH 24 Oct 97
{ if (!(iy != 0) && vnode5 < INV_VAL && vnode1 < INV_VAL)
{ if (!(iy != 0) && !Float.isNaN(vnode5) && !Float.isNaN(vnode1))
*/
// test for not missing
{ if (!(iy != 0) && vnode5 == vnode5 && vnode1 == vnode1)
{
/* WLH 26 Oct 97
nodeDiff = vnode5 - vnode1;
cp = ( ( isovalue - vnode1 ) / nodeDiff ) + iz;
VX[0][nvet] = ix+1;
VY[0][nvet] = iy;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode1 ) / ( vnode5 - vnode1 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim];
*/
}
P_array[ 2*xx + 2*yy + front*zz + iy ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0040) != 0) ) /* cube vertex 2-3 */
/* WLH 24 Oct 97
{ if (!(iz != 0) && vnode3 < INV_VAL && vnode2 < INV_VAL)
{ if (!(iz != 0) && !Float.isNaN(vnode3) && !Float.isNaN(vnode2))
*/
// test for not missing
{ if (!(iz != 0) && vnode3 == vnode3 && vnode2 == vnode2)
{
/* WLH 26 Oct 97
nodeDiff = vnode3 - vnode2;
cp = ( ( isovalue - vnode2 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy+1;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode2 ) / ( vnode3 - vnode2 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + 1] +
(1.0f-cp) * samples[0][pt + 1];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + 1] +
(1.0f-cp) * samples[1][pt + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + 1] +
(1.0f-cp) * samples[2][pt + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + 1] +
(1.0f-cp) * auxValues[j][pt + 1];
*/
}
P_array[ bellow*xx + ix*ydim + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0080) != 0) ) /* cube vertex 2-6 */
/* WLH 24 Oct 97
{ if (!(ix != 0) && vnode6 < INV_VAL && vnode2 < INV_VAL)
{ if (!(ix != 0) && !Float.isNaN(vnode6) && !Float.isNaN(vnode2))
*/
// test for not missing
{ if (!(ix != 0) && vnode6 == vnode6 && vnode2 == vnode2)
{
/* WLH 26 Oct 97
nodeDiff = vnode6 - vnode2;
cp = ( ( isovalue - vnode2 ) / nodeDiff ) + iz;
VX[0][nvet] = ix;
VY[0][nvet] = iy+1;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode2 ) / ( vnode6 - vnode2 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + 1];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + 1];
*/
}
P_array[ 2*xx + 2*yy + rear*zz + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0100) != 0) ) /* cube vertex 3-7 */
/* WLH 24 Oct 97
{ if (vnode7 < INV_VAL && vnode3 < INV_VAL)
{ if (!Float.isNaN(vnode7) && !Float.isNaN(vnode3))
*/
// test for not missing
{ if (vnode7 == vnode7 && vnode3 == vnode3)
{
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode3;
cp = ( ( isovalue - vnode3 ) / nodeDiff ) + iz;
VX[0][nvet] = ix+1;
VY[0][nvet] = iy+1;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode3 ) / ( vnode7 - vnode3 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim + 1];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim + 1];
*/
}
P_array[ 2*xx + 2*yy + front*zz + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0200) != 0) ) /* cube vertex 4-5 */
/* WLH 24 Oct 97
{ if (!(iy != 0) && vnode5 < INV_VAL && vnode4 < INV_VAL)
{ if (!(iy != 0) && !Float.isNaN(vnode5) && !Float.isNaN(vnode4))
*/
// test for not missing
{ if (!(iy != 0) && vnode5 == vnode5 && vnode4 == vnode4)
{
/* WLH 26 Oct 97
nodeDiff = vnode5 - vnode4;
cp = ( ( isovalue - vnode4 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode4 ) / ( vnode5 - vnode4 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + xdim_x_ydim];
*/
}
P_array[ above*xx + ix*ydim + iy ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0400) != 0) ) /* cube vertex 4-6 */
/* WLH 24 Oct 97
{ if (!(ix != 0) && vnode6 < INV_VAL && vnode4 < INV_VAL)
{ if (!(ix != 0) && !Float.isNaN(vnode6) && !Float.isNaN(vnode4))
*/
// test for not missing
{ if (!(ix != 0) && vnode6 == vnode6 && vnode4 == vnode4)
{
/* WLH 26 Oct 97
nodeDiff = vnode6 - vnode4;
cp = ( ( isovalue - vnode4 ) / nodeDiff ) + iy;
VX[0][nvet] = ix;
VY[0][nvet] = cp;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode4 ) / ( vnode6 - vnode4 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + xdim_x_ydim];
*/
}
P_array[ 2*xx + above*yy + iy*xdim + ix ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0800) != 0) ) /* cube vertex 5-7 */
/* WLH 24 Oct 97
{ if (vnode7 < INV_VAL && vnode5 < INV_VAL)
{ if (!Float.isNaN(vnode7) && !Float.isNaN(vnode5))
*/
// test for not missing
{ if (vnode7 == vnode7 && vnode5 == vnode5)
{
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode5;
cp = ( ( isovalue - vnode5 ) / nodeDiff ) + iy;
VX[0][nvet] = ix+1;
VY[0][nvet] = cp;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode5 ) / ( vnode7 - vnode5 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim + xdim_x_ydim];
*/
}
P_array[ 2*xx + above*yy + iy*xdim + (ix+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x1000) != 0) ) /* cube vertex 6-7 */
/* WLH 24 Oct 97
{ if (vnode7 < INV_VAL && vnode6 < INV_VAL)
{ if (!Float.isNaN(vnode7) && !Float.isNaN(vnode6))
*/
// test for not missing
{ if (vnode7 == vnode7 && vnode6 == vnode6)
{
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode6;
cp = ( ( isovalue - vnode6 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy+1;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode6 ) / ( vnode7 - vnode6 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + 1 + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + 1 + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + 1 + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + 1 + xdim_x_ydim];
*/
}
P_array[ above*xx + ix*ydim + (iy+1) ] = nvet;
nvet++;
}
}
}
/* end find_vertex_invalid_cube(ncube); */
}
} /* end if (exist_polygon_in_cube(ncube)) */
ncube++; pt++;
} /* end for ( iy = 0; iy < ydim - 1; iy++ ) */
/* swap_planes(Z,rear,front); */
caseA = rear;
rear = front;
front = caseA;
pt++;
/* end swap_planes(Z,rear,front); */
} /* end for ( ix = 0; ix < xdim - 1; ix++ ) */
/* swap_planes(XY,bellow,above); */
caseA = bellow;
bellow = above;
above = caseA;
pt += ydim;
/* end swap_planes(XY,bellow,above); */
} /* end for ( iz = 0; iz < zdim - 1; iz++ ) */
// copy tempaux array into auxLevels array
for (int i=0; i<naux; i++) {
auxLevels[i] = new byte[nvet];
System.arraycopy(tempaux[i], 0, auxLevels[i], 0, nvet);
}
return nvet;
}
public static void make_normals( float[] VX, float[] VY, float[] VZ,
float[] NX, float[] NY, float[] NZ, int nvertex,
int npolygons, float[] Pnx, float[] Pny, float[] Pnz,
float[] NxA, float[] NxB, float[] NyA, float[] NyB,
float[] NzA, float[] NzB,
int[] Pol_f_Vert, int[] Vert_f_Pol)
throws VisADException {
int i, k, n;
int i1, i2, ix, iy, iz, ixb, iyb, izb;
int max_vert_per_pol, swap_flag;
float x, y, z, a, minimum_area, len;
int iv[] = new int[3];
for ( i = 0; i < nvertex; i++ ) {
NX[i] = 0;
NY[i] = 0;
NZ[i] = 0;
}
// WLH 12 Nov 2001
// minimum_area = (float) ((1.e-4 > EPS_0) ? 1.e-4 : EPS_0);
minimum_area = Float.MIN_VALUE;
/* Calculate maximum number of vertices per polygon */
k = 6; n = 7*npolygons;
while ( TRUE )
{ for (i=k+7; i<n; i+=7)
if (Vert_f_Pol[i] > Vert_f_Pol[k]) break;
if (i >= n) break; k = i;
}
max_vert_per_pol = Vert_f_Pol[k];
/* Calculate the Normals vector components for each Polygon */
/*$dir vector */
for ( i=0; i<npolygons; i++) { /* Vectorized */
if (Vert_f_Pol[6+i*7]>0) { /* check for valid polygon added by BEP 2-13-92 */
NxA[i] = VX[Vert_f_Pol[1+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyA[i] = VY[Vert_f_Pol[1+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzA[i] = VZ[Vert_f_Pol[1+i*7]] - VZ[Vert_f_Pol[0+i*7]];
}
}
swap_flag = 0;
for ( k = 2; k < max_vert_per_pol; k++ )
{
if (swap_flag==0) {
/*$dir no_recurrence */ /* Vectorized */
for ( i=0; i<npolygons; i++ ) {
if ( Vert_f_Pol[k+i*7] >= 0 ) {
NxB[i] = VX[Vert_f_Pol[k+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyB[i] = VY[Vert_f_Pol[k+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzB[i] = VZ[Vert_f_Pol[k+i*7]] - VZ[Vert_f_Pol[0+i*7]];
Pnx[i] = NyA[i]*NzB[i] - NzA[i]*NyB[i];
Pny[i] = NzA[i]*NxB[i] - NxA[i]*NzB[i];
Pnz[i] = NxA[i]*NyB[i] - NyA[i]*NxB[i];
NxA[i] = Pnx[i]*Pnx[i] + Pny[i]*Pny[i] + Pnz[i]*Pnz[i];
if (NxA[i] > minimum_area) {
Pnx[i] /= NxA[i];
Pny[i] /= NxA[i];
Pnz[i] /= NxA[i];
}
}
}
}
else { /* swap_flag!=0 */
/*$dir no_recurrence */ /* Vectorized */
for ( i=0; i<npolygons; i++ ) {
if ( Vert_f_Pol[k+i*7] >= 0 ) {
NxA[i] = VX[Vert_f_Pol[k+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyA[i] = VY[Vert_f_Pol[k+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzA[i] = VZ[Vert_f_Pol[k+i*7]] - VZ[Vert_f_Pol[0+i*7]];
Pnx[i] = NyB[i]*NzA[i] - NzB[i]*NyA[i];
Pny[i] = NzB[i]*NxA[i] - NxB[i]*NzA[i];
Pnz[i] = NxB[i]*NyA[i] - NyB[i]*NxA[i];
NxB[i] = Pnx[i]*Pnx[i] + Pny[i]*Pny[i] + Pnz[i]*Pnz[i];
if (NxB[i] > minimum_area) {
Pnx[i] /= NxB[i];
Pny[i] /= NxB[i];
Pnz[i] /= NxB[i];
}
}
}
}
/* This Loop <CAN'T> be Vectorized */
for ( i=0; i<npolygons; i++ )
{ if (Vert_f_Pol[k+i*7] >= 0)
{ iv[0] = Vert_f_Pol[0+i*7];
iv[1] = Vert_f_Pol[(k-1)+i*7];
iv[2] = Vert_f_Pol[k+i*7];
x = Pnx[i]; y = Pny[i]; z = Pnz[i];
// Update the origin vertex
NX[iv[0]] += x; NY[iv[0]] += y; NZ[iv[0]] += z;
// Update the vertex that defines the first vector
NX[iv[1]] += x; NY[iv[1]] += y; NZ[iv[1]] += z;
// Update the vertex that defines the second vector
NX[iv[2]] += x; NY[iv[2]] += y; NZ[iv[2]] += z;
}
}
swap_flag = ( (swap_flag != 0) ? 0 : 1 );
}
/* Normalize the Normals */
for ( i=0; i<nvertex; i++ ) /* Vectorized */
{ len = (float) Math.sqrt(NX[i]*NX[i] + NY[i]*NY[i] + NZ[i]*NZ[i]);
if (len > EPS_0) {
NX[i] /= len;
NY[i] /= len;
NZ[i] /= len;
}
}
}
public static int poly_triangle_stripe( int[] vet_pol, int[] Tri_Stripe,
int nvertex, int npolygons, int[] Pol_f_Vert,
int[] Vert_f_Pol ) throws VisADException {
int i, j, k, m, ii, npol, cpol, idx, off, Nvt,
vA, vB, ivA, ivB, iST, last_pol;
boolean f_line_conection = false;
last_pol = 0;
npol = 0;
iST = 0;
ivB = 0;
for (i=0; i<npolygons; i++) vet_pol[i] = 1; /* Vectorized */
while (TRUE)
{
/* find_unselected_pol(cpol); */
for (cpol=last_pol; cpol<npolygons; cpol++) {
if ( (vet_pol[cpol] != 0) ) break;
}
if (cpol == npolygons) {
cpol = -1;
}
else {
last_pol = cpol;
}
/* end find_unselected_pol(cpol); */
if (cpol < 0) break;
/* update_polygon */
vet_pol[cpol] = 0;
/* end update_polygon */
/* get_vertices_of_pol(cpol,Vt,Nvt); { */
Nvt = Vert_f_Pol[(j=cpol*7)+6];
off = j;
/* } */
/* end get_vertices_of_pol(cpol,Vt,Nvt); { */
for (ivA=0; ivA<Nvt; ivA++) {
ivB = (((ivA+1)==Nvt) ? 0:(ivA+1));
/* get_pol_vert(Vt[ivA],Vt[ivB],npol) { */
npol = -1;
if (Vert_f_Pol[ivA+off]>=0 && Vert_f_Pol[ivB+off]>=0) {
i=Vert_f_Pol[ivA+off]*9;
k=i+Pol_f_Vert [i+8];
j=Vert_f_Pol[ivB+off]*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j <m ) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
(vet_pol[Pol_f_Vert[i]] != 0) ) {
npol=Pol_f_Vert [i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
/* } */
/* end get_pol_vert(Vt[ivA],Vt[ivB],npol) { */
if (npol >= 0) break;
}
/* insert polygon alone */
if (npol < 0)
{ /*ptT = NTAB + STAB[Nvt-3];*/
idx = STAB[Nvt-3];
if (iST > 0)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx]+off];
}
else f_line_conection = true; /* WLH 3-9-95 added */
for (ii=0; ii< ((Nvt < 6) ? Nvt:6); ii++) {
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx++]+off];
}
continue;
}
if (( (ivB != 0) && ivA==(ivB-1)) || ( !(ivB != 0) && ivA==Nvt-1)) {
/* ptT = ITAB + STAB[Nvt-3] + (ivB+1)*Nvt; */
idx = STAB[Nvt-3] + (ivB+1)*Nvt;
if (f_line_conection)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[idx-1]+off];
f_line_conection = false;
}
for (ii=0; ii<((Nvt < 6) ? Nvt:6); ii++) {
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[--idx]+off];
}
}
else {
/* ptT = NTAB + STAB[Nvt-3] + (ivB+1)*Nvt; */
idx = STAB[Nvt-3] + (ivB+1)*Nvt;
if (f_line_conection)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx-1]+off];
f_line_conection = false;
}
for (ii=0; ii<((Nvt < 6) ? Nvt:6); ii++) {
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[--idx]+off];
}
}
vB = Tri_Stripe[iST-1];
vA = Tri_Stripe[iST-2];
cpol = npol;
while (TRUE)
{
/* get_vertices_of_pol(cpol,Vt,Nvt) { */
Nvt = Vert_f_Pol [(j=cpol*7)+6];
off = j;
/* } */
/* update_polygon(cpol) */
vet_pol[cpol] = 0;
for (ivA=0; ivA<Nvt && Vert_f_Pol[ivA+off]!=vA; ivA++);
for (ivB=0; ivB<Nvt && Vert_f_Pol[ivB+off]!=vB; ivB++);
if (( (ivB != 0) && ivA==(ivB-1)) || (!(ivB != 0) && ivA==Nvt-1)) {
/* ptT = NTAB + STAB[Nvt-3] + ivA*Nvt + 2; */
idx = STAB[Nvt-3] + ivA*Nvt + 2;
for (ii=2; ii<((Nvt < 6) ? Nvt:6); ii++)
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx++]+off];
}
else {
/* ptT = ITAB + STAB[Nvt-3] + ivA*Nvt + 2; */
idx = STAB[Nvt-3] + ivA*Nvt + 2;
for (ii=2; ii<((Nvt < 6) ? Nvt:6); ii++)
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[idx++]+off];
}
vB = Tri_Stripe[iST-1];
vA = Tri_Stripe[iST-2];
/* get_pol_vert(vA,vB,cpol) { */
cpol = -1;
if (vA>=0 && vB>=0) {
i=vA*9;
k=i+Pol_f_Vert [i+8];
j=vB*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j<m) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] && (vet_pol[Pol_f_Vert[i]] != 0) ) {
cpol=Pol_f_Vert[i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
/* } */
if (cpol < 0) {
vA = Tri_Stripe[iST-3];
/* get_pol_vert(vA,vB,cpol) { */
cpol = -1;
if (vA>=0 && vB>=0) {
i=vA*9;
k=i+Pol_f_Vert [i+8];
j=vB*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j<m) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
(vet_pol[Pol_f_Vert[i]] != 0) ) {
cpol=Pol_f_Vert[i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
/* } */
if (cpol < 0) {
f_line_conection = true;
break;
}
else {
+ // WLH 5 May 2004 - fix bug vintage 1990 or 91
+ if (iST > 0) {
+ Tri_Stripe[iST] = Tri_Stripe[iST-1];
+ iST++;
+ }
Tri_Stripe[iST++] = vA;
i = vA;
vA = vB;
vB = i;
}
}
}
}
return iST;
}
public static float[] makeNormals(float[] coordinates, int LengthX,
int LengthY) {
int Length = LengthX * LengthY;
float[] normals = new float[3 * Length];
int k = 0;
int ki, kj;
int LengthX3 = 3 * LengthX;
for (int i=0; i<LengthY; i++) {
for (int j=0; j<LengthX; j++) {
float c0 = coordinates[k];
float c1 = coordinates[k+1];
float c2 = coordinates[k+2];
float n0 = 0.0f;
float n1 = 0.0f;
float n2 = 0.0f;
float n, m, m0, m1, m2, q0, q1, q2;
for (int ip = -1; ip<=1; ip += 2) {
for (int jp = -1; jp<=1; jp += 2) {
int ii = i + ip;
int jj = j + jp;
if (0 <= ii && ii < LengthY && 0 <= jj && jj < LengthX) {
ki = k + ip * LengthX3;
kj = k + jp * 3;
m0 = (coordinates[kj+2] - c2) * (coordinates[ki+1] - c1) -
(coordinates[kj+1] - c1) * (coordinates[ki+2] - c2);
m1 = (coordinates[kj] - c0) * (coordinates[ki+2] - c2) -
(coordinates[kj+2] - c2) * (coordinates[ki] - c0);
m2 = (coordinates[kj+1] - c1) * (coordinates[ki] - c0) -
(coordinates[kj] - c0) * (coordinates[ki+1] - c1);
m = (float) Math.sqrt(m0 * m0 + m1 * m1 + m2 * m2);
if (ip == jp) {
q0 = m0 / m;
q1 = m1 / m;
q2 = m2 / m;
}
else {
q0 = -m0 / m;
q1 = -m1 / m;
q2 = -m2 / m;
}
if (q0 == q0) {
n0 += q0;
n1 += q1;
n2 += q2;
}
else {
/*
System.out.println("m = " + m + " " + m0 + " " + m1 + " " + m2 + " " +
n0 + " " + n1 + " " + n2 + " ip, jp = " + ip + " " + jp);
System.out.println("k = " + k + " " + ki + " " + kj);
System.out.println("c = " + c0 + " " + c1 + " " + c2);
System.out.println("coordinates[ki] = " + coordinates[ki] + " " +
coordinates[ki+1] + " " + coordinates[ki+2]); // == c ??
System.out.println("coordinates[kj] = " + coordinates[kj] + " " +
coordinates[kj+1] + " " + coordinates[kj+2]);
System.out.println("LengthX = " + LengthX + " " + LengthY + " " +
LengthX3);
*/
}
}
}
}
n = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
normals[k] = n0 / n;
normals[k+1] = n1 / n;
normals[k+2] = n2 / n;
if (normals[k] != normals[k]) {
normals[k] = 0.0f;
normals[k+1] = 0.0f;
normals[k+2] = -1.0f;
}
/*
System.out.println("makeNormals " + k + " " + normals[k] + " " + normals[k+1] + " " +
normals[k+2]);
*/
k += 3;
} // end for (int j=0; j<LengthX; j++)
} // end for (int i=0; i<LengthY; i++)
return normals;
}
/** create a 2-D GeometryArray from this Set and color_values */
public VisADGeometryArray make2DGeometry(byte[][] color_values,
boolean indexed) throws VisADException {
if (DomainDimension != 3) {
throw new SetException("Gridded3DSet.make2DGeometry: " +
"DomainDimension must be 3");
}
if (ManifoldDimension != 2) {
throw new SetException("Gridded3DSet.make2DGeometry: " +
"ManifoldDimension must be 2");
}
if (LengthX < 2 || LengthY < 2) {
/* WLH 26 June 98
throw new SetException("Gridded3DSet.make2DGeometry: " +
"LengthX and LengthY must be at least 2");
*/
VisADPointArray array = new VisADPointArray();
setGeometryArray(array, 4, color_values);
return array;
}
if (indexed) {
VisADIndexedTriangleStripArray array =
new VisADIndexedTriangleStripArray();
// set up indices into 2-D grid
array.indexCount = (LengthY - 1) * (2 * LengthX);
int[] indices = new int[array.indexCount];
array.stripVertexCounts = new int[LengthY - 1];
int k = 0;
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX;
array.stripVertexCounts[i] = 2 * LengthX;
for (int j=0; j<LengthX; j++) {
indices[k++] = m;
indices[k++] = m + LengthX;
m++;
}
}
array.indices = indices;
// take the garbage out
indices = null;
// set coordinates and colors
setGeometryArray(array, 4, color_values);
// calculate normals
float[] coordinates = array.coordinates;
float[] normals = makeNormals(coordinates, LengthX, LengthY);
array.normals = normals;
return array;
}
else { // if (!indexed)
VisADTriangleStripArray array = new VisADTriangleStripArray();
float[][] samples = getSamples(false);
array.stripVertexCounts = new int[LengthY - 1];
for (int i=0; i<LengthY-1; i++) {
array.stripVertexCounts[i] = 2 * LengthX;
}
int len = (LengthY - 1) * (2 * LengthX);
array.vertexCount = len;
// calculate normals
float[] normals = new float[3 * Length];
int k = 0;
int k3 = 0;
int ki, kj;
for (int i=0; i<LengthY; i++) {
for (int j=0; j<LengthX; j++) {
float c0 = samples[0][k3];
float c1 = samples[1][k3];
float c2 = samples[2][k3];
float n0 = 0.0f;
float n1 = 0.0f;
float n2 = 0.0f;
float n, m, m0, m1, m2;
boolean any = false;
for (int ip = -1; ip<=1; ip += 2) {
for (int jp = -1; jp<=1; jp += 2) {
int ii = i + ip;
int jj = j + jp;
ki = k3 + ip * LengthX;
kj = k3 + jp;
if (0 <= ii && ii < LengthY && 0 <= jj && jj < LengthX &&
samples[0][ki] == samples[0][ki] &&
samples[1][ki] == samples[1][ki] &&
samples[2][ki] == samples[2][ki] &&
samples[0][kj] == samples[0][kj] &&
samples[1][kj] == samples[1][kj] &&
samples[2][kj] == samples[2][kj]) {
any = true;
m0 = (samples[2][kj] - c2) * (samples[1][ki] - c1) -
(samples[1][kj] - c1) * (samples[2][ki] - c2);
m1 = (samples[0][kj] - c0) * (samples[2][ki] - c2) -
(samples[2][kj] - c2) * (samples[0][ki] - c0);
m2 = (samples[1][kj] - c1) * (samples[0][ki] - c0) -
(samples[0][kj] - c0) * (samples[1][ki] - c1);
m = (float) Math.sqrt(m0 * m0 + m1 * m1 + m2 * m2);
if (ip == jp) {
n0 += m0 / m;
n1 += m1 / m;
n2 += m2 / m;
}
else {
n0 -= m0 / m;
n1 -= m1 / m;
n2 -= m2 / m;
}
}
}
}
n = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
if (any) {
normals[k] = n0 / n;
normals[k+1] = n1 / n;
normals[k+2] = n2 / n;
}
else {
normals[k] = 0.0f;
normals[k+1] = 0.0f;
normals[k+2] = 1.0f;
}
k += 3;
k3++;
} // end for (int j=0; j<LengthX; j++)
} // end for (int i=0; i<LengthY; i++)
array.normals = new float[3 * len];
// shuffle normals into array.normals
k = 0;
int LengthX3 = 3 * LengthX;
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX3;
for (int j=0; j<LengthX; j++) {
array.normals[k] = normals[m];
array.normals[k+1] = normals[m+1];
array.normals[k+2] = normals[m+2];
array.normals[k+3] = normals[m+LengthX3];
array.normals[k+4] = normals[m+LengthX3+1];
array.normals[k+5] = normals[m+LengthX3+2];
k += 6;
m += 3;
}
}
normals = null;
/*
int nmiss = 0;
int nsmall = 0;
*/
array.coordinates = new float[3 * len];
// shuffle samples into array.coordinates
k = 0;
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX;
for (int j=0; j<LengthX; j++) {
array.coordinates[k] = samples[0][m];
array.coordinates[k+1] = samples[1][m];
array.coordinates[k+2] = samples[2][m];
array.coordinates[k+3] = samples[0][m+LengthX];
array.coordinates[k+4] = samples[1][m+LengthX];
array.coordinates[k+5] = samples[2][m+LengthX];
/*
if (samples[0][m] != samples[0][m] ||
samples[1][m] != samples[1][m] ||
samples[2][m] != samples[2][m]) nmiss++;
double size = Math.sqrt(samples[0][m] * samples[0][m] +
samples[1][m] * samples[1][m] +
samples[2][m] * samples[2][m]);
if (size < 0.2) nsmall++;
*/
k += 6;
m++;
}
}
// System.out.println("make2DGeometry nmiss = " + nmiss + " nsmall = " + nsmall);
if (color_values != null) {
int color_length = color_values.length;
array.colors = new byte[color_length * len];
// shuffle samples into array.coordinates
k = 0;
if (color_length == 4) {
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX;
for (int j=0; j<LengthX; j++) {
array.colors[k] = color_values[0][m];
array.colors[k+1] = color_values[1][m];
array.colors[k+2] = color_values[2][m];
array.colors[k+3] = color_values[3][m];
k += color_length;
array.colors[k] = color_values[0][m+LengthX];
array.colors[k+1] = color_values[1][m+LengthX];
array.colors[k+2] = color_values[2][m+LengthX];
array.colors[k+3] = color_values[3][m+LengthX];
k += color_length;
m++;
}
}
}
else { // if (color_length == 3)
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX;
for (int j=0; j<LengthX; j++) {
array.colors[k] = color_values[0][m];
array.colors[k+1] = color_values[1][m];
array.colors[k+2] = color_values[2][m];
k += color_length;
array.colors[k] = color_values[0][m+LengthX];
array.colors[k+1] = color_values[1][m+LengthX];
array.colors[k+2] = color_values[2][m+LengthX];
k += color_length;
m++;
}
}
}
}
return array;
} // end if (!indexed)
}
public Object cloneButType(MathType type) throws VisADException {
if (ManifoldDimension == 3) {
return new Gridded3DSet(type, Samples, LengthX, LengthY, LengthZ,
DomainCoordinateSystem, SetUnits, SetErrors);
}
else if (ManifoldDimension == 2) {
return new Gridded3DSet(type, Samples, LengthX, LengthY,
DomainCoordinateSystem, SetUnits, SetErrors);
}
else {
return new Gridded3DSet(type, Samples, LengthX,
DomainCoordinateSystem, SetUnits, SetErrors);
}
}
/* run 'java visad.Gridded3DSet < formatted_input_stream'
to test the Gridded3DSet class */
public static void main(String[] argv) throws VisADException {
// Define input stream
InputStreamReader inStr = new InputStreamReader(System.in);
// Define temporary integer array
int[] ints = new int[80];
try {
ints[0] = inStr.read();
}
catch(Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
int l = 0;
while (ints[l] != 10) {
try {
ints[++l] = inStr.read();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
}
// convert array of integers to array of characters
char[] chars = new char[l];
for (int i=0; i<l; i++) {
chars[i] = (char) ints[i];
}
int num_coords = Integer.parseInt(new String(chars));
// num_coords should be a nice round number
if (num_coords % 9 != 0) {
throw new SetException("Gridded3DSet: input coordinates"
+" must be divisible by 9 for main function testing routines.");
}
// Define size of Samples array
float[][] samp = new float[3][num_coords];
System.out.println("num_dimensions = 3, num_coords = "+num_coords+"\n");
// Skip blank line
try {
ints[0] = inStr.read();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
for (int c=0; c<num_coords; c++) {
for (int d=0; d<3; d++) {
l = 0;
try {
ints[0] = inStr.read();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
while ( (ints[l] != 32) && (ints[l] != 10) ) {
try {
ints[++l] = inStr.read();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
}
chars = new char[l];
for (int i=0; i<l; i++) {
chars[i] = (char) ints[i];
}
samp[d][c] = (Float.valueOf(new String(chars))).floatValue();
}
}
// do EOF stuff
try {
inStr.close();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
// Set up instance of Gridded3DSet
RealType vis_xcoord = RealType.getRealType("xcoord");
RealType vis_ycoord = RealType.getRealType("ycoord");
RealType vis_zcoord = RealType.getRealType("zcoord");
RealType[] vis_array = {vis_xcoord, vis_ycoord, vis_zcoord};
RealTupleType vis_tuple = new RealTupleType(vis_array);
Gridded3DSet gSet3D = new Gridded3DSet(vis_tuple, samp,
3, 3, num_coords/9);
System.out.println("Lengths = 3 3 " + num_coords/9 + " wedge = ");
int[] wedge = gSet3D.getWedge();
for (int i=0; i<wedge.length; i++) System.out.println(" " + wedge[i]);
// print out Samples information
System.out.println("Samples ("+gSet3D.LengthX+" x "+gSet3D.LengthY
+" x "+gSet3D.LengthZ+"):");
for (int i=0; i<gSet3D.LengthX*gSet3D.LengthY*gSet3D.LengthZ; i++) {
System.out.println("#"+i+":\t"+gSet3D.Samples[0][i]
+", "+gSet3D.Samples[1][i]
+", "+gSet3D.Samples[2][i]);
}
// Test gridToValue function
System.out.println("\ngridToValue test:");
int myLengthX = gSet3D.LengthX+1;
int myLengthY = gSet3D.LengthY+1;
int myLengthZ = gSet3D.LengthZ+1;
float[][] myGrid = new float[3][myLengthX*myLengthY*myLengthZ];
for (int k=0; k<myLengthZ; k++) {
for (int j=0; j<myLengthY; j++) {
for (int i=0; i<myLengthX; i++) {
int index = k*myLengthY*myLengthX+j*myLengthX+i;
myGrid[0][index] = i-0.5f;
myGrid[1][index] = j-0.5f;
myGrid[2][index] = k-0.5f;
if (myGrid[0][index] < 0) myGrid[0][index] += 0.1;
if (myGrid[1][index] < 0) myGrid[1][index] += 0.1;
if (myGrid[2][index] < 0) myGrid[2][index] += 0.1;
if (myGrid[0][index] > gSet3D.LengthX-1) myGrid[0][index] -= 0.1;
if (myGrid[1][index] > gSet3D.LengthY-1) myGrid[1][index] -= 0.1;
if (myGrid[2][index] > gSet3D.LengthZ-1) myGrid[2][index] -= 0.1;
}
}
}
float[][] myValue = gSet3D.gridToValue(myGrid);
for (int i=0; i<myLengthX*myLengthY*myLengthZ; i++) {
System.out.println("("+((float) Math.round(1000000
*myGrid[0][i]) /1000000)+", "
+((float) Math.round(1000000
*myGrid[1][i]) /1000000)+", "
+((float) Math.round(1000000
*myGrid[2][i]) /1000000)+") \t--> "
+((float) Math.round(1000000
*myValue[0][i]) /1000000)+", "
+((float) Math.round(1000000
*myValue[1][i]) /1000000)+", "
+((float) Math.round(1000000
*myValue[2][i]) /1000000));
}
// Test valueToGrid function
System.out.println("\nvalueToGrid test:");
float[][] gridTwo = gSet3D.valueToGrid(myValue);
for (int i=0; i<gridTwo[0].length; i++) {
System.out.print(((float) Math.round(1000000
*myValue[0][i]) /1000000)+", "
+((float) Math.round(1000000
*myValue[1][i]) /1000000)+", "
+((float) Math.round(1000000
*myValue[2][i]) /1000000)+"\t--> (");
if (Float.isNaN(gridTwo[0][i])) {
System.out.print("NaN, ");
}
else {
System.out.print(((float) Math.round(1000000
*gridTwo[0][i]) /1000000)+", ");
}
if (Float.isNaN(gridTwo[1][i])) {
System.out.print("NaN, ");
}
else {
System.out.print(((float) Math.round(1000000
*gridTwo[1][i]) /1000000)+", ");
}
if (Float.isNaN(gridTwo[2][i])) {
System.out.println("NaN)");
}
else {
System.out.println(((float) Math.round(1000000
*gridTwo[2][i]) /1000000)+")");
}
}
System.out.println();
}
/* Here's the output with sample file Gridded3D.txt:
iris 28% java visad.Gridded3DSet < Gridded3D.txt
num_dimensions = 3, num_coords = 27
Lengths = 3 3 3 wedge =
0
1
2
5
4
3
. . .
Samples (3 x 3 x 3):
#0: 18.629837, 8.529864, 10.997844
#1: 42.923097, 10.123978, 11.198275
. . .
#25: 32.343298, 39.600872, 36.238975
#26: 49.919754, 40.119875, 36.018752
gridToValue test:
(-0.4, -0.4, -0.4) --> 10.819755, -0.172592, 5.179111
(0.5, -0.4, -0.4) --> 32.683689, 1.262111, 5.359499
. . .
(1.5, 2.4, 2.4) --> 43.844996, 48.904708, 40.008508
(2.4, 2.4, 2.4) --> 59.663807, 49.37181, 39.810308
valueToGrid test:
10.819755, -0.172592, 5.179111 --> (-0.4, -0.4, -0.4)
32.683689, 1.262111, 5.359499 --> (0.5, -0.4, -0.4)
. . .
43.844996, 48.904708, 40.008508 --> (1.5, 2.4, 2.4)
59.663807, 49.37181, 39.810308 --> (2.4, 2.4, 2.4)
iris 29%
*/
}
| true | true | private int isosurf( float isovalue, int[] ptFLAG, int nvertex_estimate,
int npolygons, float[] ptGRID, int xdim, int ydim,
int zdim, float[][] VX, float[][] VY, float[][] VZ,
byte[][] auxValues, byte[][] auxLevels,
int[][] Pol_f_Vert, int[] Vert_f_Pol )
throws VisADException {
int ix, iy, iz, caseA, above, bellow, front, rear, mm, nn;
int ii, jj, kk, ncube, cpl, pvp, pa, ve;
int[] calc_edge = new int[13];
int xx, yy, zz;
float cp;
float vnode0 = 0;
float vnode1 = 0;
float vnode2 = 0;
float vnode3 = 0;
float vnode4 = 0;
float vnode5 = 0;
float vnode6 = 0;
float vnode7 = 0;
int pt = 0;
int n_pol;
int aa;
int bb;
int temp;
float nodeDiff;
int xdim_x_ydim = xdim*ydim;
int nvet;
int t;
float[][] samples = getSamples(false);
int naux = (auxValues != null) ? auxValues.length : 0;
if (naux > 0) {
if (auxLevels == null || auxLevels.length != naux) {
throw new SetException("Gridded3DSet.isosurf: "
+"auxLevels length " + auxLevels.length +
" doesn't match expected " + naux);
}
for (int i=0; i<naux; i++) {
if (auxValues[i].length != Length) {
throw new SetException("Gridded3DSet.isosurf: expected auxValues " +
" length#" + i + " to be " + Length +
", not " + auxValues[i].length);
}
}
}
else {
if (auxLevels != null) {
throw new SetException("Gridded3DSet.isosurf: "
+"auxValues null but auxLevels not null");
}
}
// temporary storage of auxLevels structure
byte[][] tempaux = (naux > 0) ? new byte[naux][nvertex_estimate] : null;
bellow = rear = 0; above = front = 1;
/* Initialize the Auxiliar Arrays of Pointers */
/* WLH 25 Oct 97
ix = 9 * (npolygons*2 + 50);
iy = 7 * npolygons;
ii = ix + iy;
*/
for (jj=0; jj<Pol_f_Vert[0].length; jj++) {
Pol_f_Vert[0][jj] = BIG_NEG;
}
for (jj=8; jj<Pol_f_Vert[0].length; jj+=9) {
Pol_f_Vert[0][jj] = 0;
}
for (jj=0; jj<Vert_f_Pol.length; jj++) {
Vert_f_Pol[jj] = BIG_NEG;
}
for (jj=6; jj<Vert_f_Pol.length; jj+=7) {
Vert_f_Pol[jj] = 0;
}
/* Allocate the auxiliar edge vectors
size ixPlane = (xdim - 1) * ydim = xdim_x_ydim - ydim
size iyPlane = (ydim - 1) * xdim = xdim_x_ydim - xdim
size izPlane = xdim
*/
xx = xdim_x_ydim - ydim;
yy = xdim_x_ydim - xdim;
zz = ydim;
ii = 2 * (xx + yy + zz);
int[] P_array = new int[ii];
/* Calculate the Vertex of the Polygons which edges were
calculated above */
nvet = ncube = cpl = pvp = 0;
for ( iz = 0; iz < zdim - 1; iz++ ) {
for ( ix = 0; ix < xdim - 1; ix++ ) {
for ( iy = 0; iy < ydim - 1; iy++ ) {
if ( (ptFLAG[ncube] != 0 & ptFLAG[ncube] != 0xFF) ) {
if (nvet + 12 > nvertex_estimate) {
// allocate more space
nvertex_estimate = 2 * (nvet + 12);
if (naux > 0) {
for (int i=0; i<naux; i++) {
byte[] tt = tempaux[i];
tempaux[i] = new byte[nvertex_estimate];
System.arraycopy(tt, 0, tempaux[i], 0, nvet);
}
}
float[] tt = VX[0];
VX[0] = new float[nvertex_estimate];
System.arraycopy(tt, 0, VX[0], 0, tt.length);
tt = VY[0];
VY[0] = new float[nvertex_estimate];
System.arraycopy(tt, 0, VY[0], 0, tt.length);
tt = VZ[0];
VZ[0] = new float[nvertex_estimate];
System.arraycopy(tt, 0, VZ[0], 0, tt.length);
int big_ix = 9 * (nvertex_estimate + 50);
int[] it = Pol_f_Vert[0];
Pol_f_Vert[0] = new int[big_ix];
for (jj=0; jj<Pol_f_Vert[0].length; jj++) {
Pol_f_Vert[0][jj] = BIG_NEG;
}
for (jj=8; jj<Pol_f_Vert[0].length; jj+=9) {
Pol_f_Vert[0][jj] = 0;
}
System.arraycopy(it, 0, Pol_f_Vert[0], 0, it.length);
}
/* WLH 2 April 99 */
vnode0 = ptGRID[pt];
vnode1 = ptGRID[pt + ydim];
vnode2 = ptGRID[pt + 1];
vnode3 = ptGRID[pt + ydim + 1];
vnode4 = ptGRID[pt + xdim_x_ydim];
vnode5 = ptGRID[pt + ydim + xdim_x_ydim];
vnode6 = ptGRID[pt + 1 + xdim_x_ydim];
vnode7 = ptGRID[pt + 1 + ydim + xdim_x_ydim];
if ( (ptFLAG[ncube] < MAX_FLAG_NUM) ) {
/* fill_Vert_f_Pol(ncube); */
kk = pol_edges[ptFLAG[ncube]][2];
aa = ptFLAG[ncube];
bb = 4;
pa = pvp;
n_pol = pol_edges[ptFLAG[ncube]][1];
for (ii=0; ii < n_pol; ii++) {
Vert_f_Pol[pa+6] = ve = kk&MASK;
ve+=pa;
for (jj=pa; jj<ve && jj<pa+6; jj++) {
Vert_f_Pol[jj] = pol_edges[aa][bb];
bb++;
if (bb >= 16) {
aa++;
bb -= 16;
}
}
kk >>= 4; pa += 7;
}
/* end fill_Vert_f_Pol(ncube); */
/* */
/* find_vertex(); */
/* WLH 2 April 99
vnode0 = ptGRID[pt];
vnode1 = ptGRID[pt + ydim];
vnode2 = ptGRID[pt + 1];
vnode3 = ptGRID[pt + ydim + 1];
vnode4 = ptGRID[pt + xdim_x_ydim];
vnode5 = ptGRID[pt + ydim + xdim_x_ydim];
vnode6 = ptGRID[pt + 1 + xdim_x_ydim];
vnode7 = ptGRID[pt + 1 + ydim + xdim_x_ydim];
*/
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0002) != 0) ) { /* cube vertex 0-1 */
if ( (iz != 0) || (iy != 0) ) {
calc_edge[1] = P_array[ bellow*xx + ix*ydim + iy ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode1 - vnode0;
cp = ( ( isovalue - vnode0 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode0 ) / ( vnode1 - vnode0 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim] + (1.0f-cp) * samples[0][pt];
VY[0][nvet] = (float) cp * samples[1][pt + ydim] + (1.0f-cp) * samples[1][pt];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim] + (1.0f-cp) * samples[2][pt];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt] < 0) ?
((float) auxValues[j][pt]) + 256.0f :
((float) auxValues[j][pt]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim] +
(1.0f-cp) * auxValues[j][pt];
*/
}
calc_edge[1] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0004) != 0) ) { /* cube vertex 0-2 */
if ( (iz != 0) || (ix != 0) ) {
calc_edge[2] = P_array[ 2*xx + bellow*yy + iy*xdim + ix ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode2 - vnode0;
cp = ( ( isovalue - vnode0 ) / nodeDiff ) + iy;
VX[0][nvet] = ix;
VY[0][nvet] = cp;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode0 ) / ( vnode2 - vnode0 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1] + (1.0f-cp) * samples[0][pt];
VY[0][nvet] = (float) cp * samples[1][pt + 1] + (1.0f-cp) * samples[1][pt];
VZ[0][nvet] = (float) cp * samples[2][pt + 1] + (1.0f-cp) * samples[2][pt];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt] < 0) ?
((float) auxValues[j][pt]) + 256.0f :
((float) auxValues[j][pt]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1] +
(1.0f-cp) * auxValues[j][pt];
*/
}
calc_edge[2] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0008) != 0) ) { /* cube vertex 0-4 */
if ( (ix != 0) || (iy != 0) ) {
calc_edge[3] = P_array[ 2*xx + 2*yy + rear*zz + iy ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode4 - vnode0;
cp = ( ( isovalue - vnode0 ) / nodeDiff ) + iz;
VX[0][nvet] = ix;
VY[0][nvet] = iy;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode0 ) / ( vnode4 - vnode0 ) );
VX[0][nvet] = (float) cp * samples[0][pt + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt];
VY[0][nvet] = (float) cp * samples[1][pt + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt];
VZ[0][nvet] = (float) cp * samples[2][pt + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt] < 0) ?
((float) auxValues[j][pt]) + 256.0f :
((float) auxValues[j][pt]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt];
*/
}
calc_edge[3] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0010) != 0) ) { /* cube vertex 1-3 */
if ( (iz != 0) ) {
calc_edge[4] = P_array[ 2*xx + bellow*yy + iy*xdim + (ix+1) ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode3 - vnode1;
cp = ( ( isovalue - vnode1 ) / nodeDiff ) + iy;
VX[0][nvet] = ix+1;
VY[0][nvet] = cp;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode1 ) / ( vnode3 - vnode1 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + 1] +
(1.0f-cp) * samples[0][pt + ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + 1] +
(1.0f-cp) * samples[1][pt + ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + 1] +
(1.0f-cp) * samples[2][pt + ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + 1] +
(1.0f-cp) * auxValues[j][pt + ydim];
*/
}
calc_edge[4] = nvet;
P_array[ 2*xx + bellow*yy + iy*xdim + (ix+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0020) != 0) ) { /* cube vertex 1-5 */
if ( (iy != 0) ) {
calc_edge[5] = P_array[ 2*xx + 2*yy + front*zz + iy ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode5 - vnode1;
cp = ( ( isovalue - vnode1 ) / nodeDiff ) + iz;
VX[0][nvet] = ix+1;
VY[0][nvet] = iy;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode1 ) / ( vnode5 - vnode1 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim];
*/
}
calc_edge[5] = nvet;
P_array[ 2*xx + 2*yy + front*zz + iy ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0040) != 0) ) { /* cube vertex 2-3 */
if ( (iz != 0) ) {
calc_edge[6] = P_array[ bellow*xx + ix*ydim + (iy+1) ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode3 - vnode2;
cp = ( ( isovalue - vnode2 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy+1;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode2 ) / ( vnode3 - vnode2 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + 1] +
(1.0f-cp) * samples[0][pt + 1];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + 1] +
(1.0f-cp) * samples[1][pt + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + 1] +
(1.0f-cp) * samples[2][pt + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + 1] +
(1.0f-cp) * auxValues[j][pt + 1];
*/
}
calc_edge[6] = nvet;
P_array[ bellow*xx + ix*ydim + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0080) != 0) ) { /* cube vertex 2-6 */
if ( (ix != 0) ) {
calc_edge[7] = P_array[ 2*xx + 2*yy + rear*zz + (iy+1) ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode6 - vnode2;
cp = ( ( isovalue - vnode2 ) / nodeDiff ) + iz;
VX[0][nvet] = ix;
VY[0][nvet] = iy+1;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode2 ) / ( vnode6 - vnode2 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + 1];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + 1];
*/
}
calc_edge[7] = nvet;
P_array[ 2*xx + 2*yy + rear*zz + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0100) != 0) ) { /* cube vertex 3-7 */
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode3;
cp = ( ( isovalue - vnode3 ) / nodeDiff ) + iz;
VX[0][nvet] = ix+1;
VY[0][nvet] = iy+1;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode3 ) / ( vnode7 - vnode3 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim + 1];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim + 1];
*/
}
calc_edge[8] = nvet;
P_array[ 2*xx + 2*yy + front*zz + (iy+1) ] = nvet;
nvet++;
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0200) != 0) ) { /* cube vertex 4-5 */
if ( (iy != 0) ) {
calc_edge[9] = P_array[ above*xx + ix*ydim + iy ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode5 - vnode4;
cp = ( ( isovalue - vnode4 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode4 ) / ( vnode5 - vnode4 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + xdim_x_ydim];
*/
}
calc_edge[9] = nvet;
P_array[ above*xx + ix*ydim + iy ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0400) != 0) ) { /* cube vertex 4-6 */
if ( (ix != 0) ) {
calc_edge[10] = P_array[ 2*xx + above*yy + iy*xdim + ix ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode6 - vnode4;
cp = ( ( isovalue - vnode4 ) / nodeDiff ) + iy;
VX[0][nvet] = ix;
VY[0][nvet] = cp;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode4 ) / ( vnode6 - vnode4 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + xdim_x_ydim];
*/
}
calc_edge[10] = nvet;
P_array[ 2*xx + above*yy + iy*xdim + ix ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0800) != 0) ) { /* cube vertex 5-7 */
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode5;
cp = ( ( isovalue - vnode5 ) / nodeDiff ) + iy;
VX[0][nvet] = ix+1;
VY[0][nvet] = cp;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode5 ) / ( vnode7 - vnode5 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim + xdim_x_ydim];
*/
}
calc_edge[11] = nvet;
P_array[ 2*xx + above*yy + iy*xdim + (ix+1) ] = nvet;
nvet++;
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x1000) != 0) ) { /* cube vertex 6-7 */
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode6;
cp = ( ( isovalue - vnode6 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy+1;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode6 ) / ( vnode7 - vnode6 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + 1 + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + 1 + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + 1 + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + 1 + xdim_x_ydim];
*/
}
calc_edge[12] = nvet;
P_array[ above*xx + ix*ydim + (iy+1) ] = nvet;
nvet++;
}
/* end find_vertex(); */
/* update_data_structure(ncube); */
kk = pol_edges[ptFLAG[ncube]][2];
nn = pol_edges[ptFLAG[ncube]][1];
for (ii=0; ii<nn; ii++) {
mm = pvp+(kk&MASK);
for (jj=pvp; jj<mm; jj++) {
Vert_f_Pol [jj] = ve = calc_edge[Vert_f_Pol [jj]];
// Pol_f_Vert[0][ve*9 + (Pol_f_Vert[0][ve*9 + 8])++] = cpl;
temp = Pol_f_Vert[0][ve*9 + 8];
Pol_f_Vert[0][ve*9 + temp] = cpl;
Pol_f_Vert[0][ve*9 + 8] = temp + 1;
}
kk >>= 4; pvp += 7; cpl++;
}
/* end update_data_structure(ncube); */
}
else { // !(ptFLAG[ncube] < MAX_FLAG_NUM)
/* find_vertex_invalid_cube(ncube); */
ptFLAG[ncube] &= 0x1FF;
if ( (ptFLAG[ncube] != 0 & ptFLAG[ncube] != 0xFF) )
{ if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0010) != 0) ) /* cube vertex 1-3 */
/* WLH 24 Oct 97
{ if (!(iz != 0 ) && vnode3 < INV_VAL && vnode1 < INV_VAL)
{ if (!(iz != 0 ) && !Float.isNaN(vnode3) && !Float.isNaN(vnode1))
*/
// test for not missing
{ if (!(iz != 0 ) && vnode3 == vnode3 && vnode1 == vnode1)
{
/* WLH 26 Oct 97
nodeDiff = vnode3 - vnode1;
cp = ( ( isovalue - vnode1 ) / nodeDiff ) + iy;
VX[0][nvet] = ix+1;
VY[0][nvet] = cp;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode1 ) / ( vnode3 - vnode1 ) );
// WLH 4 Aug 2000 - replace Samples by samples
VX[0][nvet] = (float) cp * samples[0][pt + ydim + 1] +
(1.0f-cp) * samples[0][pt + ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + 1] +
(1.0f-cp) * samples[1][pt + ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + 1] +
(1.0f-cp) * samples[2][pt + ydim];
// end WLH 4 Aug 2000 - replace Samples by samples
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + 1] +
(1.0f-cp) * auxValues[j][pt + ydim];
*/
}
P_array[ 2*xx + bellow*yy + iy*xdim + (ix+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0020) != 0) ) /* cube vertex 1-5 */
/* WLH 24 Oct 97
{ if (!(iy != 0) && vnode5 < INV_VAL && vnode1 < INV_VAL)
{ if (!(iy != 0) && !Float.isNaN(vnode5) && !Float.isNaN(vnode1))
*/
// test for not missing
{ if (!(iy != 0) && vnode5 == vnode5 && vnode1 == vnode1)
{
/* WLH 26 Oct 97
nodeDiff = vnode5 - vnode1;
cp = ( ( isovalue - vnode1 ) / nodeDiff ) + iz;
VX[0][nvet] = ix+1;
VY[0][nvet] = iy;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode1 ) / ( vnode5 - vnode1 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim];
*/
}
P_array[ 2*xx + 2*yy + front*zz + iy ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0040) != 0) ) /* cube vertex 2-3 */
/* WLH 24 Oct 97
{ if (!(iz != 0) && vnode3 < INV_VAL && vnode2 < INV_VAL)
{ if (!(iz != 0) && !Float.isNaN(vnode3) && !Float.isNaN(vnode2))
*/
// test for not missing
{ if (!(iz != 0) && vnode3 == vnode3 && vnode2 == vnode2)
{
/* WLH 26 Oct 97
nodeDiff = vnode3 - vnode2;
cp = ( ( isovalue - vnode2 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy+1;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode2 ) / ( vnode3 - vnode2 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + 1] +
(1.0f-cp) * samples[0][pt + 1];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + 1] +
(1.0f-cp) * samples[1][pt + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + 1] +
(1.0f-cp) * samples[2][pt + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + 1] +
(1.0f-cp) * auxValues[j][pt + 1];
*/
}
P_array[ bellow*xx + ix*ydim + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0080) != 0) ) /* cube vertex 2-6 */
/* WLH 24 Oct 97
{ if (!(ix != 0) && vnode6 < INV_VAL && vnode2 < INV_VAL)
{ if (!(ix != 0) && !Float.isNaN(vnode6) && !Float.isNaN(vnode2))
*/
// test for not missing
{ if (!(ix != 0) && vnode6 == vnode6 && vnode2 == vnode2)
{
/* WLH 26 Oct 97
nodeDiff = vnode6 - vnode2;
cp = ( ( isovalue - vnode2 ) / nodeDiff ) + iz;
VX[0][nvet] = ix;
VY[0][nvet] = iy+1;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode2 ) / ( vnode6 - vnode2 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + 1];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + 1];
*/
}
P_array[ 2*xx + 2*yy + rear*zz + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0100) != 0) ) /* cube vertex 3-7 */
/* WLH 24 Oct 97
{ if (vnode7 < INV_VAL && vnode3 < INV_VAL)
{ if (!Float.isNaN(vnode7) && !Float.isNaN(vnode3))
*/
// test for not missing
{ if (vnode7 == vnode7 && vnode3 == vnode3)
{
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode3;
cp = ( ( isovalue - vnode3 ) / nodeDiff ) + iz;
VX[0][nvet] = ix+1;
VY[0][nvet] = iy+1;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode3 ) / ( vnode7 - vnode3 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim + 1];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim + 1];
*/
}
P_array[ 2*xx + 2*yy + front*zz + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0200) != 0) ) /* cube vertex 4-5 */
/* WLH 24 Oct 97
{ if (!(iy != 0) && vnode5 < INV_VAL && vnode4 < INV_VAL)
{ if (!(iy != 0) && !Float.isNaN(vnode5) && !Float.isNaN(vnode4))
*/
// test for not missing
{ if (!(iy != 0) && vnode5 == vnode5 && vnode4 == vnode4)
{
/* WLH 26 Oct 97
nodeDiff = vnode5 - vnode4;
cp = ( ( isovalue - vnode4 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode4 ) / ( vnode5 - vnode4 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + xdim_x_ydim];
*/
}
P_array[ above*xx + ix*ydim + iy ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0400) != 0) ) /* cube vertex 4-6 */
/* WLH 24 Oct 97
{ if (!(ix != 0) && vnode6 < INV_VAL && vnode4 < INV_VAL)
{ if (!(ix != 0) && !Float.isNaN(vnode6) && !Float.isNaN(vnode4))
*/
// test for not missing
{ if (!(ix != 0) && vnode6 == vnode6 && vnode4 == vnode4)
{
/* WLH 26 Oct 97
nodeDiff = vnode6 - vnode4;
cp = ( ( isovalue - vnode4 ) / nodeDiff ) + iy;
VX[0][nvet] = ix;
VY[0][nvet] = cp;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode4 ) / ( vnode6 - vnode4 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + xdim_x_ydim];
*/
}
P_array[ 2*xx + above*yy + iy*xdim + ix ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0800) != 0) ) /* cube vertex 5-7 */
/* WLH 24 Oct 97
{ if (vnode7 < INV_VAL && vnode5 < INV_VAL)
{ if (!Float.isNaN(vnode7) && !Float.isNaN(vnode5))
*/
// test for not missing
{ if (vnode7 == vnode7 && vnode5 == vnode5)
{
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode5;
cp = ( ( isovalue - vnode5 ) / nodeDiff ) + iy;
VX[0][nvet] = ix+1;
VY[0][nvet] = cp;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode5 ) / ( vnode7 - vnode5 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim + xdim_x_ydim];
*/
}
P_array[ 2*xx + above*yy + iy*xdim + (ix+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x1000) != 0) ) /* cube vertex 6-7 */
/* WLH 24 Oct 97
{ if (vnode7 < INV_VAL && vnode6 < INV_VAL)
{ if (!Float.isNaN(vnode7) && !Float.isNaN(vnode6))
*/
// test for not missing
{ if (vnode7 == vnode7 && vnode6 == vnode6)
{
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode6;
cp = ( ( isovalue - vnode6 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy+1;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode6 ) / ( vnode7 - vnode6 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + 1 + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + 1 + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + 1 + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + 1 + xdim_x_ydim];
*/
}
P_array[ above*xx + ix*ydim + (iy+1) ] = nvet;
nvet++;
}
}
}
/* end find_vertex_invalid_cube(ncube); */
}
} /* end if (exist_polygon_in_cube(ncube)) */
ncube++; pt++;
} /* end for ( iy = 0; iy < ydim - 1; iy++ ) */
/* swap_planes(Z,rear,front); */
caseA = rear;
rear = front;
front = caseA;
pt++;
/* end swap_planes(Z,rear,front); */
} /* end for ( ix = 0; ix < xdim - 1; ix++ ) */
/* swap_planes(XY,bellow,above); */
caseA = bellow;
bellow = above;
above = caseA;
pt += ydim;
/* end swap_planes(XY,bellow,above); */
} /* end for ( iz = 0; iz < zdim - 1; iz++ ) */
// copy tempaux array into auxLevels array
for (int i=0; i<naux; i++) {
auxLevels[i] = new byte[nvet];
System.arraycopy(tempaux[i], 0, auxLevels[i], 0, nvet);
}
return nvet;
}
public static void make_normals( float[] VX, float[] VY, float[] VZ,
float[] NX, float[] NY, float[] NZ, int nvertex,
int npolygons, float[] Pnx, float[] Pny, float[] Pnz,
float[] NxA, float[] NxB, float[] NyA, float[] NyB,
float[] NzA, float[] NzB,
int[] Pol_f_Vert, int[] Vert_f_Pol)
throws VisADException {
int i, k, n;
int i1, i2, ix, iy, iz, ixb, iyb, izb;
int max_vert_per_pol, swap_flag;
float x, y, z, a, minimum_area, len;
int iv[] = new int[3];
for ( i = 0; i < nvertex; i++ ) {
NX[i] = 0;
NY[i] = 0;
NZ[i] = 0;
}
// WLH 12 Nov 2001
// minimum_area = (float) ((1.e-4 > EPS_0) ? 1.e-4 : EPS_0);
minimum_area = Float.MIN_VALUE;
/* Calculate maximum number of vertices per polygon */
k = 6; n = 7*npolygons;
while ( TRUE )
{ for (i=k+7; i<n; i+=7)
if (Vert_f_Pol[i] > Vert_f_Pol[k]) break;
if (i >= n) break; k = i;
}
max_vert_per_pol = Vert_f_Pol[k];
/* Calculate the Normals vector components for each Polygon */
/*$dir vector */
for ( i=0; i<npolygons; i++) { /* Vectorized */
if (Vert_f_Pol[6+i*7]>0) { /* check for valid polygon added by BEP 2-13-92 */
NxA[i] = VX[Vert_f_Pol[1+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyA[i] = VY[Vert_f_Pol[1+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzA[i] = VZ[Vert_f_Pol[1+i*7]] - VZ[Vert_f_Pol[0+i*7]];
}
}
swap_flag = 0;
for ( k = 2; k < max_vert_per_pol; k++ )
{
if (swap_flag==0) {
/*$dir no_recurrence */ /* Vectorized */
for ( i=0; i<npolygons; i++ ) {
if ( Vert_f_Pol[k+i*7] >= 0 ) {
NxB[i] = VX[Vert_f_Pol[k+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyB[i] = VY[Vert_f_Pol[k+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzB[i] = VZ[Vert_f_Pol[k+i*7]] - VZ[Vert_f_Pol[0+i*7]];
Pnx[i] = NyA[i]*NzB[i] - NzA[i]*NyB[i];
Pny[i] = NzA[i]*NxB[i] - NxA[i]*NzB[i];
Pnz[i] = NxA[i]*NyB[i] - NyA[i]*NxB[i];
NxA[i] = Pnx[i]*Pnx[i] + Pny[i]*Pny[i] + Pnz[i]*Pnz[i];
if (NxA[i] > minimum_area) {
Pnx[i] /= NxA[i];
Pny[i] /= NxA[i];
Pnz[i] /= NxA[i];
}
}
}
}
else { /* swap_flag!=0 */
/*$dir no_recurrence */ /* Vectorized */
for ( i=0; i<npolygons; i++ ) {
if ( Vert_f_Pol[k+i*7] >= 0 ) {
NxA[i] = VX[Vert_f_Pol[k+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyA[i] = VY[Vert_f_Pol[k+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzA[i] = VZ[Vert_f_Pol[k+i*7]] - VZ[Vert_f_Pol[0+i*7]];
Pnx[i] = NyB[i]*NzA[i] - NzB[i]*NyA[i];
Pny[i] = NzB[i]*NxA[i] - NxB[i]*NzA[i];
Pnz[i] = NxB[i]*NyA[i] - NyB[i]*NxA[i];
NxB[i] = Pnx[i]*Pnx[i] + Pny[i]*Pny[i] + Pnz[i]*Pnz[i];
if (NxB[i] > minimum_area) {
Pnx[i] /= NxB[i];
Pny[i] /= NxB[i];
Pnz[i] /= NxB[i];
}
}
}
}
/* This Loop <CAN'T> be Vectorized */
for ( i=0; i<npolygons; i++ )
{ if (Vert_f_Pol[k+i*7] >= 0)
{ iv[0] = Vert_f_Pol[0+i*7];
iv[1] = Vert_f_Pol[(k-1)+i*7];
iv[2] = Vert_f_Pol[k+i*7];
x = Pnx[i]; y = Pny[i]; z = Pnz[i];
// Update the origin vertex
NX[iv[0]] += x; NY[iv[0]] += y; NZ[iv[0]] += z;
// Update the vertex that defines the first vector
NX[iv[1]] += x; NY[iv[1]] += y; NZ[iv[1]] += z;
// Update the vertex that defines the second vector
NX[iv[2]] += x; NY[iv[2]] += y; NZ[iv[2]] += z;
}
}
swap_flag = ( (swap_flag != 0) ? 0 : 1 );
}
/* Normalize the Normals */
for ( i=0; i<nvertex; i++ ) /* Vectorized */
{ len = (float) Math.sqrt(NX[i]*NX[i] + NY[i]*NY[i] + NZ[i]*NZ[i]);
if (len > EPS_0) {
NX[i] /= len;
NY[i] /= len;
NZ[i] /= len;
}
}
}
public static int poly_triangle_stripe( int[] vet_pol, int[] Tri_Stripe,
int nvertex, int npolygons, int[] Pol_f_Vert,
int[] Vert_f_Pol ) throws VisADException {
int i, j, k, m, ii, npol, cpol, idx, off, Nvt,
vA, vB, ivA, ivB, iST, last_pol;
boolean f_line_conection = false;
last_pol = 0;
npol = 0;
iST = 0;
ivB = 0;
for (i=0; i<npolygons; i++) vet_pol[i] = 1; /* Vectorized */
while (TRUE)
{
/* find_unselected_pol(cpol); */
for (cpol=last_pol; cpol<npolygons; cpol++) {
if ( (vet_pol[cpol] != 0) ) break;
}
if (cpol == npolygons) {
cpol = -1;
}
else {
last_pol = cpol;
}
/* end find_unselected_pol(cpol); */
if (cpol < 0) break;
/* update_polygon */
vet_pol[cpol] = 0;
/* end update_polygon */
/* get_vertices_of_pol(cpol,Vt,Nvt); { */
Nvt = Vert_f_Pol[(j=cpol*7)+6];
off = j;
/* } */
/* end get_vertices_of_pol(cpol,Vt,Nvt); { */
for (ivA=0; ivA<Nvt; ivA++) {
ivB = (((ivA+1)==Nvt) ? 0:(ivA+1));
/* get_pol_vert(Vt[ivA],Vt[ivB],npol) { */
npol = -1;
if (Vert_f_Pol[ivA+off]>=0 && Vert_f_Pol[ivB+off]>=0) {
i=Vert_f_Pol[ivA+off]*9;
k=i+Pol_f_Vert [i+8];
j=Vert_f_Pol[ivB+off]*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j <m ) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
(vet_pol[Pol_f_Vert[i]] != 0) ) {
npol=Pol_f_Vert [i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
/* } */
/* end get_pol_vert(Vt[ivA],Vt[ivB],npol) { */
if (npol >= 0) break;
}
/* insert polygon alone */
if (npol < 0)
{ /*ptT = NTAB + STAB[Nvt-3];*/
idx = STAB[Nvt-3];
if (iST > 0)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx]+off];
}
else f_line_conection = true; /* WLH 3-9-95 added */
for (ii=0; ii< ((Nvt < 6) ? Nvt:6); ii++) {
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx++]+off];
}
continue;
}
if (( (ivB != 0) && ivA==(ivB-1)) || ( !(ivB != 0) && ivA==Nvt-1)) {
/* ptT = ITAB + STAB[Nvt-3] + (ivB+1)*Nvt; */
idx = STAB[Nvt-3] + (ivB+1)*Nvt;
if (f_line_conection)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[idx-1]+off];
f_line_conection = false;
}
for (ii=0; ii<((Nvt < 6) ? Nvt:6); ii++) {
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[--idx]+off];
}
}
else {
/* ptT = NTAB + STAB[Nvt-3] + (ivB+1)*Nvt; */
idx = STAB[Nvt-3] + (ivB+1)*Nvt;
if (f_line_conection)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx-1]+off];
f_line_conection = false;
}
for (ii=0; ii<((Nvt < 6) ? Nvt:6); ii++) {
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[--idx]+off];
}
}
vB = Tri_Stripe[iST-1];
vA = Tri_Stripe[iST-2];
cpol = npol;
while (TRUE)
{
/* get_vertices_of_pol(cpol,Vt,Nvt) { */
Nvt = Vert_f_Pol [(j=cpol*7)+6];
off = j;
/* } */
/* update_polygon(cpol) */
vet_pol[cpol] = 0;
for (ivA=0; ivA<Nvt && Vert_f_Pol[ivA+off]!=vA; ivA++);
for (ivB=0; ivB<Nvt && Vert_f_Pol[ivB+off]!=vB; ivB++);
if (( (ivB != 0) && ivA==(ivB-1)) || (!(ivB != 0) && ivA==Nvt-1)) {
/* ptT = NTAB + STAB[Nvt-3] + ivA*Nvt + 2; */
idx = STAB[Nvt-3] + ivA*Nvt + 2;
for (ii=2; ii<((Nvt < 6) ? Nvt:6); ii++)
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx++]+off];
}
else {
/* ptT = ITAB + STAB[Nvt-3] + ivA*Nvt + 2; */
idx = STAB[Nvt-3] + ivA*Nvt + 2;
for (ii=2; ii<((Nvt < 6) ? Nvt:6); ii++)
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[idx++]+off];
}
vB = Tri_Stripe[iST-1];
vA = Tri_Stripe[iST-2];
/* get_pol_vert(vA,vB,cpol) { */
cpol = -1;
if (vA>=0 && vB>=0) {
i=vA*9;
k=i+Pol_f_Vert [i+8];
j=vB*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j<m) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] && (vet_pol[Pol_f_Vert[i]] != 0) ) {
cpol=Pol_f_Vert[i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
/* } */
if (cpol < 0) {
vA = Tri_Stripe[iST-3];
/* get_pol_vert(vA,vB,cpol) { */
cpol = -1;
if (vA>=0 && vB>=0) {
i=vA*9;
k=i+Pol_f_Vert [i+8];
j=vB*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j<m) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
(vet_pol[Pol_f_Vert[i]] != 0) ) {
cpol=Pol_f_Vert[i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
/* } */
if (cpol < 0) {
f_line_conection = true;
break;
}
else {
Tri_Stripe[iST++] = vA;
i = vA;
vA = vB;
vB = i;
}
}
}
}
return iST;
}
public static float[] makeNormals(float[] coordinates, int LengthX,
int LengthY) {
int Length = LengthX * LengthY;
float[] normals = new float[3 * Length];
int k = 0;
int ki, kj;
int LengthX3 = 3 * LengthX;
for (int i=0; i<LengthY; i++) {
for (int j=0; j<LengthX; j++) {
float c0 = coordinates[k];
float c1 = coordinates[k+1];
float c2 = coordinates[k+2];
float n0 = 0.0f;
float n1 = 0.0f;
float n2 = 0.0f;
float n, m, m0, m1, m2, q0, q1, q2;
for (int ip = -1; ip<=1; ip += 2) {
for (int jp = -1; jp<=1; jp += 2) {
int ii = i + ip;
int jj = j + jp;
if (0 <= ii && ii < LengthY && 0 <= jj && jj < LengthX) {
ki = k + ip * LengthX3;
kj = k + jp * 3;
m0 = (coordinates[kj+2] - c2) * (coordinates[ki+1] - c1) -
(coordinates[kj+1] - c1) * (coordinates[ki+2] - c2);
m1 = (coordinates[kj] - c0) * (coordinates[ki+2] - c2) -
(coordinates[kj+2] - c2) * (coordinates[ki] - c0);
m2 = (coordinates[kj+1] - c1) * (coordinates[ki] - c0) -
(coordinates[kj] - c0) * (coordinates[ki+1] - c1);
m = (float) Math.sqrt(m0 * m0 + m1 * m1 + m2 * m2);
if (ip == jp) {
q0 = m0 / m;
q1 = m1 / m;
q2 = m2 / m;
}
else {
q0 = -m0 / m;
q1 = -m1 / m;
q2 = -m2 / m;
}
if (q0 == q0) {
n0 += q0;
n1 += q1;
n2 += q2;
}
else {
/*
System.out.println("m = " + m + " " + m0 + " " + m1 + " " + m2 + " " +
n0 + " " + n1 + " " + n2 + " ip, jp = " + ip + " " + jp);
System.out.println("k = " + k + " " + ki + " " + kj);
System.out.println("c = " + c0 + " " + c1 + " " + c2);
System.out.println("coordinates[ki] = " + coordinates[ki] + " " +
coordinates[ki+1] + " " + coordinates[ki+2]); // == c ??
System.out.println("coordinates[kj] = " + coordinates[kj] + " " +
coordinates[kj+1] + " " + coordinates[kj+2]);
System.out.println("LengthX = " + LengthX + " " + LengthY + " " +
LengthX3);
*/
}
}
}
}
n = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
normals[k] = n0 / n;
normals[k+1] = n1 / n;
normals[k+2] = n2 / n;
if (normals[k] != normals[k]) {
normals[k] = 0.0f;
normals[k+1] = 0.0f;
normals[k+2] = -1.0f;
}
/*
System.out.println("makeNormals " + k + " " + normals[k] + " " + normals[k+1] + " " +
normals[k+2]);
*/
k += 3;
} // end for (int j=0; j<LengthX; j++)
} // end for (int i=0; i<LengthY; i++)
return normals;
}
/** create a 2-D GeometryArray from this Set and color_values */
public VisADGeometryArray make2DGeometry(byte[][] color_values,
boolean indexed) throws VisADException {
if (DomainDimension != 3) {
throw new SetException("Gridded3DSet.make2DGeometry: " +
"DomainDimension must be 3");
}
if (ManifoldDimension != 2) {
throw new SetException("Gridded3DSet.make2DGeometry: " +
"ManifoldDimension must be 2");
}
if (LengthX < 2 || LengthY < 2) {
/* WLH 26 June 98
throw new SetException("Gridded3DSet.make2DGeometry: " +
"LengthX and LengthY must be at least 2");
*/
VisADPointArray array = new VisADPointArray();
setGeometryArray(array, 4, color_values);
return array;
}
if (indexed) {
VisADIndexedTriangleStripArray array =
new VisADIndexedTriangleStripArray();
// set up indices into 2-D grid
array.indexCount = (LengthY - 1) * (2 * LengthX);
int[] indices = new int[array.indexCount];
array.stripVertexCounts = new int[LengthY - 1];
int k = 0;
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX;
array.stripVertexCounts[i] = 2 * LengthX;
for (int j=0; j<LengthX; j++) {
indices[k++] = m;
indices[k++] = m + LengthX;
m++;
}
}
array.indices = indices;
// take the garbage out
indices = null;
// set coordinates and colors
setGeometryArray(array, 4, color_values);
// calculate normals
float[] coordinates = array.coordinates;
float[] normals = makeNormals(coordinates, LengthX, LengthY);
array.normals = normals;
return array;
}
else { // if (!indexed)
VisADTriangleStripArray array = new VisADTriangleStripArray();
float[][] samples = getSamples(false);
array.stripVertexCounts = new int[LengthY - 1];
for (int i=0; i<LengthY-1; i++) {
array.stripVertexCounts[i] = 2 * LengthX;
}
int len = (LengthY - 1) * (2 * LengthX);
array.vertexCount = len;
// calculate normals
float[] normals = new float[3 * Length];
int k = 0;
int k3 = 0;
int ki, kj;
for (int i=0; i<LengthY; i++) {
for (int j=0; j<LengthX; j++) {
float c0 = samples[0][k3];
float c1 = samples[1][k3];
float c2 = samples[2][k3];
float n0 = 0.0f;
float n1 = 0.0f;
float n2 = 0.0f;
float n, m, m0, m1, m2;
boolean any = false;
for (int ip = -1; ip<=1; ip += 2) {
for (int jp = -1; jp<=1; jp += 2) {
int ii = i + ip;
int jj = j + jp;
ki = k3 + ip * LengthX;
kj = k3 + jp;
if (0 <= ii && ii < LengthY && 0 <= jj && jj < LengthX &&
samples[0][ki] == samples[0][ki] &&
samples[1][ki] == samples[1][ki] &&
samples[2][ki] == samples[2][ki] &&
samples[0][kj] == samples[0][kj] &&
samples[1][kj] == samples[1][kj] &&
samples[2][kj] == samples[2][kj]) {
any = true;
m0 = (samples[2][kj] - c2) * (samples[1][ki] - c1) -
(samples[1][kj] - c1) * (samples[2][ki] - c2);
m1 = (samples[0][kj] - c0) * (samples[2][ki] - c2) -
(samples[2][kj] - c2) * (samples[0][ki] - c0);
m2 = (samples[1][kj] - c1) * (samples[0][ki] - c0) -
(samples[0][kj] - c0) * (samples[1][ki] - c1);
m = (float) Math.sqrt(m0 * m0 + m1 * m1 + m2 * m2);
if (ip == jp) {
n0 += m0 / m;
n1 += m1 / m;
n2 += m2 / m;
}
else {
n0 -= m0 / m;
n1 -= m1 / m;
n2 -= m2 / m;
}
}
}
}
n = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
if (any) {
normals[k] = n0 / n;
normals[k+1] = n1 / n;
normals[k+2] = n2 / n;
}
else {
normals[k] = 0.0f;
normals[k+1] = 0.0f;
normals[k+2] = 1.0f;
}
k += 3;
k3++;
} // end for (int j=0; j<LengthX; j++)
} // end for (int i=0; i<LengthY; i++)
array.normals = new float[3 * len];
// shuffle normals into array.normals
k = 0;
int LengthX3 = 3 * LengthX;
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX3;
for (int j=0; j<LengthX; j++) {
array.normals[k] = normals[m];
array.normals[k+1] = normals[m+1];
array.normals[k+2] = normals[m+2];
array.normals[k+3] = normals[m+LengthX3];
array.normals[k+4] = normals[m+LengthX3+1];
array.normals[k+5] = normals[m+LengthX3+2];
k += 6;
m += 3;
}
}
normals = null;
/*
int nmiss = 0;
int nsmall = 0;
*/
array.coordinates = new float[3 * len];
// shuffle samples into array.coordinates
k = 0;
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX;
for (int j=0; j<LengthX; j++) {
array.coordinates[k] = samples[0][m];
array.coordinates[k+1] = samples[1][m];
array.coordinates[k+2] = samples[2][m];
array.coordinates[k+3] = samples[0][m+LengthX];
array.coordinates[k+4] = samples[1][m+LengthX];
array.coordinates[k+5] = samples[2][m+LengthX];
/*
if (samples[0][m] != samples[0][m] ||
samples[1][m] != samples[1][m] ||
samples[2][m] != samples[2][m]) nmiss++;
double size = Math.sqrt(samples[0][m] * samples[0][m] +
samples[1][m] * samples[1][m] +
samples[2][m] * samples[2][m]);
if (size < 0.2) nsmall++;
*/
k += 6;
m++;
}
}
// System.out.println("make2DGeometry nmiss = " + nmiss + " nsmall = " + nsmall);
if (color_values != null) {
int color_length = color_values.length;
array.colors = new byte[color_length * len];
// shuffle samples into array.coordinates
k = 0;
if (color_length == 4) {
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX;
for (int j=0; j<LengthX; j++) {
array.colors[k] = color_values[0][m];
array.colors[k+1] = color_values[1][m];
array.colors[k+2] = color_values[2][m];
array.colors[k+3] = color_values[3][m];
k += color_length;
array.colors[k] = color_values[0][m+LengthX];
array.colors[k+1] = color_values[1][m+LengthX];
array.colors[k+2] = color_values[2][m+LengthX];
array.colors[k+3] = color_values[3][m+LengthX];
k += color_length;
m++;
}
}
}
else { // if (color_length == 3)
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX;
for (int j=0; j<LengthX; j++) {
array.colors[k] = color_values[0][m];
array.colors[k+1] = color_values[1][m];
array.colors[k+2] = color_values[2][m];
k += color_length;
array.colors[k] = color_values[0][m+LengthX];
array.colors[k+1] = color_values[1][m+LengthX];
array.colors[k+2] = color_values[2][m+LengthX];
k += color_length;
m++;
}
}
}
}
return array;
} // end if (!indexed)
}
public Object cloneButType(MathType type) throws VisADException {
if (ManifoldDimension == 3) {
return new Gridded3DSet(type, Samples, LengthX, LengthY, LengthZ,
DomainCoordinateSystem, SetUnits, SetErrors);
}
else if (ManifoldDimension == 2) {
return new Gridded3DSet(type, Samples, LengthX, LengthY,
DomainCoordinateSystem, SetUnits, SetErrors);
}
else {
return new Gridded3DSet(type, Samples, LengthX,
DomainCoordinateSystem, SetUnits, SetErrors);
}
}
/* run 'java visad.Gridded3DSet < formatted_input_stream'
to test the Gridded3DSet class */
public static void main(String[] argv) throws VisADException {
// Define input stream
InputStreamReader inStr = new InputStreamReader(System.in);
// Define temporary integer array
int[] ints = new int[80];
try {
ints[0] = inStr.read();
}
catch(Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
int l = 0;
while (ints[l] != 10) {
try {
ints[++l] = inStr.read();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
}
// convert array of integers to array of characters
char[] chars = new char[l];
for (int i=0; i<l; i++) {
chars[i] = (char) ints[i];
}
int num_coords = Integer.parseInt(new String(chars));
// num_coords should be a nice round number
if (num_coords % 9 != 0) {
throw new SetException("Gridded3DSet: input coordinates"
+" must be divisible by 9 for main function testing routines.");
}
// Define size of Samples array
float[][] samp = new float[3][num_coords];
System.out.println("num_dimensions = 3, num_coords = "+num_coords+"\n");
// Skip blank line
try {
ints[0] = inStr.read();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
for (int c=0; c<num_coords; c++) {
for (int d=0; d<3; d++) {
l = 0;
try {
ints[0] = inStr.read();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
while ( (ints[l] != 32) && (ints[l] != 10) ) {
try {
ints[++l] = inStr.read();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
}
chars = new char[l];
for (int i=0; i<l; i++) {
chars[i] = (char) ints[i];
}
samp[d][c] = (Float.valueOf(new String(chars))).floatValue();
}
}
// do EOF stuff
try {
inStr.close();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
// Set up instance of Gridded3DSet
RealType vis_xcoord = RealType.getRealType("xcoord");
RealType vis_ycoord = RealType.getRealType("ycoord");
RealType vis_zcoord = RealType.getRealType("zcoord");
RealType[] vis_array = {vis_xcoord, vis_ycoord, vis_zcoord};
RealTupleType vis_tuple = new RealTupleType(vis_array);
Gridded3DSet gSet3D = new Gridded3DSet(vis_tuple, samp,
3, 3, num_coords/9);
System.out.println("Lengths = 3 3 " + num_coords/9 + " wedge = ");
int[] wedge = gSet3D.getWedge();
for (int i=0; i<wedge.length; i++) System.out.println(" " + wedge[i]);
// print out Samples information
System.out.println("Samples ("+gSet3D.LengthX+" x "+gSet3D.LengthY
+" x "+gSet3D.LengthZ+"):");
for (int i=0; i<gSet3D.LengthX*gSet3D.LengthY*gSet3D.LengthZ; i++) {
System.out.println("#"+i+":\t"+gSet3D.Samples[0][i]
+", "+gSet3D.Samples[1][i]
+", "+gSet3D.Samples[2][i]);
}
// Test gridToValue function
System.out.println("\ngridToValue test:");
int myLengthX = gSet3D.LengthX+1;
int myLengthY = gSet3D.LengthY+1;
int myLengthZ = gSet3D.LengthZ+1;
float[][] myGrid = new float[3][myLengthX*myLengthY*myLengthZ];
for (int k=0; k<myLengthZ; k++) {
for (int j=0; j<myLengthY; j++) {
for (int i=0; i<myLengthX; i++) {
int index = k*myLengthY*myLengthX+j*myLengthX+i;
myGrid[0][index] = i-0.5f;
myGrid[1][index] = j-0.5f;
myGrid[2][index] = k-0.5f;
if (myGrid[0][index] < 0) myGrid[0][index] += 0.1;
if (myGrid[1][index] < 0) myGrid[1][index] += 0.1;
if (myGrid[2][index] < 0) myGrid[2][index] += 0.1;
if (myGrid[0][index] > gSet3D.LengthX-1) myGrid[0][index] -= 0.1;
if (myGrid[1][index] > gSet3D.LengthY-1) myGrid[1][index] -= 0.1;
if (myGrid[2][index] > gSet3D.LengthZ-1) myGrid[2][index] -= 0.1;
}
}
}
float[][] myValue = gSet3D.gridToValue(myGrid);
for (int i=0; i<myLengthX*myLengthY*myLengthZ; i++) {
System.out.println("("+((float) Math.round(1000000
*myGrid[0][i]) /1000000)+", "
+((float) Math.round(1000000
*myGrid[1][i]) /1000000)+", "
+((float) Math.round(1000000
*myGrid[2][i]) /1000000)+") \t--> "
+((float) Math.round(1000000
*myValue[0][i]) /1000000)+", "
+((float) Math.round(1000000
*myValue[1][i]) /1000000)+", "
+((float) Math.round(1000000
*myValue[2][i]) /1000000));
}
// Test valueToGrid function
System.out.println("\nvalueToGrid test:");
float[][] gridTwo = gSet3D.valueToGrid(myValue);
for (int i=0; i<gridTwo[0].length; i++) {
System.out.print(((float) Math.round(1000000
*myValue[0][i]) /1000000)+", "
+((float) Math.round(1000000
*myValue[1][i]) /1000000)+", "
+((float) Math.round(1000000
*myValue[2][i]) /1000000)+"\t--> (");
if (Float.isNaN(gridTwo[0][i])) {
System.out.print("NaN, ");
}
else {
System.out.print(((float) Math.round(1000000
*gridTwo[0][i]) /1000000)+", ");
}
if (Float.isNaN(gridTwo[1][i])) {
System.out.print("NaN, ");
}
else {
System.out.print(((float) Math.round(1000000
*gridTwo[1][i]) /1000000)+", ");
}
if (Float.isNaN(gridTwo[2][i])) {
System.out.println("NaN)");
}
else {
System.out.println(((float) Math.round(1000000
*gridTwo[2][i]) /1000000)+")");
}
}
System.out.println();
}
/* Here's the output with sample file Gridded3D.txt:
iris 28% java visad.Gridded3DSet < Gridded3D.txt
num_dimensions = 3, num_coords = 27
Lengths = 3 3 3 wedge =
0
1
2
5
4
3
. . .
Samples (3 x 3 x 3):
#0: 18.629837, 8.529864, 10.997844
#1: 42.923097, 10.123978, 11.198275
. . .
#25: 32.343298, 39.600872, 36.238975
#26: 49.919754, 40.119875, 36.018752
gridToValue test:
(-0.4, -0.4, -0.4) --> 10.819755, -0.172592, 5.179111
(0.5, -0.4, -0.4) --> 32.683689, 1.262111, 5.359499
. . .
(1.5, 2.4, 2.4) --> 43.844996, 48.904708, 40.008508
(2.4, 2.4, 2.4) --> 59.663807, 49.37181, 39.810308
valueToGrid test:
10.819755, -0.172592, 5.179111 --> (-0.4, -0.4, -0.4)
32.683689, 1.262111, 5.359499 --> (0.5, -0.4, -0.4)
. . .
43.844996, 48.904708, 40.008508 --> (1.5, 2.4, 2.4)
59.663807, 49.37181, 39.810308 --> (2.4, 2.4, 2.4)
iris 29%
*/
}
| private int isosurf( float isovalue, int[] ptFLAG, int nvertex_estimate,
int npolygons, float[] ptGRID, int xdim, int ydim,
int zdim, float[][] VX, float[][] VY, float[][] VZ,
byte[][] auxValues, byte[][] auxLevels,
int[][] Pol_f_Vert, int[] Vert_f_Pol )
throws VisADException {
int ix, iy, iz, caseA, above, bellow, front, rear, mm, nn;
int ii, jj, kk, ncube, cpl, pvp, pa, ve;
int[] calc_edge = new int[13];
int xx, yy, zz;
float cp;
float vnode0 = 0;
float vnode1 = 0;
float vnode2 = 0;
float vnode3 = 0;
float vnode4 = 0;
float vnode5 = 0;
float vnode6 = 0;
float vnode7 = 0;
int pt = 0;
int n_pol;
int aa;
int bb;
int temp;
float nodeDiff;
int xdim_x_ydim = xdim*ydim;
int nvet;
int t;
float[][] samples = getSamples(false);
int naux = (auxValues != null) ? auxValues.length : 0;
if (naux > 0) {
if (auxLevels == null || auxLevels.length != naux) {
throw new SetException("Gridded3DSet.isosurf: "
+"auxLevels length " + auxLevels.length +
" doesn't match expected " + naux);
}
for (int i=0; i<naux; i++) {
if (auxValues[i].length != Length) {
throw new SetException("Gridded3DSet.isosurf: expected auxValues " +
" length#" + i + " to be " + Length +
", not " + auxValues[i].length);
}
}
}
else {
if (auxLevels != null) {
throw new SetException("Gridded3DSet.isosurf: "
+"auxValues null but auxLevels not null");
}
}
// temporary storage of auxLevels structure
byte[][] tempaux = (naux > 0) ? new byte[naux][nvertex_estimate] : null;
bellow = rear = 0; above = front = 1;
/* Initialize the Auxiliar Arrays of Pointers */
/* WLH 25 Oct 97
ix = 9 * (npolygons*2 + 50);
iy = 7 * npolygons;
ii = ix + iy;
*/
for (jj=0; jj<Pol_f_Vert[0].length; jj++) {
Pol_f_Vert[0][jj] = BIG_NEG;
}
for (jj=8; jj<Pol_f_Vert[0].length; jj+=9) {
Pol_f_Vert[0][jj] = 0;
}
for (jj=0; jj<Vert_f_Pol.length; jj++) {
Vert_f_Pol[jj] = BIG_NEG;
}
for (jj=6; jj<Vert_f_Pol.length; jj+=7) {
Vert_f_Pol[jj] = 0;
}
/* Allocate the auxiliar edge vectors
size ixPlane = (xdim - 1) * ydim = xdim_x_ydim - ydim
size iyPlane = (ydim - 1) * xdim = xdim_x_ydim - xdim
size izPlane = xdim
*/
xx = xdim_x_ydim - ydim;
yy = xdim_x_ydim - xdim;
zz = ydim;
ii = 2 * (xx + yy + zz);
int[] P_array = new int[ii];
/* Calculate the Vertex of the Polygons which edges were
calculated above */
nvet = ncube = cpl = pvp = 0;
for ( iz = 0; iz < zdim - 1; iz++ ) {
for ( ix = 0; ix < xdim - 1; ix++ ) {
for ( iy = 0; iy < ydim - 1; iy++ ) {
if ( (ptFLAG[ncube] != 0 & ptFLAG[ncube] != 0xFF) ) {
if (nvet + 12 > nvertex_estimate) {
// allocate more space
nvertex_estimate = 2 * (nvet + 12);
if (naux > 0) {
for (int i=0; i<naux; i++) {
byte[] tt = tempaux[i];
tempaux[i] = new byte[nvertex_estimate];
System.arraycopy(tt, 0, tempaux[i], 0, nvet);
}
}
float[] tt = VX[0];
VX[0] = new float[nvertex_estimate];
System.arraycopy(tt, 0, VX[0], 0, tt.length);
tt = VY[0];
VY[0] = new float[nvertex_estimate];
System.arraycopy(tt, 0, VY[0], 0, tt.length);
tt = VZ[0];
VZ[0] = new float[nvertex_estimate];
System.arraycopy(tt, 0, VZ[0], 0, tt.length);
int big_ix = 9 * (nvertex_estimate + 50);
int[] it = Pol_f_Vert[0];
Pol_f_Vert[0] = new int[big_ix];
for (jj=0; jj<Pol_f_Vert[0].length; jj++) {
Pol_f_Vert[0][jj] = BIG_NEG;
}
for (jj=8; jj<Pol_f_Vert[0].length; jj+=9) {
Pol_f_Vert[0][jj] = 0;
}
System.arraycopy(it, 0, Pol_f_Vert[0], 0, it.length);
}
/* WLH 2 April 99 */
vnode0 = ptGRID[pt];
vnode1 = ptGRID[pt + ydim];
vnode2 = ptGRID[pt + 1];
vnode3 = ptGRID[pt + ydim + 1];
vnode4 = ptGRID[pt + xdim_x_ydim];
vnode5 = ptGRID[pt + ydim + xdim_x_ydim];
vnode6 = ptGRID[pt + 1 + xdim_x_ydim];
vnode7 = ptGRID[pt + 1 + ydim + xdim_x_ydim];
if ( (ptFLAG[ncube] < MAX_FLAG_NUM) ) {
/* fill_Vert_f_Pol(ncube); */
kk = pol_edges[ptFLAG[ncube]][2];
aa = ptFLAG[ncube];
bb = 4;
pa = pvp;
n_pol = pol_edges[ptFLAG[ncube]][1];
for (ii=0; ii < n_pol; ii++) {
Vert_f_Pol[pa+6] = ve = kk&MASK;
ve+=pa;
for (jj=pa; jj<ve && jj<pa+6; jj++) {
Vert_f_Pol[jj] = pol_edges[aa][bb];
bb++;
if (bb >= 16) {
aa++;
bb -= 16;
}
}
kk >>= 4; pa += 7;
}
/* end fill_Vert_f_Pol(ncube); */
/* */
/* find_vertex(); */
/* WLH 2 April 99
vnode0 = ptGRID[pt];
vnode1 = ptGRID[pt + ydim];
vnode2 = ptGRID[pt + 1];
vnode3 = ptGRID[pt + ydim + 1];
vnode4 = ptGRID[pt + xdim_x_ydim];
vnode5 = ptGRID[pt + ydim + xdim_x_ydim];
vnode6 = ptGRID[pt + 1 + xdim_x_ydim];
vnode7 = ptGRID[pt + 1 + ydim + xdim_x_ydim];
*/
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0002) != 0) ) { /* cube vertex 0-1 */
if ( (iz != 0) || (iy != 0) ) {
calc_edge[1] = P_array[ bellow*xx + ix*ydim + iy ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode1 - vnode0;
cp = ( ( isovalue - vnode0 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode0 ) / ( vnode1 - vnode0 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim] + (1.0f-cp) * samples[0][pt];
VY[0][nvet] = (float) cp * samples[1][pt + ydim] + (1.0f-cp) * samples[1][pt];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim] + (1.0f-cp) * samples[2][pt];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt] < 0) ?
((float) auxValues[j][pt]) + 256.0f :
((float) auxValues[j][pt]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim] +
(1.0f-cp) * auxValues[j][pt];
*/
}
calc_edge[1] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0004) != 0) ) { /* cube vertex 0-2 */
if ( (iz != 0) || (ix != 0) ) {
calc_edge[2] = P_array[ 2*xx + bellow*yy + iy*xdim + ix ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode2 - vnode0;
cp = ( ( isovalue - vnode0 ) / nodeDiff ) + iy;
VX[0][nvet] = ix;
VY[0][nvet] = cp;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode0 ) / ( vnode2 - vnode0 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1] + (1.0f-cp) * samples[0][pt];
VY[0][nvet] = (float) cp * samples[1][pt + 1] + (1.0f-cp) * samples[1][pt];
VZ[0][nvet] = (float) cp * samples[2][pt + 1] + (1.0f-cp) * samples[2][pt];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt] < 0) ?
((float) auxValues[j][pt]) + 256.0f :
((float) auxValues[j][pt]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1] +
(1.0f-cp) * auxValues[j][pt];
*/
}
calc_edge[2] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0008) != 0) ) { /* cube vertex 0-4 */
if ( (ix != 0) || (iy != 0) ) {
calc_edge[3] = P_array[ 2*xx + 2*yy + rear*zz + iy ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode4 - vnode0;
cp = ( ( isovalue - vnode0 ) / nodeDiff ) + iz;
VX[0][nvet] = ix;
VY[0][nvet] = iy;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode0 ) / ( vnode4 - vnode0 ) );
VX[0][nvet] = (float) cp * samples[0][pt + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt];
VY[0][nvet] = (float) cp * samples[1][pt + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt];
VZ[0][nvet] = (float) cp * samples[2][pt + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt] < 0) ?
((float) auxValues[j][pt]) + 256.0f :
((float) auxValues[j][pt]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt];
*/
}
calc_edge[3] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0010) != 0) ) { /* cube vertex 1-3 */
if ( (iz != 0) ) {
calc_edge[4] = P_array[ 2*xx + bellow*yy + iy*xdim + (ix+1) ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode3 - vnode1;
cp = ( ( isovalue - vnode1 ) / nodeDiff ) + iy;
VX[0][nvet] = ix+1;
VY[0][nvet] = cp;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode1 ) / ( vnode3 - vnode1 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + 1] +
(1.0f-cp) * samples[0][pt + ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + 1] +
(1.0f-cp) * samples[1][pt + ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + 1] +
(1.0f-cp) * samples[2][pt + ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + 1] +
(1.0f-cp) * auxValues[j][pt + ydim];
*/
}
calc_edge[4] = nvet;
P_array[ 2*xx + bellow*yy + iy*xdim + (ix+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0020) != 0) ) { /* cube vertex 1-5 */
if ( (iy != 0) ) {
calc_edge[5] = P_array[ 2*xx + 2*yy + front*zz + iy ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode5 - vnode1;
cp = ( ( isovalue - vnode1 ) / nodeDiff ) + iz;
VX[0][nvet] = ix+1;
VY[0][nvet] = iy;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode1 ) / ( vnode5 - vnode1 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim];
*/
}
calc_edge[5] = nvet;
P_array[ 2*xx + 2*yy + front*zz + iy ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0040) != 0) ) { /* cube vertex 2-3 */
if ( (iz != 0) ) {
calc_edge[6] = P_array[ bellow*xx + ix*ydim + (iy+1) ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode3 - vnode2;
cp = ( ( isovalue - vnode2 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy+1;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode2 ) / ( vnode3 - vnode2 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + 1] +
(1.0f-cp) * samples[0][pt + 1];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + 1] +
(1.0f-cp) * samples[1][pt + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + 1] +
(1.0f-cp) * samples[2][pt + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + 1] +
(1.0f-cp) * auxValues[j][pt + 1];
*/
}
calc_edge[6] = nvet;
P_array[ bellow*xx + ix*ydim + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0080) != 0) ) { /* cube vertex 2-6 */
if ( (ix != 0) ) {
calc_edge[7] = P_array[ 2*xx + 2*yy + rear*zz + (iy+1) ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode6 - vnode2;
cp = ( ( isovalue - vnode2 ) / nodeDiff ) + iz;
VX[0][nvet] = ix;
VY[0][nvet] = iy+1;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode2 ) / ( vnode6 - vnode2 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + 1];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + 1];
*/
}
calc_edge[7] = nvet;
P_array[ 2*xx + 2*yy + rear*zz + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0100) != 0) ) { /* cube vertex 3-7 */
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode3;
cp = ( ( isovalue - vnode3 ) / nodeDiff ) + iz;
VX[0][nvet] = ix+1;
VY[0][nvet] = iy+1;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode3 ) / ( vnode7 - vnode3 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim + 1];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim + 1];
*/
}
calc_edge[8] = nvet;
P_array[ 2*xx + 2*yy + front*zz + (iy+1) ] = nvet;
nvet++;
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0200) != 0) ) { /* cube vertex 4-5 */
if ( (iy != 0) ) {
calc_edge[9] = P_array[ above*xx + ix*ydim + iy ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode5 - vnode4;
cp = ( ( isovalue - vnode4 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode4 ) / ( vnode5 - vnode4 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + xdim_x_ydim];
*/
}
calc_edge[9] = nvet;
P_array[ above*xx + ix*ydim + iy ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0400) != 0) ) { /* cube vertex 4-6 */
if ( (ix != 0) ) {
calc_edge[10] = P_array[ 2*xx + above*yy + iy*xdim + ix ];
}
else {
/* WLH 26 Oct 97
nodeDiff = vnode6 - vnode4;
cp = ( ( isovalue - vnode4 ) / nodeDiff ) + iy;
VX[0][nvet] = ix;
VY[0][nvet] = cp;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode4 ) / ( vnode6 - vnode4 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + xdim_x_ydim];
*/
}
calc_edge[10] = nvet;
P_array[ 2*xx + above*yy + iy*xdim + ix ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0800) != 0) ) { /* cube vertex 5-7 */
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode5;
cp = ( ( isovalue - vnode5 ) / nodeDiff ) + iy;
VX[0][nvet] = ix+1;
VY[0][nvet] = cp;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode5 ) / ( vnode7 - vnode5 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim + xdim_x_ydim];
*/
}
calc_edge[11] = nvet;
P_array[ 2*xx + above*yy + iy*xdim + (ix+1) ] = nvet;
nvet++;
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x1000) != 0) ) { /* cube vertex 6-7 */
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode6;
cp = ( ( isovalue - vnode6 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy+1;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode6 ) / ( vnode7 - vnode6 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + 1 + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + 1 + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + 1 + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + 1 + xdim_x_ydim];
*/
}
calc_edge[12] = nvet;
P_array[ above*xx + ix*ydim + (iy+1) ] = nvet;
nvet++;
}
/* end find_vertex(); */
/* update_data_structure(ncube); */
kk = pol_edges[ptFLAG[ncube]][2];
nn = pol_edges[ptFLAG[ncube]][1];
for (ii=0; ii<nn; ii++) {
mm = pvp+(kk&MASK);
for (jj=pvp; jj<mm; jj++) {
Vert_f_Pol [jj] = ve = calc_edge[Vert_f_Pol [jj]];
// Pol_f_Vert[0][ve*9 + (Pol_f_Vert[0][ve*9 + 8])++] = cpl;
temp = Pol_f_Vert[0][ve*9 + 8];
Pol_f_Vert[0][ve*9 + temp] = cpl;
Pol_f_Vert[0][ve*9 + 8] = temp + 1;
}
kk >>= 4; pvp += 7; cpl++;
}
/* end update_data_structure(ncube); */
}
else { // !(ptFLAG[ncube] < MAX_FLAG_NUM)
/* find_vertex_invalid_cube(ncube); */
ptFLAG[ncube] &= 0x1FF;
if ( (ptFLAG[ncube] != 0 & ptFLAG[ncube] != 0xFF) )
{ if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0010) != 0) ) /* cube vertex 1-3 */
/* WLH 24 Oct 97
{ if (!(iz != 0 ) && vnode3 < INV_VAL && vnode1 < INV_VAL)
{ if (!(iz != 0 ) && !Float.isNaN(vnode3) && !Float.isNaN(vnode1))
*/
// test for not missing
{ if (!(iz != 0 ) && vnode3 == vnode3 && vnode1 == vnode1)
{
/* WLH 26 Oct 97
nodeDiff = vnode3 - vnode1;
cp = ( ( isovalue - vnode1 ) / nodeDiff ) + iy;
VX[0][nvet] = ix+1;
VY[0][nvet] = cp;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode1 ) / ( vnode3 - vnode1 ) );
// WLH 4 Aug 2000 - replace Samples by samples
VX[0][nvet] = (float) cp * samples[0][pt + ydim + 1] +
(1.0f-cp) * samples[0][pt + ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + 1] +
(1.0f-cp) * samples[1][pt + ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + 1] +
(1.0f-cp) * samples[2][pt + ydim];
// end WLH 4 Aug 2000 - replace Samples by samples
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + 1] +
(1.0f-cp) * auxValues[j][pt + ydim];
*/
}
P_array[ 2*xx + bellow*yy + iy*xdim + (ix+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0020) != 0) ) /* cube vertex 1-5 */
/* WLH 24 Oct 97
{ if (!(iy != 0) && vnode5 < INV_VAL && vnode1 < INV_VAL)
{ if (!(iy != 0) && !Float.isNaN(vnode5) && !Float.isNaN(vnode1))
*/
// test for not missing
{ if (!(iy != 0) && vnode5 == vnode5 && vnode1 == vnode1)
{
/* WLH 26 Oct 97
nodeDiff = vnode5 - vnode1;
cp = ( ( isovalue - vnode1 ) / nodeDiff ) + iz;
VX[0][nvet] = ix+1;
VY[0][nvet] = iy;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode1 ) / ( vnode5 - vnode1 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim] < 0) ?
((float) auxValues[j][pt + ydim]) + 256.0f :
((float) auxValues[j][pt + ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim];
*/
}
P_array[ 2*xx + 2*yy + front*zz + iy ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0040) != 0) ) /* cube vertex 2-3 */
/* WLH 24 Oct 97
{ if (!(iz != 0) && vnode3 < INV_VAL && vnode2 < INV_VAL)
{ if (!(iz != 0) && !Float.isNaN(vnode3) && !Float.isNaN(vnode2))
*/
// test for not missing
{ if (!(iz != 0) && vnode3 == vnode3 && vnode2 == vnode2)
{
/* WLH 26 Oct 97
nodeDiff = vnode3 - vnode2;
cp = ( ( isovalue - vnode2 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy+1;
VZ[0][nvet] = iz;
*/
cp = ( ( isovalue - vnode2 ) / ( vnode3 - vnode2 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + 1] +
(1.0f-cp) * samples[0][pt + 1];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + 1] +
(1.0f-cp) * samples[1][pt + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + 1] +
(1.0f-cp) * samples[2][pt + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + 1] +
(1.0f-cp) * auxValues[j][pt + 1];
*/
}
P_array[ bellow*xx + ix*ydim + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0080) != 0) ) /* cube vertex 2-6 */
/* WLH 24 Oct 97
{ if (!(ix != 0) && vnode6 < INV_VAL && vnode2 < INV_VAL)
{ if (!(ix != 0) && !Float.isNaN(vnode6) && !Float.isNaN(vnode2))
*/
// test for not missing
{ if (!(ix != 0) && vnode6 == vnode6 && vnode2 == vnode2)
{
/* WLH 26 Oct 97
nodeDiff = vnode6 - vnode2;
cp = ( ( isovalue - vnode2 ) / nodeDiff ) + iz;
VX[0][nvet] = ix;
VY[0][nvet] = iy+1;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode2 ) / ( vnode6 - vnode2 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + 1];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1] < 0) ?
((float) auxValues[j][pt + 1]) + 256.0f :
((float) auxValues[j][pt + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + 1];
*/
}
P_array[ 2*xx + 2*yy + rear*zz + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0100) != 0) ) /* cube vertex 3-7 */
/* WLH 24 Oct 97
{ if (vnode7 < INV_VAL && vnode3 < INV_VAL)
{ if (!Float.isNaN(vnode7) && !Float.isNaN(vnode3))
*/
// test for not missing
{ if (vnode7 == vnode7 && vnode3 == vnode3)
{
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode3;
cp = ( ( isovalue - vnode3 ) / nodeDiff ) + iz;
VX[0][nvet] = ix+1;
VY[0][nvet] = iy+1;
VZ[0][nvet] = cp;
*/
cp = ( ( isovalue - vnode3 ) / ( vnode7 - vnode3 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim + 1];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim + 1];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim + 1];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim + 1] < 0) ?
((float) auxValues[j][pt + ydim + 1]) + 256.0f :
((float) auxValues[j][pt + ydim + 1]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim + 1];
*/
}
P_array[ 2*xx + 2*yy + front*zz + (iy+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0200) != 0) ) /* cube vertex 4-5 */
/* WLH 24 Oct 97
{ if (!(iy != 0) && vnode5 < INV_VAL && vnode4 < INV_VAL)
{ if (!(iy != 0) && !Float.isNaN(vnode5) && !Float.isNaN(vnode4))
*/
// test for not missing
{ if (!(iy != 0) && vnode5 == vnode5 && vnode4 == vnode4)
{
/* WLH 26 Oct 97
nodeDiff = vnode5 - vnode4;
cp = ( ( isovalue - vnode4 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode4 ) / ( vnode5 - vnode4 ) );
VX[0][nvet] = (float) cp * samples[0][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + xdim_x_ydim];
*/
}
P_array[ above*xx + ix*ydim + iy ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0400) != 0) ) /* cube vertex 4-6 */
/* WLH 24 Oct 97
{ if (!(ix != 0) && vnode6 < INV_VAL && vnode4 < INV_VAL)
{ if (!(ix != 0) && !Float.isNaN(vnode6) && !Float.isNaN(vnode4))
*/
// test for not missing
{ if (!(ix != 0) && vnode6 == vnode6 && vnode4 == vnode4)
{
/* WLH 26 Oct 97
nodeDiff = vnode6 - vnode4;
cp = ( ( isovalue - vnode4 ) / nodeDiff ) + iy;
VX[0][nvet] = ix;
VY[0][nvet] = cp;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode4 ) / ( vnode6 - vnode4 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + xdim_x_ydim];
*/
}
P_array[ 2*xx + above*yy + iy*xdim + ix ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x0800) != 0) ) /* cube vertex 5-7 */
/* WLH 24 Oct 97
{ if (vnode7 < INV_VAL && vnode5 < INV_VAL)
{ if (!Float.isNaN(vnode7) && !Float.isNaN(vnode5))
*/
// test for not missing
{ if (vnode7 == vnode7 && vnode5 == vnode5)
{
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode5;
cp = ( ( isovalue - vnode5 ) / nodeDiff ) + iy;
VX[0][nvet] = ix+1;
VY[0][nvet] = cp;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode5 ) / ( vnode7 - vnode5 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + ydim + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + ydim + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + ydim + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + ydim + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + ydim + xdim_x_ydim];
*/
}
P_array[ 2*xx + above*yy + iy*xdim + (ix+1) ] = nvet;
nvet++;
}
}
if ( ((pol_edges[ptFLAG[ncube]][3] & 0x1000) != 0) ) /* cube vertex 6-7 */
/* WLH 24 Oct 97
{ if (vnode7 < INV_VAL && vnode6 < INV_VAL)
{ if (!Float.isNaN(vnode7) && !Float.isNaN(vnode6))
*/
// test for not missing
{ if (vnode7 == vnode7 && vnode6 == vnode6)
{
/* WLH 26 Oct 97
nodeDiff = vnode7 - vnode6;
cp = ( ( isovalue - vnode6 ) / nodeDiff ) + ix;
VX[0][nvet] = cp;
VY[0][nvet] = iy+1;
VZ[0][nvet] = iz+1;
*/
cp = ( ( isovalue - vnode6 ) / ( vnode7 - vnode6 ) );
VX[0][nvet] = (float) cp * samples[0][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[0][pt + 1 + xdim_x_ydim];
VY[0][nvet] = (float) cp * samples[1][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[1][pt + 1 + xdim_x_ydim];
VZ[0][nvet] = (float) cp * samples[2][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * samples[2][pt + 1 + xdim_x_ydim];
for (int j=0; j<naux; j++) {
t = (int) ( cp * ((auxValues[j][pt + 1 + ydim + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + ydim + xdim_x_ydim]) ) +
(1.0f - cp) * ((auxValues[j][pt + 1 + xdim_x_ydim] < 0) ?
((float) auxValues[j][pt + 1 + xdim_x_ydim]) + 256.0f :
((float) auxValues[j][pt + 1 + xdim_x_ydim]) ) );
tempaux[j][nvet] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
tempaux[j][nvet] = (float) cp * auxValues[j][pt + 1 + ydim + xdim_x_ydim] +
(1.0f-cp) * auxValues[j][pt + 1 + xdim_x_ydim];
*/
}
P_array[ above*xx + ix*ydim + (iy+1) ] = nvet;
nvet++;
}
}
}
/* end find_vertex_invalid_cube(ncube); */
}
} /* end if (exist_polygon_in_cube(ncube)) */
ncube++; pt++;
} /* end for ( iy = 0; iy < ydim - 1; iy++ ) */
/* swap_planes(Z,rear,front); */
caseA = rear;
rear = front;
front = caseA;
pt++;
/* end swap_planes(Z,rear,front); */
} /* end for ( ix = 0; ix < xdim - 1; ix++ ) */
/* swap_planes(XY,bellow,above); */
caseA = bellow;
bellow = above;
above = caseA;
pt += ydim;
/* end swap_planes(XY,bellow,above); */
} /* end for ( iz = 0; iz < zdim - 1; iz++ ) */
// copy tempaux array into auxLevels array
for (int i=0; i<naux; i++) {
auxLevels[i] = new byte[nvet];
System.arraycopy(tempaux[i], 0, auxLevels[i], 0, nvet);
}
return nvet;
}
public static void make_normals( float[] VX, float[] VY, float[] VZ,
float[] NX, float[] NY, float[] NZ, int nvertex,
int npolygons, float[] Pnx, float[] Pny, float[] Pnz,
float[] NxA, float[] NxB, float[] NyA, float[] NyB,
float[] NzA, float[] NzB,
int[] Pol_f_Vert, int[] Vert_f_Pol)
throws VisADException {
int i, k, n;
int i1, i2, ix, iy, iz, ixb, iyb, izb;
int max_vert_per_pol, swap_flag;
float x, y, z, a, minimum_area, len;
int iv[] = new int[3];
for ( i = 0; i < nvertex; i++ ) {
NX[i] = 0;
NY[i] = 0;
NZ[i] = 0;
}
// WLH 12 Nov 2001
// minimum_area = (float) ((1.e-4 > EPS_0) ? 1.e-4 : EPS_0);
minimum_area = Float.MIN_VALUE;
/* Calculate maximum number of vertices per polygon */
k = 6; n = 7*npolygons;
while ( TRUE )
{ for (i=k+7; i<n; i+=7)
if (Vert_f_Pol[i] > Vert_f_Pol[k]) break;
if (i >= n) break; k = i;
}
max_vert_per_pol = Vert_f_Pol[k];
/* Calculate the Normals vector components for each Polygon */
/*$dir vector */
for ( i=0; i<npolygons; i++) { /* Vectorized */
if (Vert_f_Pol[6+i*7]>0) { /* check for valid polygon added by BEP 2-13-92 */
NxA[i] = VX[Vert_f_Pol[1+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyA[i] = VY[Vert_f_Pol[1+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzA[i] = VZ[Vert_f_Pol[1+i*7]] - VZ[Vert_f_Pol[0+i*7]];
}
}
swap_flag = 0;
for ( k = 2; k < max_vert_per_pol; k++ )
{
if (swap_flag==0) {
/*$dir no_recurrence */ /* Vectorized */
for ( i=0; i<npolygons; i++ ) {
if ( Vert_f_Pol[k+i*7] >= 0 ) {
NxB[i] = VX[Vert_f_Pol[k+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyB[i] = VY[Vert_f_Pol[k+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzB[i] = VZ[Vert_f_Pol[k+i*7]] - VZ[Vert_f_Pol[0+i*7]];
Pnx[i] = NyA[i]*NzB[i] - NzA[i]*NyB[i];
Pny[i] = NzA[i]*NxB[i] - NxA[i]*NzB[i];
Pnz[i] = NxA[i]*NyB[i] - NyA[i]*NxB[i];
NxA[i] = Pnx[i]*Pnx[i] + Pny[i]*Pny[i] + Pnz[i]*Pnz[i];
if (NxA[i] > minimum_area) {
Pnx[i] /= NxA[i];
Pny[i] /= NxA[i];
Pnz[i] /= NxA[i];
}
}
}
}
else { /* swap_flag!=0 */
/*$dir no_recurrence */ /* Vectorized */
for ( i=0; i<npolygons; i++ ) {
if ( Vert_f_Pol[k+i*7] >= 0 ) {
NxA[i] = VX[Vert_f_Pol[k+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyA[i] = VY[Vert_f_Pol[k+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzA[i] = VZ[Vert_f_Pol[k+i*7]] - VZ[Vert_f_Pol[0+i*7]];
Pnx[i] = NyB[i]*NzA[i] - NzB[i]*NyA[i];
Pny[i] = NzB[i]*NxA[i] - NxB[i]*NzA[i];
Pnz[i] = NxB[i]*NyA[i] - NyB[i]*NxA[i];
NxB[i] = Pnx[i]*Pnx[i] + Pny[i]*Pny[i] + Pnz[i]*Pnz[i];
if (NxB[i] > minimum_area) {
Pnx[i] /= NxB[i];
Pny[i] /= NxB[i];
Pnz[i] /= NxB[i];
}
}
}
}
/* This Loop <CAN'T> be Vectorized */
for ( i=0; i<npolygons; i++ )
{ if (Vert_f_Pol[k+i*7] >= 0)
{ iv[0] = Vert_f_Pol[0+i*7];
iv[1] = Vert_f_Pol[(k-1)+i*7];
iv[2] = Vert_f_Pol[k+i*7];
x = Pnx[i]; y = Pny[i]; z = Pnz[i];
// Update the origin vertex
NX[iv[0]] += x; NY[iv[0]] += y; NZ[iv[0]] += z;
// Update the vertex that defines the first vector
NX[iv[1]] += x; NY[iv[1]] += y; NZ[iv[1]] += z;
// Update the vertex that defines the second vector
NX[iv[2]] += x; NY[iv[2]] += y; NZ[iv[2]] += z;
}
}
swap_flag = ( (swap_flag != 0) ? 0 : 1 );
}
/* Normalize the Normals */
for ( i=0; i<nvertex; i++ ) /* Vectorized */
{ len = (float) Math.sqrt(NX[i]*NX[i] + NY[i]*NY[i] + NZ[i]*NZ[i]);
if (len > EPS_0) {
NX[i] /= len;
NY[i] /= len;
NZ[i] /= len;
}
}
}
public static int poly_triangle_stripe( int[] vet_pol, int[] Tri_Stripe,
int nvertex, int npolygons, int[] Pol_f_Vert,
int[] Vert_f_Pol ) throws VisADException {
int i, j, k, m, ii, npol, cpol, idx, off, Nvt,
vA, vB, ivA, ivB, iST, last_pol;
boolean f_line_conection = false;
last_pol = 0;
npol = 0;
iST = 0;
ivB = 0;
for (i=0; i<npolygons; i++) vet_pol[i] = 1; /* Vectorized */
while (TRUE)
{
/* find_unselected_pol(cpol); */
for (cpol=last_pol; cpol<npolygons; cpol++) {
if ( (vet_pol[cpol] != 0) ) break;
}
if (cpol == npolygons) {
cpol = -1;
}
else {
last_pol = cpol;
}
/* end find_unselected_pol(cpol); */
if (cpol < 0) break;
/* update_polygon */
vet_pol[cpol] = 0;
/* end update_polygon */
/* get_vertices_of_pol(cpol,Vt,Nvt); { */
Nvt = Vert_f_Pol[(j=cpol*7)+6];
off = j;
/* } */
/* end get_vertices_of_pol(cpol,Vt,Nvt); { */
for (ivA=0; ivA<Nvt; ivA++) {
ivB = (((ivA+1)==Nvt) ? 0:(ivA+1));
/* get_pol_vert(Vt[ivA],Vt[ivB],npol) { */
npol = -1;
if (Vert_f_Pol[ivA+off]>=0 && Vert_f_Pol[ivB+off]>=0) {
i=Vert_f_Pol[ivA+off]*9;
k=i+Pol_f_Vert [i+8];
j=Vert_f_Pol[ivB+off]*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j <m ) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
(vet_pol[Pol_f_Vert[i]] != 0) ) {
npol=Pol_f_Vert [i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
/* } */
/* end get_pol_vert(Vt[ivA],Vt[ivB],npol) { */
if (npol >= 0) break;
}
/* insert polygon alone */
if (npol < 0)
{ /*ptT = NTAB + STAB[Nvt-3];*/
idx = STAB[Nvt-3];
if (iST > 0)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx]+off];
}
else f_line_conection = true; /* WLH 3-9-95 added */
for (ii=0; ii< ((Nvt < 6) ? Nvt:6); ii++) {
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx++]+off];
}
continue;
}
if (( (ivB != 0) && ivA==(ivB-1)) || ( !(ivB != 0) && ivA==Nvt-1)) {
/* ptT = ITAB + STAB[Nvt-3] + (ivB+1)*Nvt; */
idx = STAB[Nvt-3] + (ivB+1)*Nvt;
if (f_line_conection)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[idx-1]+off];
f_line_conection = false;
}
for (ii=0; ii<((Nvt < 6) ? Nvt:6); ii++) {
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[--idx]+off];
}
}
else {
/* ptT = NTAB + STAB[Nvt-3] + (ivB+1)*Nvt; */
idx = STAB[Nvt-3] + (ivB+1)*Nvt;
if (f_line_conection)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx-1]+off];
f_line_conection = false;
}
for (ii=0; ii<((Nvt < 6) ? Nvt:6); ii++) {
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[--idx]+off];
}
}
vB = Tri_Stripe[iST-1];
vA = Tri_Stripe[iST-2];
cpol = npol;
while (TRUE)
{
/* get_vertices_of_pol(cpol,Vt,Nvt) { */
Nvt = Vert_f_Pol [(j=cpol*7)+6];
off = j;
/* } */
/* update_polygon(cpol) */
vet_pol[cpol] = 0;
for (ivA=0; ivA<Nvt && Vert_f_Pol[ivA+off]!=vA; ivA++);
for (ivB=0; ivB<Nvt && Vert_f_Pol[ivB+off]!=vB; ivB++);
if (( (ivB != 0) && ivA==(ivB-1)) || (!(ivB != 0) && ivA==Nvt-1)) {
/* ptT = NTAB + STAB[Nvt-3] + ivA*Nvt + 2; */
idx = STAB[Nvt-3] + ivA*Nvt + 2;
for (ii=2; ii<((Nvt < 6) ? Nvt:6); ii++)
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx++]+off];
}
else {
/* ptT = ITAB + STAB[Nvt-3] + ivA*Nvt + 2; */
idx = STAB[Nvt-3] + ivA*Nvt + 2;
for (ii=2; ii<((Nvt < 6) ? Nvt:6); ii++)
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[idx++]+off];
}
vB = Tri_Stripe[iST-1];
vA = Tri_Stripe[iST-2];
/* get_pol_vert(vA,vB,cpol) { */
cpol = -1;
if (vA>=0 && vB>=0) {
i=vA*9;
k=i+Pol_f_Vert [i+8];
j=vB*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j<m) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] && (vet_pol[Pol_f_Vert[i]] != 0) ) {
cpol=Pol_f_Vert[i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
/* } */
if (cpol < 0) {
vA = Tri_Stripe[iST-3];
/* get_pol_vert(vA,vB,cpol) { */
cpol = -1;
if (vA>=0 && vB>=0) {
i=vA*9;
k=i+Pol_f_Vert [i+8];
j=vB*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j<m) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
(vet_pol[Pol_f_Vert[i]] != 0) ) {
cpol=Pol_f_Vert[i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
/* } */
if (cpol < 0) {
f_line_conection = true;
break;
}
else {
// WLH 5 May 2004 - fix bug vintage 1990 or 91
if (iST > 0) {
Tri_Stripe[iST] = Tri_Stripe[iST-1];
iST++;
}
Tri_Stripe[iST++] = vA;
i = vA;
vA = vB;
vB = i;
}
}
}
}
return iST;
}
public static float[] makeNormals(float[] coordinates, int LengthX,
int LengthY) {
int Length = LengthX * LengthY;
float[] normals = new float[3 * Length];
int k = 0;
int ki, kj;
int LengthX3 = 3 * LengthX;
for (int i=0; i<LengthY; i++) {
for (int j=0; j<LengthX; j++) {
float c0 = coordinates[k];
float c1 = coordinates[k+1];
float c2 = coordinates[k+2];
float n0 = 0.0f;
float n1 = 0.0f;
float n2 = 0.0f;
float n, m, m0, m1, m2, q0, q1, q2;
for (int ip = -1; ip<=1; ip += 2) {
for (int jp = -1; jp<=1; jp += 2) {
int ii = i + ip;
int jj = j + jp;
if (0 <= ii && ii < LengthY && 0 <= jj && jj < LengthX) {
ki = k + ip * LengthX3;
kj = k + jp * 3;
m0 = (coordinates[kj+2] - c2) * (coordinates[ki+1] - c1) -
(coordinates[kj+1] - c1) * (coordinates[ki+2] - c2);
m1 = (coordinates[kj] - c0) * (coordinates[ki+2] - c2) -
(coordinates[kj+2] - c2) * (coordinates[ki] - c0);
m2 = (coordinates[kj+1] - c1) * (coordinates[ki] - c0) -
(coordinates[kj] - c0) * (coordinates[ki+1] - c1);
m = (float) Math.sqrt(m0 * m0 + m1 * m1 + m2 * m2);
if (ip == jp) {
q0 = m0 / m;
q1 = m1 / m;
q2 = m2 / m;
}
else {
q0 = -m0 / m;
q1 = -m1 / m;
q2 = -m2 / m;
}
if (q0 == q0) {
n0 += q0;
n1 += q1;
n2 += q2;
}
else {
/*
System.out.println("m = " + m + " " + m0 + " " + m1 + " " + m2 + " " +
n0 + " " + n1 + " " + n2 + " ip, jp = " + ip + " " + jp);
System.out.println("k = " + k + " " + ki + " " + kj);
System.out.println("c = " + c0 + " " + c1 + " " + c2);
System.out.println("coordinates[ki] = " + coordinates[ki] + " " +
coordinates[ki+1] + " " + coordinates[ki+2]); // == c ??
System.out.println("coordinates[kj] = " + coordinates[kj] + " " +
coordinates[kj+1] + " " + coordinates[kj+2]);
System.out.println("LengthX = " + LengthX + " " + LengthY + " " +
LengthX3);
*/
}
}
}
}
n = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
normals[k] = n0 / n;
normals[k+1] = n1 / n;
normals[k+2] = n2 / n;
if (normals[k] != normals[k]) {
normals[k] = 0.0f;
normals[k+1] = 0.0f;
normals[k+2] = -1.0f;
}
/*
System.out.println("makeNormals " + k + " " + normals[k] + " " + normals[k+1] + " " +
normals[k+2]);
*/
k += 3;
} // end for (int j=0; j<LengthX; j++)
} // end for (int i=0; i<LengthY; i++)
return normals;
}
/** create a 2-D GeometryArray from this Set and color_values */
public VisADGeometryArray make2DGeometry(byte[][] color_values,
boolean indexed) throws VisADException {
if (DomainDimension != 3) {
throw new SetException("Gridded3DSet.make2DGeometry: " +
"DomainDimension must be 3");
}
if (ManifoldDimension != 2) {
throw new SetException("Gridded3DSet.make2DGeometry: " +
"ManifoldDimension must be 2");
}
if (LengthX < 2 || LengthY < 2) {
/* WLH 26 June 98
throw new SetException("Gridded3DSet.make2DGeometry: " +
"LengthX and LengthY must be at least 2");
*/
VisADPointArray array = new VisADPointArray();
setGeometryArray(array, 4, color_values);
return array;
}
if (indexed) {
VisADIndexedTriangleStripArray array =
new VisADIndexedTriangleStripArray();
// set up indices into 2-D grid
array.indexCount = (LengthY - 1) * (2 * LengthX);
int[] indices = new int[array.indexCount];
array.stripVertexCounts = new int[LengthY - 1];
int k = 0;
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX;
array.stripVertexCounts[i] = 2 * LengthX;
for (int j=0; j<LengthX; j++) {
indices[k++] = m;
indices[k++] = m + LengthX;
m++;
}
}
array.indices = indices;
// take the garbage out
indices = null;
// set coordinates and colors
setGeometryArray(array, 4, color_values);
// calculate normals
float[] coordinates = array.coordinates;
float[] normals = makeNormals(coordinates, LengthX, LengthY);
array.normals = normals;
return array;
}
else { // if (!indexed)
VisADTriangleStripArray array = new VisADTriangleStripArray();
float[][] samples = getSamples(false);
array.stripVertexCounts = new int[LengthY - 1];
for (int i=0; i<LengthY-1; i++) {
array.stripVertexCounts[i] = 2 * LengthX;
}
int len = (LengthY - 1) * (2 * LengthX);
array.vertexCount = len;
// calculate normals
float[] normals = new float[3 * Length];
int k = 0;
int k3 = 0;
int ki, kj;
for (int i=0; i<LengthY; i++) {
for (int j=0; j<LengthX; j++) {
float c0 = samples[0][k3];
float c1 = samples[1][k3];
float c2 = samples[2][k3];
float n0 = 0.0f;
float n1 = 0.0f;
float n2 = 0.0f;
float n, m, m0, m1, m2;
boolean any = false;
for (int ip = -1; ip<=1; ip += 2) {
for (int jp = -1; jp<=1; jp += 2) {
int ii = i + ip;
int jj = j + jp;
ki = k3 + ip * LengthX;
kj = k3 + jp;
if (0 <= ii && ii < LengthY && 0 <= jj && jj < LengthX &&
samples[0][ki] == samples[0][ki] &&
samples[1][ki] == samples[1][ki] &&
samples[2][ki] == samples[2][ki] &&
samples[0][kj] == samples[0][kj] &&
samples[1][kj] == samples[1][kj] &&
samples[2][kj] == samples[2][kj]) {
any = true;
m0 = (samples[2][kj] - c2) * (samples[1][ki] - c1) -
(samples[1][kj] - c1) * (samples[2][ki] - c2);
m1 = (samples[0][kj] - c0) * (samples[2][ki] - c2) -
(samples[2][kj] - c2) * (samples[0][ki] - c0);
m2 = (samples[1][kj] - c1) * (samples[0][ki] - c0) -
(samples[0][kj] - c0) * (samples[1][ki] - c1);
m = (float) Math.sqrt(m0 * m0 + m1 * m1 + m2 * m2);
if (ip == jp) {
n0 += m0 / m;
n1 += m1 / m;
n2 += m2 / m;
}
else {
n0 -= m0 / m;
n1 -= m1 / m;
n2 -= m2 / m;
}
}
}
}
n = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
if (any) {
normals[k] = n0 / n;
normals[k+1] = n1 / n;
normals[k+2] = n2 / n;
}
else {
normals[k] = 0.0f;
normals[k+1] = 0.0f;
normals[k+2] = 1.0f;
}
k += 3;
k3++;
} // end for (int j=0; j<LengthX; j++)
} // end for (int i=0; i<LengthY; i++)
array.normals = new float[3 * len];
// shuffle normals into array.normals
k = 0;
int LengthX3 = 3 * LengthX;
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX3;
for (int j=0; j<LengthX; j++) {
array.normals[k] = normals[m];
array.normals[k+1] = normals[m+1];
array.normals[k+2] = normals[m+2];
array.normals[k+3] = normals[m+LengthX3];
array.normals[k+4] = normals[m+LengthX3+1];
array.normals[k+5] = normals[m+LengthX3+2];
k += 6;
m += 3;
}
}
normals = null;
/*
int nmiss = 0;
int nsmall = 0;
*/
array.coordinates = new float[3 * len];
// shuffle samples into array.coordinates
k = 0;
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX;
for (int j=0; j<LengthX; j++) {
array.coordinates[k] = samples[0][m];
array.coordinates[k+1] = samples[1][m];
array.coordinates[k+2] = samples[2][m];
array.coordinates[k+3] = samples[0][m+LengthX];
array.coordinates[k+4] = samples[1][m+LengthX];
array.coordinates[k+5] = samples[2][m+LengthX];
/*
if (samples[0][m] != samples[0][m] ||
samples[1][m] != samples[1][m] ||
samples[2][m] != samples[2][m]) nmiss++;
double size = Math.sqrt(samples[0][m] * samples[0][m] +
samples[1][m] * samples[1][m] +
samples[2][m] * samples[2][m]);
if (size < 0.2) nsmall++;
*/
k += 6;
m++;
}
}
// System.out.println("make2DGeometry nmiss = " + nmiss + " nsmall = " + nsmall);
if (color_values != null) {
int color_length = color_values.length;
array.colors = new byte[color_length * len];
// shuffle samples into array.coordinates
k = 0;
if (color_length == 4) {
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX;
for (int j=0; j<LengthX; j++) {
array.colors[k] = color_values[0][m];
array.colors[k+1] = color_values[1][m];
array.colors[k+2] = color_values[2][m];
array.colors[k+3] = color_values[3][m];
k += color_length;
array.colors[k] = color_values[0][m+LengthX];
array.colors[k+1] = color_values[1][m+LengthX];
array.colors[k+2] = color_values[2][m+LengthX];
array.colors[k+3] = color_values[3][m+LengthX];
k += color_length;
m++;
}
}
}
else { // if (color_length == 3)
for (int i=0; i<LengthY-1; i++) {
int m = i * LengthX;
for (int j=0; j<LengthX; j++) {
array.colors[k] = color_values[0][m];
array.colors[k+1] = color_values[1][m];
array.colors[k+2] = color_values[2][m];
k += color_length;
array.colors[k] = color_values[0][m+LengthX];
array.colors[k+1] = color_values[1][m+LengthX];
array.colors[k+2] = color_values[2][m+LengthX];
k += color_length;
m++;
}
}
}
}
return array;
} // end if (!indexed)
}
public Object cloneButType(MathType type) throws VisADException {
if (ManifoldDimension == 3) {
return new Gridded3DSet(type, Samples, LengthX, LengthY, LengthZ,
DomainCoordinateSystem, SetUnits, SetErrors);
}
else if (ManifoldDimension == 2) {
return new Gridded3DSet(type, Samples, LengthX, LengthY,
DomainCoordinateSystem, SetUnits, SetErrors);
}
else {
return new Gridded3DSet(type, Samples, LengthX,
DomainCoordinateSystem, SetUnits, SetErrors);
}
}
/* run 'java visad.Gridded3DSet < formatted_input_stream'
to test the Gridded3DSet class */
public static void main(String[] argv) throws VisADException {
// Define input stream
InputStreamReader inStr = new InputStreamReader(System.in);
// Define temporary integer array
int[] ints = new int[80];
try {
ints[0] = inStr.read();
}
catch(Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
int l = 0;
while (ints[l] != 10) {
try {
ints[++l] = inStr.read();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
}
// convert array of integers to array of characters
char[] chars = new char[l];
for (int i=0; i<l; i++) {
chars[i] = (char) ints[i];
}
int num_coords = Integer.parseInt(new String(chars));
// num_coords should be a nice round number
if (num_coords % 9 != 0) {
throw new SetException("Gridded3DSet: input coordinates"
+" must be divisible by 9 for main function testing routines.");
}
// Define size of Samples array
float[][] samp = new float[3][num_coords];
System.out.println("num_dimensions = 3, num_coords = "+num_coords+"\n");
// Skip blank line
try {
ints[0] = inStr.read();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
for (int c=0; c<num_coords; c++) {
for (int d=0; d<3; d++) {
l = 0;
try {
ints[0] = inStr.read();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
while ( (ints[l] != 32) && (ints[l] != 10) ) {
try {
ints[++l] = inStr.read();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
}
chars = new char[l];
for (int i=0; i<l; i++) {
chars[i] = (char) ints[i];
}
samp[d][c] = (Float.valueOf(new String(chars))).floatValue();
}
}
// do EOF stuff
try {
inStr.close();
}
catch (Exception e) {
throw new SetException("Gridded3DSet: "+e);
}
// Set up instance of Gridded3DSet
RealType vis_xcoord = RealType.getRealType("xcoord");
RealType vis_ycoord = RealType.getRealType("ycoord");
RealType vis_zcoord = RealType.getRealType("zcoord");
RealType[] vis_array = {vis_xcoord, vis_ycoord, vis_zcoord};
RealTupleType vis_tuple = new RealTupleType(vis_array);
Gridded3DSet gSet3D = new Gridded3DSet(vis_tuple, samp,
3, 3, num_coords/9);
System.out.println("Lengths = 3 3 " + num_coords/9 + " wedge = ");
int[] wedge = gSet3D.getWedge();
for (int i=0; i<wedge.length; i++) System.out.println(" " + wedge[i]);
// print out Samples information
System.out.println("Samples ("+gSet3D.LengthX+" x "+gSet3D.LengthY
+" x "+gSet3D.LengthZ+"):");
for (int i=0; i<gSet3D.LengthX*gSet3D.LengthY*gSet3D.LengthZ; i++) {
System.out.println("#"+i+":\t"+gSet3D.Samples[0][i]
+", "+gSet3D.Samples[1][i]
+", "+gSet3D.Samples[2][i]);
}
// Test gridToValue function
System.out.println("\ngridToValue test:");
int myLengthX = gSet3D.LengthX+1;
int myLengthY = gSet3D.LengthY+1;
int myLengthZ = gSet3D.LengthZ+1;
float[][] myGrid = new float[3][myLengthX*myLengthY*myLengthZ];
for (int k=0; k<myLengthZ; k++) {
for (int j=0; j<myLengthY; j++) {
for (int i=0; i<myLengthX; i++) {
int index = k*myLengthY*myLengthX+j*myLengthX+i;
myGrid[0][index] = i-0.5f;
myGrid[1][index] = j-0.5f;
myGrid[2][index] = k-0.5f;
if (myGrid[0][index] < 0) myGrid[0][index] += 0.1;
if (myGrid[1][index] < 0) myGrid[1][index] += 0.1;
if (myGrid[2][index] < 0) myGrid[2][index] += 0.1;
if (myGrid[0][index] > gSet3D.LengthX-1) myGrid[0][index] -= 0.1;
if (myGrid[1][index] > gSet3D.LengthY-1) myGrid[1][index] -= 0.1;
if (myGrid[2][index] > gSet3D.LengthZ-1) myGrid[2][index] -= 0.1;
}
}
}
float[][] myValue = gSet3D.gridToValue(myGrid);
for (int i=0; i<myLengthX*myLengthY*myLengthZ; i++) {
System.out.println("("+((float) Math.round(1000000
*myGrid[0][i]) /1000000)+", "
+((float) Math.round(1000000
*myGrid[1][i]) /1000000)+", "
+((float) Math.round(1000000
*myGrid[2][i]) /1000000)+") \t--> "
+((float) Math.round(1000000
*myValue[0][i]) /1000000)+", "
+((float) Math.round(1000000
*myValue[1][i]) /1000000)+", "
+((float) Math.round(1000000
*myValue[2][i]) /1000000));
}
// Test valueToGrid function
System.out.println("\nvalueToGrid test:");
float[][] gridTwo = gSet3D.valueToGrid(myValue);
for (int i=0; i<gridTwo[0].length; i++) {
System.out.print(((float) Math.round(1000000
*myValue[0][i]) /1000000)+", "
+((float) Math.round(1000000
*myValue[1][i]) /1000000)+", "
+((float) Math.round(1000000
*myValue[2][i]) /1000000)+"\t--> (");
if (Float.isNaN(gridTwo[0][i])) {
System.out.print("NaN, ");
}
else {
System.out.print(((float) Math.round(1000000
*gridTwo[0][i]) /1000000)+", ");
}
if (Float.isNaN(gridTwo[1][i])) {
System.out.print("NaN, ");
}
else {
System.out.print(((float) Math.round(1000000
*gridTwo[1][i]) /1000000)+", ");
}
if (Float.isNaN(gridTwo[2][i])) {
System.out.println("NaN)");
}
else {
System.out.println(((float) Math.round(1000000
*gridTwo[2][i]) /1000000)+")");
}
}
System.out.println();
}
/* Here's the output with sample file Gridded3D.txt:
iris 28% java visad.Gridded3DSet < Gridded3D.txt
num_dimensions = 3, num_coords = 27
Lengths = 3 3 3 wedge =
0
1
2
5
4
3
. . .
Samples (3 x 3 x 3):
#0: 18.629837, 8.529864, 10.997844
#1: 42.923097, 10.123978, 11.198275
. . .
#25: 32.343298, 39.600872, 36.238975
#26: 49.919754, 40.119875, 36.018752
gridToValue test:
(-0.4, -0.4, -0.4) --> 10.819755, -0.172592, 5.179111
(0.5, -0.4, -0.4) --> 32.683689, 1.262111, 5.359499
. . .
(1.5, 2.4, 2.4) --> 43.844996, 48.904708, 40.008508
(2.4, 2.4, 2.4) --> 59.663807, 49.37181, 39.810308
valueToGrid test:
10.819755, -0.172592, 5.179111 --> (-0.4, -0.4, -0.4)
32.683689, 1.262111, 5.359499 --> (0.5, -0.4, -0.4)
. . .
43.844996, 48.904708, 40.008508 --> (1.5, 2.4, 2.4)
59.663807, 49.37181, 39.810308 --> (2.4, 2.4, 2.4)
iris 29%
*/
}
|
diff --git a/src/java/org/apache/nutch/parse/ParserChecker.java b/src/java/org/apache/nutch/parse/ParserChecker.java
index fce48cfc..aa2674bd 100644
--- a/src/java/org/apache/nutch/parse/ParserChecker.java
+++ b/src/java/org/apache/nutch/parse/ParserChecker.java
@@ -1,143 +1,143 @@
/**
* 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.nutch.parse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.SignatureFactory;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.Protocol;
import org.apache.nutch.protocol.ProtocolFactory;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.StringUtil;
/**
* Parser checker, useful for testing parser.
*
* @author John Xing
*/
public class ParserChecker implements Tool {
public static final Logger LOG = LoggerFactory.getLogger(ParserChecker.class);
public ParserChecker() {
}
Configuration conf = null;
public int run(String[] args) throws Exception {
boolean dumpText = false;
boolean force = false;
String contentType = null;
String url = null;
String usage = "Usage: ParserChecker [-dumpText] [-forceAs mimeType] url";
if (args.length == 0) {
System.err.println(usage);
System.exit(-1);
}
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-forceAs")) {
force = true;
contentType = args[++i];
} else if (args[i].equals("-dumpText")) {
dumpText = true;
} else if (i != args.length - 1) {
System.err.println(usage);
System.exit(-1);
} else {
url = args[i];
}
}
if (LOG.isInfoEnabled()) {
LOG.info("fetching: " + url);
}
ProtocolFactory factory = new ProtocolFactory(conf);
Protocol protocol = factory.getProtocol(url);
Content content = protocol.getProtocolOutput(new Text(url),
new CrawlDatum()).getContent();
if (content == null) {
System.err.println("Can't fetch URL successfully");
return (-1);
}
if (force) {
content.setContentType(contentType);
} else {
contentType = content.getContentType();
}
if (contentType == null) {
System.err.println("");
return (-1);
}
ParseResult parseResult = new ParseUtil(conf).parse(content);
// Calculate the signature
byte[] signature = SignatureFactory.getSignature(getConf()).calculate(content, parseResult.get(new Text(url)));
if (LOG.isInfoEnabled()) {
LOG.info("parsing: " + url);
LOG.info("contentType: " + contentType);
LOG.info("signature: " + StringUtil.toHexString(signature));
}
for (java.util.Map.Entry<Text, Parse> entry : parseResult) {
Parse parse = entry.getValue();
System.out.print("---------\nUrl\n---------------\n");
System.out.print(entry.getKey());
- System.out.print("---------\nParseData\n---------\n");
+ System.out.print("\n---------\nParseData\n---------\n");
System.out.print(parse.getData().toString());
if (dumpText) {
System.out.print("---------\nParseText\n---------\n");
System.out.print(parse.getText());
}
}
return 0;
}
@Override
public Configuration getConf() {
return conf;
}
@Override
public void setConf(Configuration c) {
conf = c;
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(NutchConfiguration.create(), new ParserChecker(),
args);
System.exit(res);
}
}
| true | true | public int run(String[] args) throws Exception {
boolean dumpText = false;
boolean force = false;
String contentType = null;
String url = null;
String usage = "Usage: ParserChecker [-dumpText] [-forceAs mimeType] url";
if (args.length == 0) {
System.err.println(usage);
System.exit(-1);
}
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-forceAs")) {
force = true;
contentType = args[++i];
} else if (args[i].equals("-dumpText")) {
dumpText = true;
} else if (i != args.length - 1) {
System.err.println(usage);
System.exit(-1);
} else {
url = args[i];
}
}
if (LOG.isInfoEnabled()) {
LOG.info("fetching: " + url);
}
ProtocolFactory factory = new ProtocolFactory(conf);
Protocol protocol = factory.getProtocol(url);
Content content = protocol.getProtocolOutput(new Text(url),
new CrawlDatum()).getContent();
if (content == null) {
System.err.println("Can't fetch URL successfully");
return (-1);
}
if (force) {
content.setContentType(contentType);
} else {
contentType = content.getContentType();
}
if (contentType == null) {
System.err.println("");
return (-1);
}
ParseResult parseResult = new ParseUtil(conf).parse(content);
// Calculate the signature
byte[] signature = SignatureFactory.getSignature(getConf()).calculate(content, parseResult.get(new Text(url)));
if (LOG.isInfoEnabled()) {
LOG.info("parsing: " + url);
LOG.info("contentType: " + contentType);
LOG.info("signature: " + StringUtil.toHexString(signature));
}
for (java.util.Map.Entry<Text, Parse> entry : parseResult) {
Parse parse = entry.getValue();
System.out.print("---------\nUrl\n---------------\n");
System.out.print(entry.getKey());
System.out.print("---------\nParseData\n---------\n");
System.out.print(parse.getData().toString());
if (dumpText) {
System.out.print("---------\nParseText\n---------\n");
System.out.print(parse.getText());
}
}
return 0;
}
| public int run(String[] args) throws Exception {
boolean dumpText = false;
boolean force = false;
String contentType = null;
String url = null;
String usage = "Usage: ParserChecker [-dumpText] [-forceAs mimeType] url";
if (args.length == 0) {
System.err.println(usage);
System.exit(-1);
}
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-forceAs")) {
force = true;
contentType = args[++i];
} else if (args[i].equals("-dumpText")) {
dumpText = true;
} else if (i != args.length - 1) {
System.err.println(usage);
System.exit(-1);
} else {
url = args[i];
}
}
if (LOG.isInfoEnabled()) {
LOG.info("fetching: " + url);
}
ProtocolFactory factory = new ProtocolFactory(conf);
Protocol protocol = factory.getProtocol(url);
Content content = protocol.getProtocolOutput(new Text(url),
new CrawlDatum()).getContent();
if (content == null) {
System.err.println("Can't fetch URL successfully");
return (-1);
}
if (force) {
content.setContentType(contentType);
} else {
contentType = content.getContentType();
}
if (contentType == null) {
System.err.println("");
return (-1);
}
ParseResult parseResult = new ParseUtil(conf).parse(content);
// Calculate the signature
byte[] signature = SignatureFactory.getSignature(getConf()).calculate(content, parseResult.get(new Text(url)));
if (LOG.isInfoEnabled()) {
LOG.info("parsing: " + url);
LOG.info("contentType: " + contentType);
LOG.info("signature: " + StringUtil.toHexString(signature));
}
for (java.util.Map.Entry<Text, Parse> entry : parseResult) {
Parse parse = entry.getValue();
System.out.print("---------\nUrl\n---------------\n");
System.out.print(entry.getKey());
System.out.print("\n---------\nParseData\n---------\n");
System.out.print(parse.getData().toString());
if (dumpText) {
System.out.print("---------\nParseText\n---------\n");
System.out.print(parse.getText());
}
}
return 0;
}
|
diff --git a/src/main/java/com/mavenlab/caspian/controller/SMRTBookingController.java b/src/main/java/com/mavenlab/caspian/controller/SMRTBookingController.java
index f914832..bfc70f7 100644
--- a/src/main/java/com/mavenlab/caspian/controller/SMRTBookingController.java
+++ b/src/main/java/com/mavenlab/caspian/controller/SMRTBookingController.java
@@ -1,658 +1,658 @@
/**
* Copyright (c) 2012 Maven Lab Private Limited. All rights reserved.
*/
package com.mavenlab.caspian.controller;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Pattern;
import com.mavenlab.caspian.dto.Address;
import com.mavenlab.caspian.dto.Booking;
import com.mavenlab.caspian.interfacing.GatewayRest;
import com.mavenlab.caspian.interfacing.Response;
import com.mavenlab.caspian.interfacing.response.AddressResponse;
import com.mavenlab.caspian.interfacing.response.ErrorResponse;
import com.mavenlab.caspian.interfacing.response.GetBookingResponse;
import com.mavenlab.caspian.model.Client;
import com.mavenlab.caspian.model.Job;
import com.mavenlab.caspian.model.Properties;
import com.mavenlab.caspian.model.TaxiCompany;
import com.mavenlab.caspian.model.TaxiType;
import com.mavenlab.caspian.session.PropertiesManager;
import com.mavenlab.caspian.util.DateUtil;
/**
* Class : LocationController.java
*
* @author <a href="mailto:[email protected]">Yogie Kurniawan</a>
* @since Aug 7, 2012 3:04:12 PM
*/
@Named("smrtBookingController")
@SessionScoped
public class SMRTBookingController implements Serializable {
private static final long serialVersionUID = -4277135961285843276L;
@Inject
private Logger log;
@PersistenceContext
private EntityManager em;
private String name;
private String fullAddress = "Singapore";
private Address address;
private List<Address> addresses = new ArrayList<Address>();
private List<TaxiType> taxiTypes = new ArrayList<TaxiType>();
private List<Booking> bookings = new ArrayList<Booking>();
private String pickupAddress;
private String pickupPoint;
@Pattern(regexp = "(8|9)[0-9]{7}", message = "MOBILE NO: Must have 8 digits and first digit must starts with 8 or 9")
private String msisdn;
private int taxiType;
private int numberOfCabs;
private boolean advanceBooking;
private Date pickupDateTime;
private String pickupDateTimeString;
private String destination;
private String schedule;
private TaxiCompany taxiCompany;
private Client client;
private String deviceId = "JnVh0lXaCgd1BBakENR6WAbBcxlntT3BccAnop4MXHJSaivfTr";
@Inject
private GatewayRest gateway;
@SuppressWarnings("unchecked")
@PostConstruct
public void init() {
taxiTypes = em.createNamedQuery("caspian.entity.TaxiType.findByCompany").setParameter("companyId", 2).getResultList();
taxiCompany = em.find(TaxiCompany.class, 2);
client = em.find(Client.class, 2);
advanceBooking = false;
schedule = Booking.NOW;
}
public void enableAdvance() {
setAdvanceBooking(Boolean.TRUE);
setSchedule(Booking.ADVANCE);
log.info("ENABLE ADVANCE BOOKING");
}
public void disableAdvance() {
setAdvanceBooking(Boolean.FALSE);
setSchedule(Booking.NOW);
log.info("DISABLE ADVANCE BOOKING");
}
public void toggleAdvBooking() {
if(advanceBooking) {
enableAdvance();
} else {
disableAdvance();
}
}
/**
* Get Taxi Category Name
*
* @param taxiType
* @return {@link String}
*/
public String getTaxiCategory(int taxiType) {
for (TaxiType t : taxiTypes) {
if (t.getCategoryId() == taxiType) {
return t.getName();
}
}
return "ANY";
}
/**
* Select a pickup address
*
* @param address
* @return String
*/
public String selectPickupAddress(String address) {
setPickupAddress(address);
return "pm:new";
}
/**
* Proceed
*
* @return String
*/
@SuppressWarnings("unchecked")
public String proceed() {
Map<String, String> props = new HashMap<String, String>();
if(advanceBooking) {
try {
if(pickupDateTimeString != null)
setPickupDateTime(DateUtil.formatToDate("dd/MM/yyyy HH:mm", pickupDateTimeString));
log.info("PICKUP DATE TIME : " + DateUtil.formatToString("dd/MM/yyyy HH:mm",pickupDateTime));
List<Properties> list = em.createNamedQuery("caspian.entity.Properties.findAll").getResultList();
for (Properties p : list) {
props.put(p.getName(), p.getValue());
}
int minBookingTime = Integer.parseInt(props.get("com.mavenlab.caspian.AdvanceBookingMinimalMinutes")); //minute
int maxBookingTime = Integer.parseInt(props.get("com.mavenlab.caspian.AdvanceBookingMaximalHours")); //hour
Date nowDate = new Date(System.currentTimeMillis());
Date dateMin = new Date(nowDate.getTime() + (minBookingTime * 60*1000));
Date dateMax = new Date(nowDate.getTime() + (maxBookingTime * 60*60*1000));
// Calendar calNow = Calendar.getInstance();
// Calendar calMin = Calendar.getInstance();
// Calendar calMax = Calendar.getInstance();
// calNow.setTimeInMillis(nowDate.getTime());
// calMin.setTimeInMillis(nowDate.getTime() + (minBookingTime * 60*1000));
// calMax.setTimeInMillis(nowDate.getTime() + (maxBookingTime *60*60*1000));
log.info("VALIDATE");
if(pickupDateTime.before(dateMin) || pickupDateTime.after(dateMax)) {
log.info("VALIDATE FAILED");
FacesContext.getCurrentInstance().addMessage("null", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Advance Booking", "Advance Booking Should be more than 30minutes and within 72hours"));
- throw new Exception("Advance Booking Should be more than 30minutes and within 72hours");
+ return "pm:new";
}
} catch(Exception e) {
e.printStackTrace();
}
}
log.info("PROCEED: " + pickupAddress);
pickupPoint = pickupPoint != null ? pickupPoint.toUpperCase() : null;
addresses = new ArrayList<Address>();
address = null;
if (pickupAddress != null && !pickupAddress.isEmpty()) {
pickupAddress = pickupAddress.toUpperCase();
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
try {
Response response = gateway.findAddresses("", msisdn, 2, taxiCompany.getId(), client.getMerchantKey(), deviceId, req.getRemoteAddr(), pickupAddress, req);
if (response instanceof ErrorResponse) {
throw new Exception(response.getMessage());
}
if (response.getStatus() > 0) {
AddressResponse res = (AddressResponse) response;
addresses = res.getAddresses().getAddresses();
if (addresses != null && addresses.size() > 1) {
return "pm:address";
} else if (addresses != null && addresses.size() == 1) {
address = addresses.get(0);
setFullAddress(address.getFullAddress());
pickupAddress = getFullAddress();
return "confirm.htm";
}
} else {
throw new Exception(response.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage("null", new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), e.getMessage()));
}
}
return "pm:new";
}
/**
* Check Status
*/
public void checkStatus() {
log.info("CHECK STATUS => " + msisdn);
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
try {
Response response = gateway.getActiveBookingList("", msisdn, 2, taxiCompany.getId(), client.getMerchantKey(), deviceId, req.getRemoteAddr(), req);
if (response instanceof ErrorResponse) {
throw new Exception(response.getMessage());
}
if (response.getStatus() > 0) {
GetBookingResponse res = (GetBookingResponse) response;
bookings = res.getBookings().getBookings();
} else {
throw new Exception(response.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage("null", new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), e.getMessage()));
}
}
/**
* Detect and Address
*/
@SuppressWarnings("rawtypes")
public void detectAddress() {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
Map map = context.getExternalContext().getRequestParameterMap();
Object parameter = map.get("fulladdress");
try {
String phoneNo = "92424086";
if (msisdn != null && !msisdn.isEmpty()) {
phoneNo = msisdn;
}
Response response = gateway.findAddresses("", phoneNo, 2, taxiCompany.getId(), client.getMerchantKey(), deviceId, req.getRemoteAddr(), parameter.toString(), req);
if (response instanceof ErrorResponse) {
throw new Exception(response.getMessage());
}
if (response.getStatus() > 0) {
AddressResponse res = (AddressResponse) response;
addresses = res.getAddresses().getAddresses();
if (addresses != null && addresses.size() > 0) {
setFullAddress(addresses.get(0).getFullAddress());
pickupAddress = getFullAddress();
} else {
setFullAddress("UNABLE TO DETECT LOCATION");
pickupAddress = null;
}
} else {
throw new Exception(response.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage("null", new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), e.getMessage()));
}
}
/**
* Cancel Booking
*/
public void cancel() {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
Map map = context.getExternalContext().getRequestParameterMap();
Object parameter = map.get("bookingId");
try {
Response response = gateway.cancelCab("", msisdn, 2, taxiCompany.getId(), client.getMerchantKey(), deviceId, req.getRemoteAddr(), parameter.toString(), req);
if (response instanceof ErrorResponse) {
throw new Exception(response.getMessage());
}
if (response.getStatus() > 0) {
log.info("SUCCESSFULLY CANCEL => " + parameter.toString());
} else {
throw new Exception(response.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage("null", new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), e.getMessage()));
}
}
public String rebooking(String jobNo) {
try {
Job job = (Job) em.createNamedQuery("caspian.entity.job.findByJobId").setParameter("jobId", Long.valueOf(jobNo)).getSingleResult();
Long bookingId = job.getBookingId();
com.mavenlab.caspian.model.Booking booking = em.find(com.mavenlab.caspian.model.Booking.class, bookingId);
setMsisdn(booking.getMsisdn());
setName(booking.getName());
String pickupaddress = booking.getBlockNo() + " " + booking.getRoadName();
if (booking.getBuildingName() != null && !booking.getBuildingName().isEmpty()) {
pickupaddress += " " + booking.getBuildingName();
}
pickupaddress += " " + booking.getPostalCode();
setPickupAddress(pickupaddress);
setPickupPoint(booking.getPickupPoint());
setNumberOfCabs(booking.getNumberOfCabs());
setTaxiType(booking.getTaxiType());
setSchedule(booking.getSchedule());
setPickupDateTimeString("");
setPickupDateTime(null);
if(booking.getSchedule().equals(Booking.ADVANCE)) {
setAdvanceBooking(true);
setDestination(booking.getDestination());
} else {
setAdvanceBooking(false);
}
return "new.htm";
} catch(Exception e) {
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage("null", new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), e.getMessage()));
}
return "pm:status";
}
/**
* Confirm Booking
*
* @return {@link String}
*/
public String confirm() {
log.info("CONFIRM: " + msisdn + "|" + address + "|" + taxiType);
log.info(client.getMerchantKey() + "|" + taxiCompany.getId());
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
try {
Response response = gateway.bookingCab("", msisdn, 2, taxiCompany.getId(), client.getMerchantKey(), deviceId, req.getRemoteAddr(), address.getBlock(), address.getRoadName(), address.getBuildingName(), address.getPostalCode(), address.getAddressReference(), pickupPoint, numberOfCabs, taxiType, schedule, DateUtil.formatToString("dd/MM/yyyy", pickupDateTime), DateUtil.formatToString("HH:mm", pickupDateTime), destination, name, req);
if (response instanceof ErrorResponse) {
throw new Exception(response.getMessage());
}
if (response.getStatus() > 0) {
return "status.htm";
} else {
throw new Exception(response.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage("null", new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), e.getMessage()));
}
return "pm:confirm";
}
/**
* @return the addresses
*/
public List<Address> getAddresses() {
return addresses;
}
/**
* @param addresses
* the addresses to set
*/
public void setAddresses(List<Address> addresses) {
this.addresses = addresses;
}
/**
* @return the fullAddress
*/
public String getFullAddress() {
return fullAddress;
}
/**
* @param fullAddress
* the fullAddress to set
*/
public void setFullAddress(String fullAddress) {
this.fullAddress = fullAddress;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the address
*/
public Address getAddress() {
return address;
}
/**
* @param address
* the address to set
*/
public void setAddress(Address address) {
this.address = address;
}
/**
* @return the pickupAddress
*/
public String getPickupAddress() {
return pickupAddress;
}
/**
* @param pickupAddress
* the pickupAddress to set
*/
public void setPickupAddress(String pickupAddress) {
this.pickupAddress = pickupAddress;
}
/**
* @return the pickupDateTimeString
*/
public String getPickupDateTimeString() {
return pickupDateTimeString;
}
/**
* @param pickupDateTimeString the pickupDateTimeString to set
*/
public void setPickupDateTimeString(String pickupDateTimeString) {
this.pickupDateTimeString = pickupDateTimeString;
}
/**
* @return the msisdn
*/
public String getMsisdn() {
return msisdn;
}
/**
* @param msisdn
* the msisdn to set
*/
public void setMsisdn(String msisdn) {
this.msisdn = msisdn;
}
/**
* @return the pickupPoint
*/
public String getPickupPoint() {
return pickupPoint;
}
/**
* @param pickupPoint
* the pickupPoint to set
*/
public void setPickupPoint(String pickupPoint) {
this.pickupPoint = pickupPoint;
}
/**
* @return the taxiType
*/
public int getTaxiType() {
return taxiType;
}
/**
* @param taxiType
* the taxiType to set
*/
public void setTaxiType(int taxiType) {
this.taxiType = taxiType;
}
/**
* @return the numberOfCabs
*/
public int getNumberOfCabs() {
return numberOfCabs;
}
/**
* @param numberOfCabs
* the numberOfCabs to set
*/
public void setNumberOfCabs(int numberOfCabs) {
this.numberOfCabs = numberOfCabs;
}
/**
* @return the advanceBooking
*/
public boolean isAdvanceBooking() {
return advanceBooking;
}
/**
* @param advanceBooking
* the advanceBooking to set
*/
public void setAdvanceBooking(boolean advanceBooking) {
this.advanceBooking = advanceBooking;
}
/**
* @return the pickupDateTime
*/
public Date getPickupDateTime() {
return pickupDateTime;
}
/**
* @param pickupDateTime
* the pickupDateTime to set
*/
public void setPickupDateTime(Date pickupDateTime) {
this.pickupDateTime = pickupDateTime;
}
/**
* @return the destination
*/
public String getDestination() {
return destination;
}
/**
* @param destination
* the destination to set
*/
public void setDestination(String destination) {
this.destination = destination;
}
/**
* @return the taxiTypes
*/
public List<TaxiType> getTaxiTypes() {
return taxiTypes;
}
/**
* @param taxiTypes
* the taxiTypes to set
*/
public void setTaxiTypes(List<TaxiType> taxiTypes) {
this.taxiTypes = taxiTypes;
}
/**
* @return the schedule
*/
public String getSchedule() {
return schedule;
}
/**
* @param schedule
* the schedule to set
*/
public void setSchedule(String schedule) {
this.schedule = schedule;
}
/**
* @return the taxiCompany
*/
public TaxiCompany getTaxiCompany() {
return taxiCompany;
}
/**
* @param taxiCompany
* the taxiCompany to set
*/
public void setTaxiCompany(TaxiCompany taxiCompany) {
this.taxiCompany = taxiCompany;
}
/**
* @return the client
*/
public Client getClient() {
return client;
}
/**
* @param client
* the client to set
*/
public void setClient(Client client) {
this.client = client;
}
/**
* @return the bookings
*/
public List<Booking> getBookings() {
return bookings;
}
/**
* @param bookings
* the bookings to set
*/
public void setBookings(List<Booking> bookings) {
this.bookings = bookings;
}
/**
* Format from Date to String
*
* @param pattern
* @param date
* @return String
*/
public static String formatToString(String pattern, Date date) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
} catch (Exception e) {
return null;
}
}
}
| true | true | public String proceed() {
Map<String, String> props = new HashMap<String, String>();
if(advanceBooking) {
try {
if(pickupDateTimeString != null)
setPickupDateTime(DateUtil.formatToDate("dd/MM/yyyy HH:mm", pickupDateTimeString));
log.info("PICKUP DATE TIME : " + DateUtil.formatToString("dd/MM/yyyy HH:mm",pickupDateTime));
List<Properties> list = em.createNamedQuery("caspian.entity.Properties.findAll").getResultList();
for (Properties p : list) {
props.put(p.getName(), p.getValue());
}
int minBookingTime = Integer.parseInt(props.get("com.mavenlab.caspian.AdvanceBookingMinimalMinutes")); //minute
int maxBookingTime = Integer.parseInt(props.get("com.mavenlab.caspian.AdvanceBookingMaximalHours")); //hour
Date nowDate = new Date(System.currentTimeMillis());
Date dateMin = new Date(nowDate.getTime() + (minBookingTime * 60*1000));
Date dateMax = new Date(nowDate.getTime() + (maxBookingTime * 60*60*1000));
// Calendar calNow = Calendar.getInstance();
// Calendar calMin = Calendar.getInstance();
// Calendar calMax = Calendar.getInstance();
// calNow.setTimeInMillis(nowDate.getTime());
// calMin.setTimeInMillis(nowDate.getTime() + (minBookingTime * 60*1000));
// calMax.setTimeInMillis(nowDate.getTime() + (maxBookingTime *60*60*1000));
log.info("VALIDATE");
if(pickupDateTime.before(dateMin) || pickupDateTime.after(dateMax)) {
log.info("VALIDATE FAILED");
FacesContext.getCurrentInstance().addMessage("null", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Advance Booking", "Advance Booking Should be more than 30minutes and within 72hours"));
throw new Exception("Advance Booking Should be more than 30minutes and within 72hours");
}
} catch(Exception e) {
e.printStackTrace();
}
}
log.info("PROCEED: " + pickupAddress);
pickupPoint = pickupPoint != null ? pickupPoint.toUpperCase() : null;
addresses = new ArrayList<Address>();
address = null;
if (pickupAddress != null && !pickupAddress.isEmpty()) {
pickupAddress = pickupAddress.toUpperCase();
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
try {
Response response = gateway.findAddresses("", msisdn, 2, taxiCompany.getId(), client.getMerchantKey(), deviceId, req.getRemoteAddr(), pickupAddress, req);
if (response instanceof ErrorResponse) {
throw new Exception(response.getMessage());
}
if (response.getStatus() > 0) {
AddressResponse res = (AddressResponse) response;
addresses = res.getAddresses().getAddresses();
if (addresses != null && addresses.size() > 1) {
return "pm:address";
} else if (addresses != null && addresses.size() == 1) {
address = addresses.get(0);
setFullAddress(address.getFullAddress());
pickupAddress = getFullAddress();
return "confirm.htm";
}
} else {
throw new Exception(response.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage("null", new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), e.getMessage()));
}
}
return "pm:new";
}
| public String proceed() {
Map<String, String> props = new HashMap<String, String>();
if(advanceBooking) {
try {
if(pickupDateTimeString != null)
setPickupDateTime(DateUtil.formatToDate("dd/MM/yyyy HH:mm", pickupDateTimeString));
log.info("PICKUP DATE TIME : " + DateUtil.formatToString("dd/MM/yyyy HH:mm",pickupDateTime));
List<Properties> list = em.createNamedQuery("caspian.entity.Properties.findAll").getResultList();
for (Properties p : list) {
props.put(p.getName(), p.getValue());
}
int minBookingTime = Integer.parseInt(props.get("com.mavenlab.caspian.AdvanceBookingMinimalMinutes")); //minute
int maxBookingTime = Integer.parseInt(props.get("com.mavenlab.caspian.AdvanceBookingMaximalHours")); //hour
Date nowDate = new Date(System.currentTimeMillis());
Date dateMin = new Date(nowDate.getTime() + (minBookingTime * 60*1000));
Date dateMax = new Date(nowDate.getTime() + (maxBookingTime * 60*60*1000));
// Calendar calNow = Calendar.getInstance();
// Calendar calMin = Calendar.getInstance();
// Calendar calMax = Calendar.getInstance();
// calNow.setTimeInMillis(nowDate.getTime());
// calMin.setTimeInMillis(nowDate.getTime() + (minBookingTime * 60*1000));
// calMax.setTimeInMillis(nowDate.getTime() + (maxBookingTime *60*60*1000));
log.info("VALIDATE");
if(pickupDateTime.before(dateMin) || pickupDateTime.after(dateMax)) {
log.info("VALIDATE FAILED");
FacesContext.getCurrentInstance().addMessage("null", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Advance Booking", "Advance Booking Should be more than 30minutes and within 72hours"));
return "pm:new";
}
} catch(Exception e) {
e.printStackTrace();
}
}
log.info("PROCEED: " + pickupAddress);
pickupPoint = pickupPoint != null ? pickupPoint.toUpperCase() : null;
addresses = new ArrayList<Address>();
address = null;
if (pickupAddress != null && !pickupAddress.isEmpty()) {
pickupAddress = pickupAddress.toUpperCase();
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
try {
Response response = gateway.findAddresses("", msisdn, 2, taxiCompany.getId(), client.getMerchantKey(), deviceId, req.getRemoteAddr(), pickupAddress, req);
if (response instanceof ErrorResponse) {
throw new Exception(response.getMessage());
}
if (response.getStatus() > 0) {
AddressResponse res = (AddressResponse) response;
addresses = res.getAddresses().getAddresses();
if (addresses != null && addresses.size() > 1) {
return "pm:address";
} else if (addresses != null && addresses.size() == 1) {
address = addresses.get(0);
setFullAddress(address.getFullAddress());
pickupAddress = getFullAddress();
return "confirm.htm";
}
} else {
throw new Exception(response.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage("null", new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), e.getMessage()));
}
}
return "pm:new";
}
|
diff --git a/src/com/jme/animation/Bone.java b/src/com/jme/animation/Bone.java
index f955359d3..85a7b907b 100755
--- a/src/com/jme/animation/Bone.java
+++ b/src/com/jme/animation/Bone.java
@@ -1,341 +1,341 @@
/*
* Copyright (c) 2003-2006 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme.animation;
import java.io.IOException;
import java.util.ArrayList;
import com.jme.math.Matrix3f;
import com.jme.math.Matrix4f;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.scene.Controller;
import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.util.export.InputCapsule;
import com.jme.util.export.JMEExporter;
import com.jme.util.export.JMEImporter;
import com.jme.util.export.OutputCapsule;
import com.jme.util.export.Savable;
/**
* Bone defines a scenegraph node that defines a single bone object within
* a skeletal system. The bone defines a bind matrix which will transform the
* bone into the pose position. This bine matrix is used to position the bone
* with the skin, then move the skin to its world position.
*
*/
public class Bone extends Node implements Savable {
private static final long serialVersionUID = 1L;
protected Matrix4f bindMatrix = new Matrix4f();
protected AnimationController animationController;
protected static final Vector3f workVectA = new Vector3f();
protected static final Matrix4f transform = new Matrix4f();
protected transient Vector3f oldScale = new Vector3f();
protected transient Vector3f oldTran = new Vector3f();
protected transient Quaternion oldRot = new Quaternion();
protected transient boolean boneChanged = false;
protected transient boolean skinRoot = false;
protected transient ArrayList<BoneChangeListener> changeListeners;
public Bone() {
super();
}
/**
* Creates a new bone with the supplied name.
* @param name the name of this bone.
*/
public Bone(String name) {
super(name);
}
/**
* creates a new bone with a given name and a bind matrix.
* @param name the name of the bone.
* @param bindMatrix the bind matrix of the bone.
*/
public Bone(String name, Matrix4f bindMatrix) {
super(name);
this.bindMatrix = bindMatrix;
}
/**
* applyBone affects a given vertex by its current world position. This
* is done by first placing the vertex into the pose position using the
* bind matrix, then transforming it into world space using the bone's
* world rotation and world translation.
* @param inf the influence this bone affects the vertex. Including its
* offset and weight.
* @param vstore the vertex to manipulate.
* @param nstore the normal to manipulate.
*/
public void applyBone(BoneInfluence inf, Vector3f vstore, Vector3f nstore) {
transform.loadIdentity();
transform.setRotationQuaternion(worldRotation);
transform.setTranslation(worldTranslation);
if(inf.vOffset != null) {
workVectA.set(inf.vOffset);
bindMatrix.inverseTranslateVect(workVectA);
bindMatrix.inverseRotateVect(workVectA);
transform.rotateVect(workVectA);
transform.translateVect(workVectA);
workVectA.multLocal(inf.weight);
vstore.addLocal(workVectA);
}
if (inf.nOffset != null) {
workVectA.set(inf.nOffset);
bindMatrix.inverseRotateVect(workVectA);
- transform.inverseRotateVect(workVectA);
+ transform.rotateVect(workVectA);
workVectA.multLocal(inf.weight);
nstore.addLocal(workVectA);
}
}
/**
* retrieves the bind matrix of this bone.
* @return the bind matrix of this bone.
*/
public Matrix4f getBindMatrix() {
return bindMatrix;
}
/**
* sets the bind matrix of this bone.
* @param bindMatrix the bind matrix of this bone.
*/
public void setBindMatrix(Matrix4f bindMatrix) {
this.bindMatrix = bindMatrix;
}
public void addController(Controller c) {
super.addController(c);
if(c instanceof AnimationController) {
((AnimationController)c).setSkeleton(this);
animationController = (AnimationController)c;
}
}
public void updateGeometricState(float time, boolean initiator) {
if(parent == null || !(parent instanceof Bone)) {
resetChangeValues();
}
super.updateGeometricState(time, initiator);
}
public void resetChangeValues() {
boneChanged = false;
for(int i = 0, maxSize = getQuantity(); i < maxSize; i++) {
if(getChild(i) instanceof Bone) {
((Bone)getChild(i)).resetChangeValues();
}
}
}
@Override
public void updateWorldVectors() {
if (parent instanceof Bone) {
super.updateWorldVectors();
} else {
Node tempParent = parent;
parent = null;
super.updateWorldVectors();
parent = tempParent;
}
if(skinRoot) {
if (boneChanged || hasTransformChanged()) {
fireBoneChange();
}
}
}
public AnimationController getAnimationController() {
return animationController;
}
public void write(JMEExporter e) throws IOException {
super.write(e);
OutputCapsule cap = e.getCapsule(this);
cap.write(bindMatrix, "bindMatrix", new Matrix4f());
cap.write(animationController, "animationController", null);
}
public void read(JMEImporter e) throws IOException {
super.read(e);
InputCapsule cap = e.getCapsule(this);
bindMatrix = (Matrix4f)cap.readSavable("bindMatrix", new Matrix4f());
animationController = (AnimationController)cap.readSavable("animationController", null);
}
public void revertToBind() {
worldTranslation.set(bindMatrix.toTranslationVector());
bindMatrix.toRotationQuat(worldRotation);
worldRotation.normalize();
if (children != null)
for (Spatial child : children) {
if (child instanceof Bone)
((Bone)child).revertToBind();
}
}
public Bone getRootSkeleton() {
if (parent instanceof Bone)
return ((Bone)parent).getRootSkeleton();
else return this;
}
public void addBoneListener(BoneChangeListener listener) {
if (changeListeners == null)
changeListeners = new ArrayList<BoneChangeListener>();
changeListeners.add(listener);
propogateBoneChangeToChildren(true);
skinRoot = true;
}
public void removeBoneListener(BoneChangeListener listener) {
if (changeListeners == null) {
return;
}
changeListeners.remove(listener);
propogateBoneChangeToChildren(true);
if(changeListeners.size() == 0) {
skinRoot = false;
}
}
protected int getListenerQuantity() {
if (changeListeners == null)
return 0;
else return changeListeners.size();
}
protected void fireBoneChange() {
if (changeListeners == null) return;
BoneChangeEvent event = new BoneChangeEvent(this);
for (int x = getListenerQuantity(); --x >= 0 ;) {
changeListeners.get(x).boneChanged(event);
}
}
public boolean isSkinRoot() {
return skinRoot;
}
public void setSkinRoot(boolean skinRoot) {
this.skinRoot = skinRoot;
}
public void propogateBoneChangeToParent(boolean initiator) {
if(!boneChanged || initiator) {
boneChanged = true;
if(parent != null && parent instanceof Bone) {
((Bone)parent).propogateBoneChangeToParent(false);
}
}
}
public void propogateBoneChangeToChildren(boolean initiator) {
if(!boneChanged || initiator) {
boneChanged = true;
Spatial child;
for(int i = 0, max = getQuantity(); i < max; i++) {
child = getChild(i);
if(child instanceof Bone) {
((Bone)child).propogateBoneChangeToChildren(false);
}
}
}
}
protected boolean hasTransformChanged() {
boolean rVal = false;
if (!oldRot.equals(getWorldRotation())
|| !oldTran.equals(getWorldTranslation())
|| !oldScale.equals(getWorldScale())) {
rVal = true;
oldRot.set(getWorldRotation());
oldTran.set(getWorldTranslation());
oldScale.set(getWorldScale());
}
return rVal;
}
public void propogateBoneChange(boolean initiator) {
propogateBoneChangeToParent(initiator);
propogateBoneChangeToChildren(initiator);
}
public void setLocalRotation(Matrix3f rotation) {
super.setLocalRotation(rotation);
propogateBoneChange(true);
}
public void setLocalRotation(Quaternion quaternion) {
super.setLocalRotation(quaternion);
propogateBoneChange(true);
}
public void setLocalTranslation(Vector3f localTranslation) {
super.setLocalTranslation(localTranslation);
propogateBoneChange(true);
}
public void setLocalScale(Vector3f localScale) {
super.setLocalScale(localScale);
propogateBoneChange(true);
}
public void setLocalScale(float localScale) {
super.setLocalScale(localScale);
propogateBoneChange(true);
}
}
| true | true | public void applyBone(BoneInfluence inf, Vector3f vstore, Vector3f nstore) {
transform.loadIdentity();
transform.setRotationQuaternion(worldRotation);
transform.setTranslation(worldTranslation);
if(inf.vOffset != null) {
workVectA.set(inf.vOffset);
bindMatrix.inverseTranslateVect(workVectA);
bindMatrix.inverseRotateVect(workVectA);
transform.rotateVect(workVectA);
transform.translateVect(workVectA);
workVectA.multLocal(inf.weight);
vstore.addLocal(workVectA);
}
if (inf.nOffset != null) {
workVectA.set(inf.nOffset);
bindMatrix.inverseRotateVect(workVectA);
transform.inverseRotateVect(workVectA);
workVectA.multLocal(inf.weight);
nstore.addLocal(workVectA);
}
}
| public void applyBone(BoneInfluence inf, Vector3f vstore, Vector3f nstore) {
transform.loadIdentity();
transform.setRotationQuaternion(worldRotation);
transform.setTranslation(worldTranslation);
if(inf.vOffset != null) {
workVectA.set(inf.vOffset);
bindMatrix.inverseTranslateVect(workVectA);
bindMatrix.inverseRotateVect(workVectA);
transform.rotateVect(workVectA);
transform.translateVect(workVectA);
workVectA.multLocal(inf.weight);
vstore.addLocal(workVectA);
}
if (inf.nOffset != null) {
workVectA.set(inf.nOffset);
bindMatrix.inverseRotateVect(workVectA);
transform.rotateVect(workVectA);
workVectA.multLocal(inf.weight);
nstore.addLocal(workVectA);
}
}
|
diff --git a/src/main/java/edu/cshl/schatz/jnomics/tools/GridJobMain.java b/src/main/java/edu/cshl/schatz/jnomics/tools/GridJobMain.java
index f28efac..f50f66c 100644
--- a/src/main/java/edu/cshl/schatz/jnomics/tools/GridJobMain.java
+++ b/src/main/java/edu/cshl/schatz/jnomics/tools/GridJobMain.java
@@ -1,181 +1,176 @@
package edu.cshl.schatz.jnomics.tools;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.Tool;
import org.slf4j.LoggerFactory;
import us.kbase.shock.client.BasicShockClient;
import edu.cshl.schatz.jnomics.grid.JnomicsGridJobBuilder;
import edu.cshl.schatz.jnomics.util.FileUtil;
import edu.cshl.schatz.jnomics.util.ShockUtil;
import java.io.FilenameFilter;
import java.io.File;
import java.io.InputStream;
public class GridJobMain extends Configured implements Tool {
private final static org.slf4j.Logger logger = LoggerFactory.getLogger(JnomicsGridJobBuilder.class);
private static String printUsage = "Invalid Argument! Program will now Exit... ";
private static final Map<String,Class> gridClasses =
new HashMap<String,Class>(){
{
put("tophat",AlignTophat.class);
put("Cufflinks",CufflinksSuite.class);
}
};
public static void main(String[] args) throws Exception{
String jobname = args[0].substring(args[0].lastIndexOf(":") + 1);
final String jobid = System.getenv("JOB_ID");
String userhome = System.getProperty("user.home");
Configuration conf = new Configuration();
File conffile = new File(System.getProperty("user.home")+"/" + jobname + ".xml");
logger.info(" args is " + args[0] +" jobname is " + jobname );
if (conffile.canRead()){
logger.info("Reading the Job Configuration File: " + conffile);
}
FileSystem fs1 = null;
conf.addResource(new Path(conffile.getAbsolutePath()));
String gridJob = conf.get("grid.job.name");
System.out.println(gridJob);
String[] jobparts = conf.get("grid.job.name").split("-");
String username = jobparts[0];
Path hdfs_job_path = null;
try{
URI hdfs_uri = new URI(conf.get("fs.default.name"));
fs1 = FileSystem.get(hdfs_uri,conf,username);
hdfs_job_path = new Path( fs1.getHomeDirectory().toString());
if(gridJob.matches(".*-fastqtopege-.*")){
String in1 = conf.get("fastq1","");
String in2 = conf.get("fastq2","");
String dest = conf.get("grid.output.dir", "");
if( in1 == "" || in2 == "" || dest == ""){
throw new Exception("bad configuration");
}
Path in1p = new Path(in1);
Path in2p = new Path(in2);
Path destp = new Path(dest);
InputStream in1fs = fs1.open(in1p);
InputStream in2fs = fs1.open(in2p);
new PairedEndLoader().load(in1fs, in2fs, destp, fs1);
in1fs.close();
in2fs.close();
}else if(gridJob.matches(".*-write-.*")){
String shockurl = conf.get("shock-url","");
String shocktoken = new String(Base64.decodeBase64(conf.get("shock-token","")));
String proxy = conf.get("http-proxy","");
//ShockUtil.setHttpProxy(proxy);
logger.info("Shock url " + shockurl + " Token is " + shocktoken);
String filename = conf.get("grid.input.dir","");
logger.info("filename " + filename);
- try{
- FileUtil.copyToShock(shockurl, shocktoken,proxy, fs1 , filename);
- copyanddelete(fs1,jobid,userhome,hdfs_job_path);
- }catch(Exception e){
- e.printStackTrace();
- }
+ FileUtil.copyToShock(shockurl, shocktoken,proxy, fs1 , filename);
+ //copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else if(gridJob.matches(".*-read-.*")){
String shockurl = conf.get("shock-url","");
String shocktoken = new String(Base64.decodeBase64(conf.get("shock-token","")));
logger.info("Shock url " + shockurl + " Token is " + shocktoken);
String proxy = conf.get("http-proxy","");
//ShockUtil.setHttpProxy(proxy);
String nodeid = conf.get("grid.input.dir","");
String dest = conf.get("grid.output.dir","");
logger.info("nodeid : " + nodeid);
- try{
- FileUtil.copyFromShock(shockurl, shocktoken, proxy, fs1 , nodeid,dest);
+ FileUtil.copyFromShock(shockurl, shocktoken, proxy, fs1 , nodeid,dest);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
- }catch(Exception e){
- e.printStackTrace();
- }
+ //}catch(Exception e){
+ // e.printStackTrace();
+ //}
}else if(gridJob.matches(".*-wsupload-.*")){
System.out.println("Uploading the Expression object to Workspace");
WorkspaceUpload ws = new WorkspaceUpload(conf);
ws.uploadExpression(fs1,conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else if(gridJob.matches(".*-tophat-.*")){
System.out.println("Executing tophat");
AlignTophat tophat = new AlignTophat(conf);
tophat.prepareBinaries(fs1, conf);
tophat.align(fs1, conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else {
System.out.println("Executing Cufflinks");
CufflinksSuite cuff = new CufflinksSuite(conf);
cuff.prepareBinaries(fs1, conf);
if(gridJob.matches(".*-cufflinks-.*")){
cuff.callCufflinks(fs1,conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else if(gridJob.matches(".*-cuffmerge-.*")){
cuff.callCuffmerge(fs1,conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else if(gridJob.matches(".*-cuffdiff-.*")){
cuff.callCuffdiff(fs1,conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else if(gridJob.matches(".*-cuffcompare-.*")){
cuff.callCuffcompare(fs1,conf);
}
}
}catch(Exception e) {
// e.printStackTrace();
throw new Exception(e.toString());
}finally{
//copyanddelete(fs1,jobid,userhome,hdfs_job_path);
copyanddelete(fs1,jobid,userhome,hdfs_job_path);
fs1.close();
conffile.delete();
}
}
private static WorkspaceUpload WorkspaceUpload(Configuration conf) {
// TODO Auto-generated method stub
return null;
}
@Override
public int run(String[] args) throws Exception {
return 0;
}
public static void copyanddelete(FileSystem fs2,final String job_id, String source, Path hdfs_job_path ) throws Exception {
File[] files = new File(source).listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(job_id);
}
});
for(File file : files)
{
String fname = file.getName();
logger.info("Copying log files to hdfs : " + hdfs_job_path+"/"+ file.getName());
// if(!fname.endsWith("po"+job_id) && !fname.endsWith("pe"+job_id)){
fs2.copyFromLocalFile(true,new Path(file.getAbsolutePath()),hdfs_job_path);
// }else{
// logger.info("Deleting file" + file.getAbsolutePath() );
// file.delete();
// }
}
}
}
| false | true | public static void main(String[] args) throws Exception{
String jobname = args[0].substring(args[0].lastIndexOf(":") + 1);
final String jobid = System.getenv("JOB_ID");
String userhome = System.getProperty("user.home");
Configuration conf = new Configuration();
File conffile = new File(System.getProperty("user.home")+"/" + jobname + ".xml");
logger.info(" args is " + args[0] +" jobname is " + jobname );
if (conffile.canRead()){
logger.info("Reading the Job Configuration File: " + conffile);
}
FileSystem fs1 = null;
conf.addResource(new Path(conffile.getAbsolutePath()));
String gridJob = conf.get("grid.job.name");
System.out.println(gridJob);
String[] jobparts = conf.get("grid.job.name").split("-");
String username = jobparts[0];
Path hdfs_job_path = null;
try{
URI hdfs_uri = new URI(conf.get("fs.default.name"));
fs1 = FileSystem.get(hdfs_uri,conf,username);
hdfs_job_path = new Path( fs1.getHomeDirectory().toString());
if(gridJob.matches(".*-fastqtopege-.*")){
String in1 = conf.get("fastq1","");
String in2 = conf.get("fastq2","");
String dest = conf.get("grid.output.dir", "");
if( in1 == "" || in2 == "" || dest == ""){
throw new Exception("bad configuration");
}
Path in1p = new Path(in1);
Path in2p = new Path(in2);
Path destp = new Path(dest);
InputStream in1fs = fs1.open(in1p);
InputStream in2fs = fs1.open(in2p);
new PairedEndLoader().load(in1fs, in2fs, destp, fs1);
in1fs.close();
in2fs.close();
}else if(gridJob.matches(".*-write-.*")){
String shockurl = conf.get("shock-url","");
String shocktoken = new String(Base64.decodeBase64(conf.get("shock-token","")));
String proxy = conf.get("http-proxy","");
//ShockUtil.setHttpProxy(proxy);
logger.info("Shock url " + shockurl + " Token is " + shocktoken);
String filename = conf.get("grid.input.dir","");
logger.info("filename " + filename);
try{
FileUtil.copyToShock(shockurl, shocktoken,proxy, fs1 , filename);
copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}catch(Exception e){
e.printStackTrace();
}
}else if(gridJob.matches(".*-read-.*")){
String shockurl = conf.get("shock-url","");
String shocktoken = new String(Base64.decodeBase64(conf.get("shock-token","")));
logger.info("Shock url " + shockurl + " Token is " + shocktoken);
String proxy = conf.get("http-proxy","");
//ShockUtil.setHttpProxy(proxy);
String nodeid = conf.get("grid.input.dir","");
String dest = conf.get("grid.output.dir","");
logger.info("nodeid : " + nodeid);
try{
FileUtil.copyFromShock(shockurl, shocktoken, proxy, fs1 , nodeid,dest);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}catch(Exception e){
e.printStackTrace();
}
}else if(gridJob.matches(".*-wsupload-.*")){
System.out.println("Uploading the Expression object to Workspace");
WorkspaceUpload ws = new WorkspaceUpload(conf);
ws.uploadExpression(fs1,conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else if(gridJob.matches(".*-tophat-.*")){
System.out.println("Executing tophat");
AlignTophat tophat = new AlignTophat(conf);
tophat.prepareBinaries(fs1, conf);
tophat.align(fs1, conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else {
System.out.println("Executing Cufflinks");
CufflinksSuite cuff = new CufflinksSuite(conf);
cuff.prepareBinaries(fs1, conf);
if(gridJob.matches(".*-cufflinks-.*")){
cuff.callCufflinks(fs1,conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else if(gridJob.matches(".*-cuffmerge-.*")){
cuff.callCuffmerge(fs1,conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else if(gridJob.matches(".*-cuffdiff-.*")){
cuff.callCuffdiff(fs1,conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else if(gridJob.matches(".*-cuffcompare-.*")){
cuff.callCuffcompare(fs1,conf);
}
}
}catch(Exception e) {
// e.printStackTrace();
throw new Exception(e.toString());
}finally{
//copyanddelete(fs1,jobid,userhome,hdfs_job_path);
copyanddelete(fs1,jobid,userhome,hdfs_job_path);
fs1.close();
conffile.delete();
}
}
| public static void main(String[] args) throws Exception{
String jobname = args[0].substring(args[0].lastIndexOf(":") + 1);
final String jobid = System.getenv("JOB_ID");
String userhome = System.getProperty("user.home");
Configuration conf = new Configuration();
File conffile = new File(System.getProperty("user.home")+"/" + jobname + ".xml");
logger.info(" args is " + args[0] +" jobname is " + jobname );
if (conffile.canRead()){
logger.info("Reading the Job Configuration File: " + conffile);
}
FileSystem fs1 = null;
conf.addResource(new Path(conffile.getAbsolutePath()));
String gridJob = conf.get("grid.job.name");
System.out.println(gridJob);
String[] jobparts = conf.get("grid.job.name").split("-");
String username = jobparts[0];
Path hdfs_job_path = null;
try{
URI hdfs_uri = new URI(conf.get("fs.default.name"));
fs1 = FileSystem.get(hdfs_uri,conf,username);
hdfs_job_path = new Path( fs1.getHomeDirectory().toString());
if(gridJob.matches(".*-fastqtopege-.*")){
String in1 = conf.get("fastq1","");
String in2 = conf.get("fastq2","");
String dest = conf.get("grid.output.dir", "");
if( in1 == "" || in2 == "" || dest == ""){
throw new Exception("bad configuration");
}
Path in1p = new Path(in1);
Path in2p = new Path(in2);
Path destp = new Path(dest);
InputStream in1fs = fs1.open(in1p);
InputStream in2fs = fs1.open(in2p);
new PairedEndLoader().load(in1fs, in2fs, destp, fs1);
in1fs.close();
in2fs.close();
}else if(gridJob.matches(".*-write-.*")){
String shockurl = conf.get("shock-url","");
String shocktoken = new String(Base64.decodeBase64(conf.get("shock-token","")));
String proxy = conf.get("http-proxy","");
//ShockUtil.setHttpProxy(proxy);
logger.info("Shock url " + shockurl + " Token is " + shocktoken);
String filename = conf.get("grid.input.dir","");
logger.info("filename " + filename);
FileUtil.copyToShock(shockurl, shocktoken,proxy, fs1 , filename);
//copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else if(gridJob.matches(".*-read-.*")){
String shockurl = conf.get("shock-url","");
String shocktoken = new String(Base64.decodeBase64(conf.get("shock-token","")));
logger.info("Shock url " + shockurl + " Token is " + shocktoken);
String proxy = conf.get("http-proxy","");
//ShockUtil.setHttpProxy(proxy);
String nodeid = conf.get("grid.input.dir","");
String dest = conf.get("grid.output.dir","");
logger.info("nodeid : " + nodeid);
FileUtil.copyFromShock(shockurl, shocktoken, proxy, fs1 , nodeid,dest);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
//}catch(Exception e){
// e.printStackTrace();
//}
}else if(gridJob.matches(".*-wsupload-.*")){
System.out.println("Uploading the Expression object to Workspace");
WorkspaceUpload ws = new WorkspaceUpload(conf);
ws.uploadExpression(fs1,conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else if(gridJob.matches(".*-tophat-.*")){
System.out.println("Executing tophat");
AlignTophat tophat = new AlignTophat(conf);
tophat.prepareBinaries(fs1, conf);
tophat.align(fs1, conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else {
System.out.println("Executing Cufflinks");
CufflinksSuite cuff = new CufflinksSuite(conf);
cuff.prepareBinaries(fs1, conf);
if(gridJob.matches(".*-cufflinks-.*")){
cuff.callCufflinks(fs1,conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else if(gridJob.matches(".*-cuffmerge-.*")){
cuff.callCuffmerge(fs1,conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else if(gridJob.matches(".*-cuffdiff-.*")){
cuff.callCuffdiff(fs1,conf);
// copyanddelete(fs1,jobid,userhome,hdfs_job_path);
}else if(gridJob.matches(".*-cuffcompare-.*")){
cuff.callCuffcompare(fs1,conf);
}
}
}catch(Exception e) {
// e.printStackTrace();
throw new Exception(e.toString());
}finally{
//copyanddelete(fs1,jobid,userhome,hdfs_job_path);
copyanddelete(fs1,jobid,userhome,hdfs_job_path);
fs1.close();
conffile.delete();
}
}
|
diff --git a/patientview-parent/radar/src/main/java/org/patientview/radar/web/pages/patient/AddPatientPage.java b/patientview-parent/radar/src/main/java/org/patientview/radar/web/pages/patient/AddPatientPage.java
index 3d6a408a..7fb9e23a 100644
--- a/patientview-parent/radar/src/main/java/org/patientview/radar/web/pages/patient/AddPatientPage.java
+++ b/patientview-parent/radar/src/main/java/org/patientview/radar/web/pages/patient/AddPatientPage.java
@@ -1,198 +1,200 @@
package org.patientview.radar.web.pages.patient;
import org.apache.commons.collections.CollectionUtils;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.feedback.IFeedbackMessageFilter;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.util.ListModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.patientview.model.Patient;
import org.patientview.model.Sex;
import org.patientview.model.enums.NhsNumberType;
import org.patientview.radar.dao.generic.DiseaseGroupDao;
import org.patientview.radar.model.filter.DemographicsFilter;
import org.patientview.radar.model.generic.AddPatientModel;
import org.patientview.radar.model.user.ProfessionalUser;
import org.patientview.radar.model.user.User;
import org.patientview.radar.service.DemographicsManager;
import org.patientview.radar.service.PatientManager;
import org.patientview.radar.service.UserManager;
import org.patientview.radar.service.UtilityManager;
import org.patientview.radar.web.RadarApplication;
import org.patientview.radar.web.RadarSecuredSession;
import org.patientview.radar.web.components.ComponentHelper;
import org.patientview.radar.web.components.RadarRequiredDropdownChoice;
import org.patientview.radar.web.components.RadarRequiredTextField;
import org.patientview.radar.web.pages.BasePage;
import org.patientview.radar.web.panels.CreatePatientPanel;
import org.patientview.radar.web.panels.SelectPatientPanel;
import java.util.ArrayList;
import java.util.List;
/**
* generic add patient page
* if you select srns or mpgn then redirects to phase1 patients page otherwise goes to generic patients page
*/
@AuthorizeInstantiation({User.ROLE_PROFESSIONAL, User.ROLE_SUPER_USER})
public class AddPatientPage extends BasePage {
public static final String NHS_NUMBER_INVALID_MSG = "NHS or CHI number is not valid";
@SpringBean
private DiseaseGroupDao diseaseGroupDao;
@SpringBean
private DemographicsManager demographicsManager;
@SpringBean
private UserManager userManager;
@SpringBean
private UtilityManager utilityManager;
@SpringBean
private PatientManager patientManager;
public AddPatientPage() {
ProfessionalUser user = (ProfessionalUser) RadarSecuredSession.get().getUser();
// list of items to update in ajax submits
final List<Component> componentsToUpdateList = new ArrayList<Component>();
CompoundPropertyModel<AddPatientModel> addPatientModel =
new CompoundPropertyModel<AddPatientModel>(new AddPatientModel());
addPatientModel.getObject().setCentre(user.getCentre());
final IModel<List<Patient>> patientListModel = new ListModel<Patient>();
final SelectPatientPanel selectPatientPanel = new SelectPatientPanel("selectPatientPanel", patientListModel);
selectPatientPanel.setVisible(false);
final CreatePatientPanel createPatientPanel = new CreatePatientPanel("createPatientPanel", addPatientModel);
createPatientPanel.setVisible(false);
// create form
Form<AddPatientModel> form = new Form<AddPatientModel>("form", addPatientModel) {
final AddPatientModel model = getModelObject();
@Override
protected void onSubmit() {
// just show the user one error at a time
DemographicsFilter demographicsFilter = new DemographicsFilter();
demographicsFilter.addSearchCriteria(DemographicsFilter.UserField.NHSNO.toString(),
model.getPatientId());
// check nhs number is valid
if (!demographicsManager.isNhsNumberValidWhenUppercaseLettersAreAllowed(model.getPatientId())) {
selectPatientPanel.setVisible(false);
+ createPatientPanel.setVisible(false);
error(NHS_NUMBER_INVALID_MSG);
} else if (CollectionUtils.isNotEmpty(userManager.getPatientRadarMappings(model.getPatientId()))) {
// check that this nhsno has a mapping in the radar system
selectPatientPanel.setVisible(false);
+ createPatientPanel.setVisible(false);
error("A patient with this NHS or CHI number already exists");
}
if (!hasError()) {
patientListModel.setObject(patientManager.getPatientByNhsNumber(model.getPatientId()));
// If there is results show them otherwise hide them
if (CollectionUtils.isNotEmpty(patientListModel.getObject())) {
selectPatientPanel.setPatientModel(model);
selectPatientPanel.setVisible(true);
} else {
selectPatientPanel.setVisible(false);
}
createPatientPanel.setVisible(true);
setResponsePage(this.getPage());
}
}
};
// create components
RadarRequiredTextField id = new RadarRequiredTextField("patientId", form, componentsToUpdateList);
RadarRequiredDropdownChoice idType =
new RadarRequiredDropdownChoice("nhsNumberType", NhsNumberType.getNhsNumberTypesAsList(),
new ChoiceRenderer() {
@Override
public Object getDisplayValue(Object object) {
return ((NhsNumberType) object).getName();
}
@Override
public String getIdValue(Object object, int index) {
return ((NhsNumberType) object).getId() + "";
}
}, form, componentsToUpdateList);
RadarRequiredDropdownChoice diseaseGroup =
new RadarRequiredDropdownChoice("diseaseGroup", diseaseGroupDao.getAll(),
new ChoiceRenderer<Sex>("name", "id"), form, componentsToUpdateList);
Label pageNumber = new Label("pageNumber", RadarApplication.ADD_PATIENT_PAGE_N0 + "");
// submit link
AjaxSubmitLink submit = new AjaxSubmitLink("submit") {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdateList);
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdateList);
}
};
// feedback panel
final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback", new IFeedbackMessageFilter() {
public boolean accept(FeedbackMessage feedbackMessage) {
String message = feedbackMessage.getMessage().toString();
return message != null && message.length() > 0;
}
});
feedbackPanel.setOutputMarkupPlaceholderTag(true);
componentsToUpdateList.add(feedbackPanel);
final WebMarkupContainer guidanceContainer = new WebMarkupContainer("guidanceContainer");
guidanceContainer.setOutputMarkupPlaceholderTag(true);
guidanceContainer.setVisible(true);
guidanceContainer.add(
new ExternalLink("consentFormsAndDiseaseGroupsCriteriaLink",
"http://www.rarerenal.org/join/criteria-and-consent/"));
guidanceContainer.add(
new ExternalLink("enrollingAPatientGuideLink", "http://rarerenal.org/radar-registry/" +
"radar-registry-background-information/radar-recruitment-guide/"));
// add the components
form.add(id, idType, diseaseGroup, submit, feedbackPanel, guidanceContainer);
add(form, selectPatientPanel, createPatientPanel, pageNumber);
}
public void load() {
}
}
| false | true | public AddPatientPage() {
ProfessionalUser user = (ProfessionalUser) RadarSecuredSession.get().getUser();
// list of items to update in ajax submits
final List<Component> componentsToUpdateList = new ArrayList<Component>();
CompoundPropertyModel<AddPatientModel> addPatientModel =
new CompoundPropertyModel<AddPatientModel>(new AddPatientModel());
addPatientModel.getObject().setCentre(user.getCentre());
final IModel<List<Patient>> patientListModel = new ListModel<Patient>();
final SelectPatientPanel selectPatientPanel = new SelectPatientPanel("selectPatientPanel", patientListModel);
selectPatientPanel.setVisible(false);
final CreatePatientPanel createPatientPanel = new CreatePatientPanel("createPatientPanel", addPatientModel);
createPatientPanel.setVisible(false);
// create form
Form<AddPatientModel> form = new Form<AddPatientModel>("form", addPatientModel) {
final AddPatientModel model = getModelObject();
@Override
protected void onSubmit() {
// just show the user one error at a time
DemographicsFilter demographicsFilter = new DemographicsFilter();
demographicsFilter.addSearchCriteria(DemographicsFilter.UserField.NHSNO.toString(),
model.getPatientId());
// check nhs number is valid
if (!demographicsManager.isNhsNumberValidWhenUppercaseLettersAreAllowed(model.getPatientId())) {
selectPatientPanel.setVisible(false);
error(NHS_NUMBER_INVALID_MSG);
} else if (CollectionUtils.isNotEmpty(userManager.getPatientRadarMappings(model.getPatientId()))) {
// check that this nhsno has a mapping in the radar system
selectPatientPanel.setVisible(false);
error("A patient with this NHS or CHI number already exists");
}
if (!hasError()) {
patientListModel.setObject(patientManager.getPatientByNhsNumber(model.getPatientId()));
// If there is results show them otherwise hide them
if (CollectionUtils.isNotEmpty(patientListModel.getObject())) {
selectPatientPanel.setPatientModel(model);
selectPatientPanel.setVisible(true);
} else {
selectPatientPanel.setVisible(false);
}
createPatientPanel.setVisible(true);
setResponsePage(this.getPage());
}
}
};
// create components
RadarRequiredTextField id = new RadarRequiredTextField("patientId", form, componentsToUpdateList);
RadarRequiredDropdownChoice idType =
new RadarRequiredDropdownChoice("nhsNumberType", NhsNumberType.getNhsNumberTypesAsList(),
new ChoiceRenderer() {
@Override
public Object getDisplayValue(Object object) {
return ((NhsNumberType) object).getName();
}
@Override
public String getIdValue(Object object, int index) {
return ((NhsNumberType) object).getId() + "";
}
}, form, componentsToUpdateList);
RadarRequiredDropdownChoice diseaseGroup =
new RadarRequiredDropdownChoice("diseaseGroup", diseaseGroupDao.getAll(),
new ChoiceRenderer<Sex>("name", "id"), form, componentsToUpdateList);
Label pageNumber = new Label("pageNumber", RadarApplication.ADD_PATIENT_PAGE_N0 + "");
// submit link
AjaxSubmitLink submit = new AjaxSubmitLink("submit") {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdateList);
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdateList);
}
};
// feedback panel
final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback", new IFeedbackMessageFilter() {
public boolean accept(FeedbackMessage feedbackMessage) {
String message = feedbackMessage.getMessage().toString();
return message != null && message.length() > 0;
}
});
feedbackPanel.setOutputMarkupPlaceholderTag(true);
componentsToUpdateList.add(feedbackPanel);
final WebMarkupContainer guidanceContainer = new WebMarkupContainer("guidanceContainer");
guidanceContainer.setOutputMarkupPlaceholderTag(true);
guidanceContainer.setVisible(true);
guidanceContainer.add(
new ExternalLink("consentFormsAndDiseaseGroupsCriteriaLink",
"http://www.rarerenal.org/join/criteria-and-consent/"));
guidanceContainer.add(
new ExternalLink("enrollingAPatientGuideLink", "http://rarerenal.org/radar-registry/" +
"radar-registry-background-information/radar-recruitment-guide/"));
// add the components
form.add(id, idType, diseaseGroup, submit, feedbackPanel, guidanceContainer);
add(form, selectPatientPanel, createPatientPanel, pageNumber);
}
| public AddPatientPage() {
ProfessionalUser user = (ProfessionalUser) RadarSecuredSession.get().getUser();
// list of items to update in ajax submits
final List<Component> componentsToUpdateList = new ArrayList<Component>();
CompoundPropertyModel<AddPatientModel> addPatientModel =
new CompoundPropertyModel<AddPatientModel>(new AddPatientModel());
addPatientModel.getObject().setCentre(user.getCentre());
final IModel<List<Patient>> patientListModel = new ListModel<Patient>();
final SelectPatientPanel selectPatientPanel = new SelectPatientPanel("selectPatientPanel", patientListModel);
selectPatientPanel.setVisible(false);
final CreatePatientPanel createPatientPanel = new CreatePatientPanel("createPatientPanel", addPatientModel);
createPatientPanel.setVisible(false);
// create form
Form<AddPatientModel> form = new Form<AddPatientModel>("form", addPatientModel) {
final AddPatientModel model = getModelObject();
@Override
protected void onSubmit() {
// just show the user one error at a time
DemographicsFilter demographicsFilter = new DemographicsFilter();
demographicsFilter.addSearchCriteria(DemographicsFilter.UserField.NHSNO.toString(),
model.getPatientId());
// check nhs number is valid
if (!demographicsManager.isNhsNumberValidWhenUppercaseLettersAreAllowed(model.getPatientId())) {
selectPatientPanel.setVisible(false);
createPatientPanel.setVisible(false);
error(NHS_NUMBER_INVALID_MSG);
} else if (CollectionUtils.isNotEmpty(userManager.getPatientRadarMappings(model.getPatientId()))) {
// check that this nhsno has a mapping in the radar system
selectPatientPanel.setVisible(false);
createPatientPanel.setVisible(false);
error("A patient with this NHS or CHI number already exists");
}
if (!hasError()) {
patientListModel.setObject(patientManager.getPatientByNhsNumber(model.getPatientId()));
// If there is results show them otherwise hide them
if (CollectionUtils.isNotEmpty(patientListModel.getObject())) {
selectPatientPanel.setPatientModel(model);
selectPatientPanel.setVisible(true);
} else {
selectPatientPanel.setVisible(false);
}
createPatientPanel.setVisible(true);
setResponsePage(this.getPage());
}
}
};
// create components
RadarRequiredTextField id = new RadarRequiredTextField("patientId", form, componentsToUpdateList);
RadarRequiredDropdownChoice idType =
new RadarRequiredDropdownChoice("nhsNumberType", NhsNumberType.getNhsNumberTypesAsList(),
new ChoiceRenderer() {
@Override
public Object getDisplayValue(Object object) {
return ((NhsNumberType) object).getName();
}
@Override
public String getIdValue(Object object, int index) {
return ((NhsNumberType) object).getId() + "";
}
}, form, componentsToUpdateList);
RadarRequiredDropdownChoice diseaseGroup =
new RadarRequiredDropdownChoice("diseaseGroup", diseaseGroupDao.getAll(),
new ChoiceRenderer<Sex>("name", "id"), form, componentsToUpdateList);
Label pageNumber = new Label("pageNumber", RadarApplication.ADD_PATIENT_PAGE_N0 + "");
// submit link
AjaxSubmitLink submit = new AjaxSubmitLink("submit") {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdateList);
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdateList);
}
};
// feedback panel
final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback", new IFeedbackMessageFilter() {
public boolean accept(FeedbackMessage feedbackMessage) {
String message = feedbackMessage.getMessage().toString();
return message != null && message.length() > 0;
}
});
feedbackPanel.setOutputMarkupPlaceholderTag(true);
componentsToUpdateList.add(feedbackPanel);
final WebMarkupContainer guidanceContainer = new WebMarkupContainer("guidanceContainer");
guidanceContainer.setOutputMarkupPlaceholderTag(true);
guidanceContainer.setVisible(true);
guidanceContainer.add(
new ExternalLink("consentFormsAndDiseaseGroupsCriteriaLink",
"http://www.rarerenal.org/join/criteria-and-consent/"));
guidanceContainer.add(
new ExternalLink("enrollingAPatientGuideLink", "http://rarerenal.org/radar-registry/" +
"radar-registry-background-information/radar-recruitment-guide/"));
// add the components
form.add(id, idType, diseaseGroup, submit, feedbackPanel, guidanceContainer);
add(form, selectPatientPanel, createPatientPanel, pageNumber);
}
|
diff --git a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/tools/merger/actor/ActorMergerSDF.java b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/tools/merger/actor/ActorMergerSDF.java
index e4c2dd413..c3c596a4c 100644
--- a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/tools/merger/actor/ActorMergerSDF.java
+++ b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/tools/merger/actor/ActorMergerSDF.java
@@ -1,466 +1,466 @@
/*
* Copyright (c) 2010, EPFL
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the EPFL nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package net.sf.orcc.tools.merger.actor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.orcc.df.Action;
import net.sf.orcc.df.Actor;
import net.sf.orcc.df.Connection;
import net.sf.orcc.df.DfFactory;
import net.sf.orcc.df.Network;
import net.sf.orcc.df.Pattern;
import net.sf.orcc.df.Port;
import net.sf.orcc.df.util.DfSwitch;
import net.sf.orcc.graph.Vertex;
import net.sf.orcc.ir.Block;
import net.sf.orcc.ir.BlockBasic;
import net.sf.orcc.ir.BlockWhile;
import net.sf.orcc.ir.Def;
import net.sf.orcc.ir.ExprBinary;
import net.sf.orcc.ir.Expression;
import net.sf.orcc.ir.InstAssign;
import net.sf.orcc.ir.InstLoad;
import net.sf.orcc.ir.InstStore;
import net.sf.orcc.ir.IrFactory;
import net.sf.orcc.ir.OpBinary;
import net.sf.orcc.ir.Procedure;
import net.sf.orcc.ir.Type;
import net.sf.orcc.ir.Use;
import net.sf.orcc.ir.Var;
import net.sf.orcc.ir.util.AbstractIrVisitor;
import net.sf.orcc.ir.util.IrUtil;
import net.sf.orcc.moc.CSDFMoC;
import net.sf.orcc.moc.Invocation;
import net.sf.orcc.moc.MocFactory;
import net.sf.orcc.moc.SDFMoC;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.util.EcoreUtil.Copier;
/**
* This class defines the transformation from a network of SDF actors into a
* single cluster actor.
*
* @author Ghislain Roquier
* @author Herve Yviquel
*
*/
public class ActorMergerSDF extends DfSwitch<Actor> {
/**
* This class defines a transformation to update the FIFO accesses.
*
* @author Ghislain Roquier
*
*/
public class ChangeFifoArrayAccess extends AbstractIrVisitor<Void> {
private Procedure body;
private Map<Var, Integer> loads;
private Pattern oldInputPattern;
private Pattern oldOutputPattern;
private Map<Var, Integer> stores;
/**
* Create a new visitor able to update the FIFO accesses.
*
* @param action
* the action containing the old patterns
* @param body
* the procedure to update
*/
public ChangeFifoArrayAccess(Action action, Procedure body) {
this.body = body;
this.oldInputPattern = action.getInputPattern();
this.oldOutputPattern = action.getOutputPattern();
}
@Override
public Void caseInstLoad(InstLoad load) {
Use use = load.getSource();
Var var = use.getVariable();
Port port = oldInputPattern.getPort(var);
if (port != null) {
if (buffersMap.containsKey(port)) {
var = buffersMap.get(port);
} else {
var = inputPattern.getVariable(portsMap.get(port));
}
int cns = oldInputPattern.getNumTokens(port);
loads.put(var, cns);
use.setVariable(var);
List<Expression> indexes = load.getIndexes();
Expression e1 = irFactory.createExprVar(body.getLocal(var
.getName() + "_r"));
Expression e2 = IrUtil.copy(indexes.get(0));
Expression bop = irFactory.createExprBinary(e1, OpBinary.PLUS,
e2, e1.getType());
indexes.set(0, bop);
}
return null;
}
@Override
public Void caseInstStore(InstStore store) {
Def def = store.getTarget();
Var var = def.getVariable();
Port port = oldOutputPattern.getPort(var);
if (port != null) {
if (buffersMap.containsKey(port)) {
var = buffersMap.get(port);
} else {
var = outputPattern.getVariable(portsMap.get(port));
}
int prd = oldOutputPattern.getNumTokens(port);
stores.put(var, prd);
def.setVariable(var);
Expression e1 = irFactory.createExprVar(body.getLocal(var
.getName() + "_w"));
Expression e2 = IrUtil.copy(store.getIndexes().get(0));
Expression bop = irFactory.createExprBinary(e1, OpBinary.PLUS,
e2, e1.getType());
store.getIndexes().set(0, bop);
}
port = oldInputPattern.getPort(var);
if (port != null) {
if (buffersMap.containsKey(port)) {
var = buffersMap.get(port);
} else {
var = inputPattern.getPortToVarMap()
.get(portsMap.get(port));
}
int cns = oldInputPattern.getNumTokens(port);
stores.put(var, cns);
def.setVariable(var);
Expression e1 = irFactory.createExprVar(body.getLocal(var
.getName() + "_r"));
Expression e2 = IrUtil.copy(store.getIndexes().get(0));
Expression bop = irFactory.createExprBinary(e1, OpBinary.PLUS,
e2, e1.getType());
store.getIndexes().set(0, bop);
}
return null;
}
@Override
public Void caseProcedure(Procedure procedure) {
loads = new HashMap<Var, Integer>();
stores = new HashMap<Var, Integer>();
super.caseProcedure(procedure);
// Update indexes
for (Map.Entry<Var, Integer> entry : loads.entrySet()) {
Var var = entry.getKey();
int cns = entry.getValue();
Var readVar = body.getLocal(var.getName() + "_r");
ExprBinary incr = irFactory.createExprBinary(
irFactory.createExprVar(readVar), OpBinary.PLUS,
irFactory.createExprInt(cns), readVar.getType());
InstAssign assign = irFactory.createInstAssign(readVar, incr);
procedure.getLast().add(assign);
}
for (Map.Entry<Var, Integer> entry : stores.entrySet()) {
Var var = entry.getKey();
int prd = entry.getValue();
Var readVar = body.getLocal(var.getName() + "_w");
ExprBinary incr = irFactory.createExprBinary(
irFactory.createExprVar(readVar), OpBinary.PLUS,
irFactory.createExprInt(prd), readVar.getType());
InstAssign assign = irFactory.createInstAssign(readVar, incr);
procedure.getLast().add(assign);
}
return null;
}
}
private static final DfFactory dfFactory = DfFactory.eINSTANCE;
private static final IrFactory irFactory = IrFactory.eINSTANCE;
private Actor superActor;
private Pattern inputPattern;
private Pattern outputPattern;
private Map<Port, Var> buffersMap = new HashMap<Port, Var>();
private Map<Port, Port> portsMap = new HashMap<Port, Port>();
private Copier copier;
private int depth;
private SASLoopScheduler scheduler;
/**
* Creates a new merger for connected SDF actor.
*
* @param scheduler
* the pre-initialized single appearance schedule
* @param copier
* the associated copier
*/
public ActorMergerSDF(SASLoopScheduler scheduler, Copier copier) {
this.scheduler = scheduler;
this.copier = copier;
}
@Override
public Actor caseNetwork(Network network) {
superActor = dfFactory.createActor();
buffersMap = new HashMap<Port, Var>();
portsMap = new HashMap<Port, Port>();
superActor.setName(network.getName());
SDFMoC sdfMoC = MocFactory.eINSTANCE.createSDFMoC();
superActor.setMoC(sdfMoC);
// Create input/output ports
for (Port port : network.getInputs()) {
Port portCopy = (Port) copier.copy(port);
Connection connection = (Connection) port.getOutgoing().get(0);
Actor tgt = connection.getTarget().getAdapter(Actor.class);
CSDFMoC moc = (CSDFMoC) tgt.getMoC();
int cns = scheduler.getRepetitions(tgt)
* moc.getNumTokensConsumed(connection.getTargetPort());
sdfMoC.getInputPattern().setNumTokens(portCopy, cns);
superActor.getInputs().add(portCopy);
portsMap.put(connection.getTargetPort(), portCopy);
}
for (Port port : network.getOutputs()) {
Port portCopy = (Port) copier.copy(port);
Connection connection = (Connection) port.getIncoming().get(0);
Actor src = connection.getSource().getAdapter(Actor.class);
CSDFMoC moc = (CSDFMoC) src.getMoC();
int prd = scheduler.getRepetitions(src)
* moc.getNumTokensProduced(connection.getSourcePort());
sdfMoC.getOutputPattern().setNumTokens(portCopy, prd);
superActor.getOutputs().add(portCopy);
portsMap.put(connection.getSourcePort(), portCopy);
}
- // Move state variables and procedures
+ // Move variables and procedures
for (Vertex vertex : network.getChildren()) {
Actor actor = vertex.getAdapter(Actor.class);
- String id = actor.getName();
for (Procedure proc : new ArrayList<Procedure>(actor.getProcs())) {
- if (!proc.isNative()) {
- proc.setName(id + "_" + proc.getName());
- superActor.getProcs().add(proc);
- }
+ proc.setName(actor.getName() + "_" + proc.getName());
+ superActor.getProcs().add(proc);
}
for (Var var : new ArrayList<Var>(actor.getStateVars())) {
superActor.addStateVar(var);
}
+ for (Var param : new ArrayList<Var>(actor.getParameters())) {
+ superActor.addStateVar(param);
+ }
}
// Create the merged action
inputPattern = dfFactory.createPattern();
for (Port port : superActor.getInputs()) {
int numTokens = sdfMoC.getNumTokensConsumed(port);
Type type = irFactory.createTypeList(numTokens,
EcoreUtil.copy(port.getType()));
Var var = irFactory.createVar(0, type, port.getName(), true);
inputPattern.setNumTokens(port, numTokens);
inputPattern.setVariable(port, var);
}
outputPattern = dfFactory.createPattern();
for (Port port : superActor.getOutputs()) {
int numTokens = sdfMoC.getNumTokensProduced(port);
Type type = irFactory.createTypeList(numTokens,
EcoreUtil.copy(port.getType()));
Var var = irFactory.createVar(0, type, port.getName(), true);
outputPattern.setNumTokens(port, numTokens);
outputPattern.setVariable(port, var);
}
Pattern peekPattern = dfFactory.createPattern();
Procedure scheduler = irFactory.createProcedure(
"isSchedulable_mergedAction", 0, irFactory.createTypeBool());
scheduler.getLast().add(
irFactory.createInstReturn(irFactory.createExprBool(true)));
Procedure body = createBody();
Action action = dfFactory.createAction("mergedAction", inputPattern,
outputPattern, peekPattern, scheduler, body);
superActor.getActions().add(action);
superActor.getActionsOutsideFsm().add(action);
return superActor;
}
/**
* Creates the body of the static action.
*
* @return the body of the static action
*/
private Procedure createBody() {
Procedure body = irFactory.createProcedure("mergedAction", 0,
irFactory.createTypeVoid());
// Create counters for inputs
for (Port port : superActor.getInputs()) {
Var readIdx = body.newTempLocalVariable(
irFactory.createTypeInt(32), port.getName() + "_r");
readIdx.setInitialValue(irFactory.createExprInt(0));
}
// Create counters for outputs
for (Port port : superActor.getOutputs()) {
Var writeIdx = body.newTempLocalVariable(
irFactory.createTypeInt(32), port.getName() + "_w");
writeIdx.setInitialValue(irFactory.createExprInt(0));
}
int index = 0;
// Create buffers and counters for inner connections
for (Connection conn : scheduler.getMaxTokens().keySet()) {
String name = "buffer_" + index++;
// create inner buffer
int size = scheduler.getMaxTokens().get(conn);
Type eltType = conn.getSourcePort().getType();
Type type = irFactory.createTypeList(size, eltType);
Var buffer = body.newTempLocalVariable(type, name);
// create write counter
Var writeIdx = body.newTempLocalVariable(
irFactory.createTypeInt(32), name + "_w");
writeIdx.setInitialValue(irFactory.createExprInt(0));
// create read counter
Var readIdx = body.newTempLocalVariable(
irFactory.createTypeInt(32), name + "_r");
readIdx.setInitialValue(irFactory.createExprInt(0));
buffersMap.put(conn.getSourcePort(), buffer);
buffersMap.put(conn.getTargetPort(), buffer);
}
// Add loop counter(s)
int i = 0;
do { // one loop var is required even if the schedule as a depth of 0
Var counter = irFactory.createVar(0, irFactory.createTypeInt(32),
"idx_" + i, true);
body.getLocals().add(counter);
i++;
} while (i < scheduler.getDepth());
createStaticSchedule(body, scheduler.getSchedule(), body.getBlocks());
return body;
}
/**
* Create the procedural code of a static schedule.
*
* @param procedure
* the associated procedure
* @param schedule
* the current schedule
* @param blocks
* the current list of blocks
*/
private void createStaticSchedule(Procedure procedure, Schedule schedule,
List<Block> blocks) {
for (Iterand iterand : schedule.getIterands()) {
if (iterand.isActor()) {
Actor actor = iterand.getActor();
CSDFMoC moc = (CSDFMoC) actor.getMoC();
for (Invocation invocation : moc.getInvocations()) {
Action action = invocation.getAction();
// Copy local variable
for (Var var : new ArrayList<Var>(action.getBody()
.getLocals())) {
procedure.addLocal(var);
}
new ChangeFifoArrayAccess(action, procedure)
.doSwitch(action.getBody());
blocks.addAll(action.getBody().getBlocks());
}
} else {
Schedule sched = iterand.getSchedule();
Var loopVar = procedure.getLocal("idx_" + depth);
// init counter
BlockBasic block = IrUtil.getLast(blocks);
block.add(irFactory.createInstAssign(loopVar,
irFactory.createExprInt(0)));
// while loop
Expression condition = irFactory.createExprBinary(
irFactory.createExprVar(loopVar), OpBinary.LT,
irFactory.createExprInt(sched.getIterationCount()),
irFactory.createTypeBool());
BlockWhile blockWhile = irFactory.createBlockWhile();
blockWhile.setJoinBlock(irFactory.createBlockBasic());
blockWhile.setCondition(condition);
blocks.add(blockWhile);
depth++;
// recursion
createStaticSchedule(procedure, sched, blockWhile.getBlocks());
depth--;
// Increment current while loop variable
Expression expr = irFactory
.createExprBinary(irFactory.createExprVar(loopVar),
OpBinary.PLUS, irFactory.createExprInt(1),
irFactory.createTypeInt(32));
InstAssign assign = irFactory.createInstAssign(loopVar, expr);
IrUtil.getLast(blockWhile.getBlocks()).add(assign);
}
}
}
}
| false | true | public Actor caseNetwork(Network network) {
superActor = dfFactory.createActor();
buffersMap = new HashMap<Port, Var>();
portsMap = new HashMap<Port, Port>();
superActor.setName(network.getName());
SDFMoC sdfMoC = MocFactory.eINSTANCE.createSDFMoC();
superActor.setMoC(sdfMoC);
// Create input/output ports
for (Port port : network.getInputs()) {
Port portCopy = (Port) copier.copy(port);
Connection connection = (Connection) port.getOutgoing().get(0);
Actor tgt = connection.getTarget().getAdapter(Actor.class);
CSDFMoC moc = (CSDFMoC) tgt.getMoC();
int cns = scheduler.getRepetitions(tgt)
* moc.getNumTokensConsumed(connection.getTargetPort());
sdfMoC.getInputPattern().setNumTokens(portCopy, cns);
superActor.getInputs().add(portCopy);
portsMap.put(connection.getTargetPort(), portCopy);
}
for (Port port : network.getOutputs()) {
Port portCopy = (Port) copier.copy(port);
Connection connection = (Connection) port.getIncoming().get(0);
Actor src = connection.getSource().getAdapter(Actor.class);
CSDFMoC moc = (CSDFMoC) src.getMoC();
int prd = scheduler.getRepetitions(src)
* moc.getNumTokensProduced(connection.getSourcePort());
sdfMoC.getOutputPattern().setNumTokens(portCopy, prd);
superActor.getOutputs().add(portCopy);
portsMap.put(connection.getSourcePort(), portCopy);
}
// Move state variables and procedures
for (Vertex vertex : network.getChildren()) {
Actor actor = vertex.getAdapter(Actor.class);
String id = actor.getName();
for (Procedure proc : new ArrayList<Procedure>(actor.getProcs())) {
if (!proc.isNative()) {
proc.setName(id + "_" + proc.getName());
superActor.getProcs().add(proc);
}
}
for (Var var : new ArrayList<Var>(actor.getStateVars())) {
superActor.addStateVar(var);
}
}
// Create the merged action
inputPattern = dfFactory.createPattern();
for (Port port : superActor.getInputs()) {
int numTokens = sdfMoC.getNumTokensConsumed(port);
Type type = irFactory.createTypeList(numTokens,
EcoreUtil.copy(port.getType()));
Var var = irFactory.createVar(0, type, port.getName(), true);
inputPattern.setNumTokens(port, numTokens);
inputPattern.setVariable(port, var);
}
outputPattern = dfFactory.createPattern();
for (Port port : superActor.getOutputs()) {
int numTokens = sdfMoC.getNumTokensProduced(port);
Type type = irFactory.createTypeList(numTokens,
EcoreUtil.copy(port.getType()));
Var var = irFactory.createVar(0, type, port.getName(), true);
outputPattern.setNumTokens(port, numTokens);
outputPattern.setVariable(port, var);
}
Pattern peekPattern = dfFactory.createPattern();
Procedure scheduler = irFactory.createProcedure(
"isSchedulable_mergedAction", 0, irFactory.createTypeBool());
scheduler.getLast().add(
irFactory.createInstReturn(irFactory.createExprBool(true)));
Procedure body = createBody();
Action action = dfFactory.createAction("mergedAction", inputPattern,
outputPattern, peekPattern, scheduler, body);
superActor.getActions().add(action);
superActor.getActionsOutsideFsm().add(action);
return superActor;
}
| public Actor caseNetwork(Network network) {
superActor = dfFactory.createActor();
buffersMap = new HashMap<Port, Var>();
portsMap = new HashMap<Port, Port>();
superActor.setName(network.getName());
SDFMoC sdfMoC = MocFactory.eINSTANCE.createSDFMoC();
superActor.setMoC(sdfMoC);
// Create input/output ports
for (Port port : network.getInputs()) {
Port portCopy = (Port) copier.copy(port);
Connection connection = (Connection) port.getOutgoing().get(0);
Actor tgt = connection.getTarget().getAdapter(Actor.class);
CSDFMoC moc = (CSDFMoC) tgt.getMoC();
int cns = scheduler.getRepetitions(tgt)
* moc.getNumTokensConsumed(connection.getTargetPort());
sdfMoC.getInputPattern().setNumTokens(portCopy, cns);
superActor.getInputs().add(portCopy);
portsMap.put(connection.getTargetPort(), portCopy);
}
for (Port port : network.getOutputs()) {
Port portCopy = (Port) copier.copy(port);
Connection connection = (Connection) port.getIncoming().get(0);
Actor src = connection.getSource().getAdapter(Actor.class);
CSDFMoC moc = (CSDFMoC) src.getMoC();
int prd = scheduler.getRepetitions(src)
* moc.getNumTokensProduced(connection.getSourcePort());
sdfMoC.getOutputPattern().setNumTokens(portCopy, prd);
superActor.getOutputs().add(portCopy);
portsMap.put(connection.getSourcePort(), portCopy);
}
// Move variables and procedures
for (Vertex vertex : network.getChildren()) {
Actor actor = vertex.getAdapter(Actor.class);
for (Procedure proc : new ArrayList<Procedure>(actor.getProcs())) {
proc.setName(actor.getName() + "_" + proc.getName());
superActor.getProcs().add(proc);
}
for (Var var : new ArrayList<Var>(actor.getStateVars())) {
superActor.addStateVar(var);
}
for (Var param : new ArrayList<Var>(actor.getParameters())) {
superActor.addStateVar(param);
}
}
// Create the merged action
inputPattern = dfFactory.createPattern();
for (Port port : superActor.getInputs()) {
int numTokens = sdfMoC.getNumTokensConsumed(port);
Type type = irFactory.createTypeList(numTokens,
EcoreUtil.copy(port.getType()));
Var var = irFactory.createVar(0, type, port.getName(), true);
inputPattern.setNumTokens(port, numTokens);
inputPattern.setVariable(port, var);
}
outputPattern = dfFactory.createPattern();
for (Port port : superActor.getOutputs()) {
int numTokens = sdfMoC.getNumTokensProduced(port);
Type type = irFactory.createTypeList(numTokens,
EcoreUtil.copy(port.getType()));
Var var = irFactory.createVar(0, type, port.getName(), true);
outputPattern.setNumTokens(port, numTokens);
outputPattern.setVariable(port, var);
}
Pattern peekPattern = dfFactory.createPattern();
Procedure scheduler = irFactory.createProcedure(
"isSchedulable_mergedAction", 0, irFactory.createTypeBool());
scheduler.getLast().add(
irFactory.createInstReturn(irFactory.createExprBool(true)));
Procedure body = createBody();
Action action = dfFactory.createAction("mergedAction", inputPattern,
outputPattern, peekPattern, scheduler, body);
superActor.getActions().add(action);
superActor.getActionsOutsideFsm().add(action);
return superActor;
}
|
diff --git a/org/jruby/core/RbModule.java b/org/jruby/core/RbModule.java
index daf9e2b2e..d0909a44e 100644
--- a/org/jruby/core/RbModule.java
+++ b/org/jruby/core/RbModule.java
@@ -1,139 +1,139 @@
/*
* RbModule.java - No description
* Created on 04. Juli 2001, 22:53
*
* Copyright (C) 2001 Jan Arne Petersen, Stefan Matthias Aust, Alan Moore, Benoit Cerrina
* Jan Arne Petersen <[email protected]>
* Stefan Matthias Aust <[email protected]>
* Alan Moore <[email protected]>
* Benoit Cerrina <[email protected]>
*
* JRuby - http://jruby.sourceforge.net
*
* This file is part of JRuby
*
* JRuby 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.
*
* JRuby 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 JRuby; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jruby.core;
import org.jruby.*;
/**
*
* @author jpetersen
*/
public class RbModule {
public static void initModuleClass(RubyClass moduleClass) {
moduleClass.defineMethod("===", getMethod("op_eqq", RubyObject.class, false));
moduleClass.defineMethod("<=>", getMethod("op_cmp", RubyObject.class, false));
moduleClass.defineMethod("<", getMethod("op_lt", RubyObject.class, false));
moduleClass.defineMethod("<=", getMethod("op_le", RubyObject.class, false));
moduleClass.defineMethod(">", getMethod("op_gt", RubyObject.class, false));
moduleClass.defineMethod(">=", getMethod("op_ge", RubyObject.class, false));
moduleClass.defineMethod("clone", getMethod("m_clone", false));
moduleClass.defineMethod("dup", getMethod("m_dup", false));
moduleClass.defineMethod("to_s", getMethod("m_to_s", false));
moduleClass.defineMethod("included_modules", getMethod("m_included_modules", false));
moduleClass.defineMethod("name", getMethod("m_name", false));
moduleClass.defineMethod("ancestors", getMethod("m_ancestors", false));
moduleClass.definePrivateMethod("attr", getMethod("m_attr", RubySymbol.class, true));
moduleClass.definePrivateMethod("attr_reader", getMethod("m_attr_reader", true));
moduleClass.definePrivateMethod("attr_writer", getMethod("m_attr_writer", true));
moduleClass.definePrivateMethod("attr_accessor", getMethod("m_attr_accessor", true));
moduleClass.defineSingletonMethod("new", getSingletonMethod("m_new", false));
moduleClass.defineMethod("initialize", getMethod("m_initialize", true));
moduleClass.defineMethod("instance_methods", getMethod("m_instance_methods", true));
moduleClass.defineMethod("public_instance_methods", getMethod("m_instance_methods", true));
moduleClass.defineMethod("protected_instance_methods", getMethod("m_protected_instance_methods", true));
moduleClass.defineMethod("private_instance_methods", getMethod("m_private_instance_methods", true));
moduleClass.defineMethod("constants", getMethod("m_constants", false));
moduleClass.defineMethod("const_get", getMethod("m_const_get", RubySymbol.class, false));
moduleClass.defineMethod("const_set", getMethod("m_const_set", RubySymbol.class, RubyObject.class));
moduleClass.defineMethod("const_defined?", getMethod("m_const_defined", RubySymbol.class, false));
moduleClass.definePrivateMethod("method_added", getDummyMethod());
moduleClass.defineMethod("class_variables", getMethod("m_class_variables", false));
moduleClass.definePrivateMethod("remove_class_variable", getMethod("m_remove_class_variable", RubyObject.class, false));
- moduleClass.definePrivateMethod("append_features", getMethod("m_remove_append_features", RubyModule.class, false));
+ moduleClass.definePrivateMethod("append_features", getMethod("m_append_features", RubyModule.class, false));
moduleClass.definePrivateMethod("extend_object", getMethod("m_extend_object", RubyObject.class, false));
moduleClass.definePrivateMethod("include", getMethod("m_include", true));
moduleClass.definePrivateMethod("public", getMethod("m_public", true));
moduleClass.definePrivateMethod("protected", getMethod("m_protected", true));
moduleClass.definePrivateMethod("private", getMethod("m_private", true));
moduleClass.definePrivateMethod("module_function", getMethod("m_module_function", true));
moduleClass.defineMethod("method_defined?", getMethod("m_method_defined", RubyObject.class, false));
moduleClass.defineMethod("public_class_method", getMethod("m_public_class_method", true));
moduleClass.defineMethod("private_class_method", getMethod("m_private_class_method", true));
/*
rb_define_method(rb_cModule, "module_eval", rb_mod_module_eval, -1);
rb_define_method(rb_cModule, "class_eval", rb_mod_module_eval, -1);
*/
moduleClass.defineMethod("remove_method", getMethod("remove_method", RubyObject.class, false));
moduleClass.defineMethod("undef_method", getMethod("undef_method", RubyObject.class, false));
moduleClass.defineMethod("alias_method", getMethod("alias_method", RubyObject.class, RubyObject.class));
/*rb_define_private_method(rb_cModule, "define_method", rb_mod_define_method, -1);
rb_define_singleton_method(rb_cModule, "nesting", rb_mod_nesting, 0);
rb_define_singleton_method(rb_cModule, "constants", rb_mod_s_constants, 0);*/
}
public static RubyCallbackMethod getDummyMethod() {
return new RubyCallbackMethod() {
public RubyObject execute(RubyObject recv, RubyObject[] args, Ruby ruby) {
return ruby.getNil();
}
};
}
public static RubyCallbackMethod getMethod(String methodName, boolean restArgs) {
if (restArgs) {
return new ReflectionCallbackMethod(RubyModule.class, methodName, RubyObject[].class, true);
} else {
return new ReflectionCallbackMethod(RubyModule.class, methodName);
}
}
public static RubyCallbackMethod getMethod(String methodName, Class arg1, boolean restArgs) {
if (restArgs) {
return new ReflectionCallbackMethod(RubyModule.class, methodName, new Class[] {arg1, RubyObject[].class}, true);
} else {
return new ReflectionCallbackMethod(RubyModule.class, methodName, arg1);
}
}
public static RubyCallbackMethod getMethod(String methodName, Class arg1, Class arg2) {
return new ReflectionCallbackMethod(RubyModule.class, methodName, new Class[] {arg1, arg2});
}
public static RubyCallbackMethod getSingletonMethod(String methodName, boolean restArgs) {
if (restArgs) {
return new ReflectionCallbackMethod(RubyModule.class, methodName, RubyObject[].class, true, true);
} else {
return new ReflectionCallbackMethod(RubyModule.class, methodName, false, true);
}
}
/*public static RubyCallbackMethod getSingletonMethod(String methodName, Class arg1) {
return new ReflectionCallbackMethod(RubyModule.class, methodName, arg1, false, true);
}*/
}
| true | true | public static void initModuleClass(RubyClass moduleClass) {
moduleClass.defineMethod("===", getMethod("op_eqq", RubyObject.class, false));
moduleClass.defineMethod("<=>", getMethod("op_cmp", RubyObject.class, false));
moduleClass.defineMethod("<", getMethod("op_lt", RubyObject.class, false));
moduleClass.defineMethod("<=", getMethod("op_le", RubyObject.class, false));
moduleClass.defineMethod(">", getMethod("op_gt", RubyObject.class, false));
moduleClass.defineMethod(">=", getMethod("op_ge", RubyObject.class, false));
moduleClass.defineMethod("clone", getMethod("m_clone", false));
moduleClass.defineMethod("dup", getMethod("m_dup", false));
moduleClass.defineMethod("to_s", getMethod("m_to_s", false));
moduleClass.defineMethod("included_modules", getMethod("m_included_modules", false));
moduleClass.defineMethod("name", getMethod("m_name", false));
moduleClass.defineMethod("ancestors", getMethod("m_ancestors", false));
moduleClass.definePrivateMethod("attr", getMethod("m_attr", RubySymbol.class, true));
moduleClass.definePrivateMethod("attr_reader", getMethod("m_attr_reader", true));
moduleClass.definePrivateMethod("attr_writer", getMethod("m_attr_writer", true));
moduleClass.definePrivateMethod("attr_accessor", getMethod("m_attr_accessor", true));
moduleClass.defineSingletonMethod("new", getSingletonMethod("m_new", false));
moduleClass.defineMethod("initialize", getMethod("m_initialize", true));
moduleClass.defineMethod("instance_methods", getMethod("m_instance_methods", true));
moduleClass.defineMethod("public_instance_methods", getMethod("m_instance_methods", true));
moduleClass.defineMethod("protected_instance_methods", getMethod("m_protected_instance_methods", true));
moduleClass.defineMethod("private_instance_methods", getMethod("m_private_instance_methods", true));
moduleClass.defineMethod("constants", getMethod("m_constants", false));
moduleClass.defineMethod("const_get", getMethod("m_const_get", RubySymbol.class, false));
moduleClass.defineMethod("const_set", getMethod("m_const_set", RubySymbol.class, RubyObject.class));
moduleClass.defineMethod("const_defined?", getMethod("m_const_defined", RubySymbol.class, false));
moduleClass.definePrivateMethod("method_added", getDummyMethod());
moduleClass.defineMethod("class_variables", getMethod("m_class_variables", false));
moduleClass.definePrivateMethod("remove_class_variable", getMethod("m_remove_class_variable", RubyObject.class, false));
moduleClass.definePrivateMethod("append_features", getMethod("m_remove_append_features", RubyModule.class, false));
moduleClass.definePrivateMethod("extend_object", getMethod("m_extend_object", RubyObject.class, false));
moduleClass.definePrivateMethod("include", getMethod("m_include", true));
moduleClass.definePrivateMethod("public", getMethod("m_public", true));
moduleClass.definePrivateMethod("protected", getMethod("m_protected", true));
moduleClass.definePrivateMethod("private", getMethod("m_private", true));
moduleClass.definePrivateMethod("module_function", getMethod("m_module_function", true));
moduleClass.defineMethod("method_defined?", getMethod("m_method_defined", RubyObject.class, false));
moduleClass.defineMethod("public_class_method", getMethod("m_public_class_method", true));
moduleClass.defineMethod("private_class_method", getMethod("m_private_class_method", true));
/*
rb_define_method(rb_cModule, "module_eval", rb_mod_module_eval, -1);
rb_define_method(rb_cModule, "class_eval", rb_mod_module_eval, -1);
*/
moduleClass.defineMethod("remove_method", getMethod("remove_method", RubyObject.class, false));
moduleClass.defineMethod("undef_method", getMethod("undef_method", RubyObject.class, false));
moduleClass.defineMethod("alias_method", getMethod("alias_method", RubyObject.class, RubyObject.class));
/*rb_define_private_method(rb_cModule, "define_method", rb_mod_define_method, -1);
rb_define_singleton_method(rb_cModule, "nesting", rb_mod_nesting, 0);
rb_define_singleton_method(rb_cModule, "constants", rb_mod_s_constants, 0);*/
}
| public static void initModuleClass(RubyClass moduleClass) {
moduleClass.defineMethod("===", getMethod("op_eqq", RubyObject.class, false));
moduleClass.defineMethod("<=>", getMethod("op_cmp", RubyObject.class, false));
moduleClass.defineMethod("<", getMethod("op_lt", RubyObject.class, false));
moduleClass.defineMethod("<=", getMethod("op_le", RubyObject.class, false));
moduleClass.defineMethod(">", getMethod("op_gt", RubyObject.class, false));
moduleClass.defineMethod(">=", getMethod("op_ge", RubyObject.class, false));
moduleClass.defineMethod("clone", getMethod("m_clone", false));
moduleClass.defineMethod("dup", getMethod("m_dup", false));
moduleClass.defineMethod("to_s", getMethod("m_to_s", false));
moduleClass.defineMethod("included_modules", getMethod("m_included_modules", false));
moduleClass.defineMethod("name", getMethod("m_name", false));
moduleClass.defineMethod("ancestors", getMethod("m_ancestors", false));
moduleClass.definePrivateMethod("attr", getMethod("m_attr", RubySymbol.class, true));
moduleClass.definePrivateMethod("attr_reader", getMethod("m_attr_reader", true));
moduleClass.definePrivateMethod("attr_writer", getMethod("m_attr_writer", true));
moduleClass.definePrivateMethod("attr_accessor", getMethod("m_attr_accessor", true));
moduleClass.defineSingletonMethod("new", getSingletonMethod("m_new", false));
moduleClass.defineMethod("initialize", getMethod("m_initialize", true));
moduleClass.defineMethod("instance_methods", getMethod("m_instance_methods", true));
moduleClass.defineMethod("public_instance_methods", getMethod("m_instance_methods", true));
moduleClass.defineMethod("protected_instance_methods", getMethod("m_protected_instance_methods", true));
moduleClass.defineMethod("private_instance_methods", getMethod("m_private_instance_methods", true));
moduleClass.defineMethod("constants", getMethod("m_constants", false));
moduleClass.defineMethod("const_get", getMethod("m_const_get", RubySymbol.class, false));
moduleClass.defineMethod("const_set", getMethod("m_const_set", RubySymbol.class, RubyObject.class));
moduleClass.defineMethod("const_defined?", getMethod("m_const_defined", RubySymbol.class, false));
moduleClass.definePrivateMethod("method_added", getDummyMethod());
moduleClass.defineMethod("class_variables", getMethod("m_class_variables", false));
moduleClass.definePrivateMethod("remove_class_variable", getMethod("m_remove_class_variable", RubyObject.class, false));
moduleClass.definePrivateMethod("append_features", getMethod("m_append_features", RubyModule.class, false));
moduleClass.definePrivateMethod("extend_object", getMethod("m_extend_object", RubyObject.class, false));
moduleClass.definePrivateMethod("include", getMethod("m_include", true));
moduleClass.definePrivateMethod("public", getMethod("m_public", true));
moduleClass.definePrivateMethod("protected", getMethod("m_protected", true));
moduleClass.definePrivateMethod("private", getMethod("m_private", true));
moduleClass.definePrivateMethod("module_function", getMethod("m_module_function", true));
moduleClass.defineMethod("method_defined?", getMethod("m_method_defined", RubyObject.class, false));
moduleClass.defineMethod("public_class_method", getMethod("m_public_class_method", true));
moduleClass.defineMethod("private_class_method", getMethod("m_private_class_method", true));
/*
rb_define_method(rb_cModule, "module_eval", rb_mod_module_eval, -1);
rb_define_method(rb_cModule, "class_eval", rb_mod_module_eval, -1);
*/
moduleClass.defineMethod("remove_method", getMethod("remove_method", RubyObject.class, false));
moduleClass.defineMethod("undef_method", getMethod("undef_method", RubyObject.class, false));
moduleClass.defineMethod("alias_method", getMethod("alias_method", RubyObject.class, RubyObject.class));
/*rb_define_private_method(rb_cModule, "define_method", rb_mod_define_method, -1);
rb_define_singleton_method(rb_cModule, "nesting", rb_mod_nesting, 0);
rb_define_singleton_method(rb_cModule, "constants", rb_mod_s_constants, 0);*/
}
|
diff --git a/src/java/me/pavlina/alco/llvm/RET.java b/src/java/me/pavlina/alco/llvm/RET.java
index 847cdb9..faaa8e7 100644
--- a/src/java/me/pavlina/alco/llvm/RET.java
+++ b/src/java/me/pavlina/alco/llvm/RET.java
@@ -1,42 +1,42 @@
// Copyright (c) 2011, Christopher Pavlina. All rights reserved.
package me.pavlina.alco.llvm;
/**
* ret */
public class RET implements Terminator {
String type, value;
Instruction iValue;
public RET () {}
/**
* Type */
public RET type (String t) { type = t; return this; }
/**
* Value */
public RET value (String v) { value = v; return this; }
/**
* Type and value */
public RET value (Instruction i) { iValue = i; return this; }
public String toString () {
if (iValue != null) {
type = iValue.getType ();
value = iValue.getId ();
}
- if (iValue == null)
+ if (value == null)
return "ret void\n";
else
return "ret " + type + " " + value + "\n";
}
public boolean needsId () { return false; }
public void setId (String id) {}
public String getId () { throw new RuntimeException (); }
public String getType () { return null; }
}
| true | true | public String toString () {
if (iValue != null) {
type = iValue.getType ();
value = iValue.getId ();
}
if (iValue == null)
return "ret void\n";
else
return "ret " + type + " " + value + "\n";
}
| public String toString () {
if (iValue != null) {
type = iValue.getType ();
value = iValue.getId ();
}
if (value == null)
return "ret void\n";
else
return "ret " + type + " " + value + "\n";
}
|
diff --git a/src/org/red5/server/api/service/ServiceUtils.java b/src/org/red5/server/api/service/ServiceUtils.java
index cbce99d6..9428edbf 100644
--- a/src/org/red5/server/api/service/ServiceUtils.java
+++ b/src/org/red5/server/api/service/ServiceUtils.java
@@ -1,331 +1,334 @@
package org.red5.server.api.service;
/*
* RED5 Open Source Flash Server - http://www.osflash.org/red5
*
* Copyright (c) 2006-2007 by respective authors (see below). All rights reserved.
*
* 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
*/
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.red5.server.api.IClient;
import org.red5.server.api.IConnection;
import org.red5.server.api.IScope;
import org.red5.server.api.Red5;
/**
* Utility functions to invoke methods on connections.
*
* @author The Red5 Project ([email protected])
* @author Joachim Bauch ([email protected])
*
*/
public class ServiceUtils {
/**
* Invoke a method on the current connection.
*
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
* @return <code>true</code> if the connection supports method calls,
* otherwise <code>false</code>
*/
public static boolean invokeOnConnection(String method, Object[] params) {
return invokeOnConnection(method, params, null);
}
/**
* Invoke a method on the current connection and handle result.
*
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
* @param callback
* object to notify when result is received
* @return <code>true</code> if the connection supports method calls,
* otherwise <code>false</code>
*/
public static boolean invokeOnConnection(String method, Object[] params,
IPendingServiceCallback callback) {
IConnection conn = Red5.getConnectionLocal();
return invokeOnConnection(conn, method, params, callback);
}
/**
* Invoke a method on a given connection.
*
* @param conn
* connection to invoke method on
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
* @return <code>true</code> if the connection supports method calls,
* otherwise <code>false</code>
*/
public static boolean invokeOnConnection(IConnection conn, String method,
Object[] params) {
return invokeOnConnection(conn, method, params, null);
}
/**
* Invoke a method on a given connection and handle result.
*
* @param conn
* connection to invoke method on
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
* @param callback
* object to notify when result is received
* @return <code>true</code> if the connection supports method calls,
* otherwise <code>false</code>
*/
public static boolean invokeOnConnection(IConnection conn, String method,
Object[] params, IPendingServiceCallback callback) {
if (conn instanceof IServiceCapableConnection) {
if (callback == null) {
((IServiceCapableConnection) conn).invoke(method, params);
} else {
((IServiceCapableConnection) conn).invoke(method, params,
callback);
}
return true;
} else {
return false;
}
}
/**
* Invoke a method on all connections to the current scope.
*
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
*/
public static void invokeOnAllConnections(String method, Object[] params) {
invokeOnAllConnections(method, params, null);
}
/**
* Invoke a method on all connections to the current scope and handle
* result.
*
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
* @param callback
* object to notify when result is received
*/
public static void invokeOnAllConnections(String method, Object[] params,
IPendingServiceCallback callback) {
IScope scope = Red5.getConnectionLocal().getScope();
invokeOnAllConnections(scope, method, params, callback);
}
/**
* Invoke a method on all connections to a given scope.
*
* @param scope
* scope to get connections for
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
*/
public static void invokeOnAllConnections(IScope scope, String method,
Object[] params) {
invokeOnAllConnections(scope, method, params, null);
}
/**
* Invoke a method on all connections to a given scope and handle result.
*
* @param scope
* scope to get connections for
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
* @param callback
* object to notify when result is received
*/
public static void invokeOnAllConnections(IScope scope, String method,
Object[] params, IPendingServiceCallback callback) {
invokeOnClient(null, scope, method, params, callback);
}
/**
* Invoke a method on all connections of a client to a given scope.
*
* @param client
* client to get connections for
* @param scope
* scope to get connections of the client from
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
*/
public static void invokeOnClient(IClient client, IScope scope,
String method, Object[] params) {
invokeOnClient(client, scope, method, params, null);
}
/**
* Invoke a method on all connections of a client to a given scope and
* handle result.
*
* @param client
* client to get connections for
* @param scope
* scope to get connections of the client from
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
* @param callback
* object to notify when result is received
*/
public static void invokeOnClient(IClient client, IScope scope,
String method, Object[] params, IPendingServiceCallback callback) {
Set<IConnection> connections;
if (client == null) {
connections = new HashSet<IConnection>();
Iterator<IConnection> iter = scope.getConnections();
while (iter.hasNext()) {
connections.add(iter.next());
}
} else {
connections = scope.lookupConnections(client);
+ if (connections == null)
+ // Client is not connected to the scope
+ return;
}
if (callback == null) {
for (IConnection conn : connections) {
invokeOnConnection(conn, method, params);
}
} else {
for (IConnection conn : connections) {
invokeOnConnection(conn, method, params, callback);
}
}
}
/**
* Notify a method on the current connection.
*
* @param method
* name of the method to notify
* @param params
* parameters to pass to the method
* @return <code>true</code> if the connection supports method calls,
* otherwise <code>false</code>
*/
public static boolean notifyOnConnection(String method, Object[] params) {
IConnection conn = Red5.getConnectionLocal();
return notifyOnConnection(conn, method, params);
}
/**
* Notify a method on a given connection.
*
* @param conn
* connection to notify method on
* @param method
* name of the method to notify
* @param params
* parameters to pass to the method
* @return <code>true</code> if the connection supports method calls,
* otherwise <code>false</code>
*/
public static boolean notifyOnConnection(IConnection conn, String method,
Object[] params) {
if (conn instanceof IServiceCapableConnection) {
((IServiceCapableConnection) conn).notify(method, params);
return true;
} else {
return false;
}
}
/**
* Notify a method on all connections to the current scope.
*
* @param method
* name of the method to notifynotify
* @param params
* parameters to pass to the method
*/
public static void notifyOnAllConnections(String method, Object[] params) {
IScope scope = Red5.getConnectionLocal().getScope();
notifyOnAllConnections(scope, method, params);
}
/**
* Notfy a method on all connections to a given scope.
*
* @param scope
* scope to get connections for
* @param method
* name of the method to notify
* @param params
* parameters to pass to the method
*/
public static void notifyOnAllConnections(IScope scope, String method,
Object[] params) {
notifyOnClient(null, scope, method, params);
}
/**
* Notify a method on all connections of a client to a given scope.
*
* @param client
* client to get connections for
* @param scope
* scope to get connections of the client from
* @param method
* name of the method to notify
* @param params
* parameters to pass to the method
*/
public static void notifyOnClient(IClient client, IScope scope,
String method, Object[] params) {
Set<IConnection> connections;
if (client == null) {
connections = new HashSet<IConnection>();
Iterator<IConnection> iter = scope.getConnections();
while (iter.hasNext()) {
connections.add(iter.next());
}
} else {
connections = scope.lookupConnections(client);
}
for (IConnection conn : connections) {
notifyOnConnection(conn, method, params);
}
}
}
| true | true | public static void invokeOnClient(IClient client, IScope scope,
String method, Object[] params, IPendingServiceCallback callback) {
Set<IConnection> connections;
if (client == null) {
connections = new HashSet<IConnection>();
Iterator<IConnection> iter = scope.getConnections();
while (iter.hasNext()) {
connections.add(iter.next());
}
} else {
connections = scope.lookupConnections(client);
}
if (callback == null) {
for (IConnection conn : connections) {
invokeOnConnection(conn, method, params);
}
} else {
for (IConnection conn : connections) {
invokeOnConnection(conn, method, params, callback);
}
}
}
| public static void invokeOnClient(IClient client, IScope scope,
String method, Object[] params, IPendingServiceCallback callback) {
Set<IConnection> connections;
if (client == null) {
connections = new HashSet<IConnection>();
Iterator<IConnection> iter = scope.getConnections();
while (iter.hasNext()) {
connections.add(iter.next());
}
} else {
connections = scope.lookupConnections(client);
if (connections == null)
// Client is not connected to the scope
return;
}
if (callback == null) {
for (IConnection conn : connections) {
invokeOnConnection(conn, method, params);
}
} else {
for (IConnection conn : connections) {
invokeOnConnection(conn, method, params, callback);
}
}
}
|
diff --git a/sims/app/controllers/SecureController.java b/sims/app/controllers/SecureController.java
index 4a2dcf6..95c7523 100644
--- a/sims/app/controllers/SecureController.java
+++ b/sims/app/controllers/SecureController.java
@@ -1,30 +1,30 @@
package controllers;
import models.User;
import play.mvc.Before;
import play.mvc.Controller;
import play.mvc.With;
/**
* Controller que requiere autenticación y setea usuario loggeado.
*
*
* @author Juan Edi
* @since Jun 13, 2012
*/
@With(Secure.class)
public abstract class SecureController extends Controller {
@Before
static void setConnectedUser() {
if (Security.isConnected()) {
User user = connectedUser();
- renderArgs.put("user", user);
+ renderArgs.put("loggedUser", user);
}
}
static User connectedUser() {
return User.find("byUsername", Security.connected()).first();
}
}
| true | true | static void setConnectedUser() {
if (Security.isConnected()) {
User user = connectedUser();
renderArgs.put("user", user);
}
}
| static void setConnectedUser() {
if (Security.isConnected()) {
User user = connectedUser();
renderArgs.put("loggedUser", user);
}
}
|
diff --git a/omod/src/main/java/org/openmrs/module/emr/fragment/controller/paperrecord/ArchivesRoomFragmentController.java b/omod/src/main/java/org/openmrs/module/emr/fragment/controller/paperrecord/ArchivesRoomFragmentController.java
index 258b4b92..b2f538a6 100644
--- a/omod/src/main/java/org/openmrs/module/emr/fragment/controller/paperrecord/ArchivesRoomFragmentController.java
+++ b/omod/src/main/java/org/openmrs/module/emr/fragment/controller/paperrecord/ArchivesRoomFragmentController.java
@@ -1,78 +1,78 @@
/*
* 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.emr.fragment.controller.paperrecord;
import org.openmrs.module.emr.EmrContext;
import org.openmrs.module.emr.paperrecord.PaperRecordRequest;
import org.openmrs.module.emr.paperrecord.PaperRecordService;
import org.openmrs.ui.framework.UiUtils;
import org.openmrs.ui.framework.annotation.SpringBean;
import org.openmrs.ui.framework.fragment.action.FailureResult;
import org.openmrs.ui.framework.fragment.action.FragmentActionResult;
import org.openmrs.ui.framework.fragment.action.SuccessResult;
import org.springframework.web.bind.annotation.RequestParam;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class ArchivesRoomFragmentController {
DateFormat timeFormat = new SimpleDateFormat("HH:mm");
public FragmentActionResult markPaperRecordRequestAsSent(@RequestParam(value = "identifier", required = true) String identifier,
@SpringBean("paperRecordService") PaperRecordService paperRecordService,
UiUtils ui) {
// fetch the pending request associated with this message
PaperRecordRequest paperRecordRequest = paperRecordService.getPendingPaperRecordRequestByIdentifier(identifier);
if (paperRecordRequest == null) {
// if matching request found, determine what error we need to return
paperRecordRequest = paperRecordService.getSentPaperRecordRequestByIdentifier(identifier);
if (paperRecordRequest == null) {
return new FailureResult(ui.message("emr.archivesRoom.error.paperRecordNotRequested", ui.format(identifier)));
}
else {
return new FailureResult(ui.message("emr.archivesRooms.error.paperRecordAlreadySent", ui.format(identifier),
ui.format(paperRecordRequest.getRequestLocation()), ui.format(paperRecordRequest.getDateStatusChanged())));
}
}
else {
// otherwise, mark the record as sent
paperRecordService.markPaperRequestRequestAsSent(paperRecordRequest);
return new SuccessResult(ui.message("emr.archivesRoom.recordFound.message") + "<br/><br/>"
+ ui.message("emr.archivesRoom.recordNumber.label") + ": " + ui.format(identifier + "<br/><br/>"
+ ui.message("emr.archivesRoom.requestedBy.label") + ": " + ui.format(paperRecordRequest.getRequestLocation() + "<br/><br/>"
- + ui.message("emr.archviesRoom.requestedAt.label") + ": " + timeFormat.format(paperRecordRequest.getDateCreated()))));
+ + ui.message("emr.archivesRoom.requestedAt.label") + ": " + timeFormat.format(paperRecordRequest.getDateCreated()))));
}
}
public FragmentActionResult reprintLabel(@RequestParam("requestId") PaperRecordRequest request,
@SpringBean("paperRecordService") PaperRecordService paperRecordService,
EmrContext emrContext) {
Boolean result = paperRecordService.printPaperRecordLabel(request, emrContext.getSessionLocation());
if (result) {
return new SuccessResult();
}
else {
return new FailureResult("unable to print paper record label");
}
}
}
| true | true | public FragmentActionResult markPaperRecordRequestAsSent(@RequestParam(value = "identifier", required = true) String identifier,
@SpringBean("paperRecordService") PaperRecordService paperRecordService,
UiUtils ui) {
// fetch the pending request associated with this message
PaperRecordRequest paperRecordRequest = paperRecordService.getPendingPaperRecordRequestByIdentifier(identifier);
if (paperRecordRequest == null) {
// if matching request found, determine what error we need to return
paperRecordRequest = paperRecordService.getSentPaperRecordRequestByIdentifier(identifier);
if (paperRecordRequest == null) {
return new FailureResult(ui.message("emr.archivesRoom.error.paperRecordNotRequested", ui.format(identifier)));
}
else {
return new FailureResult(ui.message("emr.archivesRooms.error.paperRecordAlreadySent", ui.format(identifier),
ui.format(paperRecordRequest.getRequestLocation()), ui.format(paperRecordRequest.getDateStatusChanged())));
}
}
else {
// otherwise, mark the record as sent
paperRecordService.markPaperRequestRequestAsSent(paperRecordRequest);
return new SuccessResult(ui.message("emr.archivesRoom.recordFound.message") + "<br/><br/>"
+ ui.message("emr.archivesRoom.recordNumber.label") + ": " + ui.format(identifier + "<br/><br/>"
+ ui.message("emr.archivesRoom.requestedBy.label") + ": " + ui.format(paperRecordRequest.getRequestLocation() + "<br/><br/>"
+ ui.message("emr.archviesRoom.requestedAt.label") + ": " + timeFormat.format(paperRecordRequest.getDateCreated()))));
}
}
| public FragmentActionResult markPaperRecordRequestAsSent(@RequestParam(value = "identifier", required = true) String identifier,
@SpringBean("paperRecordService") PaperRecordService paperRecordService,
UiUtils ui) {
// fetch the pending request associated with this message
PaperRecordRequest paperRecordRequest = paperRecordService.getPendingPaperRecordRequestByIdentifier(identifier);
if (paperRecordRequest == null) {
// if matching request found, determine what error we need to return
paperRecordRequest = paperRecordService.getSentPaperRecordRequestByIdentifier(identifier);
if (paperRecordRequest == null) {
return new FailureResult(ui.message("emr.archivesRoom.error.paperRecordNotRequested", ui.format(identifier)));
}
else {
return new FailureResult(ui.message("emr.archivesRooms.error.paperRecordAlreadySent", ui.format(identifier),
ui.format(paperRecordRequest.getRequestLocation()), ui.format(paperRecordRequest.getDateStatusChanged())));
}
}
else {
// otherwise, mark the record as sent
paperRecordService.markPaperRequestRequestAsSent(paperRecordRequest);
return new SuccessResult(ui.message("emr.archivesRoom.recordFound.message") + "<br/><br/>"
+ ui.message("emr.archivesRoom.recordNumber.label") + ": " + ui.format(identifier + "<br/><br/>"
+ ui.message("emr.archivesRoom.requestedBy.label") + ": " + ui.format(paperRecordRequest.getRequestLocation() + "<br/><br/>"
+ ui.message("emr.archivesRoom.requestedAt.label") + ": " + timeFormat.format(paperRecordRequest.getDateCreated()))));
}
}
|
diff --git a/araqne-logdb/src/test/java/org/araqne/logdb/query/parser/ParseKvParserTest.java b/araqne-logdb/src/test/java/org/araqne/logdb/query/parser/ParseKvParserTest.java
index 5e2958b5..9d0129dc 100644
--- a/araqne-logdb/src/test/java/org/araqne/logdb/query/parser/ParseKvParserTest.java
+++ b/araqne-logdb/src/test/java/org/araqne/logdb/query/parser/ParseKvParserTest.java
@@ -1,86 +1,86 @@
/*
* Copyright 2013 Eediom 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 org.araqne.logdb.query.parser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.HashMap;
import java.util.Map;
import org.araqne.logdb.QueryCommand;
import org.araqne.logdb.QueryCommandPipe;
import org.araqne.logdb.QueryParserService;
import org.araqne.logdb.Row;
import org.araqne.logdb.impl.FunctionRegistryImpl;
import org.araqne.logdb.query.command.ParseKv;
import org.araqne.logdb.query.engine.QueryParserServiceImpl;
import org.junit.Before;
import org.junit.Test;
public class ParseKvParserTest {
private QueryParserService queryParserService;
@Before
public void setup() {
QueryParserServiceImpl p = new QueryParserServiceImpl();
p.setFunctionRegistry(new FunctionRegistryImpl());
queryParserService = p;
}
@Test
public void testQuery() {
ParseKvParser parser = new ParseKvParser();
parser.setQueryParserService(queryParserService);
ParseKv kv = (ParseKv) parser.parse(null, "parsekv");
DummyOutput out = new DummyOutput();
kv.setOutput(new QueryCommandPipe(out));
assertEquals("line", kv.getField());
assertFalse(kv.isOverlay());
assertEquals(" ", kv.getPairDelim());
assertEquals("=", kv.getKvDelim());
- assertEquals("parsekv field=line overlay=false pairdelim=\" \" kvdelim=\"=\"", kv.toString());
+ assertEquals("parsekv", kv.toString());
// test field extraction
String line = "a=1 b=2 c=3";
Map<String, Object> m = new HashMap<String, Object>();
m.put("line", line);
kv.onPush(new Row(m));
Row o = out.output;
assertEquals(3, o.map().size());
assertEquals("1", o.get("a"));
assertEquals("2", o.get("b"));
assertEquals("3", o.get("c"));
}
private class DummyOutput extends QueryCommand {
private Row output;
@Override
public String getName() {
return "output";
}
@Override
public void onPush(Row m) {
output = m;
}
}
}
| true | true | public void testQuery() {
ParseKvParser parser = new ParseKvParser();
parser.setQueryParserService(queryParserService);
ParseKv kv = (ParseKv) parser.parse(null, "parsekv");
DummyOutput out = new DummyOutput();
kv.setOutput(new QueryCommandPipe(out));
assertEquals("line", kv.getField());
assertFalse(kv.isOverlay());
assertEquals(" ", kv.getPairDelim());
assertEquals("=", kv.getKvDelim());
assertEquals("parsekv field=line overlay=false pairdelim=\" \" kvdelim=\"=\"", kv.toString());
// test field extraction
String line = "a=1 b=2 c=3";
Map<String, Object> m = new HashMap<String, Object>();
m.put("line", line);
kv.onPush(new Row(m));
Row o = out.output;
assertEquals(3, o.map().size());
assertEquals("1", o.get("a"));
assertEquals("2", o.get("b"));
assertEquals("3", o.get("c"));
}
| public void testQuery() {
ParseKvParser parser = new ParseKvParser();
parser.setQueryParserService(queryParserService);
ParseKv kv = (ParseKv) parser.parse(null, "parsekv");
DummyOutput out = new DummyOutput();
kv.setOutput(new QueryCommandPipe(out));
assertEquals("line", kv.getField());
assertFalse(kv.isOverlay());
assertEquals(" ", kv.getPairDelim());
assertEquals("=", kv.getKvDelim());
assertEquals("parsekv", kv.toString());
// test field extraction
String line = "a=1 b=2 c=3";
Map<String, Object> m = new HashMap<String, Object>();
m.put("line", line);
kv.onPush(new Row(m));
Row o = out.output;
assertEquals(3, o.map().size());
assertEquals("1", o.get("a"));
assertEquals("2", o.get("b"));
assertEquals("3", o.get("c"));
}
|
diff --git a/srcj/com/sun/electric/tool/user/KeyBindingManager.java b/srcj/com/sun/electric/tool/user/KeyBindingManager.java
index 474e73864..294d82a7b 100644
--- a/srcj/com/sun/electric/tool/user/KeyBindingManager.java
+++ b/srcj/com/sun/electric/tool/user/KeyBindingManager.java
@@ -1,1097 +1,1098 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: KeyBindingManager.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.user;
import com.sun.electric.tool.user.dialogs.EDialog;
import com.sun.electric.tool.user.dialogs.EModelessDialog;
import com.sun.electric.tool.user.dialogs.GetInfoText;
import com.sun.electric.tool.user.dialogs.OpenFile;
import com.sun.electric.tool.user.help.ManualViewer;
import com.sun.electric.tool.user.ui.EditWindow;
import com.sun.electric.tool.user.ui.KeyBindings;
import com.sun.electric.tool.user.ui.KeyStrokePair;
import com.sun.electric.tool.user.ui.TextWindow;
import com.sun.electric.tool.user.ui.TopLevel;
import com.sun.electric.tool.user.ui.WindowContent;
import com.sun.electric.tool.user.ui.WindowFrame;
import com.sun.electric.tool.user.waveform.WaveformWindow;
import java.awt.Component;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.prefs.Preferences;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JDialog;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
/**
* The KeyBindingManager manages key bindings and their associated actions. It
* implements a <code>KeyListener</code> so it can be added as a key listener
* to any component.
* <p><p>
* The <i>inputMap</i> uses <code>KeyStrokes</code> as it's keys, and stores Objects
* of type Set. The Set contains Strings and the set will guarantee they are not repetead.
* <p>
* Each String is then used as a key into the HashMap <i>actionMap</i> to retrieve
* a KeyBindings object. Each key bindings object has a list of actions which can then be
* performed.
* <p>
* This model is similar to jawa.swing.InputMap and java.swing.ActionMap.
* However, secondary InputMaps allow two-stroke key bindings. Additionally,
* the KeybindingManager has been enveloped in an object which can
* then be inserted into the event hierarchy in different ways, instead of having
* to set a Component's InputMap and ActionMap.
* <p><p>
* Two-stroke bindings:<p>
* The KeyBindingManager has a HashMap <i>prefixedInputMapMaps</i>. A prefixStroke
* is used as a key to this table to obtain an inputMap (HashMap) based on the prefixStroke.
* From here it is the same as before with the inputMap and actionMap:
* A KeyStroke is then used as a key to find a List of Strings. The Strings are
* then used as a key into <i>actionMap</i> to get a KeyBindings object and
* perform the associated action. There is only one actionMap.
* <p>
*
* @author gainsley
*/
public class KeyBindingManager implements KeyEventDispatcher
{
// ----------------------------- object stuff ---------------------------------
/** Hash table of lists all key bindings */ private Map<KeyStroke,Set<String>> inputMap;
/** Hash table of all actions */ private Map<String,Object> actionMap;
/** last prefix key pressed */ private KeyStroke lastPrefix;
/** Hash table of hash of lists of prefixed key bindings */ private Map<KeyStroke,Map<KeyStroke,Set<String>>> prefixedInputMapMaps;
/** action to take on prefix key hit */ private PrefixAction prefixAction;
/** where to store Preferences */ private Preferences prefs;
/** prefix on pref key, if desired */ private String prefPrefix;
// ----------------------------- global stuff ----------------------------------
/** Listener to register for catching keys */ //public static KeyBindingListener listener = new KeyBindingListener();
/** All key binding manangers */ private static List<KeyBindingManager> allManagers = new ArrayList<KeyBindingManager>();
/** debug preference saving */ private static final boolean debugPrefs = false;
/** debug key bindings */ private static final boolean DEBUG = false;
/**
* Construct a new KeyBindingManager that can act as a KeyListener
* on a Component.
*/
public KeyBindingManager(String prefPrefix, Preferences prefs) {
inputMap = new HashMap<KeyStroke,Set<String>>();
actionMap = new HashMap<String,Object>();
prefixedInputMapMaps = new HashMap<KeyStroke,Map<KeyStroke,Set<String>>>();
lastPrefix = null;
prefixAction = new PrefixAction(this);
this.prefs = prefs;
this.prefPrefix = prefPrefix;
// add prefix action to action map
actionMap.put(PrefixAction.actionDesc, prefixAction);
// register this with KeyboardFocusManager
// so we receive all KeyEvents
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
//KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(this);
// add to list of all managers
synchronized(allManagers) {
allManagers.add(this);
}
initialize();
}
public boolean dispatchKeyEvent(KeyEvent e)
{
return processKeyEvent(e);
}
/**
* Called when disposing of this manager, allows memory used to
* be reclaimed by removing static references to this.
*/
public void finished() {
synchronized(allManagers) {
allManagers.remove(this);
}
//KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventPostProcessor(this);
}
private boolean initialized = false;
/**
* Initialize: Reads all stored key bindings from preferences
*/
private synchronized void initialize() {
/* String [] allKeys;
try {
allKeys = prefs.keys();
} catch (BackingStoreException e) {
e.printStackTrace();
return;
}
for (int i = 0; i < allKeys.length; i++) {
// read bindings
String key = allKeys[i].replaceFirst(prefPrefix, "");
// old binding format and new format conflict, add check to avoid duplicates
if (actionMap.containsKey(key)) continue;
if (debugPrefs) System.out.println("looking for prefs key "+key);
KeyBindings keys = new KeyBindings(key);
List pairs = getBindingsFromPrefs(key);
// if any bindings, set usingDefaults false, and add them
if (pairs != null) {
keys.setUsingDefaultKeys(false); // set usingDefaults false
actionMap.put(key, keys);
for (Iterator it = pairs.iterator(); it.hasNext(); ) {
KeyStrokePair pair = (KeyStrokePair)it.next();
if (pair == null) continue;
addKeyBinding(key, pair);
}
}
}*/
}
private static class KeyBindingColumn
{
int hits = 0; // how many key bindings use this modifier
int maxLength = 0;
String name;
KeyBindingColumn(String n)
{
name = n;
}
public String toString() { return name; }
public String getHeader()
{
String n = name;
for (int l = name.length(); l < maxLength; l++)
n += " ";
return n + " | ";
}
public String getColumn(Object value)
{
String column = "";
int fillStart = 0;
if (value != null)
{
String n = value.toString();
fillStart = n.length();
column += n;
}
// filling
for (int l = fillStart; l < maxLength; l++)
column +=" ";
return column + " | ";
}
public void addHit(Set<String> set)
{
hits++;
int len = set.toString().length();
if (len > maxLength)
maxLength = len;
}
public boolean equals(Object obj)
{
String key = obj.toString();
boolean found = key.equals(name);
return found;
}
}
private static class KeyBindingColumnSort implements Comparator<KeyBindingColumn>
{
public int compare(KeyBindingColumn s1, KeyBindingColumn s2)
{
int bb1 = s1.hits;
int bb2 = s2.hits;
if (bb1 < bb2) return 1; // sorting from max to min
else if (bb1 > bb2) return -1;
return (0); // identical
}
}
/** Method to print existing KeyStrokes in std output for help
*/
public void printKeyBindings()
{
Map<String,Map<String,Set<String>>> set = new HashMap<String,Map<String,Set<String>>>();
List<String> keyList = new ArrayList<String>(); // has to be a list so it could be sorted.
List<KeyBindingColumn> columnList = new ArrayList<KeyBindingColumn>(); // has to be a list so it could be sorted.
KeyBindingColumn row = new KeyBindingColumn("Keys");
Set<String> tmpSet = new HashSet<String>();
columnList.add(row); // inserting the first row with key names as column
for (Map.Entry<KeyStroke,Set<String>> map : inputMap.entrySet())
{
KeyStroke keyS = map.getKey();
String key = KeyStrokePair.getStringFromKeyStroke(keyS);
Map<String,Set<String>> m = set.get(key);
if (m == null)
{
m = new HashMap<String,Set<String>>();
set.put(key, m);
keyList.add(key);
tmpSet.clear();
tmpSet.add(key);
row.addHit(tmpSet);
}
String modifier = KeyEvent.getKeyModifiersText(keyS.getModifiers());
KeyBindingColumn newCol = new KeyBindingColumn(modifier);
int index = columnList.indexOf(newCol);
KeyBindingColumn col = (index > -1) ? columnList.get(index) : null;
if (col == null)
{
col = newCol;
columnList.add(col);
}
col.addHit(map.getValue());
m.put(modifier, map.getValue());
}
Collections.sort(keyList);
Collections.sort(columnList, new KeyBindingColumnSort());
// Header
String headerLine = "\n";
for (KeyBindingColumn column : columnList)
{
String header = column.getHeader();
System.out.print(header);
for (int i = 0; i < header.length(); i++)
headerLine += "-";
}
System.out.println(headerLine);
for (String key : keyList)
{
// System.out.print(key);
for (KeyBindingColumn column : columnList)
{
Object value = (column == row) ? key : (Object)set.get(key).get(column.name);
System.out.print(column.getColumn(value));
}
System.out.println();
}
}
// ---------------------------- Prefix Action Class -----------------------------
/**
* Class PrefixAction is an action performed when a prefix key is hit.
* This then registers that prefix key with the KeyBindingManager.
* This allows key bindings to consist of two-key sequences.
*/
private static class PrefixAction extends AbstractAction
{
/** The action description analagous to KeyBinding */ public static final String actionDesc = "KeyBindingManager prefix action";
/** the key binding manager using this aciton */ private KeyBindingManager manager;
public PrefixAction(KeyBindingManager manager) {
super();
this.manager = manager;
}
public void actionPerformed(ActionEvent e) {
KeyEvent keyEvent = (KeyEvent)e.getSource();
KeyStroke stroke = KeyStroke.getKeyStrokeForEvent(keyEvent);
manager.setPrefixKey(stroke);
if (DEBUG) System.out.println("prefix key '"+KeyStrokePair.keyStrokeToString(stroke)+"' hit...");
}
}
/**
* Called by the KeyBindingManager's prefixAction to register
* that a prefix key has been hit.
* @param prefix the prefix key
*/
private synchronized void setPrefixKey(KeyStroke prefix) {
this.lastPrefix = prefix;
}
// ------------------------------ Key Processing ---------------------------------
/*
public static class KeyBindingListener implements KeyListener
{
public void keyPressed(KeyEvent e) {
for (Iterator it = allManagers.iterator(); it.hasNext(); ) {
KeyBindingManager m = (KeyBindingManager)it.next();
if (m.processKeyEvent(e)) return;
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}
public boolean postProcessKeyEvent(KeyEvent e) {
return processKeyEvent(e);
}
*/
/**
* Says whether or not KeyBindingManager will bind to this key event
* @param e the KeyEvent
* @return true if the KeyBindingManager can bind to this event
*/
public static boolean validKeyEvent(KeyEvent e) {
// only look at key pressed events
// if (e.getID() != KeyEvent.KEY_PRESSED && e.getID() != KeyEvent.KEY_TYPED) return false;
if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT ||
e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN) return true;
if (e.getID() != KeyEvent.KEY_PRESSED) return false;
// ignore modifier only events (CTRL, SHIFT etc just by themselves)
if (e.getKeyCode() == KeyEvent.VK_CONTROL) return false;
if (e.getKeyCode() == KeyEvent.VK_SHIFT) return false;
if (e.getKeyCode() == KeyEvent.VK_ALT) return false;
if (e.getKeyCode() == KeyEvent.VK_META) return false;
return true;
}
/**
* Process a KeyEvent by finding what actionListeners should be
* activated as a result of the event. The keyBindingManager keeps
* one stroke of history so that two-stroke events can be distinguished.
* @param e the KeyEvent
* @return true if event consumed, false if not and nothing done.
*/
public synchronized boolean processKeyEvent(KeyEvent e) {
if (DEBUG) System.out.println("got event (consumed="+e.isConsumed()+") "+e);
// see if this is a valid key event
if (!validKeyEvent(e)) return false;
// ignore events that come from dialogs, or non-Control events that are not from an EditWindow/WaveformWindow
Component c = e.getComponent();
boolean valid = false;
while (c != null)
{
if (c instanceof EditWindow) { valid = true; break; }
if (c instanceof WaveformWindow.OnePanel) { valid = true; break; }
if (c instanceof TopLevel) { valid = true; break; }
if (c instanceof EDialog) { lastPrefix = null; return false; }
if (c instanceof EModelessDialog) { lastPrefix = null; return false; }
if (c instanceof JOptionPane) { lastPrefix = null; return false; }
if (c instanceof TextWindow.TextWindowPanel) { lastPrefix = null; return false; }
if (c instanceof OpenFile.OpenFileSwing) { lastPrefix = null; return false; }
if (c instanceof GetInfoText.EIPEditorPane) { lastPrefix = null; return false; }
if (c instanceof GetInfoText.EIPTextField) { lastPrefix = null; return false; }
if (c instanceof ManualViewer) { lastPrefix = null; return false; }
if (c instanceof ManualViewer.EditHTML) { lastPrefix = null; return false; }
c = c.getParent();
}
if (!valid && (e.getModifiers() & InputEvent.CTRL_MASK) == 0)
{ lastPrefix = null; return false; }
// see if any popup menus are visible
WindowFrame wf = WindowFrame.getCurrentWindowFrame();
JMenuBar mb = wf.getFrame().getJMenuBar();
for(int i=0; i<mb.getMenuCount(); i++)
{
JMenu m = mb.getMenu(i);
if (m == null) continue;
if (!m.isPopupMenuVisible()) continue;
lastPrefix = null; // someone did something with it, null prefix key
return false;
}
// get KeyStroke
KeyStroke stroke = KeyStroke.getKeyStrokeForEvent(e);
if (DEBUG) System.out.println(" Current key is "+stroke+", code="+e.getKeyCode()+", type="+stroke.getKeyEventType());
// convert arrow keys which appear only on release event
// if ((e.getModifiers() & (InputEvent.CTRL_MASK|InputEvent.SHIFT_MASK)) != InputEvent.CTRL_MASK &&
// stroke.getKeyEventType() == KeyEvent.KEY_RELEASED)
// {
// if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT ||
// e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN)
// {
// stroke = KeyStroke.getKeyStroke(e.getKeyCode(), stroke.getModifiers());
// }
// } else
{
// remove shift modifier from Events. Lets KeyStrokes like '<' register correctly,
// because they are always delivered as SHIFT-'<'.
-// if ((e.getModifiers() & InputEvent.SHIFT_MASK) != 0 && !Character.isLetter(e.getKeyCode()) && !Character.isDigit(e.getKeyCode()))
- if (!Character.isLetter(e.getKeyCode()) && !Character.isDigit(e.getKeyCode()))
+ if ((e.getModifiers() & InputEvent.SHIFT_MASK) != 0 && !Character.isLetter(e.getKeyCode()) && !Character.isDigit(e.getKeyCode()))
{
if (e.getKeyCode() != KeyEvent.VK_LEFT && e.getKeyCode() != KeyEvent.VK_RIGHT &&
e.getKeyCode() != KeyEvent.VK_UP && e.getKeyCode() != KeyEvent.VK_DOWN)
stroke = KeyStroke.getKeyStroke(e.getKeyChar());
}
+ if (e.getKeyCode() == '[' || e.getKeyCode() == ']')
+ stroke = KeyStroke.getKeyStroke(e.getKeyChar());
}
// ignore if consumed
if (e.isConsumed()) {
lastPrefix = null; // someone did something with it, null prefix key
return false;
}
Map<KeyStroke,Set<String>> inputMapToUse = inputMap;
// check if we should use prefixed key map instead of regular inputMap
if (lastPrefix != null) {
// get input map based on prefix key
inputMapToUse = prefixedInputMapMaps.get(lastPrefix);
if (inputMapToUse == null) { lastPrefix = null; return false; }
}
ActionListener action = null;
ActionEvent evt = new ActionEvent(e, ActionEvent.ACTION_PERFORMED, stroke.toString(), stroke.getModifiers());
boolean actionPerformed = false;
boolean prefixActionPerformed = false;
// get set of action strings, iterate over them
Set<String> keyBindingList = inputMapToUse.get(stroke);
if (keyBindingList != null) {
for (String actionDesc : keyBindingList) {
// get KeyBinding object from action map, activate its action
// note that if this is a prefixed action, this could actually be a
// PrefixAction object instead of a KeyBinding object.
action = (ActionListener)actionMap.get(actionDesc);
if (action instanceof PrefixAction) {
if (!prefixActionPerformed) {
action.actionPerformed(evt); // only do this once
prefixActionPerformed = true;
}
} else {
action.actionPerformed(evt);
lastPrefix = null;
}
actionPerformed = true;
}
}
if (!actionPerformed) {
// if no action to perform, perhaps the user hit a prefix key, then
// decided to start another prefix-key-combo (that does not result in
// a valid binding with the first prefix, obviously). We'll be nice
// and check for this case
Map prefixMap = prefixedInputMapMaps.get(stroke);
if (prefixMap != null) {
// valid prefix key, fire prefix event
prefixAction.actionPerformed(evt);
actionPerformed = true;
} else {
lastPrefix = null; // nothing to do
}
}
if (DEBUG) System.out.println(" actionPerformed="+actionPerformed);
if (actionPerformed) {
e.consume(); // consume event if we did something useful with it
return true; // let KeyboardFocusManager know we consumed event
}
// otherwise, do not consume, and return false to let KeyboardFocusManager
// know that we did nothing with Event, and to pass it on
return false;
}
// -------------- Static Methods Applied to All KeyBindingManagers ----------------
/**
* Get a list of conflicting key bindings from all KeyBindingManagers.
* @param pair the keystrokepair
* @return a list of conflicting KeyBindings from all KeyBindingManagers
*/
public static List<KeyBindings> getConflictsAllManagers(KeyStrokePair pair) {
List<KeyBindings> conflicts = new ArrayList<KeyBindings>();
synchronized(allManagers) {
for (KeyBindingManager m : allManagers) {
conflicts.addAll(m.getConflictingKeyBindings(pair));
}
}
return conflicts;
}
// --------------------- Public Methods to Manage Bindings ----------------------
/**
* Adds a default KeyBinding. If any keyBindings are found for
* <code>k.actionDesc</code>, those are used instead. Note that <code>k</code>
* cannot be null, but it's stroke and prefixStroke can be null. However,
* it's actionDesc and action must be valid.
* @param actionDesc the action description
* @param pair a key stroke pair
*/
public synchronized void addDefaultKeyBinding(String actionDesc, KeyStrokePair pair) {
if (pair == null) return;
// add to default bindings
KeyBindings keys = (KeyBindings)actionMap.get(actionDesc);
if (keys == null) {
keys = new KeyBindings(actionDesc);
actionMap.put(actionDesc, keys);
}
keys.addDefaultKeyBinding(pair);
/*
if (keys.getUsingDefaultKeys()) {
// using default keys, add default key to active maps
addKeyBinding(actionDesc, pair);
}
*/
}
/**
* Adds a user specified KeyBindings. Also adds it to stored user preference.
* @param actionDesc the action description
* @param pair a key stroke pair
*/
public synchronized void addUserKeyBinding(String actionDesc, KeyStrokePair pair) {
if (pair == null) return;
// add to active bindings (also adds to KeyBindings object)
KeyBindings keys = addKeyBinding(actionDesc, pair);
// now using user specified key bindings, set usingDefaults false
keys.setUsingDefaultKeys(false);
// user has modified bindings, write all current bindings to prefs
setBindingsToPrefs(keys.getActionDesc());
}
/**
* Add an action listener on actionDesc
* @param actionDesc the action description
* @param action the action listener to add
*/
public synchronized void addActionListener(String actionDesc, ActionListener action) {
// add to default set of KeyBindings
KeyBindings keys = (KeyBindings)actionMap.get(actionDesc);
if (keys == null) {
keys = new KeyBindings(actionDesc);
actionMap.put(actionDesc, keys);
}
keys.addActionListener(action);
}
/**
* Removes a key binding from the active bindings, and writes new bindings
* set to preferences.
* @param actionDesc the describing action
* @param k the KeyStrokePair to remove
*/
public synchronized void removeKeyBinding(String actionDesc, KeyStrokePair k) {
Map<KeyStroke,Set<String>> inputMapToUse = inputMap;
// if prefix stroke exists, remove one prefixAction key string
// (may be more than one if more than one binding has prefixStroke as it's prefix)
if (k.getPrefixStroke() != null) {
Set<String> set = inputMap.get(k.getPrefixStroke());
if (set != null) {
for (String str : set) {
if (str.equals(PrefixAction.actionDesc)) {
set.remove(str);
break;
}
}
}
// get input map to use
inputMapToUse = prefixedInputMapMaps.get(k.getPrefixStroke());
}
// remove stroke
if (inputMapToUse != null) {
Set<String> set = inputMapToUse.get(k.getStroke());
if (set != null) set.remove(actionDesc);
}
// remove action
KeyBindings bindings = (KeyBindings)actionMap.get(actionDesc);
bindings.removeKeyBinding(k);
bindings.setUsingDefaultKeys(false);
// user has modified bindings, write all current bindings to prefs
setBindingsToPrefs(actionDesc);
}
/**
* Get list of default KeyBindings for <code>actionDesc</code>
* @param actionDesc the action description
* @return list of KeyStrokePairs.
*/
/*
public synchronized List getDefaultKeyBindingsFor(String actionDesc) {
KeyBindings keys = (KeyBindings)defaultActionMap.get(actionDesc);
List bindings = new ArrayList();
for (Iterator it = keys.getKeyStrokePairs(); it.hasNext(); ) {
bindings.add((KeyStrokePair)it.next());
}
return bindings;
}
*/
/**
* Set <code>actionDesc<code> to use default KeyBindings
* @param actionDesc the action description
*/
public synchronized void resetKeyBindings(String actionDesc) {
// remove all previous bindings
KeyBindings keys = (KeyBindings)actionMap.get(actionDesc);
if (keys != null) {
// get new iterator each time, because removeKeyStrokePair modifies the list
while(true) {
Iterator<KeyStrokePair> it = keys.getKeyStrokePairs();
if (!it.hasNext()) break;
KeyStrokePair pair = it.next();
removeKeyBinding(actionDesc, pair);
}
}
// remove any user saved preferences
//prefs.remove(actionDesc);
prefs.remove(prefPrefix+actionDesc);
// add in default key bindings
for (Iterator<KeyStrokePair> it = keys.getDefaultKeyStrokePairs(); it.hasNext(); ) {
KeyStrokePair k = it.next();
addKeyBinding(actionDesc, k);
}
keys.setUsingDefaultKeys(true);
}
/**
* Get bindings for action string
* @param actionDesc string describing action (KeyBinding.actionDesc)
* @return a KeyBindings object, or null.
*/
public synchronized KeyBindings getKeyBindings(String actionDesc) {
return (KeyBindings)actionMap.get(actionDesc);
}
/**
* Class that converts internal key mappings to InputMap and ActionMap objects.
*/
public static class KeyMaps
{
private InputMap im;
private ActionMap am;
KeyMaps(KeyBindingManager kbm, Map<KeyStroke,Set<String>> inputMap, Map<String,Object> actionMap)
{
im = new InputMap();
am = new ActionMap();
for(KeyStroke ks : inputMap.keySet())
{
Set<String> theSet = inputMap.get(ks);
if (theSet.size() > 0)
{
String actionName = theSet.iterator().next();
im.put(ks, actionName);
am.put(actionName, new MyAbstractAction(actionName, kbm));
}
}
}
public InputMap getInputMap() { return im; }
public ActionMap getActionMap() { return am; }
}
private static class MyAbstractAction extends AbstractAction
{
private String actionName;
private KeyBindingManager kbm;
MyAbstractAction(String actionName, KeyBindingManager kbm)
{
this.actionName = actionName;
this.kbm = kbm;
}
public void actionPerformed(ActionEvent event)
{
KeyBindings kb = kbm.getKeyBindings(actionName);
kb.actionPerformed(event);
}
}
/**
* Method to return an object that has real InputMap and ActionMap objects.
* @return a KeyMaps object.
*/
public KeyMaps getKeyMaps()
{
KeyMaps km = new KeyMaps(this, inputMap, actionMap);
return km;
}
/**
* Set the faked event source of the KeyBindings object. See
* KeyBindings.setEventSource() for details.
* @param actionDesc the action description used to find the KeyBindings object.
* @param source the object to use as the source of the event. (Event.getSource()).
*/
public synchronized void setEventSource(String actionDesc, Object source) {
KeyBindings keys = (KeyBindings)actionMap.get(actionDesc);
keys.setEventSource(source);
}
/**
* Returns true if KeyBindings for the action described by
* actionDesc are already present in hash tables.
* @param actionDesc the action description of the KeyBindings
* @return true if key binding found in manager, false otherwise.
*/
/*
public synchronized boolean hasKeyBindings(String actionDesc) {
KeyBindings k = (KeyBindings)actionMap.get(actionDesc);
if (k != null) return true;
return false;
}
*/
/**
* Get a list of KeyBindings that conflict with the key combo
* <code>prefixStroke, stroke</code>. A conflict is registered if:
* an existing stroke is the same as <code>prefixStroke</code>; or
* an existing stroke is the same <code>stroke</code>
* (if <code>prefixStroke</code> is null);
* or an existing prefixStroke,stroke combo is the same as
* <code>prefixStroke,stroke</code>.
* <p>
* The returned list consists of newly created KeyBindings objects, not
* KeyBindings objects that are used in the key manager database.
* This is because not all KeyStrokePairs in an existing KeyBindings
* object will necessarily conflict. However, there may be more than
* one KeyStrokePair in a returned KeyBindings object from the list if
* more than one KeyStrokePair does actually conflict.
* <p>
* Returns an empty list if there are no conflicts.
* @param pair the KeyStrokePair
* @return a list of conflicting <code>KeyBindings</code>. Empty list if no conflicts.
*/
public synchronized List<KeyBindings> getConflictingKeyBindings(KeyStrokePair pair) {
List<KeyBindings> conflicts = new ArrayList<KeyBindings>(); // list of actual KeyBindings
List<String> conflictsStrings = new ArrayList<String>(); // list of action strings
Map<KeyStroke,Set<String>> inputMapToUse = inputMap;
if (pair.getPrefixStroke() != null) {
// check if conflicts with any single key Binding
Set<String> set = inputMap.get(pair.getPrefixStroke());
if (set != null) {
for (String str : set) {
if (str.equals(PrefixAction.actionDesc)) continue;
// add to conflicts
conflictsStrings.add(str);
}
}
inputMapToUse = prefixedInputMapMaps.get(pair.getPrefixStroke());
}
// find stroke conflicts
if (inputMapToUse != null) {
Set<String> set = inputMapToUse.get(pair.getStroke());
if (set != null) {
for (String str : set) {
if (str.equals(PrefixAction.actionDesc)) {
// find all string associated with prefix in prefix map
// NOTE: this condition is never true if prefixStroke is valid
// and we are using a prefixed map...prefixActions are only in primary inputMap.
Map<KeyStroke,Set<String>> prefixMap = prefixedInputMapMaps.get(pair.getStroke());
if (prefixMap != null) {
for (Iterator<Set<String>> it2 = prefixMap.values().iterator(); it2.hasNext(); ) {
// all existing prefixStroke,stroke combos conflict, so add them all
Set<String> prefixList = it2.next(); // this is a set of strings
conflictsStrings.addAll(prefixList);
}
}
} else {
conflictsStrings.add(str); // otherwise this is a key actionDesc
}
}
}
}
// get all KeyBindings from ActionMap
for (String aln : conflictsStrings) {
ActionListener action = (ActionListener)actionMap.get(aln);
if (action == null) continue;
if (action instanceof PrefixAction) continue;
KeyBindings keys = (KeyBindings)action;
KeyBindings conflicting = new KeyBindings(keys.getActionDesc());
for (Iterator<KeyStrokePair> it2 = keys.getKeyStrokePairs(); it2.hasNext(); ) {
// Unfortunately, any keyBinding can map to this action, including
// ones that don't actually conflict. So we need to double check
// if binding really conflicts.
KeyStrokePair pair2 = it2.next();
if (pair.getPrefixStroke() != null) {
// check prefix conflict
if (pair2.getPrefixStroke() != null) {
// only conflict is if both prefix and stroke match
if (pair.getStroke() == pair2.getStroke())
conflicting.addKeyBinding(pair2);
} else {
// conflict if prefixStroke matches pair2.stroke
if (pair.getPrefixStroke() == pair2.getStroke())
conflicting.addKeyBinding(pair2);
}
} else {
// no prefixStroke
if (pair2.getPrefixStroke() != null) {
// conflict if stroke matches pair2.prefixStroke
if (pair.getStroke() == pair2.getPrefixStroke())
conflicting.addKeyBinding(pair2);
} else {
// no prefixStroke, both only have stroke
if (pair.getStroke() == pair2.getStroke())
conflicting.addKeyBinding(pair2);
}
}
}
// add conflicting KeyBindings to list if it has bindings in it
Iterator conflictingIt = conflicting.getKeyStrokePairs();
if (conflictingIt.hasNext()) conflicts.add(conflicting);
}
return conflicts;
}
/**
* Sets the enabled state of the action to 'b'. If b is false, it
* disables all events that occur when actionDesc takes place. If b is
* true, it enables all resulting events.
* @param actionDesc the describing action
* @param b true to enable, false to disable.
*/
public synchronized void setEnabled(String actionDesc, boolean b) {
ActionListener action = (ActionListener)actionMap.get(actionDesc);
if (action == null) return;
if (action instanceof PrefixAction) return;
KeyBindings k = (KeyBindings)action;
k.setEnabled(b);
}
/**
* Get the enabled state of the action described by 'actionDesc'.
* @param actionDesc the describing action.
* @return true if the action is enabled, false otherwise.
*/
public synchronized boolean getEnabled(String actionDesc) {
ActionListener action = (ActionListener)actionMap.get(actionDesc);
if (action == null) return false;
if (action instanceof PrefixAction) return false;
KeyBindings k = (KeyBindings)action;
return k.getEnabled();
}
/**
* Check if there are any bindings that do not have any
* associated actions.
*/
public synchronized void deleteEmptyBindings() {
Set<String> keys = actionMap.keySet();
for (String key : keys) {
ActionListener action = (ActionListener)actionMap.get(key);
if (action instanceof KeyBindings) {
KeyBindings bindings = (KeyBindings)action;
Iterator listenersIt = bindings.getActionListeners();
if (!listenersIt.hasNext()) {
// no listeners on the action
System.out.println("Warning: Deleting defunct binding for "+key+" [ "+bindings.bindingsToString()+ " ]...action does not exist anymore");
// delete bindings
removeBindingsFromPrefs(key);
}
}
}
}
// --------------------------------- Private -------------------------------------
/**
* Adds a KeyStrokePair <i>pair</i> as an active binding for action <i>actionDesc</i>.
* @param actionDesc the action description
* @param pair a key stroke pair
* @return the new KeyBindings object, or an existing KeyBindings object for actionDesc
*/
private synchronized KeyBindings addKeyBinding(String actionDesc, KeyStrokePair pair) {
if (pair == null) return null;
// warn if conflicting key bindings created
List<KeyBindings> conflicts = getConflictingKeyBindings(pair);
if (conflicts.size() > 0) {
System.out.println("WARNING: Key binding for "+actionDesc+" [ " +pair.toString()+" ] conflicts with:");
for (KeyBindings k : conflicts) {
System.out.println(" > "+k.getActionDesc()+" [ "+k.bindingsToString()+" ]");
}
}
if (DEBUG) System.out.println("Adding binding for "+actionDesc+": "+pair.toString());
KeyStroke prefixStroke = pair.getPrefixStroke();
KeyStroke stroke = pair.getStroke();
Map<KeyStroke,Set<String>> inputMapToUse = inputMap;
if (prefixStroke != null) {
// find HashMap based on prefixAction
inputMapToUse = prefixedInputMapMaps.get(prefixStroke);
if (inputMapToUse == null) {
inputMapToUse = new HashMap<KeyStroke,Set<String>>();
prefixedInputMapMaps.put(prefixStroke, inputMapToUse);
}
// add prefix action to primary input map
Set<String> set = inputMap.get(prefixStroke);
if (set == null) {
set = new HashSet<String>();
inputMap.put(prefixStroke, set);
}
set.add(PrefixAction.actionDesc);
}
// add stroke to input map to use
Set<String> set = inputMapToUse.get(stroke);
if (set == null) {
set = new HashSet<String>();
inputMapToUse.put(stroke, set);
}
set.add(actionDesc);
// add stroke to KeyBindings
KeyBindings keys = (KeyBindings)actionMap.get(actionDesc);
if (keys == null) {
// no bindings for actionDesc
keys = new KeyBindings(actionDesc);
actionMap.put(actionDesc, keys);
}
keys.addKeyBinding(pair);
return keys;
}
// ---------------------------- Preferences Storage ------------------------------
/**
* Add KeyBinding to stored user preferences.
* @param actionDesc the action description under which to store all the key bindings
*/
private synchronized void setBindingsToPrefs(String actionDesc) {
if (prefs == null) return;
if (actionDesc == null || actionDesc.equals("")) return;
KeyBindings keyBindings = (KeyBindings)actionMap.get(actionDesc);
if (keyBindings == null) return;
String actionDescAbbrev = actionDesc;
if ((actionDesc.length() + prefPrefix.length()) > Preferences.MAX_KEY_LENGTH) {
int start = actionDesc.length() + prefPrefix.length() - Preferences.MAX_KEY_LENGTH;
actionDescAbbrev = actionDesc.substring(start, actionDesc.length());
}
if (debugPrefs) System.out.println("Writing to pref '"+prefPrefix+actionDescAbbrev+"': "+keyBindings.bindingsToString());
prefs.put(prefPrefix+actionDescAbbrev, keyBindings.bindingsToString());
}
/**
* Get KeyBindings for <code>actionDesc</code> from Preferences.
* Returns null if actionDesc not present in prefs.
* @param actionDesc the action description associated with these bindings
* @return a list of KeyStrokePairs
*/
private synchronized List<KeyStrokePair> getBindingsFromPrefs(String actionDesc) {
if (prefs == null) return null;
if (actionDesc == null || actionDesc.equals("")) return null;
String actionDescAbbrev = actionDesc;
if ((actionDesc.length() + prefPrefix.length()) > Preferences.MAX_KEY_LENGTH) {
int start = actionDesc.length() + prefPrefix.length() - Preferences.MAX_KEY_LENGTH;
actionDescAbbrev = actionDesc.substring(start, actionDesc.length());
}
String keys = prefs.get(prefPrefix+actionDescAbbrev, null);
if (keys == null) return null;
if (debugPrefs) System.out.println("Read from prefs for "+prefPrefix+actionDescAbbrev+": "+keys);
KeyBindings k = new KeyBindings(actionDesc);
k.addKeyBindings(keys);
if (debugPrefs) System.out.println(" turned into: "+k.describe());
List<KeyStrokePair> bindings = new ArrayList<KeyStrokePair>();
for (Iterator<KeyStrokePair> it = k.getKeyStrokePairs(); it.hasNext(); ) {
bindings.add(it.next());
}
return bindings;
}
/**
* Restored saved bindings from preferences. Usually called after
* menu has been created.
*/
public synchronized void restoreSavedBindings(boolean initialCall) {
if (initialCall && initialized == true) return;
initialized = true;
if (prefs == null) return;
// try to see if binding saved in preferences for each action
for (Map.Entry<String,Object> entry : actionMap.entrySet()) {
String actionDesc = entry.getKey();
if (actionDesc == null || actionDesc.equals("")) continue;
// clear current bindings
if (entry.getValue() instanceof PrefixAction) {
continue;
}
KeyBindings bindings = (KeyBindings)entry.getValue();
bindings.clearKeyBindings();
// look up bindings in prefs
List<KeyStrokePair> keyPairs = getBindingsFromPrefs(bindings.getActionDesc());
if (keyPairs == null) {
// no entry found, use default settings
bindings.setUsingDefaultKeys(true);
for (Iterator<KeyStrokePair> it2 = bindings.getDefaultKeyStrokePairs(); it2.hasNext(); ) {
KeyStrokePair pair = it2.next();
addKeyBinding(actionDesc, pair);
}
} else {
// otherwise, add bindings found
bindings.setUsingDefaultKeys(false);
for (KeyStrokePair pair : keyPairs) {
addKeyBinding(actionDesc, pair);
}
}
}
}
/**
* Remove any bindings stored for actionDesc.
*/
private synchronized void removeBindingsFromPrefs(String actionDesc) {
if (prefs == null) return;
if (actionDesc == null || actionDesc.equals("")) return;
prefs.remove(prefPrefix+actionDesc);
}
}
| false | true | public synchronized boolean processKeyEvent(KeyEvent e) {
if (DEBUG) System.out.println("got event (consumed="+e.isConsumed()+") "+e);
// see if this is a valid key event
if (!validKeyEvent(e)) return false;
// ignore events that come from dialogs, or non-Control events that are not from an EditWindow/WaveformWindow
Component c = e.getComponent();
boolean valid = false;
while (c != null)
{
if (c instanceof EditWindow) { valid = true; break; }
if (c instanceof WaveformWindow.OnePanel) { valid = true; break; }
if (c instanceof TopLevel) { valid = true; break; }
if (c instanceof EDialog) { lastPrefix = null; return false; }
if (c instanceof EModelessDialog) { lastPrefix = null; return false; }
if (c instanceof JOptionPane) { lastPrefix = null; return false; }
if (c instanceof TextWindow.TextWindowPanel) { lastPrefix = null; return false; }
if (c instanceof OpenFile.OpenFileSwing) { lastPrefix = null; return false; }
if (c instanceof GetInfoText.EIPEditorPane) { lastPrefix = null; return false; }
if (c instanceof GetInfoText.EIPTextField) { lastPrefix = null; return false; }
if (c instanceof ManualViewer) { lastPrefix = null; return false; }
if (c instanceof ManualViewer.EditHTML) { lastPrefix = null; return false; }
c = c.getParent();
}
if (!valid && (e.getModifiers() & InputEvent.CTRL_MASK) == 0)
{ lastPrefix = null; return false; }
// see if any popup menus are visible
WindowFrame wf = WindowFrame.getCurrentWindowFrame();
JMenuBar mb = wf.getFrame().getJMenuBar();
for(int i=0; i<mb.getMenuCount(); i++)
{
JMenu m = mb.getMenu(i);
if (m == null) continue;
if (!m.isPopupMenuVisible()) continue;
lastPrefix = null; // someone did something with it, null prefix key
return false;
}
// get KeyStroke
KeyStroke stroke = KeyStroke.getKeyStrokeForEvent(e);
if (DEBUG) System.out.println(" Current key is "+stroke+", code="+e.getKeyCode()+", type="+stroke.getKeyEventType());
// convert arrow keys which appear only on release event
// if ((e.getModifiers() & (InputEvent.CTRL_MASK|InputEvent.SHIFT_MASK)) != InputEvent.CTRL_MASK &&
// stroke.getKeyEventType() == KeyEvent.KEY_RELEASED)
// {
// if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT ||
// e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN)
// {
// stroke = KeyStroke.getKeyStroke(e.getKeyCode(), stroke.getModifiers());
// }
// } else
{
// remove shift modifier from Events. Lets KeyStrokes like '<' register correctly,
// because they are always delivered as SHIFT-'<'.
// if ((e.getModifiers() & InputEvent.SHIFT_MASK) != 0 && !Character.isLetter(e.getKeyCode()) && !Character.isDigit(e.getKeyCode()))
if (!Character.isLetter(e.getKeyCode()) && !Character.isDigit(e.getKeyCode()))
{
if (e.getKeyCode() != KeyEvent.VK_LEFT && e.getKeyCode() != KeyEvent.VK_RIGHT &&
e.getKeyCode() != KeyEvent.VK_UP && e.getKeyCode() != KeyEvent.VK_DOWN)
stroke = KeyStroke.getKeyStroke(e.getKeyChar());
}
}
// ignore if consumed
if (e.isConsumed()) {
lastPrefix = null; // someone did something with it, null prefix key
return false;
}
Map<KeyStroke,Set<String>> inputMapToUse = inputMap;
// check if we should use prefixed key map instead of regular inputMap
if (lastPrefix != null) {
// get input map based on prefix key
inputMapToUse = prefixedInputMapMaps.get(lastPrefix);
if (inputMapToUse == null) { lastPrefix = null; return false; }
}
ActionListener action = null;
ActionEvent evt = new ActionEvent(e, ActionEvent.ACTION_PERFORMED, stroke.toString(), stroke.getModifiers());
boolean actionPerformed = false;
boolean prefixActionPerformed = false;
// get set of action strings, iterate over them
Set<String> keyBindingList = inputMapToUse.get(stroke);
if (keyBindingList != null) {
for (String actionDesc : keyBindingList) {
// get KeyBinding object from action map, activate its action
// note that if this is a prefixed action, this could actually be a
// PrefixAction object instead of a KeyBinding object.
action = (ActionListener)actionMap.get(actionDesc);
if (action instanceof PrefixAction) {
if (!prefixActionPerformed) {
action.actionPerformed(evt); // only do this once
prefixActionPerformed = true;
}
} else {
action.actionPerformed(evt);
lastPrefix = null;
}
actionPerformed = true;
}
}
if (!actionPerformed) {
// if no action to perform, perhaps the user hit a prefix key, then
// decided to start another prefix-key-combo (that does not result in
// a valid binding with the first prefix, obviously). We'll be nice
// and check for this case
Map prefixMap = prefixedInputMapMaps.get(stroke);
if (prefixMap != null) {
// valid prefix key, fire prefix event
prefixAction.actionPerformed(evt);
actionPerformed = true;
} else {
lastPrefix = null; // nothing to do
}
}
if (DEBUG) System.out.println(" actionPerformed="+actionPerformed);
if (actionPerformed) {
e.consume(); // consume event if we did something useful with it
return true; // let KeyboardFocusManager know we consumed event
}
// otherwise, do not consume, and return false to let KeyboardFocusManager
// know that we did nothing with Event, and to pass it on
return false;
}
| public synchronized boolean processKeyEvent(KeyEvent e) {
if (DEBUG) System.out.println("got event (consumed="+e.isConsumed()+") "+e);
// see if this is a valid key event
if (!validKeyEvent(e)) return false;
// ignore events that come from dialogs, or non-Control events that are not from an EditWindow/WaveformWindow
Component c = e.getComponent();
boolean valid = false;
while (c != null)
{
if (c instanceof EditWindow) { valid = true; break; }
if (c instanceof WaveformWindow.OnePanel) { valid = true; break; }
if (c instanceof TopLevel) { valid = true; break; }
if (c instanceof EDialog) { lastPrefix = null; return false; }
if (c instanceof EModelessDialog) { lastPrefix = null; return false; }
if (c instanceof JOptionPane) { lastPrefix = null; return false; }
if (c instanceof TextWindow.TextWindowPanel) { lastPrefix = null; return false; }
if (c instanceof OpenFile.OpenFileSwing) { lastPrefix = null; return false; }
if (c instanceof GetInfoText.EIPEditorPane) { lastPrefix = null; return false; }
if (c instanceof GetInfoText.EIPTextField) { lastPrefix = null; return false; }
if (c instanceof ManualViewer) { lastPrefix = null; return false; }
if (c instanceof ManualViewer.EditHTML) { lastPrefix = null; return false; }
c = c.getParent();
}
if (!valid && (e.getModifiers() & InputEvent.CTRL_MASK) == 0)
{ lastPrefix = null; return false; }
// see if any popup menus are visible
WindowFrame wf = WindowFrame.getCurrentWindowFrame();
JMenuBar mb = wf.getFrame().getJMenuBar();
for(int i=0; i<mb.getMenuCount(); i++)
{
JMenu m = mb.getMenu(i);
if (m == null) continue;
if (!m.isPopupMenuVisible()) continue;
lastPrefix = null; // someone did something with it, null prefix key
return false;
}
// get KeyStroke
KeyStroke stroke = KeyStroke.getKeyStrokeForEvent(e);
if (DEBUG) System.out.println(" Current key is "+stroke+", code="+e.getKeyCode()+", type="+stroke.getKeyEventType());
// convert arrow keys which appear only on release event
// if ((e.getModifiers() & (InputEvent.CTRL_MASK|InputEvent.SHIFT_MASK)) != InputEvent.CTRL_MASK &&
// stroke.getKeyEventType() == KeyEvent.KEY_RELEASED)
// {
// if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT ||
// e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN)
// {
// stroke = KeyStroke.getKeyStroke(e.getKeyCode(), stroke.getModifiers());
// }
// } else
{
// remove shift modifier from Events. Lets KeyStrokes like '<' register correctly,
// because they are always delivered as SHIFT-'<'.
if ((e.getModifiers() & InputEvent.SHIFT_MASK) != 0 && !Character.isLetter(e.getKeyCode()) && !Character.isDigit(e.getKeyCode()))
{
if (e.getKeyCode() != KeyEvent.VK_LEFT && e.getKeyCode() != KeyEvent.VK_RIGHT &&
e.getKeyCode() != KeyEvent.VK_UP && e.getKeyCode() != KeyEvent.VK_DOWN)
stroke = KeyStroke.getKeyStroke(e.getKeyChar());
}
if (e.getKeyCode() == '[' || e.getKeyCode() == ']')
stroke = KeyStroke.getKeyStroke(e.getKeyChar());
}
// ignore if consumed
if (e.isConsumed()) {
lastPrefix = null; // someone did something with it, null prefix key
return false;
}
Map<KeyStroke,Set<String>> inputMapToUse = inputMap;
// check if we should use prefixed key map instead of regular inputMap
if (lastPrefix != null) {
// get input map based on prefix key
inputMapToUse = prefixedInputMapMaps.get(lastPrefix);
if (inputMapToUse == null) { lastPrefix = null; return false; }
}
ActionListener action = null;
ActionEvent evt = new ActionEvent(e, ActionEvent.ACTION_PERFORMED, stroke.toString(), stroke.getModifiers());
boolean actionPerformed = false;
boolean prefixActionPerformed = false;
// get set of action strings, iterate over them
Set<String> keyBindingList = inputMapToUse.get(stroke);
if (keyBindingList != null) {
for (String actionDesc : keyBindingList) {
// get KeyBinding object from action map, activate its action
// note that if this is a prefixed action, this could actually be a
// PrefixAction object instead of a KeyBinding object.
action = (ActionListener)actionMap.get(actionDesc);
if (action instanceof PrefixAction) {
if (!prefixActionPerformed) {
action.actionPerformed(evt); // only do this once
prefixActionPerformed = true;
}
} else {
action.actionPerformed(evt);
lastPrefix = null;
}
actionPerformed = true;
}
}
if (!actionPerformed) {
// if no action to perform, perhaps the user hit a prefix key, then
// decided to start another prefix-key-combo (that does not result in
// a valid binding with the first prefix, obviously). We'll be nice
// and check for this case
Map prefixMap = prefixedInputMapMaps.get(stroke);
if (prefixMap != null) {
// valid prefix key, fire prefix event
prefixAction.actionPerformed(evt);
actionPerformed = true;
} else {
lastPrefix = null; // nothing to do
}
}
if (DEBUG) System.out.println(" actionPerformed="+actionPerformed);
if (actionPerformed) {
e.consume(); // consume event if we did something useful with it
return true; // let KeyboardFocusManager know we consumed event
}
// otherwise, do not consume, and return false to let KeyboardFocusManager
// know that we did nothing with Event, and to pass it on
return false;
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/actions/StoppedAction.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/actions/StoppedAction.java
index c9b8ec482..0b6d690d9 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/actions/StoppedAction.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/actions/StoppedAction.java
@@ -1,107 +1,108 @@
package de.fu_berlin.inf.dpp.ui.actions;
import org.apache.log4j.Logger;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.ImageData;
import org.picocontainer.Disposable;
import org.picocontainer.annotations.Inject;
import de.fu_berlin.inf.dpp.SarosPluginContext;
import de.fu_berlin.inf.dpp.annotations.Component;
import de.fu_berlin.inf.dpp.project.AbstractSarosSessionListener;
import de.fu_berlin.inf.dpp.project.ISarosSession;
import de.fu_berlin.inf.dpp.project.ISarosSessionListener;
import de.fu_berlin.inf.dpp.project.ISarosSessionManager;
import de.fu_berlin.inf.dpp.synchronize.StopManager;
import de.fu_berlin.inf.dpp.ui.ImageManager;
import de.fu_berlin.inf.dpp.ui.Messages;
import de.fu_berlin.inf.dpp.util.ObservableValue;
import de.fu_berlin.inf.dpp.util.Utils;
import de.fu_berlin.inf.dpp.util.ValueChangeListener;
/**
* The icon of this action is used as visual indicator for the user if the
* {@link StopManager} blocked the project.
*
* Pressing the button has no effect for users, unless eclipse is started with
* assertions enabled. Then it is possible to manually unblock the project for
* debugging purposes.
*/
@Component(module = "action")
public class StoppedAction extends Action implements Disposable {
private static final Logger log = Logger.getLogger(StoppedAction.class);
protected ObservableValue<Boolean> isBlockedObservable;
@Inject
protected ISarosSessionManager sessionManager;
/**
* Register to the StopManager of the new session.
*/
private final ISarosSessionListener sessionListener = new AbstractSarosSessionListener() {
@Override
public void sessionStarted(ISarosSession newSarosSession) {
isBlockedObservable = newSarosSession.getStopManager()
.getBlockedObservable();
isBlockedObservable
.addAndNotify(new ValueChangeListener<Boolean>() {
public void setValue(Boolean newValue) {
setUnblockEnabled(newValue);
}
});
}
@Override
public void sessionEnded(ISarosSession oldSarosSession) {
isBlockedObservable = null;
setUnblockEnabled(false);
}
};
public StoppedAction() {
+ setEnabled(false);
setText(Messages.StoppedAction_title);
setImageDescriptor(new ImageDescriptor() {
@Override
public ImageData getImageData() {
return ImageManager.ELCL_SAROS_SESSION_STOP_PROCESS
.getImageData();
}
});
SarosPluginContext.initComponent(this);
sessionManager.addSarosSessionListener(sessionListener);
}
void setUnblockEnabled(final boolean blocked) {
Utils.runSafeSWTAsync(log, new Runnable() {
@Override
public void run() {
setEnabled(blocked);
setToolTipText(blocked ? Messages.StoppedAction_tooltip : null);
}
});
}
@Override
public void run() {
// The Action should be disabled when there is no session.
assert sessionManager.getSarosSession() != null;
// Attention: Assertion with side effect ahead.
boolean isDebug = false;
assert (isDebug = true) == true;
if (isDebug && sessionManager.getSarosSession() != null) {
log.warn("Manually unblocking project."); //$NON-NLS-1$
sessionManager.getSarosSession().getStopManager()
.lockProject(false);
}
}
@Override
public void dispose() {
sessionManager.removeSarosSessionListener(sessionListener);
}
}
| true | true | public StoppedAction() {
setText(Messages.StoppedAction_title);
setImageDescriptor(new ImageDescriptor() {
@Override
public ImageData getImageData() {
return ImageManager.ELCL_SAROS_SESSION_STOP_PROCESS
.getImageData();
}
});
SarosPluginContext.initComponent(this);
sessionManager.addSarosSessionListener(sessionListener);
}
| public StoppedAction() {
setEnabled(false);
setText(Messages.StoppedAction_title);
setImageDescriptor(new ImageDescriptor() {
@Override
public ImageData getImageData() {
return ImageManager.ELCL_SAROS_SESSION_STOP_PROCESS
.getImageData();
}
});
SarosPluginContext.initComponent(this);
sessionManager.addSarosSessionListener(sessionListener);
}
|
diff --git a/src/com/jidesoft/swing/ScrollPaneOverview.java b/src/com/jidesoft/swing/ScrollPaneOverview.java
index 0463d17b..9530f030 100644
--- a/src/com/jidesoft/swing/ScrollPaneOverview.java
+++ b/src/com/jidesoft/swing/ScrollPaneOverview.java
@@ -1,224 +1,224 @@
package com.jidesoft.swing;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.MouseInputListener;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.geom.Area;
import java.awt.image.BufferedImage;
/**
* Original code http://forums.java.net/jive/thread.jspa?forumID=73&threadID=14674 under "Do whatever you want with this
* code" license
*/
@SuppressWarnings("serial")
public class ScrollPaneOverview extends JComponent {
private static final int MAX_SIZE = 400;
private static final int MAX_SCALE = 20;
private Component _owner;
private JScrollPane _scrollPane;
private Component _viewComponent;
protected JPopupMenu _popupMenu;
private BufferedImage _image;
private Rectangle _startRectangle;
private Rectangle _rectangle;
private Point _startPoint;
private double _scale;
private int xOffset;
private int yOffset;
private Color _selectionBorder = Color.BLACK;
public ScrollPaneOverview(JScrollPane scrollPane, Component owner) {
_scrollPane = scrollPane;
_owner = owner;
_image = null;
_startRectangle = null;
_rectangle = null;
_startPoint = null;
_scale = 0.0;
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
MouseInputListener mil = new MouseInputAdapter() {
// A new approach suggested by [email protected]
@Override
public void mousePressed(MouseEvent e) {
if (_startPoint != null) {
Point newPoint = e.getPoint();
int deltaX = (int) ((newPoint.x - _startPoint.x) / _scale);
int deltaY = (int) ((newPoint.y - _startPoint.y) / _scale);
scroll(deltaX, deltaY);
}
_startPoint = null;
_startRectangle = _rectangle;
}
@Override
public void mouseMoved(MouseEvent e) {
if (_startPoint == null) {
_startPoint = new Point(_rectangle.x + _rectangle.width / 2, _rectangle.y + _rectangle.height / 2);
}
Point newPoint = e.getPoint();
moveRectangle(newPoint.x - _startPoint.x, newPoint.y - _startPoint.y);
}
};
addMouseListener(mil);
addMouseMotionListener(mil);
_popupMenu = new JPopupMenu();
_popupMenu.setLayout(new BorderLayout());
_popupMenu.add(this, BorderLayout.CENTER);
}
public void setSelectionBorderColor(Color selectionBorder) {
_selectionBorder = selectionBorder;
}
public Color getSelectionBorder() {
return _selectionBorder;
}
@Override
protected void paintComponent(Graphics g) {
if (_image == null || _rectangle == null)
return;
Graphics2D g2d = (Graphics2D) g;
Insets insets = getInsets();
int xOffset = insets.left;
int yOffset = insets.top;
g.setColor(_scrollPane.getViewport().getView().getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(_image, xOffset, yOffset, null);
int availableWidth = getWidth() - insets.left - insets.right;
int availableHeight = getHeight() - insets.top - insets.bottom;
Area area = new Area(new Rectangle(xOffset, yOffset, availableWidth, availableHeight));
area.subtract(new Area(_rectangle));
g.setColor(new Color(255, 255, 255, 128));
g2d.fill(area);
Color oldcolor = g.getColor();
g.setColor(_selectionBorder);
g.drawRect(_rectangle.x, _rectangle.y, _rectangle.width, _rectangle.height);
g.setColor(oldcolor);
}
@Override
public Dimension getPreferredSize() {
if (_image == null || _rectangle == null)
return new Dimension();
Insets insets = getInsets();
return new Dimension(_image.getWidth(null) + insets.left + insets.right, _image.getHeight(null) + insets.top + insets.bottom);
}
public void display() {
_viewComponent = _scrollPane.getViewport().getView();
if (_viewComponent == null) {
return;
}
int maxSize = Math.max(MAX_SIZE, Math.max(_scrollPane.getWidth(), _scrollPane.getHeight()) / 2);
int width = Math.min(_viewComponent.getWidth(), _scrollPane.getViewport().getWidth() * MAX_SCALE);
- if (width == 0) {
+ if (width <= 0) {
return;
}
int height = Math.min(_viewComponent.getHeight(), _scrollPane.getViewport().getHeight() * MAX_SCALE);
- if (height == 0) {
+ if (height <= 0) {
return;
}
double scaleX = (double) maxSize / width;
double scaleY = (double) maxSize / height;
_scale = Math.max(1.0 / MAX_SCALE, Math.min(scaleX, scaleY));
_image = new BufferedImage((int) (width * _scale), (int) (height * _scale), BufferedImage.TYPE_INT_RGB);
Graphics2D g = _image.createGraphics();
// If the view is larger than the max scale allows only the the top left most part will now be painted
// One solution would be paint only the part around the current position, but I can't get it to paint - Walter Laan.
// note that without limiting the scale, the width/height will become zero (illegal for BufferedImage)
// See CornerScrollerVisualTest in the test folder
// g.setColor(_viewComponent.getBackground());
// g.fillRect(0, 0, _viewComponent.getWidth(), _viewComponent.getHeight());
// Point viewPosition = _scrollPane.getViewport().getViewPosition();
// xOffset = Math.max(0, viewPosition.x - (width / 2));
// yOffset = Math.max(0, viewPosition.y - (height / 2));
// g.translate(-xOffset, -yOffset);
// g.setClip(0, 0, width, height);
g.scale(_scale, _scale);
g.setClip(xOffset, yOffset, width, height);
/// {{{ Qian Qian 10/72007
boolean wasDoubleBuffered = _viewComponent.isDoubleBuffered();
try {
if (_viewComponent instanceof JComponent) {
((JComponent) _viewComponent).setDoubleBuffered(false);
}
_viewComponent.paint(g);
}
finally {
if (_viewComponent instanceof JComponent) {
((JComponent) _viewComponent).setDoubleBuffered(wasDoubleBuffered);
}
g.dispose();
}
/// QianQian 10/7/2007 }}}
_startRectangle = _scrollPane.getViewport().getViewRect();
Insets insets = getInsets();
_startRectangle.x = (int) (_scale * _startRectangle.x + insets.left);
_startRectangle.y = (int) (_scale * _startRectangle.y + insets.right);
_startRectangle.width *= _scale;
_startRectangle.height *= _scale;
_rectangle = _startRectangle;
Point centerPoint = new Point(_rectangle.x + _rectangle.width / 2, _rectangle.y + _rectangle.height / 2);
showPopup(-centerPoint.x, -centerPoint.y, _owner);
}
/**
* Show popup at designated location.
* <p/>
* You could override this method to show the popup in different location.
*
* @param x the x axis pixel
* @param y the y axis pixel
* @param owner the owner of the popup
*/
protected void showPopup(int x, int y, Component owner) {
_popupMenu.show(owner, x, y);
}
private void moveRectangle(int aDeltaX, int aDeltaY) {
if (_startRectangle == null)
return;
Insets insets = getInsets();
Rectangle newRect = new Rectangle(_startRectangle);
newRect.x += aDeltaX;
newRect.y += aDeltaY;
newRect.x = Math.min(Math.max(newRect.x, insets.left), getWidth() - insets.right - newRect.width);
newRect.y = Math.min(Math.max(newRect.y, insets.right), getHeight() - insets.bottom - newRect.height);
Rectangle clip = new Rectangle();
Rectangle.union(_rectangle, newRect, clip);
clip.grow(2, 2);
_rectangle = newRect;
paintImmediately(clip);
}
private void scroll(int aDeltaX, int aDeltaY) {
JComponent component = (JComponent) _scrollPane.getViewport().getView();
Rectangle rect = component.getVisibleRect();
rect.x += xOffset + aDeltaX;
rect.y += yOffset + aDeltaY;
component.scrollRectToVisible(rect);
_popupMenu.setVisible(false);
}
}
| false | true | public void display() {
_viewComponent = _scrollPane.getViewport().getView();
if (_viewComponent == null) {
return;
}
int maxSize = Math.max(MAX_SIZE, Math.max(_scrollPane.getWidth(), _scrollPane.getHeight()) / 2);
int width = Math.min(_viewComponent.getWidth(), _scrollPane.getViewport().getWidth() * MAX_SCALE);
if (width == 0) {
return;
}
int height = Math.min(_viewComponent.getHeight(), _scrollPane.getViewport().getHeight() * MAX_SCALE);
if (height == 0) {
return;
}
double scaleX = (double) maxSize / width;
double scaleY = (double) maxSize / height;
_scale = Math.max(1.0 / MAX_SCALE, Math.min(scaleX, scaleY));
_image = new BufferedImage((int) (width * _scale), (int) (height * _scale), BufferedImage.TYPE_INT_RGB);
Graphics2D g = _image.createGraphics();
// If the view is larger than the max scale allows only the the top left most part will now be painted
// One solution would be paint only the part around the current position, but I can't get it to paint - Walter Laan.
// note that without limiting the scale, the width/height will become zero (illegal for BufferedImage)
// See CornerScrollerVisualTest in the test folder
// g.setColor(_viewComponent.getBackground());
// g.fillRect(0, 0, _viewComponent.getWidth(), _viewComponent.getHeight());
// Point viewPosition = _scrollPane.getViewport().getViewPosition();
// xOffset = Math.max(0, viewPosition.x - (width / 2));
// yOffset = Math.max(0, viewPosition.y - (height / 2));
// g.translate(-xOffset, -yOffset);
// g.setClip(0, 0, width, height);
g.scale(_scale, _scale);
g.setClip(xOffset, yOffset, width, height);
/// {{{ Qian Qian 10/72007
boolean wasDoubleBuffered = _viewComponent.isDoubleBuffered();
try {
if (_viewComponent instanceof JComponent) {
((JComponent) _viewComponent).setDoubleBuffered(false);
}
_viewComponent.paint(g);
}
finally {
if (_viewComponent instanceof JComponent) {
((JComponent) _viewComponent).setDoubleBuffered(wasDoubleBuffered);
}
g.dispose();
}
/// QianQian 10/7/2007 }}}
_startRectangle = _scrollPane.getViewport().getViewRect();
Insets insets = getInsets();
_startRectangle.x = (int) (_scale * _startRectangle.x + insets.left);
_startRectangle.y = (int) (_scale * _startRectangle.y + insets.right);
_startRectangle.width *= _scale;
_startRectangle.height *= _scale;
_rectangle = _startRectangle;
Point centerPoint = new Point(_rectangle.x + _rectangle.width / 2, _rectangle.y + _rectangle.height / 2);
showPopup(-centerPoint.x, -centerPoint.y, _owner);
}
| public void display() {
_viewComponent = _scrollPane.getViewport().getView();
if (_viewComponent == null) {
return;
}
int maxSize = Math.max(MAX_SIZE, Math.max(_scrollPane.getWidth(), _scrollPane.getHeight()) / 2);
int width = Math.min(_viewComponent.getWidth(), _scrollPane.getViewport().getWidth() * MAX_SCALE);
if (width <= 0) {
return;
}
int height = Math.min(_viewComponent.getHeight(), _scrollPane.getViewport().getHeight() * MAX_SCALE);
if (height <= 0) {
return;
}
double scaleX = (double) maxSize / width;
double scaleY = (double) maxSize / height;
_scale = Math.max(1.0 / MAX_SCALE, Math.min(scaleX, scaleY));
_image = new BufferedImage((int) (width * _scale), (int) (height * _scale), BufferedImage.TYPE_INT_RGB);
Graphics2D g = _image.createGraphics();
// If the view is larger than the max scale allows only the the top left most part will now be painted
// One solution would be paint only the part around the current position, but I can't get it to paint - Walter Laan.
// note that without limiting the scale, the width/height will become zero (illegal for BufferedImage)
// See CornerScrollerVisualTest in the test folder
// g.setColor(_viewComponent.getBackground());
// g.fillRect(0, 0, _viewComponent.getWidth(), _viewComponent.getHeight());
// Point viewPosition = _scrollPane.getViewport().getViewPosition();
// xOffset = Math.max(0, viewPosition.x - (width / 2));
// yOffset = Math.max(0, viewPosition.y - (height / 2));
// g.translate(-xOffset, -yOffset);
// g.setClip(0, 0, width, height);
g.scale(_scale, _scale);
g.setClip(xOffset, yOffset, width, height);
/// {{{ Qian Qian 10/72007
boolean wasDoubleBuffered = _viewComponent.isDoubleBuffered();
try {
if (_viewComponent instanceof JComponent) {
((JComponent) _viewComponent).setDoubleBuffered(false);
}
_viewComponent.paint(g);
}
finally {
if (_viewComponent instanceof JComponent) {
((JComponent) _viewComponent).setDoubleBuffered(wasDoubleBuffered);
}
g.dispose();
}
/// QianQian 10/7/2007 }}}
_startRectangle = _scrollPane.getViewport().getViewRect();
Insets insets = getInsets();
_startRectangle.x = (int) (_scale * _startRectangle.x + insets.left);
_startRectangle.y = (int) (_scale * _startRectangle.y + insets.right);
_startRectangle.width *= _scale;
_startRectangle.height *= _scale;
_rectangle = _startRectangle;
Point centerPoint = new Point(_rectangle.x + _rectangle.width / 2, _rectangle.y + _rectangle.height / 2);
showPopup(-centerPoint.x, -centerPoint.y, _owner);
}
|
diff --git a/Admin/Matrix.java b/Admin/Matrix.java
index 5e6f6768..5f2cde85 100644
--- a/Admin/Matrix.java
+++ b/Admin/Matrix.java
@@ -1,277 +1,279 @@
import java.util.Vector;
import java.util.List;
import java.util.Iterator;
import java.util.Arrays;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.IOException;
// JDOM classes used for document representation
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Attribute;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
/**
* Converts the matrix.xml file to a matrix.texi file, suitable for
* being included from gettext's nls.texi.
*
* @author Bruno Haible
*/
public class Matrix {
public static class PoFile {
String domain;
String team;
int percentage;
public PoFile (String domain, String team, int percentage) {
this.domain = domain;
this.team = team;
this.percentage = percentage;
}
}
public static class Data {
List /* of String */ domains = new Vector();
List /* of String */ teams = new Vector();
List /* of PoFile */ po_files = new Vector();
}
public static final int FALSE = 0;
public static final int TRUE = 1;
public static final int EXTERNAL = 2;
public static void spaces (PrintWriter stream, int n) {
for (int i = n; i > 0; i--)
stream.print(' ');
}
public static void main (String[] args) {
Data data = new Data();
SAXBuilder builder = new SAXBuilder(/*true*/); // "true" turns on validation
Document doc;
try {
doc = builder.build(new File("matrix.xml"));
} catch (JDOMException e) {
e.printStackTrace();
doc = null;
System.exit(1);
}
Element po_inventory = doc.getRootElement();
{
Element domains = po_inventory.getChild("domains");
Iterator i = domains.getChildren("domain").iterator();
while (i.hasNext()) {
Element domain = (Element)i.next();
data.domains.add(domain.getAttribute("name").getValue());
}
}
{
Element teams = po_inventory.getChild("teams");
Iterator i = teams.getChildren("team").iterator();
while (i.hasNext()) {
Element team = (Element)i.next();
data.teams.add(team.getAttribute("name").getValue());
}
}
{
Element po_files = po_inventory.getChild("PoFiles");
Iterator i = po_files.getChildren("po").iterator();
while (i.hasNext()) {
Element po = (Element)i.next();
String value = po.getText();
data.po_files.add(
new PoFile(
po.getAttribute("domain").getValue(),
po.getAttribute("team").getValue(),
value.equals("") ? -1 : Integer.parseInt(value)));
}
}
// Special treatment of clisp. The percentages are incorrect.
data.domains.add("clisp");
if (!data.teams.contains("en"))
data.teams.add("en");
data.po_files.add(new PoFile("clisp","en",100));
data.po_files.add(new PoFile("clisp","de",99));
data.po_files.add(new PoFile("clisp","fr",99));
data.po_files.add(new PoFile("clisp","es",90));
data.po_files.add(new PoFile("clisp","nl",90));
try {
FileWriter f = new FileWriter("matrix.texi");
BufferedWriter bf = new BufferedWriter(f);
PrintWriter stream = new PrintWriter(bf);
String[] domains = (String[])data.domains.toArray(new String[0]);
Arrays.sort(domains);
String[] teams = (String[])data.teams.toArray(new String[0]);
Arrays.sort(teams);
int ndomains = domains.length;
int nteams = teams.length;
int[][] matrix = new int[ndomains][];
for (int d = 0; d < ndomains; d++)
matrix[d] = new int[nteams];
int[] total_per_domain = new int[ndomains];
int[] total_per_team = new int[nteams];
int total = 0;
{
Iterator i = data.po_files.iterator();
while (i.hasNext()) {
PoFile po = (PoFile)i.next();
if (po.percentage >= 50) {
int d = Arrays.binarySearch(domains,po.domain);
if (d < 0)
throw new Error("didn't find domain \""+po.domain+"\"");
int t = Arrays.binarySearch(teams,po.team);
if (t < 0)
throw new Error("didn't find team \""+po.team+"\"");
matrix[d][t] = TRUE;
total_per_domain[d]++;
total_per_team[t]++;
total++;
} else if (po.percentage < 0) {
int d = Arrays.binarySearch(domains,po.domain);
if (d < 0)
throw new Error("didn't find domain \""+po.domain+"\"");
int t = Arrays.binarySearch(teams,po.team);
- if (t < 0)
- throw new Error("didn't find team \""+po.team+"\"");
+ if (t < 0) {
+ System.err.println(po.domain+": didn't find team \""+po.team+"\"");
+ continue;
+ }
matrix[d][t] = EXTERNAL;
}
}
}
// Split into separate tables, to keep 80 column width.
int ngroups;
int[][] groups;
if (true) {
ngroups = 3;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams/3+1 };
groups[1] = new int[] { nteams/3+1, (2*nteams)/3+1 };
groups[2] = new int[] { (2*nteams)/3+1, nteams };
} else if (true) {
ngroups = 2;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams/2+1 };
groups[1] = new int[] { nteams/2+1, nteams };
} else {
ngroups = 1;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams };
}
stream.println("@example");
for (int group = 0; group < ngroups; group++) {
if (group > 0)
stream.println();
stream.println("@group");
if (group == 0)
stream.print("Ready PO files ");
else
stream.print(" ");
for (int t = groups[group][0]; t < groups[group][1]; t++)
stream.print(" "+teams[t]);
stream.println();
stream.print(" +");
for (int t = groups[group][0]; t < groups[group][1]; t++)
for (int i = teams[t].length() + 1; i > 0; i--)
stream.print('-');
stream.println("-+");
for (int d = 0; d < ndomains; d++) {
stream.print(domains[d]);
spaces(stream,16 - domains[d].length());
stream.print('|');
for (int t = groups[group][0]; t < groups[group][1]; t++) {
stream.print(' ');
if (matrix[d][t] == TRUE) {
int i = teams[t].length()-2;
spaces(stream,i/2);
stream.print("[]");
spaces(stream,(i+1)/2);
} else if (matrix[d][t] == EXTERNAL) {
int i = teams[t].length()-2;
spaces(stream,i/2);
stream.print("()");
spaces(stream,(i+1)/2);
} else {
spaces(stream,teams[t].length());
}
}
stream.print(' ');
stream.print('|');
if (group == ngroups-1) {
stream.print(' ');
String s = Integer.toString(total_per_domain[d]);
spaces(stream,2-s.length());
stream.print(s);
}
stream.println();
}
stream.print(" +");
for (int t = groups[group][0]; t < groups[group][1]; t++)
for (int i = teams[t].length() + 1; i > 0; i--)
stream.print('-');
stream.println("-+");
if (group == ngroups-1) {
String s = Integer.toString(nteams);
spaces(stream,4-s.length());
stream.print(s);
stream.print(" teams ");
} else {
stream.print(" ");
}
for (int t = groups[group][0]; t < groups[group][1]; t++)
stream.print(" "+teams[t]);
stream.println();
if (group == ngroups-1) {
String s = Integer.toString(ndomains);
spaces(stream,4-s.length());
stream.print(s);
stream.print(" domains ");
} else {
stream.print(" ");
}
for (int t = groups[group][0]; t < groups[group][1]; t++) {
stream.print(' ');
String s = Integer.toString(total_per_team[t]);
int i = teams[t].length()-2;
spaces(stream,i/2 + (2-s.length()));
stream.print(s);
spaces(stream,(i+1)/2);
}
if (group == ngroups-1) {
stream.print(' ');
stream.print(' ');
String s = Integer.toString(total);
spaces(stream,3-s.length());
stream.print(s);
}
stream.println();
stream.println("@end group");
}
stream.println("@end example");
stream.close();
bf.close();
f.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}
| true | true | public static void main (String[] args) {
Data data = new Data();
SAXBuilder builder = new SAXBuilder(/*true*/); // "true" turns on validation
Document doc;
try {
doc = builder.build(new File("matrix.xml"));
} catch (JDOMException e) {
e.printStackTrace();
doc = null;
System.exit(1);
}
Element po_inventory = doc.getRootElement();
{
Element domains = po_inventory.getChild("domains");
Iterator i = domains.getChildren("domain").iterator();
while (i.hasNext()) {
Element domain = (Element)i.next();
data.domains.add(domain.getAttribute("name").getValue());
}
}
{
Element teams = po_inventory.getChild("teams");
Iterator i = teams.getChildren("team").iterator();
while (i.hasNext()) {
Element team = (Element)i.next();
data.teams.add(team.getAttribute("name").getValue());
}
}
{
Element po_files = po_inventory.getChild("PoFiles");
Iterator i = po_files.getChildren("po").iterator();
while (i.hasNext()) {
Element po = (Element)i.next();
String value = po.getText();
data.po_files.add(
new PoFile(
po.getAttribute("domain").getValue(),
po.getAttribute("team").getValue(),
value.equals("") ? -1 : Integer.parseInt(value)));
}
}
// Special treatment of clisp. The percentages are incorrect.
data.domains.add("clisp");
if (!data.teams.contains("en"))
data.teams.add("en");
data.po_files.add(new PoFile("clisp","en",100));
data.po_files.add(new PoFile("clisp","de",99));
data.po_files.add(new PoFile("clisp","fr",99));
data.po_files.add(new PoFile("clisp","es",90));
data.po_files.add(new PoFile("clisp","nl",90));
try {
FileWriter f = new FileWriter("matrix.texi");
BufferedWriter bf = new BufferedWriter(f);
PrintWriter stream = new PrintWriter(bf);
String[] domains = (String[])data.domains.toArray(new String[0]);
Arrays.sort(domains);
String[] teams = (String[])data.teams.toArray(new String[0]);
Arrays.sort(teams);
int ndomains = domains.length;
int nteams = teams.length;
int[][] matrix = new int[ndomains][];
for (int d = 0; d < ndomains; d++)
matrix[d] = new int[nteams];
int[] total_per_domain = new int[ndomains];
int[] total_per_team = new int[nteams];
int total = 0;
{
Iterator i = data.po_files.iterator();
while (i.hasNext()) {
PoFile po = (PoFile)i.next();
if (po.percentage >= 50) {
int d = Arrays.binarySearch(domains,po.domain);
if (d < 0)
throw new Error("didn't find domain \""+po.domain+"\"");
int t = Arrays.binarySearch(teams,po.team);
if (t < 0)
throw new Error("didn't find team \""+po.team+"\"");
matrix[d][t] = TRUE;
total_per_domain[d]++;
total_per_team[t]++;
total++;
} else if (po.percentage < 0) {
int d = Arrays.binarySearch(domains,po.domain);
if (d < 0)
throw new Error("didn't find domain \""+po.domain+"\"");
int t = Arrays.binarySearch(teams,po.team);
if (t < 0)
throw new Error("didn't find team \""+po.team+"\"");
matrix[d][t] = EXTERNAL;
}
}
}
// Split into separate tables, to keep 80 column width.
int ngroups;
int[][] groups;
if (true) {
ngroups = 3;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams/3+1 };
groups[1] = new int[] { nteams/3+1, (2*nteams)/3+1 };
groups[2] = new int[] { (2*nteams)/3+1, nteams };
} else if (true) {
ngroups = 2;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams/2+1 };
groups[1] = new int[] { nteams/2+1, nteams };
} else {
ngroups = 1;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams };
}
stream.println("@example");
for (int group = 0; group < ngroups; group++) {
if (group > 0)
stream.println();
stream.println("@group");
if (group == 0)
stream.print("Ready PO files ");
else
stream.print(" ");
for (int t = groups[group][0]; t < groups[group][1]; t++)
stream.print(" "+teams[t]);
stream.println();
stream.print(" +");
for (int t = groups[group][0]; t < groups[group][1]; t++)
for (int i = teams[t].length() + 1; i > 0; i--)
stream.print('-');
stream.println("-+");
for (int d = 0; d < ndomains; d++) {
stream.print(domains[d]);
spaces(stream,16 - domains[d].length());
stream.print('|');
for (int t = groups[group][0]; t < groups[group][1]; t++) {
stream.print(' ');
if (matrix[d][t] == TRUE) {
int i = teams[t].length()-2;
spaces(stream,i/2);
stream.print("[]");
spaces(stream,(i+1)/2);
} else if (matrix[d][t] == EXTERNAL) {
int i = teams[t].length()-2;
spaces(stream,i/2);
stream.print("()");
spaces(stream,(i+1)/2);
} else {
spaces(stream,teams[t].length());
}
}
stream.print(' ');
stream.print('|');
if (group == ngroups-1) {
stream.print(' ');
String s = Integer.toString(total_per_domain[d]);
spaces(stream,2-s.length());
stream.print(s);
}
stream.println();
}
stream.print(" +");
for (int t = groups[group][0]; t < groups[group][1]; t++)
for (int i = teams[t].length() + 1; i > 0; i--)
stream.print('-');
stream.println("-+");
if (group == ngroups-1) {
String s = Integer.toString(nteams);
spaces(stream,4-s.length());
stream.print(s);
stream.print(" teams ");
} else {
stream.print(" ");
}
for (int t = groups[group][0]; t < groups[group][1]; t++)
stream.print(" "+teams[t]);
stream.println();
if (group == ngroups-1) {
String s = Integer.toString(ndomains);
spaces(stream,4-s.length());
stream.print(s);
stream.print(" domains ");
} else {
stream.print(" ");
}
for (int t = groups[group][0]; t < groups[group][1]; t++) {
stream.print(' ');
String s = Integer.toString(total_per_team[t]);
int i = teams[t].length()-2;
spaces(stream,i/2 + (2-s.length()));
stream.print(s);
spaces(stream,(i+1)/2);
}
if (group == ngroups-1) {
stream.print(' ');
stream.print(' ');
String s = Integer.toString(total);
spaces(stream,3-s.length());
stream.print(s);
}
stream.println();
stream.println("@end group");
}
stream.println("@end example");
stream.close();
bf.close();
f.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
| public static void main (String[] args) {
Data data = new Data();
SAXBuilder builder = new SAXBuilder(/*true*/); // "true" turns on validation
Document doc;
try {
doc = builder.build(new File("matrix.xml"));
} catch (JDOMException e) {
e.printStackTrace();
doc = null;
System.exit(1);
}
Element po_inventory = doc.getRootElement();
{
Element domains = po_inventory.getChild("domains");
Iterator i = domains.getChildren("domain").iterator();
while (i.hasNext()) {
Element domain = (Element)i.next();
data.domains.add(domain.getAttribute("name").getValue());
}
}
{
Element teams = po_inventory.getChild("teams");
Iterator i = teams.getChildren("team").iterator();
while (i.hasNext()) {
Element team = (Element)i.next();
data.teams.add(team.getAttribute("name").getValue());
}
}
{
Element po_files = po_inventory.getChild("PoFiles");
Iterator i = po_files.getChildren("po").iterator();
while (i.hasNext()) {
Element po = (Element)i.next();
String value = po.getText();
data.po_files.add(
new PoFile(
po.getAttribute("domain").getValue(),
po.getAttribute("team").getValue(),
value.equals("") ? -1 : Integer.parseInt(value)));
}
}
// Special treatment of clisp. The percentages are incorrect.
data.domains.add("clisp");
if (!data.teams.contains("en"))
data.teams.add("en");
data.po_files.add(new PoFile("clisp","en",100));
data.po_files.add(new PoFile("clisp","de",99));
data.po_files.add(new PoFile("clisp","fr",99));
data.po_files.add(new PoFile("clisp","es",90));
data.po_files.add(new PoFile("clisp","nl",90));
try {
FileWriter f = new FileWriter("matrix.texi");
BufferedWriter bf = new BufferedWriter(f);
PrintWriter stream = new PrintWriter(bf);
String[] domains = (String[])data.domains.toArray(new String[0]);
Arrays.sort(domains);
String[] teams = (String[])data.teams.toArray(new String[0]);
Arrays.sort(teams);
int ndomains = domains.length;
int nteams = teams.length;
int[][] matrix = new int[ndomains][];
for (int d = 0; d < ndomains; d++)
matrix[d] = new int[nteams];
int[] total_per_domain = new int[ndomains];
int[] total_per_team = new int[nteams];
int total = 0;
{
Iterator i = data.po_files.iterator();
while (i.hasNext()) {
PoFile po = (PoFile)i.next();
if (po.percentage >= 50) {
int d = Arrays.binarySearch(domains,po.domain);
if (d < 0)
throw new Error("didn't find domain \""+po.domain+"\"");
int t = Arrays.binarySearch(teams,po.team);
if (t < 0)
throw new Error("didn't find team \""+po.team+"\"");
matrix[d][t] = TRUE;
total_per_domain[d]++;
total_per_team[t]++;
total++;
} else if (po.percentage < 0) {
int d = Arrays.binarySearch(domains,po.domain);
if (d < 0)
throw new Error("didn't find domain \""+po.domain+"\"");
int t = Arrays.binarySearch(teams,po.team);
if (t < 0) {
System.err.println(po.domain+": didn't find team \""+po.team+"\"");
continue;
}
matrix[d][t] = EXTERNAL;
}
}
}
// Split into separate tables, to keep 80 column width.
int ngroups;
int[][] groups;
if (true) {
ngroups = 3;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams/3+1 };
groups[1] = new int[] { nteams/3+1, (2*nteams)/3+1 };
groups[2] = new int[] { (2*nteams)/3+1, nteams };
} else if (true) {
ngroups = 2;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams/2+1 };
groups[1] = new int[] { nteams/2+1, nteams };
} else {
ngroups = 1;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams };
}
stream.println("@example");
for (int group = 0; group < ngroups; group++) {
if (group > 0)
stream.println();
stream.println("@group");
if (group == 0)
stream.print("Ready PO files ");
else
stream.print(" ");
for (int t = groups[group][0]; t < groups[group][1]; t++)
stream.print(" "+teams[t]);
stream.println();
stream.print(" +");
for (int t = groups[group][0]; t < groups[group][1]; t++)
for (int i = teams[t].length() + 1; i > 0; i--)
stream.print('-');
stream.println("-+");
for (int d = 0; d < ndomains; d++) {
stream.print(domains[d]);
spaces(stream,16 - domains[d].length());
stream.print('|');
for (int t = groups[group][0]; t < groups[group][1]; t++) {
stream.print(' ');
if (matrix[d][t] == TRUE) {
int i = teams[t].length()-2;
spaces(stream,i/2);
stream.print("[]");
spaces(stream,(i+1)/2);
} else if (matrix[d][t] == EXTERNAL) {
int i = teams[t].length()-2;
spaces(stream,i/2);
stream.print("()");
spaces(stream,(i+1)/2);
} else {
spaces(stream,teams[t].length());
}
}
stream.print(' ');
stream.print('|');
if (group == ngroups-1) {
stream.print(' ');
String s = Integer.toString(total_per_domain[d]);
spaces(stream,2-s.length());
stream.print(s);
}
stream.println();
}
stream.print(" +");
for (int t = groups[group][0]; t < groups[group][1]; t++)
for (int i = teams[t].length() + 1; i > 0; i--)
stream.print('-');
stream.println("-+");
if (group == ngroups-1) {
String s = Integer.toString(nteams);
spaces(stream,4-s.length());
stream.print(s);
stream.print(" teams ");
} else {
stream.print(" ");
}
for (int t = groups[group][0]; t < groups[group][1]; t++)
stream.print(" "+teams[t]);
stream.println();
if (group == ngroups-1) {
String s = Integer.toString(ndomains);
spaces(stream,4-s.length());
stream.print(s);
stream.print(" domains ");
} else {
stream.print(" ");
}
for (int t = groups[group][0]; t < groups[group][1]; t++) {
stream.print(' ');
String s = Integer.toString(total_per_team[t]);
int i = teams[t].length()-2;
spaces(stream,i/2 + (2-s.length()));
stream.print(s);
spaces(stream,(i+1)/2);
}
if (group == ngroups-1) {
stream.print(' ');
stream.print(' ');
String s = Integer.toString(total);
spaces(stream,3-s.length());
stream.print(s);
}
stream.println();
stream.println("@end group");
}
stream.println("@end example");
stream.close();
bf.close();
f.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
|
diff --git a/src/org/game/runner/manager/ResourcesManager.java b/src/org/game/runner/manager/ResourcesManager.java
index 66ec43b..39e47e0 100644
--- a/src/org/game/runner/manager/ResourcesManager.java
+++ b/src/org/game/runner/manager/ResourcesManager.java
@@ -1,214 +1,214 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.game.runner.manager;
import android.graphics.Color;
import java.util.HashMap;
import java.util.Map;
import org.andengine.engine.Engine;
import org.andengine.engine.camera.Camera;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.ITiledTextureRegion;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.game.runner.GameActivity;
import org.game.runner.game.descriptor.LevelDescriptor;
import org.game.runner.game.element.background.BackgroundElement;
/**
*
* @author Karl
*/
public class ResourcesManager {
private static final ResourcesManager INSTANCE = new ResourcesManager();
public Engine engine;
public GameActivity activity;
public Camera camera;
public VertexBufferObjectManager vbom;
//Fonts
public Font fontPixel_34;
public Font fontPixel_60;
public Font fontPixel_60_gray;
public Font fontPixel_100;
public Font fontPixel_200;
//Texturess - Game
private BitmapTextureAtlas playerTextureAtlas;
public ITiledTextureRegion player;
private BitmapTextureAtlas trailTextureAtlas;
public ITextureRegion trail;
private BitmapTextureAtlas rocketTextureAtlas;
public ITiledTextureRegion rocket;
private BitmapTextureAtlas trapTextureAtlas;
public TiledTextureRegion trap;
private BitmapTextureAtlas wallTextureAtlas;
public ITextureRegion wall;
private BitmapTextureAtlas gameBackgroundTextureAtlas;
public Map<String, ITextureRegion> gameParallaxLayers = new HashMap<String, ITextureRegion>();
//Textures - Main
private BitmapTextureAtlas menuTextureAtlas;
public ITextureRegion mainMenuParallaxLayer1;
public ITextureRegion mainMenuParallaxLayer2;
public ITextureRegion mainMenuParallaxLayer3;
public ITextureRegion mainMenuParallaxLayer4;
private BitmapTextureAtlas lvlTextureAtlas;
public ITextureRegion lvlBack;
public ITextureRegion lvlLock;
public ITextureRegion lvlLeft;
public ITextureRegion lvlRight;
public ITextureRegion lvlJump;
public ITextureRegion lvlDoubleJump;
public ITextureRegion lvlRoll;
public ITextureRegion lvlPlatform;
//Textures - Splash
private BitmapTextureAtlas splashTextureAtlas;
public ITextureRegion splashHeadphones;
public static void prepareManager(Engine engine, GameActivity activity, Camera camera, VertexBufferObjectManager vbom){
getInstance().engine = engine;
getInstance().activity = activity;
getInstance().camera = camera;
getInstance().vbom = vbom;
}
public void loadFonts(){
FontFactory.setAssetBasePath("font/");
final ITexture fontPixel34Texture = new BitmapTextureAtlas(this.activity.getTextureManager(), 256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.fontPixel_34 = FontFactory.createStrokeFromAsset(this.activity.getFontManager(), fontPixel34Texture, this.activity.getAssets(), "pixel.ttf", 34, false, Color.WHITE, 1, Color.BLACK);
this.fontPixel_34.load();
final ITexture fontPixel60Texture = new BitmapTextureAtlas(this.activity.getTextureManager(), 256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.fontPixel_60 = FontFactory.createStrokeFromAsset(this.activity.getFontManager(), fontPixel60Texture, this.activity.getAssets(), "pixel.ttf", 60, false, Color.WHITE, 2, Color.BLACK);
this.fontPixel_60.load();
final ITexture fontPixel60GrayTexture = new BitmapTextureAtlas(this.activity.getTextureManager(), 256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.fontPixel_60_gray = FontFactory.createStrokeFromAsset(this.activity.getFontManager(), fontPixel60GrayTexture, this.activity.getAssets(), "pixel.ttf", 60, false, Color.GRAY, 2, Color.BLACK);
this.fontPixel_60_gray.load();
final ITexture fontPixel100Texture = new BitmapTextureAtlas(this.activity.getTextureManager(), 256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.fontPixel_100 = FontFactory.createStrokeFromAsset(this.activity.getFontManager(), fontPixel100Texture, this.activity.getAssets(), "pixel.ttf", 100, false, Color.WHITE, 2, Color.BLACK);
this.fontPixel_100.load();
final ITexture fontPixel200Texture = new BitmapTextureAtlas(this.activity.getTextureManager(), 512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.fontPixel_200 = FontFactory.createStrokeFromAsset(this.activity.getFontManager(), fontPixel200Texture, this.activity.getAssets(), "pixel.ttf", 200, false, Color.WHITE, 5, Color.BLACK);
this.fontPixel_200.load();
}
public void loadMenuResources(){
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/game/");
this.playerTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 224, 256);
this.player = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.playerTextureAtlas, this.activity, "player.png", 0, 0, 4, 4);
this.playerTextureAtlas.load();
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/main/");
this.menuTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 240, 240);
this.mainMenuParallaxLayer1 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.menuTextureAtlas, this.activity, "menu_bg_1.png", 0, 0);
this.mainMenuParallaxLayer2 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.menuTextureAtlas, this.activity, "menu_bg_2.png", 120, 0);
this.mainMenuParallaxLayer3 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.menuTextureAtlas, this.activity, "menu_bg_3.png", 0, 120);
this.mainMenuParallaxLayer4 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.menuTextureAtlas, this.activity, "menu_bg_4.png", 120, 120);
this.menuTextureAtlas.load();
this.lvlTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 130, 109);
this.lvlBack = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.lvlTextureAtlas, this.activity, "lvl_bg.png", 0, 0);
this.lvlLock = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.lvlTextureAtlas, this.activity, "lvl_lock.png", 69, 0);
this.lvlLeft = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.lvlTextureAtlas, this.activity, "lvl_left.png", 69, 51);
this.lvlRight = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.lvlTextureAtlas, this.activity, "lvl_right.png", 79, 51);
this.lvlJump = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.lvlTextureAtlas, this.activity, "lvl_jump.png", 53, 73);
this.lvlDoubleJump = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.lvlTextureAtlas, this.activity, "lvl_double_jump.png", 0, 69);
this.lvlRoll = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.lvlTextureAtlas, this.activity, "lvl_roll.png", 94, 73);
this.lvlPlatform = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.lvlTextureAtlas, this.activity, "lvl_platform.png", 80, 64);
this.lvlTextureAtlas.load();
AudioManager.getInstance().prepare("mfx/main/", "menu.xm");
}
public void unloadMenuResources(){
this.playerTextureAtlas.unload();
this.player = null;
this.menuTextureAtlas.unload();
this.mainMenuParallaxLayer1 = null;
this.mainMenuParallaxLayer2 = null;
this.mainMenuParallaxLayer3 = null;
this.mainMenuParallaxLayer4 = null;
this.lvlTextureAtlas.unload();
this.lvlBack = null;
this.lvlLock = null;
this.lvlLeft = null;
this.lvlRight = null;
this.lvlJump = null;
this.lvlDoubleJump = null;
this.lvlRoll = null;
this.lvlPlatform = null;
}
public void loadSplashResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/splash/");
this.splashTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 16, 16);
this.splashHeadphones = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.splashTextureAtlas, this.activity, "headphones.png", 0, 0);
this.splashTextureAtlas.load();
}
public void unloadSplashResources() {
this.splashTextureAtlas.unload();
this.splashHeadphones = null;
}
public void loadGameResources(LevelDescriptor level) {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/game/");
this.playerTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 224, 256);
this.player = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.playerTextureAtlas, this.activity, "player.png", 0, 0, 4, 4);
this.playerTextureAtlas.load();
this.trailTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 4, 4);
this.trail = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.trailTextureAtlas, this.activity, "trail.png", 0, 0);
this.trailTextureAtlas.load();
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/game/elements/");
this.rocketTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 368, 36);
this.rocket = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.rocketTextureAtlas, this.activity, "rocket.png", 0, 0, 4, 1);
this.rocketTextureAtlas.load();
this.trapTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 96, 32);
this.trap = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.trapTextureAtlas, this.activity, "trap.png", 0, 0, 3, 1);
this.trapTextureAtlas.load();
this.wallTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 15, 120);
this.wall = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.wallTextureAtlas, this.activity, "wall.png", 0, 0);
this.wallTextureAtlas.load();
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/game/backgrounds/");
this.gameBackgroundTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), BackgroundElement.MAX_WIDTH, BackgroundElement.MAX_HEIGHT * LevelDescriptor.MAX_BACKGROUND_ELEMENTS);
int index = 0;
for(BackgroundElement background : level.getBackgroundsElements()){
if(!this.gameParallaxLayers.containsKey(background.getResourceName())){
this.gameParallaxLayers.put(background.getResourceName(), BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.gameBackgroundTextureAtlas, this.activity, background.getResourceName() + ".png", 0, index * BackgroundElement.MAX_HEIGHT));
index++;
}
}
this.gameBackgroundTextureAtlas.load();
- AudioManager.getInstance().prepare("mfx/lvl/", level.getMusic());
+ AudioManager.getInstance().prepare("mfx/game/", level.getMusic());
}
public void unloadGameResources() {
this.playerTextureAtlas.unload();
this.player = null;
this.trailTextureAtlas.unload();
this.trail = null;
this.rocketTextureAtlas.unload();
this.rocket = null;
this.trapTextureAtlas.unload();
this.trap = null;
this.wallTextureAtlas.unload();
this.wall = null;
this.gameBackgroundTextureAtlas.unload();
this.gameParallaxLayers.clear();
}
public static ResourcesManager getInstance(){
return INSTANCE;
}
}
| true | true | public void loadGameResources(LevelDescriptor level) {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/game/");
this.playerTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 224, 256);
this.player = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.playerTextureAtlas, this.activity, "player.png", 0, 0, 4, 4);
this.playerTextureAtlas.load();
this.trailTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 4, 4);
this.trail = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.trailTextureAtlas, this.activity, "trail.png", 0, 0);
this.trailTextureAtlas.load();
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/game/elements/");
this.rocketTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 368, 36);
this.rocket = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.rocketTextureAtlas, this.activity, "rocket.png", 0, 0, 4, 1);
this.rocketTextureAtlas.load();
this.trapTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 96, 32);
this.trap = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.trapTextureAtlas, this.activity, "trap.png", 0, 0, 3, 1);
this.trapTextureAtlas.load();
this.wallTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 15, 120);
this.wall = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.wallTextureAtlas, this.activity, "wall.png", 0, 0);
this.wallTextureAtlas.load();
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/game/backgrounds/");
this.gameBackgroundTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), BackgroundElement.MAX_WIDTH, BackgroundElement.MAX_HEIGHT * LevelDescriptor.MAX_BACKGROUND_ELEMENTS);
int index = 0;
for(BackgroundElement background : level.getBackgroundsElements()){
if(!this.gameParallaxLayers.containsKey(background.getResourceName())){
this.gameParallaxLayers.put(background.getResourceName(), BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.gameBackgroundTextureAtlas, this.activity, background.getResourceName() + ".png", 0, index * BackgroundElement.MAX_HEIGHT));
index++;
}
}
this.gameBackgroundTextureAtlas.load();
AudioManager.getInstance().prepare("mfx/lvl/", level.getMusic());
}
| public void loadGameResources(LevelDescriptor level) {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/game/");
this.playerTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 224, 256);
this.player = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.playerTextureAtlas, this.activity, "player.png", 0, 0, 4, 4);
this.playerTextureAtlas.load();
this.trailTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 4, 4);
this.trail = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.trailTextureAtlas, this.activity, "trail.png", 0, 0);
this.trailTextureAtlas.load();
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/game/elements/");
this.rocketTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 368, 36);
this.rocket = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.rocketTextureAtlas, this.activity, "rocket.png", 0, 0, 4, 1);
this.rocketTextureAtlas.load();
this.trapTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 96, 32);
this.trap = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.trapTextureAtlas, this.activity, "trap.png", 0, 0, 3, 1);
this.trapTextureAtlas.load();
this.wallTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), 15, 120);
this.wall = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.wallTextureAtlas, this.activity, "wall.png", 0, 0);
this.wallTextureAtlas.load();
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/game/backgrounds/");
this.gameBackgroundTextureAtlas = new BitmapTextureAtlas(this.activity.getTextureManager(), BackgroundElement.MAX_WIDTH, BackgroundElement.MAX_HEIGHT * LevelDescriptor.MAX_BACKGROUND_ELEMENTS);
int index = 0;
for(BackgroundElement background : level.getBackgroundsElements()){
if(!this.gameParallaxLayers.containsKey(background.getResourceName())){
this.gameParallaxLayers.put(background.getResourceName(), BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.gameBackgroundTextureAtlas, this.activity, background.getResourceName() + ".png", 0, index * BackgroundElement.MAX_HEIGHT));
index++;
}
}
this.gameBackgroundTextureAtlas.load();
AudioManager.getInstance().prepare("mfx/game/", level.getMusic());
}
|
diff --git a/src/main/java/net/pterodactylus/sone/web/page/PageToadlet.java b/src/main/java/net/pterodactylus/sone/web/page/PageToadlet.java
index ed012946..2d1f35aa 100644
--- a/src/main/java/net/pterodactylus/sone/web/page/PageToadlet.java
+++ b/src/main/java/net/pterodactylus/sone/web/page/PageToadlet.java
@@ -1,177 +1,177 @@
/*
* Sone - PageToadlet.java - Copyright © 2010 David Roden
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.pterodactylus.sone.web.page;
import java.io.IOException;
import java.net.URI;
import net.pterodactylus.util.web.Header;
import net.pterodactylus.util.web.Method;
import net.pterodactylus.util.web.Page;
import net.pterodactylus.util.web.Response;
import freenet.client.HighLevelSimpleClient;
import freenet.clients.http.LinkEnabledCallback;
import freenet.clients.http.Toadlet;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.support.MultiValueTable;
import freenet.support.api.Bucket;
import freenet.support.api.HTTPRequest;
import freenet.support.io.Closer;
/**
* {@link Toadlet} implementation that is wrapped around a {@link Page}.
*
* @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a>
*/
public class PageToadlet extends Toadlet implements LinkEnabledCallback {
/** The name of the menu item. */
private final String menuName;
/** The page that handles processing. */
private final Page<FreenetRequest> page;
/** The path prefix for the page. */
private final String pathPrefix;
/**
* Creates a new toadlet that hands off processing to a {@link Page}.
*
* @param highLevelSimpleClient
* The high-level simple client
* @param menuName
* The name of the menu item
* @param page
* The page to handle processing
* @param pathPrefix
* Prefix that is prepended to all {@link Page#getPath()} return
* values
*/
protected PageToadlet(HighLevelSimpleClient highLevelSimpleClient, String menuName, Page<FreenetRequest> page, String pathPrefix) {
super(highLevelSimpleClient);
this.menuName = menuName;
this.page = page;
this.pathPrefix = pathPrefix;
}
/**
* Returns the name to display in the menu.
*
* @return The name in the menu
*/
public String getMenuName() {
return menuName;
}
/**
* {@inheritDoc}
*/
@Override
public String path() {
return pathPrefix + page.getPath();
}
/**
* Handles a HTTP GET request.
*
* @param uri
* The URI of the request
* @param httpRequest
* The HTTP request
* @param toadletContext
* The toadlet context
* @throws IOException
* if an I/O error occurs
* @throws ToadletContextClosedException
* if the toadlet context is closed
*/
public void handleMethodGET(URI uri, HTTPRequest httpRequest, ToadletContext toadletContext) throws IOException, ToadletContextClosedException {
handleRequest(new FreenetRequest(uri, Method.GET, httpRequest, toadletContext));
}
/**
* Handles a HTTP POST request.
*
* @param uri
* The URI of the request
* @param httpRequest
* The HTTP request
* @param toadletContext
* The toadlet context
* @throws IOException
* if an I/O error occurs
* @throws ToadletContextClosedException
* if the toadlet context is closed
*/
public void handleMethodPOST(URI uri, HTTPRequest httpRequest, ToadletContext toadletContext) throws IOException, ToadletContextClosedException {
handleRequest(new FreenetRequest(uri, Method.POST, httpRequest, toadletContext));
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return getClass().getName() + "[path=" + path() + ",page=" + page + "]";
}
/**
* Handles a HTTP request.
*
* @param pageRequest
* The request to handle
* @throws IOException
* if an I/O error occurs
* @throws ToadletContextClosedException
* if the toadlet context is closed
*/
private void handleRequest(FreenetRequest pageRequest) throws IOException, ToadletContextClosedException {
Bucket pageBucket = null;
try {
pageBucket = pageRequest.getToadletContext().getBucketFactory().makeBucket(-1);
Response pageResponse = new Response(pageBucket.getOutputStream());
- page.handleRequest(pageRequest, pageResponse);
+ pageResponse = page.handleRequest(pageRequest, pageResponse);
MultiValueTable<String, String> headers = new MultiValueTable<String, String>();
if (pageResponse.getHeaders() != null) {
for (Header header : pageResponse.getHeaders()) {
for (String value : header) {
headers.put(header.getName(), value);
}
}
}
writeReply(pageRequest.getToadletContext(), pageResponse.getStatusCode(), pageResponse.getContentType(), pageResponse.getStatusText(), headers, pageBucket);
} catch (Throwable t1) {
writeInternalError(t1, pageRequest.getToadletContext());
} finally {
Closer.close(pageBucket);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEnabled(ToadletContext toadletContext) {
if (page instanceof LinkEnabledCallback) {
return ((LinkEnabledCallback) page).isEnabled(toadletContext);
}
return true;
}
}
| true | true | private void handleRequest(FreenetRequest pageRequest) throws IOException, ToadletContextClosedException {
Bucket pageBucket = null;
try {
pageBucket = pageRequest.getToadletContext().getBucketFactory().makeBucket(-1);
Response pageResponse = new Response(pageBucket.getOutputStream());
page.handleRequest(pageRequest, pageResponse);
MultiValueTable<String, String> headers = new MultiValueTable<String, String>();
if (pageResponse.getHeaders() != null) {
for (Header header : pageResponse.getHeaders()) {
for (String value : header) {
headers.put(header.getName(), value);
}
}
}
writeReply(pageRequest.getToadletContext(), pageResponse.getStatusCode(), pageResponse.getContentType(), pageResponse.getStatusText(), headers, pageBucket);
} catch (Throwable t1) {
writeInternalError(t1, pageRequest.getToadletContext());
} finally {
Closer.close(pageBucket);
}
}
| private void handleRequest(FreenetRequest pageRequest) throws IOException, ToadletContextClosedException {
Bucket pageBucket = null;
try {
pageBucket = pageRequest.getToadletContext().getBucketFactory().makeBucket(-1);
Response pageResponse = new Response(pageBucket.getOutputStream());
pageResponse = page.handleRequest(pageRequest, pageResponse);
MultiValueTable<String, String> headers = new MultiValueTable<String, String>();
if (pageResponse.getHeaders() != null) {
for (Header header : pageResponse.getHeaders()) {
for (String value : header) {
headers.put(header.getName(), value);
}
}
}
writeReply(pageRequest.getToadletContext(), pageResponse.getStatusCode(), pageResponse.getContentType(), pageResponse.getStatusText(), headers, pageBucket);
} catch (Throwable t1) {
writeInternalError(t1, pageRequest.getToadletContext());
} finally {
Closer.close(pageBucket);
}
}
|
diff --git a/modules/connectors/filesystem/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/filesystem/FileConnector.java b/modules/connectors/filesystem/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/filesystem/FileConnector.java
index 8dde92187..fdbb27ba8 100644
--- a/modules/connectors/filesystem/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/filesystem/FileConnector.java
+++ b/modules/connectors/filesystem/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/filesystem/FileConnector.java
@@ -1,1115 +1,1120 @@
/* $Id: FileConnector.java 995085 2010-09-08 15:13:38Z kwright $ */
/**
* 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.manifoldcf.crawler.connectors.filesystem;
import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.agents.interfaces.*;
import org.apache.manifoldcf.crawler.interfaces.*;
import org.apache.manifoldcf.crawler.system.Logging;
import java.util.*;
import java.io.*;
/** This is the "repository connector" for a file system. It's a relative of the share crawler, and should have
* comparable basic functionality, with the exception of the ability to use ActiveDirectory and look at other shares.
*/
public class FileConnector extends org.apache.manifoldcf.crawler.connectors.BaseRepositoryConnector
{
public static final String _rcsid = "@(#)$Id: FileConnector.java 995085 2010-09-08 15:13:38Z kwright $";
// Activities that we know about
protected final static String ACTIVITY_READ = "read document";
// Relationships we know about
protected static final String RELATIONSHIP_CHILD = "child";
// Activities list
protected static final String[] activitiesList = new String[]{ACTIVITY_READ};
// Parameters that this connector cares about
// public final static String ROOTDIRECTORY = "rootdirectory";
// Local data
// protected File rootDirectory = null;
/** Constructor.
*/
public FileConnector()
{
}
/** Return the path for the UI interface JSP elements.
* These JSP's must be provided to allow the connector to be configured, and to
* permit it to present document filtering specification information in the UI.
* This method should return the name of the folder, under the <webapp>/connectors/
* area, where the appropriate JSP's can be found. The name should NOT have a slash in it.
*@return the folder part
*/
public String getJSPFolder()
{
return "filesystem";
}
/** Return the list of relationship types that this connector recognizes.
*@return the list.
*/
public String[] getRelationshipTypes()
{
return new String[]{RELATIONSHIP_CHILD};
}
/** List the activities we might report on.
*/
public String[] getActivitiesList()
{
return activitiesList;
}
/** For any given document, list the bins that it is a member of.
* For the file system, this would be typically just a blank value, but since we use this connector for testing, I have
* it returning TWO values for each document, so I can set up tests to see how the scheduler behaves under those conditions.
*/
public String[] getBinNames(String documentIdentifier)
{
// Note: This code is for testing, so we can see how documents behave when they are in various kinds of bin situations.
// The testing model is that there are documents belonging to "SLOW", to "FAST", or both to "SLOW" and "FAST" bins.
// The connector chooses which bins to assign a document to based on the identifier (which is the document's path), so
// this is something that should NOT be duplicated by other connector implementers.
if (documentIdentifier.indexOf("/BOTH/") != -1 || (documentIdentifier.indexOf("/SLOW/") != -1 && documentIdentifier.indexOf("/FAST/") != -1))
return new String[]{"SLOW","FAST"};
if (documentIdentifier.indexOf("/SLOW/") != -1)
return new String[]{"SLOW"};
if (documentIdentifier.indexOf("/FAST/") != -1)
return new String[]{"FAST"};
return new String[]{""};
}
/** Convert a document identifier to a URI. The URI is the URI that will be the unique key from
* the search index, and will be presented to the user as part of the search results.
*@param documentIdentifier is the document identifier.
*@return the document uri.
*/
protected String convertToURI(String documentIdentifier)
throws ManifoldCFException
{
//
// Note well: This MUST be a legal URI!!!
try
{
return new File(documentIdentifier).toURI().toURL().toString();
}
catch (java.io.IOException e)
{
throw new ManifoldCFException("Bad url",e);
}
}
/** Given a document specification, get either a list of starting document identifiers (seeds),
* or a list of changes (deltas), depending on whether this is a "crawled" connector or not.
* These document identifiers will be loaded into the job's queue at the beginning of the
* job's execution.
* This method can return changes only (because it is provided a time range). For full
* recrawls, the start time is always zero.
* Note that it is always ok to return MORE documents rather than less with this method.
*@param spec is a document specification (that comes from the job).
*@param startTime is the beginning of the time range to consider, inclusive.
*@param endTime is the end of the time range to consider, exclusive.
*@return the stream of local document identifiers that should be added to the queue.
*/
public IDocumentIdentifierStream getDocumentIdentifiers(DocumentSpecification spec, long startTime, long endTime)
throws ManifoldCFException
{
return new IdentifierStream(spec);
}
/** Get document versions given an array of document identifiers.
* This method is called for EVERY document that is considered. It is
* therefore important to perform as little work as possible here.
*@param documentIdentifiers is the array of local document identifiers, as understood by this connector.
*@return the corresponding version strings, with null in the places where the document no longer exists.
* Empty version strings indicate that there is no versioning ability for the corresponding document, and the document
* will always be processed.
*/
public String[] getDocumentVersions(String[] documentIdentifiers, DocumentSpecification spec)
throws ManifoldCFException, ServiceInterruption
{
String[] rval = new String[documentIdentifiers.length];
int i = 0;
while (i < rval.length)
{
File file = new File(documentIdentifiers[i]);
if (file.exists())
{
if (file.isDirectory())
{
// It's a directory. The version ID will be the
// last modified date.
long lastModified = file.lastModified();
rval[i] = new Long(lastModified).toString();
// Signal that we don't have any versioning.
// rval[i] = "";
}
else
{
// It's a file
// Get the file's modified date.
long lastModified = file.lastModified();
long fileLength = file.length();
StringBuffer sb = new StringBuffer();
sb.append(new Long(lastModified).toString()).append(":").append(new Long(fileLength).toString());
rval[i] = sb.toString();
}
}
else
rval[i] = null;
i++;
}
return rval;
}
/** Process a set of documents.
* This is the method that should cause each document to be fetched, processed, and the results either added
* to the queue of documents for the current job, and/or entered into the incremental ingestion manager.
* The document specification allows this class to filter what is done based on the job.
*@param documentIdentifiers is the set of document identifiers to process.
*@param activities is the interface this method should use to queue up new document references
* and ingest documents.
*@param spec is the document specification.
*@param scanOnly is an array corresponding to the document identifiers. It is set to true to indicate when the processing
* should only find other references, and should not actually call the ingestion methods.
*/
public void processDocuments(String[] documentIdentifiers, String[] versions, IProcessActivity activities, DocumentSpecification spec, boolean[] scanOnly)
throws ManifoldCFException, ServiceInterruption
{
int i = 0;
while (i < documentIdentifiers.length)
{
File file = new File(documentIdentifiers[i]);
if (file.exists())
{
if (file.isDirectory())
{
// Queue up stuff for directory
long startTime = System.currentTimeMillis();
String errorCode = "OK";
String errorDesc = null;
String documentIdentifier = documentIdentifiers[i];
String entityReference = documentIdentifier;
try
{
try
{
File[] files = file.listFiles();
if (files != null)
{
int j = 0;
while (j < files.length)
{
File f = files[j++];
String canonicalPath = f.getCanonicalPath();
if (checkInclude(f,canonicalPath,spec))
activities.addDocumentReference(canonicalPath,documentIdentifier,RELATIONSHIP_CHILD);
}
}
}
catch (IOException e)
{
errorCode = "IO ERROR";
errorDesc = e.getMessage();
throw new ManifoldCFException("IO Error: "+e.getMessage(),e);
}
}
finally
{
activities.recordActivity(new Long(startTime),ACTIVITY_READ,null,entityReference,errorCode,errorDesc,null);
}
}
else
{
if (!scanOnly[i])
{
// We've already avoided queuing documents that we don't want, based on file specifications.
// We still need to check based on file data.
if (checkIngest(file,spec))
{
long startTime = System.currentTimeMillis();
String errorCode = "OK";
String errorDesc = null;
Long fileLength = null;
String documentIdentifier = documentIdentifiers[i];
String version = versions[i];
String entityDescription = documentIdentifier;
try
{
// Ingest the document.
try
{
InputStream is = new FileInputStream(file);
try
{
long fileBytes = file.length();
RepositoryDocument data = new RepositoryDocument();
data.setBinary(is,fileBytes);
data.addField("uri",file.toString());
// MHL for other metadata
activities.ingestDocument(documentIdentifier,version,convertToURI(documentIdentifier),data);
fileLength = new Long(fileBytes);
}
finally
{
is.close();
}
}
catch (IOException e)
{
errorCode = "IO ERROR";
errorDesc = e.getMessage();
throw new ManifoldCFException("IO Error: "+e.getMessage(),e);
}
}
finally
{
activities.recordActivity(new Long(startTime),ACTIVITY_READ,fileLength,entityDescription,errorCode,errorDesc,null);
}
}
}
}
}
i++;
}
}
// UI support methods.
//
// These support methods come in two varieties. The first bunch is involved in setting up connection configuration information. The second bunch
// is involved in presenting and editing document specification information for a job. The two kinds of methods are accordingly treated differently,
// in that the first bunch cannot assume that the current connector object is connected, while the second bunch can. That is why the first bunch
// receives a thread context argument for all UI methods, while the second bunch does not need one (since it has already been applied via the connect()
// method, above).
/** Output the configuration header section.
* This method is called in the head section of the connector's configuration page. Its purpose is to add the required tabs to the list, and to output any
* javascript methods that might be needed by the configuration editing HTML.
*@param threadContext is the local thread context.
*@param out is the output to which any HTML should be sent.
*@param parameters are the configuration parameters, as they currently exist, for this connection being configured.
*@param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector.
*/
public void outputConfigurationHeader(IThreadContext threadContext, IHTTPOutput out, ConfigParams parameters, ArrayList tabsArray)
throws ManifoldCFException, IOException
{
out.print(
"<script type=\"text/javascript\">\n"+
"<!--\n"+
"function checkConfigForSave()\n"+
"{\n"+
" return true;\n"+
"}\n"+
"\n"+
"//-->\n"+
"</script>\n"
);
}
/** Output the configuration body section.
* This method is called in the body section of the connector's configuration page. Its purpose is to present the required form elements for editing.
* The coder can presume that the HTML that is output from this configuration will be within appropriate <html>, <body>, and <form> tags. The name of the
* form is "editconnection".
*@param threadContext is the local thread context.
*@param out is the output to which any HTML should be sent.
*@param parameters are the configuration parameters, as they currently exist, for this connection being configured.
*@param tabName is the current tab name.
*/
public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out, ConfigParams parameters, String tabName)
throws ManifoldCFException, IOException
{
}
/** Process a configuration post.
* This method is called at the start of the connector's configuration page, whenever there is a possibility that form data for a connection has been
* posted. Its purpose is to gather form information and modify the configuration parameters accordingly.
* The name of the posted form is "editconnection".
*@param threadContext is the local thread context.
*@param variableContext is the set of variables available from the post, including binary file post information.
*@param parameters are the configuration parameters, as they currently exist, for this connection being configured.
*@return null if all is well, or a string error message if there is an error that should prevent saving of the connection (and cause a redirection to an error page).
*/
public String processConfigurationPost(IThreadContext threadContext, IPostParameters variableContext, ConfigParams parameters)
throws ManifoldCFException
{
return null;
}
/** View configuration.
* This method is called in the body section of the connector's view configuration page. Its purpose is to present the connection information to the user.
* The coder can presume that the HTML that is output from this configuration will be within appropriate <html> and <body> tags.
*@param threadContext is the local thread context.
*@param out is the output to which any HTML should be sent.
*@param parameters are the configuration parameters, as they currently exist, for this connection being configured.
*/
public void viewConfiguration(IThreadContext threadContext, IHTTPOutput out, ConfigParams parameters)
throws ManifoldCFException, IOException
{
}
/** Output the specification header section.
* This method is called in the head section of a job page which has selected a repository connection of the current type. Its purpose is to add the required tabs
* to the list, and to output any javascript methods that might be needed by the job editing HTML.
*@param out is the output to which any HTML should be sent.
*@param ds is the current document specification for this job.
*@param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector.
*/
public void outputSpecificationHeader(IHTTPOutput out, DocumentSpecification ds, ArrayList tabsArray)
throws ManifoldCFException, IOException
{
tabsArray.add("Paths");
out.print(
"<script type=\"text/javascript\">\n"+
"<!--\n"+
"function checkSpecification()\n"+
"{\n"+
" // Does nothing right now.\n"+
" return true;\n"+
"}\n"+
"\n"+
"function SpecOp(n, opValue, anchorvalue)\n"+
"{\n"+
" eval(\"editjob.\"+n+\".value = \\\"\"+opValue+\"\\\"\");\n"+
" postFormSetAnchor(anchorvalue);\n"+
"}\n"+
"//-->\n"+
"</script>\n"
);
}
/** Output the specification body section.
* This method is called in the body section of a job page which has selected a repository connection of the current type. Its purpose is to present the required form elements for editing.
* The coder can presume that the HTML that is output from this configuration will be within appropriate <html>, <body>, and <form> tags. The name of the
* form is "editjob".
*@param out is the output to which any HTML should be sent.
*@param ds is the current document specification for this job.
*@param tabName is the current tab name.
*/
public void outputSpecificationBody(IHTTPOutput out, DocumentSpecification ds, String tabName)
throws ManifoldCFException, IOException
{
int i;
int k;
// Paths tab
if (tabName.equals("Paths"))
{
out.print(
"<table class=\"displaytable\">\n"+
" <tr><td class=\"separator\" colspan=\"3\"><hr/></td></tr>\n"
);
i = 0;
k = 0;
while (i < ds.getChildCount())
{
SpecificationNode sn = ds.getChild(i++);
if (sn.getType().equals("startpoint"))
{
String pathDescription = "_"+Integer.toString(k);
String pathOpName = "specop"+pathDescription;
- out.print(
+ if (k == 0)
+ {
+ out.print(
" <tr>\n"+
" <td class=\"description\"><nobr>Paths:</nobr></td>\n"+
" <td class=\"boxcell\">\n"+
" <table class=\"formtable\">\n"+
" <tr class=\"formheaderrow\">\n"+
" <td class=\"formcolumnheader\"></td>\n"+
" <td class=\"formcolumnheader\"><nobr>Root path</nobr></td>\n"+
" <td class=\"formcolumnheader\"><nobr>Rules</nobr></td>\n"+
-" </tr>\n"+
+" </tr>\n"
+ );
+ }
+ out.print(
" <tr class=\""+(((k % 2)==0)?"evenformrow":"oddformrow")+"\">\n"+
" <td class=\"formcolumncell\">\n"+
" <input type=\"hidden\" name=\""+pathOpName+"\" value=\"\"/>\n"+
" <input type=\"hidden\" name=\""+"specpath"+pathDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(sn.getAttributeValue("path"))+"\"/>\n"+
" <a name=\""+"path_"+Integer.toString(k)+"\">\n"+
" <input type=\"button\" value=\"Delete\" onClick='Javascript:SpecOp(\""+pathOpName+"\",\"Delete\",\"path_"+Integer.toString(k)+"\")' alt=\""+"Delete path #"+Integer.toString(k)+"\"/>\n"+
" </a>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(sn.getAttributeValue("path"))+" \n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"boxcell\">\n"+
" <input type=\"hidden\" name=\""+"specchildcount"+pathDescription+"\" value=\""+Integer.toString(sn.getChildCount())+"\"/>\n"+
" <table class=\"formtable\">\n"+
" <tr class=\"formheaderrow\">\n"+
" <td class=\"formcolumnheader\"></td>\n"+
" <td class=\"formcolumnheader\"><nobr>Include/exclude</nobr></td>\n"+
" <td class=\"formcolumnheader\"><nobr>File/directory</nobr></td>\n"+
" <td class=\"formcolumnheader\"><nobr>Match</nobr></td>\n"+
" </tr>\n"
);
int j = 0;
while (j < sn.getChildCount())
{
SpecificationNode excludeNode = sn.getChild(j);
String instanceDescription = "_"+Integer.toString(k)+"_"+Integer.toString(j);
String instanceOpName = "specop" + instanceDescription;
String nodeFlavor = excludeNode.getType();
String nodeType = excludeNode.getAttributeValue("type");
String nodeMatch = excludeNode.getAttributeValue("match");
out.print(
" <tr class=\"evenformrow\">\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"button\" value=\"Insert Here\" onClick='Javascript:SpecOp(\"specop"+instanceDescription+"\",\"Insert Here\",\"match_"+Integer.toString(k)+"_"+Integer.toString(j+1)+"\")' alt=\""+"Insert new match for path #"+Integer.toString(k)+" before position #"+Integer.toString(j)+"\"/>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <select name=\""+"specflavor"+instanceDescription+"\">\n"+
" <option value=\"include\">include</option>\n"+
" <option value=\"exclude\">exclude</option>\n"+
" </select>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <select name=\""+"spectype"+instanceDescription+"\">\n"+
" <option value=\"file\">File</option>\n"+
" <option value=\"directory\">Directory</option>\n"+
" </select>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"text\" size=\"10\" name=\""+"specmatch"+instanceDescription+"\" value=\"\"/>\n"+
" </nobr>\n"+
" </td>\n"+
" </tr>\n"+
" <tr class=\"oddformrow\">\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"hidden\" name=\""+"specop"+instanceDescription+"\" value=\"\"/>\n"+
" <input type=\"hidden\" name=\""+"specfl"+instanceDescription+"\" value=\""+nodeFlavor+"\"/>\n"+
" <input type=\"hidden\" name=\""+"specty"+instanceDescription+"\" value=\""+nodeType+"\"/>\n"+
" <input type=\"hidden\" name=\""+"specma"+instanceDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(nodeMatch)+"\"/>\n"+
" <a name=\""+"match_"+Integer.toString(k)+"_"+Integer.toString(j)+"\">\n"+
" <input type=\"button\" value=\"Delete\" onClick='Javascript:SpecOp(\"specop"+instanceDescription+"\",\"Delete\",\"match_"+Integer.toString(k)+"_"+Integer.toString(j)+"\")' alt=\""+"Delete path #"+Integer.toString(k)+", match spec #"+Integer.toString(j)+"\"/>\n"+
" </a>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" "+nodeFlavor+"\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" "+nodeType+"\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(nodeMatch)+"\n"+
" </nobr>\n"+
" </td>\n"+
" </tr>\n"
);
j++;
}
if (j == 0)
{
out.print(
" <tr class=\"formrow\"><td class=\"message\" colspan=\"4\">No rules defined</td></tr>\n"
);
}
out.print(
" <tr class=\"formrow\"><td class=\"lightseparator\" colspan=\"4\"><hr/></td></tr>\n"+
" <tr class=\"formrow\">\n"+
" <td class=\"formcolumncell\">\n"+
" <a name=\""+"match_"+Integer.toString(k)+"_"+Integer.toString(j)+"\">\n"+
" <input type=\"button\" value=\"Add\" onClick='Javascript:SpecOp(\""+pathOpName+"\",\"Add\",\"match_"+Integer.toString(k)+"_"+Integer.toString(j+1)+"\")' alt=\""+"Add new match for path #"+Integer.toString(k)+"\"/>\n"+
" </a>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <select name=\""+"specflavor"+pathDescription+"\">\n"+
" <option value=\"include\">include</option>\n"+
" <option value=\"exclude\">exclude</option>\n"+
" </select>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <select name=\""+"spectype"+pathDescription+"\">\n"+
" <option value=\"file\">file</option>\n"+
" <option value=\"directory\">directory</option>\n"+
" </select>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"text\" size=\"10\" name=\""+"specmatch"+pathDescription+"\" value=\"\"/>\n"+
" </nobr>\n"+
" </td>\n"+
" </tr>\n"+
" </table>\n"+
" </td>\n"+
" </tr>\n"
);
k++;
}
}
if (k == 0)
{
out.print(
" <tr class=\"formrow\"><td class=\"message\" colspan=\"3\">No documents specified</td></tr>\n"
);
}
out.print(
" <tr class=\"formrow\"><td class=\"lightseparator\" colspan=\"3\"><hr/></td></tr>\n"+
" <tr class=\"formrow\">\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <a name=\""+"path_"+Integer.toString(k)+"\">\n"+
" <input type=\"button\" value=\"Add\" onClick='Javascript:SpecOp(\"specop\",\"Add\",\"path_"+Integer.toString(i+1)+"\")' alt=\"Add new path\"/>\n"+
" <input type=\"hidden\" name=\"pathcount\" value=\""+Integer.toString(k)+"\"/>\n"+
" <input type=\"hidden\" name=\"specop\" value=\"\"/>\n"+
" </a>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"text\" size=\"80\" name=\"specpath\" value=\"\"/>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" </td>\n"+
" </tr>\n"+
" </table>\n"+
" </td>\n"+
" </tr>\n"+
"</table>\n"
);
}
else
{
i = 0;
k = 0;
while (i < ds.getChildCount())
{
SpecificationNode sn = ds.getChild(i++);
if (sn.getType().equals("startpoint"))
{
String pathDescription = "_"+Integer.toString(k);
out.print(
"<input type=\"hidden\" name=\"specpath"+pathDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(sn.getAttributeValue("path"))+"\"/>\n"+
"<input type=\"hidden\" name=\"specchildcount"+pathDescription+"\" value=\""+Integer.toString(sn.getChildCount())+"\"/>\n"
);
int j = 0;
while (j < sn.getChildCount())
{
SpecificationNode excludeNode = sn.getChild(j);
String instanceDescription = "_"+Integer.toString(k)+"_"+Integer.toString(j);
String nodeFlavor = excludeNode.getType();
String nodeType = excludeNode.getAttributeValue("type");
String nodeMatch = excludeNode.getAttributeValue("match");
out.print(
"<input type=\"hidden\" name=\"specfl"+instanceDescription+"\" value=\""+nodeFlavor+"\"/>\n"+
"<input type=\"hidden\" name=\"specty"+instanceDescription+"\" value=\""+nodeType+"\"/>\n"+
"<input type=\"hidden\" name=\"specma"+instanceDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(nodeMatch)+"\"/>\n"
);
j++;
}
k++;
}
}
out.print(
"<input type=\"hidden\" name=\"pathcount\" value=\""+Integer.toString(k)+"\"/>\n"
);
}
}
/** Process a specification post.
* This method is called at the start of job's edit or view page, whenever there is a possibility that form data for a connection has been
* posted. Its purpose is to gather form information and modify the document specification accordingly.
* The name of the posted form is "editjob".
*@param variableContext contains the post data, including binary file-upload information.
*@param ds is the current document specification for this job.
*@return null if all is well, or a string error message if there is an error that should prevent saving of the job (and cause a redirection to an error page).
*/
public String processSpecificationPost(IPostParameters variableContext, DocumentSpecification ds)
throws ManifoldCFException
{
String x = variableContext.getParameter("pathcount");
if (x != null)
{
ds.clearChildren();
// Find out how many children were sent
int pathCount = Integer.parseInt(x);
// Gather up these
int i = 0;
int k = 0;
while (i < pathCount)
{
String pathDescription = "_"+Integer.toString(i);
String pathOpName = "specop"+pathDescription;
x = variableContext.getParameter(pathOpName);
if (x != null && x.equals("Delete"))
{
// Skip to the next
i++;
continue;
}
// Path inserts won't happen until the very end
String path = variableContext.getParameter("specpath"+pathDescription);
SpecificationNode node = new SpecificationNode("startpoint");
node.setAttribute("path",path);
// Now, get the number of children
String y = variableContext.getParameter("specchildcount"+pathDescription);
int childCount = Integer.parseInt(y);
int j = 0;
int w = 0;
while (j < childCount)
{
String instanceDescription = "_"+Integer.toString(i)+"_"+Integer.toString(j);
// Look for an insert or a delete at this point
String instanceOp = "specop"+instanceDescription;
String z = variableContext.getParameter(instanceOp);
String flavor;
String type;
String match;
SpecificationNode sn;
if (z != null && z.equals("Delete"))
{
// Process the deletion as we gather
j++;
continue;
}
if (z != null && z.equals("Insert Here"))
{
// Process the insertion as we gather.
flavor = variableContext.getParameter("specflavor"+instanceDescription);
type = variableContext.getParameter("spectype"+instanceDescription);
match = variableContext.getParameter("specmatch"+instanceDescription);
sn = new SpecificationNode(flavor);
sn.setAttribute("type",type);
sn.setAttribute("match",match);
node.addChild(w++,sn);
}
flavor = variableContext.getParameter("specfl"+instanceDescription);
type = variableContext.getParameter("specty"+instanceDescription);
match = variableContext.getParameter("specma"+instanceDescription);
sn = new SpecificationNode(flavor);
sn.setAttribute("type",type);
sn.setAttribute("match",match);
node.addChild(w++,sn);
j++;
}
if (x != null && x.equals("Add"))
{
// Process adds to the end of the rules in-line
String match = variableContext.getParameter("specmatch"+pathDescription);
String type = variableContext.getParameter("spectype"+pathDescription);
String flavor = variableContext.getParameter("specflavor"+pathDescription);
SpecificationNode sn = new SpecificationNode(flavor);
sn.setAttribute("type",type);
sn.setAttribute("match",match);
node.addChild(w,sn);
}
ds.addChild(k++,node);
i++;
}
// See if there's a global add operation
String op = variableContext.getParameter("specop");
if (op != null && op.equals("Add"))
{
String path = variableContext.getParameter("specpath");
SpecificationNode node = new SpecificationNode("startpoint");
node.setAttribute("path",path);
// Now add in the defaults; these will be "include all directories" and "include all files".
SpecificationNode sn = new SpecificationNode("include");
sn.setAttribute("type","file");
sn.setAttribute("match","*");
node.addChild(node.getChildCount(),sn);
sn = new SpecificationNode("include");
sn.setAttribute("type","directory");
sn.setAttribute("match","*");
node.addChild(node.getChildCount(),sn);
ds.addChild(k,node);
}
}
return null;
}
/** View specification.
* This method is called in the body section of a job's view page. Its purpose is to present the document specification information to the user.
* The coder can presume that the HTML that is output from this configuration will be within appropriate <html> and <body> tags.
*@param out is the output to which any HTML should be sent.
*@param ds is the current document specification for this job.
*/
public void viewSpecification(IHTTPOutput out, DocumentSpecification ds)
throws ManifoldCFException, IOException
{
out.print(
"<table class=\"displaytable\">\n"
);
int i = 0;
boolean seenAny = false;
while (i < ds.getChildCount())
{
SpecificationNode sn = ds.getChild(i++);
if (sn.getType().equals("startpoint"))
{
if (seenAny == false)
{
seenAny = true;
}
out.print(
" <tr>\n"+
" <td class=\"description\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(sn.getAttributeValue("path"))+":"+"</td>\n"+
" <td class=\"value\">\n"
);
int j = 0;
while (j < sn.getChildCount())
{
SpecificationNode excludeNode = sn.getChild(j++);
out.print(
" "+(excludeNode.getType().equals("include")?"Include ":"")+"\n"+
" "+(excludeNode.getType().equals("exclude")?"Exclude ":"")+"\n"+
" "+(excludeNode.getAttributeValue("type").equals("file")?"file ":"")+"\n"+
" "+(excludeNode.getAttributeValue("type").equals("directory")?"directory ":"")+"\n"+
" "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(excludeNode.getAttributeValue("match"))+"<br/>\n"
);
}
out.print(
" </td>\n"+
" </tr>\n"
);
}
}
if (seenAny == false)
{
out.print(
" <tr><td class=\"message\">No documents specified</td></tr>\n"
);
}
out.print(
"</table>\n"
);
}
// Protected static methods
/** Check if a file or directory should be included, given a document specification.
*@param fileName is the canonical file name.
*@param documentSpecification is the specification.
*@return true if it should be included.
*/
protected static boolean checkInclude(File file, String fileName, DocumentSpecification documentSpecification)
throws ManifoldCFException
{
if (Logging.connectors.isDebugEnabled())
{
Logging.connectors.debug("Checking whether to include file '"+fileName+"'");
}
try
{
String pathPart;
String filePart;
if (file.isDirectory())
{
pathPart = fileName;
filePart = null;
}
else
{
pathPart = file.getParentFile().getCanonicalPath();
filePart = file.getName();
}
// Scan until we match a startpoint
int i = 0;
while (i < documentSpecification.getChildCount())
{
SpecificationNode sn = documentSpecification.getChild(i++);
if (sn.getType().equals("startpoint"))
{
String path = new File(sn.getAttributeValue("path")).getCanonicalPath();
if (Logging.connectors.isDebugEnabled())
{
Logging.connectors.debug("Checking path '"+path+"' against canonical '"+pathPart+"'");
}
// Compare with filename
int matchEnd = matchSubPath(path,pathPart);
if (matchEnd == -1)
{
if (Logging.connectors.isDebugEnabled())
{
Logging.connectors.debug("Match check '"+path+"' against canonical '"+pathPart+"' failed");
}
continue;
}
// matchEnd is the start of the rest of the path (after the match) in fileName.
// We need to walk through the rules and see whether it's in or out.
int j = 0;
while (j < sn.getChildCount())
{
SpecificationNode node = sn.getChild(j++);
String flavor = node.getType();
String match = node.getAttributeValue("match");
String type = node.getAttributeValue("type");
// If type is "file", then our match string is against the filePart.
// If filePart is null, then this rule is simply skipped.
String sourceMatch;
int sourceIndex;
if (type.equals("file"))
{
if (filePart == null)
continue;
sourceMatch = filePart;
sourceIndex = 0;
}
else
{
if (filePart != null)
continue;
sourceMatch = pathPart;
sourceIndex = matchEnd;
}
if (flavor.equals("include"))
{
if (checkMatch(sourceMatch,sourceIndex,match))
return true;
}
else if (flavor.equals("exclude"))
{
if (checkMatch(sourceMatch,sourceIndex,match))
return false;
}
}
}
}
if (Logging.connectors.isDebugEnabled())
{
Logging.connectors.debug("Not including '"+fileName+"' because no matching rules");
}
return false;
}
catch (IOException e)
{
throw new ManifoldCFException("IO Error",e);
}
}
/** Check if a file should be ingested, given a document specification. It is presumed that
* documents that do not pass checkInclude() will be checked with this method.
*@param file is the file.
*@param documentSpecification is the specification.
*/
protected static boolean checkIngest(File file, DocumentSpecification documentSpecification)
throws ManifoldCFException
{
// Since the only exclusions at this point are not based on file contents, this is a no-op.
// MHL
return true;
}
/** Match a sub-path. The sub-path must match the complete starting part of the full path, in a path
* sense. The returned value should point into the file name beyond the end of the matched path, or
* be -1 if there is no match.
*@param subPath is the sub path.
*@param fullPath is the full path.
*@return the index of the start of the remaining part of the full path, or -1.
*/
protected static int matchSubPath(String subPath, String fullPath)
{
if (subPath.length() > fullPath.length())
return -1;
if (fullPath.startsWith(subPath) == false)
return -1;
int rval = subPath.length();
if (fullPath.length() == rval)
return rval;
char x = fullPath.charAt(rval);
if (x == File.separatorChar)
rval++;
return rval;
}
/** Check a match between two strings with wildcards.
*@param sourceMatch is the expanded string (no wildcards)
*@param sourceIndex is the starting point in the expanded string.
*@param match is the wildcard-based string.
*@return true if there is a match.
*/
protected static boolean checkMatch(String sourceMatch, int sourceIndex, String match)
{
// Note: The java regex stuff looks pretty heavyweight for this purpose.
// I've opted to try and do a simple recursive version myself, which is not compiled.
// Basically, the match proceeds by recursive descent through the string, so that all *'s cause
// recursion.
boolean caseSensitive = true;
return processCheck(caseSensitive, sourceMatch, sourceIndex, match, 0);
}
/** Recursive worker method for checkMatch. Returns 'true' if there is a path that consumes both
* strings in their entirety in a matched way.
*@param caseSensitive is true if file names are case sensitive.
*@param sourceMatch is the source string (w/o wildcards)
*@param sourceIndex is the current point in the source string.
*@param match is the match string (w/wildcards)
*@param matchIndex is the current point in the match string.
*@return true if there is a match.
*/
protected static boolean processCheck(boolean caseSensitive, String sourceMatch, int sourceIndex,
String match, int matchIndex)
{
// Logging.connectors.debug("Matching '"+sourceMatch+"' position "+Integer.toString(sourceIndex)+
// " against '"+match+"' position "+Integer.toString(matchIndex));
// Match up through the next * we encounter
while (true)
{
// If we've reached the end, it's a match.
if (sourceMatch.length() == sourceIndex && match.length() == matchIndex)
return true;
// If one has reached the end but the other hasn't, no match
if (match.length() == matchIndex)
return false;
if (sourceMatch.length() == sourceIndex)
{
if (match.charAt(matchIndex) != '*')
return false;
matchIndex++;
continue;
}
char x = sourceMatch.charAt(sourceIndex);
char y = match.charAt(matchIndex);
if (!caseSensitive)
{
if (x >= 'A' && x <= 'Z')
x -= 'A'-'a';
if (y >= 'A' && y <= 'Z')
y -= 'A'-'a';
}
if (y == '*')
{
// Wildcard!
// We will recurse at this point.
// Basically, we want to combine the results for leaving the "*" in the match string
// at this point and advancing the source index, with skipping the "*" and leaving the source
// string alone.
return processCheck(caseSensitive,sourceMatch,sourceIndex+1,match,matchIndex) ||
processCheck(caseSensitive,sourceMatch,sourceIndex,match,matchIndex+1);
}
if (y == '?' || x == y)
{
sourceIndex++;
matchIndex++;
}
else
return false;
}
}
/** Document identifier stream.
*/
protected static class IdentifierStream implements IDocumentIdentifierStream
{
protected String[] ids = null;
protected int currentIndex = 0;
public IdentifierStream(DocumentSpecification spec)
throws ManifoldCFException
{
try
{
// Walk the specification for the "startpoint" types. Amalgamate these into a list of strings.
// Presume that all roots are startpoint nodes
int i = 0;
int j = 0;
while (i < spec.getChildCount())
{
SpecificationNode n = spec.getChild(i);
if (n.getType().equals("startpoint"))
j++;
i++;
}
ids = new String[j];
i = 0;
j = 0;
while (i < ids.length)
{
SpecificationNode n = spec.getChild(i);
if (n.getType().equals("startpoint"))
{
// The id returned MUST be in canonical form!!!
ids[j] = new File(n.getAttributeValue("path")).getCanonicalPath();
if (Logging.connectors.isDebugEnabled())
{
Logging.connectors.debug("Seed = '"+ids[j]+"'");
}
j++;
}
i++;
}
}
catch (IOException e)
{
throw new ManifoldCFException("Could not get a canonical path",e);
}
}
/** Get the next identifier.
*@return the next document identifier, or null if there are no more.
*/
public String getNextIdentifier()
throws ManifoldCFException, ServiceInterruption
{
if (currentIndex == ids.length)
return null;
return ids[currentIndex++];
}
/** Close the stream.
*/
public void close()
throws ManifoldCFException
{
ids = null;
}
}
}
| false | true | public void outputSpecificationBody(IHTTPOutput out, DocumentSpecification ds, String tabName)
throws ManifoldCFException, IOException
{
int i;
int k;
// Paths tab
if (tabName.equals("Paths"))
{
out.print(
"<table class=\"displaytable\">\n"+
" <tr><td class=\"separator\" colspan=\"3\"><hr/></td></tr>\n"
);
i = 0;
k = 0;
while (i < ds.getChildCount())
{
SpecificationNode sn = ds.getChild(i++);
if (sn.getType().equals("startpoint"))
{
String pathDescription = "_"+Integer.toString(k);
String pathOpName = "specop"+pathDescription;
out.print(
" <tr>\n"+
" <td class=\"description\"><nobr>Paths:</nobr></td>\n"+
" <td class=\"boxcell\">\n"+
" <table class=\"formtable\">\n"+
" <tr class=\"formheaderrow\">\n"+
" <td class=\"formcolumnheader\"></td>\n"+
" <td class=\"formcolumnheader\"><nobr>Root path</nobr></td>\n"+
" <td class=\"formcolumnheader\"><nobr>Rules</nobr></td>\n"+
" </tr>\n"+
" <tr class=\""+(((k % 2)==0)?"evenformrow":"oddformrow")+"\">\n"+
" <td class=\"formcolumncell\">\n"+
" <input type=\"hidden\" name=\""+pathOpName+"\" value=\"\"/>\n"+
" <input type=\"hidden\" name=\""+"specpath"+pathDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(sn.getAttributeValue("path"))+"\"/>\n"+
" <a name=\""+"path_"+Integer.toString(k)+"\">\n"+
" <input type=\"button\" value=\"Delete\" onClick='Javascript:SpecOp(\""+pathOpName+"\",\"Delete\",\"path_"+Integer.toString(k)+"\")' alt=\""+"Delete path #"+Integer.toString(k)+"\"/>\n"+
" </a>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(sn.getAttributeValue("path"))+" \n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"boxcell\">\n"+
" <input type=\"hidden\" name=\""+"specchildcount"+pathDescription+"\" value=\""+Integer.toString(sn.getChildCount())+"\"/>\n"+
" <table class=\"formtable\">\n"+
" <tr class=\"formheaderrow\">\n"+
" <td class=\"formcolumnheader\"></td>\n"+
" <td class=\"formcolumnheader\"><nobr>Include/exclude</nobr></td>\n"+
" <td class=\"formcolumnheader\"><nobr>File/directory</nobr></td>\n"+
" <td class=\"formcolumnheader\"><nobr>Match</nobr></td>\n"+
" </tr>\n"
);
int j = 0;
while (j < sn.getChildCount())
{
SpecificationNode excludeNode = sn.getChild(j);
String instanceDescription = "_"+Integer.toString(k)+"_"+Integer.toString(j);
String instanceOpName = "specop" + instanceDescription;
String nodeFlavor = excludeNode.getType();
String nodeType = excludeNode.getAttributeValue("type");
String nodeMatch = excludeNode.getAttributeValue("match");
out.print(
" <tr class=\"evenformrow\">\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"button\" value=\"Insert Here\" onClick='Javascript:SpecOp(\"specop"+instanceDescription+"\",\"Insert Here\",\"match_"+Integer.toString(k)+"_"+Integer.toString(j+1)+"\")' alt=\""+"Insert new match for path #"+Integer.toString(k)+" before position #"+Integer.toString(j)+"\"/>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <select name=\""+"specflavor"+instanceDescription+"\">\n"+
" <option value=\"include\">include</option>\n"+
" <option value=\"exclude\">exclude</option>\n"+
" </select>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <select name=\""+"spectype"+instanceDescription+"\">\n"+
" <option value=\"file\">File</option>\n"+
" <option value=\"directory\">Directory</option>\n"+
" </select>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"text\" size=\"10\" name=\""+"specmatch"+instanceDescription+"\" value=\"\"/>\n"+
" </nobr>\n"+
" </td>\n"+
" </tr>\n"+
" <tr class=\"oddformrow\">\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"hidden\" name=\""+"specop"+instanceDescription+"\" value=\"\"/>\n"+
" <input type=\"hidden\" name=\""+"specfl"+instanceDescription+"\" value=\""+nodeFlavor+"\"/>\n"+
" <input type=\"hidden\" name=\""+"specty"+instanceDescription+"\" value=\""+nodeType+"\"/>\n"+
" <input type=\"hidden\" name=\""+"specma"+instanceDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(nodeMatch)+"\"/>\n"+
" <a name=\""+"match_"+Integer.toString(k)+"_"+Integer.toString(j)+"\">\n"+
" <input type=\"button\" value=\"Delete\" onClick='Javascript:SpecOp(\"specop"+instanceDescription+"\",\"Delete\",\"match_"+Integer.toString(k)+"_"+Integer.toString(j)+"\")' alt=\""+"Delete path #"+Integer.toString(k)+", match spec #"+Integer.toString(j)+"\"/>\n"+
" </a>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" "+nodeFlavor+"\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" "+nodeType+"\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(nodeMatch)+"\n"+
" </nobr>\n"+
" </td>\n"+
" </tr>\n"
);
j++;
}
if (j == 0)
{
out.print(
" <tr class=\"formrow\"><td class=\"message\" colspan=\"4\">No rules defined</td></tr>\n"
);
}
out.print(
" <tr class=\"formrow\"><td class=\"lightseparator\" colspan=\"4\"><hr/></td></tr>\n"+
" <tr class=\"formrow\">\n"+
" <td class=\"formcolumncell\">\n"+
" <a name=\""+"match_"+Integer.toString(k)+"_"+Integer.toString(j)+"\">\n"+
" <input type=\"button\" value=\"Add\" onClick='Javascript:SpecOp(\""+pathOpName+"\",\"Add\",\"match_"+Integer.toString(k)+"_"+Integer.toString(j+1)+"\")' alt=\""+"Add new match for path #"+Integer.toString(k)+"\"/>\n"+
" </a>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <select name=\""+"specflavor"+pathDescription+"\">\n"+
" <option value=\"include\">include</option>\n"+
" <option value=\"exclude\">exclude</option>\n"+
" </select>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <select name=\""+"spectype"+pathDescription+"\">\n"+
" <option value=\"file\">file</option>\n"+
" <option value=\"directory\">directory</option>\n"+
" </select>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"text\" size=\"10\" name=\""+"specmatch"+pathDescription+"\" value=\"\"/>\n"+
" </nobr>\n"+
" </td>\n"+
" </tr>\n"+
" </table>\n"+
" </td>\n"+
" </tr>\n"
);
k++;
}
}
if (k == 0)
{
out.print(
" <tr class=\"formrow\"><td class=\"message\" colspan=\"3\">No documents specified</td></tr>\n"
);
}
out.print(
" <tr class=\"formrow\"><td class=\"lightseparator\" colspan=\"3\"><hr/></td></tr>\n"+
" <tr class=\"formrow\">\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <a name=\""+"path_"+Integer.toString(k)+"\">\n"+
" <input type=\"button\" value=\"Add\" onClick='Javascript:SpecOp(\"specop\",\"Add\",\"path_"+Integer.toString(i+1)+"\")' alt=\"Add new path\"/>\n"+
" <input type=\"hidden\" name=\"pathcount\" value=\""+Integer.toString(k)+"\"/>\n"+
" <input type=\"hidden\" name=\"specop\" value=\"\"/>\n"+
" </a>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"text\" size=\"80\" name=\"specpath\" value=\"\"/>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" </td>\n"+
" </tr>\n"+
" </table>\n"+
" </td>\n"+
" </tr>\n"+
"</table>\n"
);
}
else
{
i = 0;
k = 0;
while (i < ds.getChildCount())
{
SpecificationNode sn = ds.getChild(i++);
if (sn.getType().equals("startpoint"))
{
String pathDescription = "_"+Integer.toString(k);
out.print(
"<input type=\"hidden\" name=\"specpath"+pathDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(sn.getAttributeValue("path"))+"\"/>\n"+
"<input type=\"hidden\" name=\"specchildcount"+pathDescription+"\" value=\""+Integer.toString(sn.getChildCount())+"\"/>\n"
);
int j = 0;
while (j < sn.getChildCount())
{
SpecificationNode excludeNode = sn.getChild(j);
String instanceDescription = "_"+Integer.toString(k)+"_"+Integer.toString(j);
String nodeFlavor = excludeNode.getType();
String nodeType = excludeNode.getAttributeValue("type");
String nodeMatch = excludeNode.getAttributeValue("match");
out.print(
"<input type=\"hidden\" name=\"specfl"+instanceDescription+"\" value=\""+nodeFlavor+"\"/>\n"+
"<input type=\"hidden\" name=\"specty"+instanceDescription+"\" value=\""+nodeType+"\"/>\n"+
"<input type=\"hidden\" name=\"specma"+instanceDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(nodeMatch)+"\"/>\n"
);
j++;
}
k++;
}
}
out.print(
"<input type=\"hidden\" name=\"pathcount\" value=\""+Integer.toString(k)+"\"/>\n"
);
}
}
| public void outputSpecificationBody(IHTTPOutput out, DocumentSpecification ds, String tabName)
throws ManifoldCFException, IOException
{
int i;
int k;
// Paths tab
if (tabName.equals("Paths"))
{
out.print(
"<table class=\"displaytable\">\n"+
" <tr><td class=\"separator\" colspan=\"3\"><hr/></td></tr>\n"
);
i = 0;
k = 0;
while (i < ds.getChildCount())
{
SpecificationNode sn = ds.getChild(i++);
if (sn.getType().equals("startpoint"))
{
String pathDescription = "_"+Integer.toString(k);
String pathOpName = "specop"+pathDescription;
if (k == 0)
{
out.print(
" <tr>\n"+
" <td class=\"description\"><nobr>Paths:</nobr></td>\n"+
" <td class=\"boxcell\">\n"+
" <table class=\"formtable\">\n"+
" <tr class=\"formheaderrow\">\n"+
" <td class=\"formcolumnheader\"></td>\n"+
" <td class=\"formcolumnheader\"><nobr>Root path</nobr></td>\n"+
" <td class=\"formcolumnheader\"><nobr>Rules</nobr></td>\n"+
" </tr>\n"
);
}
out.print(
" <tr class=\""+(((k % 2)==0)?"evenformrow":"oddformrow")+"\">\n"+
" <td class=\"formcolumncell\">\n"+
" <input type=\"hidden\" name=\""+pathOpName+"\" value=\"\"/>\n"+
" <input type=\"hidden\" name=\""+"specpath"+pathDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(sn.getAttributeValue("path"))+"\"/>\n"+
" <a name=\""+"path_"+Integer.toString(k)+"\">\n"+
" <input type=\"button\" value=\"Delete\" onClick='Javascript:SpecOp(\""+pathOpName+"\",\"Delete\",\"path_"+Integer.toString(k)+"\")' alt=\""+"Delete path #"+Integer.toString(k)+"\"/>\n"+
" </a>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(sn.getAttributeValue("path"))+" \n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"boxcell\">\n"+
" <input type=\"hidden\" name=\""+"specchildcount"+pathDescription+"\" value=\""+Integer.toString(sn.getChildCount())+"\"/>\n"+
" <table class=\"formtable\">\n"+
" <tr class=\"formheaderrow\">\n"+
" <td class=\"formcolumnheader\"></td>\n"+
" <td class=\"formcolumnheader\"><nobr>Include/exclude</nobr></td>\n"+
" <td class=\"formcolumnheader\"><nobr>File/directory</nobr></td>\n"+
" <td class=\"formcolumnheader\"><nobr>Match</nobr></td>\n"+
" </tr>\n"
);
int j = 0;
while (j < sn.getChildCount())
{
SpecificationNode excludeNode = sn.getChild(j);
String instanceDescription = "_"+Integer.toString(k)+"_"+Integer.toString(j);
String instanceOpName = "specop" + instanceDescription;
String nodeFlavor = excludeNode.getType();
String nodeType = excludeNode.getAttributeValue("type");
String nodeMatch = excludeNode.getAttributeValue("match");
out.print(
" <tr class=\"evenformrow\">\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"button\" value=\"Insert Here\" onClick='Javascript:SpecOp(\"specop"+instanceDescription+"\",\"Insert Here\",\"match_"+Integer.toString(k)+"_"+Integer.toString(j+1)+"\")' alt=\""+"Insert new match for path #"+Integer.toString(k)+" before position #"+Integer.toString(j)+"\"/>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <select name=\""+"specflavor"+instanceDescription+"\">\n"+
" <option value=\"include\">include</option>\n"+
" <option value=\"exclude\">exclude</option>\n"+
" </select>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <select name=\""+"spectype"+instanceDescription+"\">\n"+
" <option value=\"file\">File</option>\n"+
" <option value=\"directory\">Directory</option>\n"+
" </select>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"text\" size=\"10\" name=\""+"specmatch"+instanceDescription+"\" value=\"\"/>\n"+
" </nobr>\n"+
" </td>\n"+
" </tr>\n"+
" <tr class=\"oddformrow\">\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"hidden\" name=\""+"specop"+instanceDescription+"\" value=\"\"/>\n"+
" <input type=\"hidden\" name=\""+"specfl"+instanceDescription+"\" value=\""+nodeFlavor+"\"/>\n"+
" <input type=\"hidden\" name=\""+"specty"+instanceDescription+"\" value=\""+nodeType+"\"/>\n"+
" <input type=\"hidden\" name=\""+"specma"+instanceDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(nodeMatch)+"\"/>\n"+
" <a name=\""+"match_"+Integer.toString(k)+"_"+Integer.toString(j)+"\">\n"+
" <input type=\"button\" value=\"Delete\" onClick='Javascript:SpecOp(\"specop"+instanceDescription+"\",\"Delete\",\"match_"+Integer.toString(k)+"_"+Integer.toString(j)+"\")' alt=\""+"Delete path #"+Integer.toString(k)+", match spec #"+Integer.toString(j)+"\"/>\n"+
" </a>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" "+nodeFlavor+"\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" "+nodeType+"\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(nodeMatch)+"\n"+
" </nobr>\n"+
" </td>\n"+
" </tr>\n"
);
j++;
}
if (j == 0)
{
out.print(
" <tr class=\"formrow\"><td class=\"message\" colspan=\"4\">No rules defined</td></tr>\n"
);
}
out.print(
" <tr class=\"formrow\"><td class=\"lightseparator\" colspan=\"4\"><hr/></td></tr>\n"+
" <tr class=\"formrow\">\n"+
" <td class=\"formcolumncell\">\n"+
" <a name=\""+"match_"+Integer.toString(k)+"_"+Integer.toString(j)+"\">\n"+
" <input type=\"button\" value=\"Add\" onClick='Javascript:SpecOp(\""+pathOpName+"\",\"Add\",\"match_"+Integer.toString(k)+"_"+Integer.toString(j+1)+"\")' alt=\""+"Add new match for path #"+Integer.toString(k)+"\"/>\n"+
" </a>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <select name=\""+"specflavor"+pathDescription+"\">\n"+
" <option value=\"include\">include</option>\n"+
" <option value=\"exclude\">exclude</option>\n"+
" </select>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <select name=\""+"spectype"+pathDescription+"\">\n"+
" <option value=\"file\">file</option>\n"+
" <option value=\"directory\">directory</option>\n"+
" </select>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"text\" size=\"10\" name=\""+"specmatch"+pathDescription+"\" value=\"\"/>\n"+
" </nobr>\n"+
" </td>\n"+
" </tr>\n"+
" </table>\n"+
" </td>\n"+
" </tr>\n"
);
k++;
}
}
if (k == 0)
{
out.print(
" <tr class=\"formrow\"><td class=\"message\" colspan=\"3\">No documents specified</td></tr>\n"
);
}
out.print(
" <tr class=\"formrow\"><td class=\"lightseparator\" colspan=\"3\"><hr/></td></tr>\n"+
" <tr class=\"formrow\">\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <a name=\""+"path_"+Integer.toString(k)+"\">\n"+
" <input type=\"button\" value=\"Add\" onClick='Javascript:SpecOp(\"specop\",\"Add\",\"path_"+Integer.toString(i+1)+"\")' alt=\"Add new path\"/>\n"+
" <input type=\"hidden\" name=\"pathcount\" value=\""+Integer.toString(k)+"\"/>\n"+
" <input type=\"hidden\" name=\"specop\" value=\"\"/>\n"+
" </a>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" <nobr>\n"+
" <input type=\"text\" size=\"80\" name=\"specpath\" value=\"\"/>\n"+
" </nobr>\n"+
" </td>\n"+
" <td class=\"formcolumncell\">\n"+
" </td>\n"+
" </tr>\n"+
" </table>\n"+
" </td>\n"+
" </tr>\n"+
"</table>\n"
);
}
else
{
i = 0;
k = 0;
while (i < ds.getChildCount())
{
SpecificationNode sn = ds.getChild(i++);
if (sn.getType().equals("startpoint"))
{
String pathDescription = "_"+Integer.toString(k);
out.print(
"<input type=\"hidden\" name=\"specpath"+pathDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(sn.getAttributeValue("path"))+"\"/>\n"+
"<input type=\"hidden\" name=\"specchildcount"+pathDescription+"\" value=\""+Integer.toString(sn.getChildCount())+"\"/>\n"
);
int j = 0;
while (j < sn.getChildCount())
{
SpecificationNode excludeNode = sn.getChild(j);
String instanceDescription = "_"+Integer.toString(k)+"_"+Integer.toString(j);
String nodeFlavor = excludeNode.getType();
String nodeType = excludeNode.getAttributeValue("type");
String nodeMatch = excludeNode.getAttributeValue("match");
out.print(
"<input type=\"hidden\" name=\"specfl"+instanceDescription+"\" value=\""+nodeFlavor+"\"/>\n"+
"<input type=\"hidden\" name=\"specty"+instanceDescription+"\" value=\""+nodeType+"\"/>\n"+
"<input type=\"hidden\" name=\"specma"+instanceDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(nodeMatch)+"\"/>\n"
);
j++;
}
k++;
}
}
out.print(
"<input type=\"hidden\" name=\"pathcount\" value=\""+Integer.toString(k)+"\"/>\n"
);
}
}
|
diff --git a/src/game/Paint.java b/src/game/Paint.java
index 471b8ae..da5ac11 100644
--- a/src/game/Paint.java
+++ b/src/game/Paint.java
@@ -1,153 +1,155 @@
package game;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Paint extends JPanel {
private static Paint paint;
private GUI gui = GUI.getInstance();
private Character character = Character.getInstance();
private Missions missions = Missions.getInstance();
private Functions functions = Functions.getInstance();
private Messages messages = Messages.getInstance();
public static Paint getInstance() {
if (paint == null) {
paint = new Paint();
}
return paint;
}
private int lastTime2, currentTime, fps;
private int lastTime = 0;
public void paintComponent(Graphics g) {
lastTime2 = currentTime;
currentTime = (int) System.currentTimeMillis();
if (currentTime - lastTime > 500) {
lastTime = currentTime;
fps = 1000 / (currentTime - lastTime2);
}
super.paintComponent(g);
// DRAW MENU BUTTONS
for (int x = 0; x < 840; x += 120) {
g.setColor(Color.black);
g.drawRect(x, 20, 120, 30);
g.setColor(Color.lightGray);
if (gui.getmY() < 76 && gui.getmY() > 47 && gui.getmX() > x + 3
&& gui.getmX() < x + 123 && gui.isMenu() == false) {
g.setColor(Color.gray);
if (gui.isClicked() == true && gui.getmX() > 720) {
gui.setMenu(true);
+ } else {
+ gui.setMenu(false);
}
}
g.fillRect(x + 1, 21, 119, 29);
}
// DRAW MENU BUTTON TEXT
g.setColor(Color.BLACK);
g.drawString("Key Text", 25, 40);
g.drawString("Attunement", 125, 40);
g.drawString("Cultralia", 245, 40);
g.drawString("Navigation", 365, 40);
g.drawString("Verba", 485, 40);
g.drawString("Gramattica", 605, 40);
g.drawString("Menu", 725, 40);
// DRAW TOP MENU TEXT
g.setColor(Color.BLACK);
g.drawString(
"Name: " + character.getName() + " Hints: "
+ character.getHints() + " Points: "
+ character.getPoints() + " Level: "
+ " " + missions.getMissionName()
+ " FPS: " + fps, 5, 15);
// DRAW MAIN WINDOW
g.setColor(Color.BLACK);
g.fillRect(0, 50, 795, 495);
g.setColor(Color.GREEN);
g.drawString(functions.getOut(), 5, 65);
// DRAW BOTTOM INPUT
// g.setColor(Color.black);
// g.drawString(gui.getInput(), 5, 555);
// DRAW MENU
if (gui.isMenu() == true) {
g.setColor(Color.darkGray);
g.drawRect(300, 122, 200, 310);
g.setColor(Color.lightGray);
g.fillRect(301, 123, 199, 309);
for (int y = 140; y < 420; y += 40) {
g.setColor(Color.black);
g.drawRect(330, y, 140, 30);
if (gui.getmY() > y + 30 && gui.getmY() < y
&& gui.getmX() > 330 && gui.getmX() < 330 + 140) {
g.setColor(Color.gray);
} else {
g.setColor(Color.lightGray);
}
g.fillRect(331, y + 1, 139, 29);
}
g.setColor(Color.black);
g.drawString("Settings", 360, 160);
// ADD UPDATE CHECKER IN THE OPTIONS MENU
g.drawString("Load Game", 360, 200);
g.drawString("Save Game", 360, 240);
g.drawString("New Game", 360, 280);
g.drawString("Help", 360, 320);
g.drawString("Exit", 360, 360);
g.drawString("Back to Game", 360, 400);
}
if (messages.isShowMessage() == true) {
BufferedImage logo = null;
try {
logo = ImageIO.read(new File("src/resource/demiurge.png"));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "lol");
}
g.setColor(Color.darkGray);
g.drawRect(240, 200, 350, 180);
g.setColor(Color.lightGray);
g.fillRect(241, 201, 349, 179);
g.setColor(Color.black);
g.drawString(messages.getMessageText(), 310, 210);
g.drawImage(logo, 250, 210, 100, 100, this);
}
}
}
| true | true | public void paintComponent(Graphics g) {
lastTime2 = currentTime;
currentTime = (int) System.currentTimeMillis();
if (currentTime - lastTime > 500) {
lastTime = currentTime;
fps = 1000 / (currentTime - lastTime2);
}
super.paintComponent(g);
// DRAW MENU BUTTONS
for (int x = 0; x < 840; x += 120) {
g.setColor(Color.black);
g.drawRect(x, 20, 120, 30);
g.setColor(Color.lightGray);
if (gui.getmY() < 76 && gui.getmY() > 47 && gui.getmX() > x + 3
&& gui.getmX() < x + 123 && gui.isMenu() == false) {
g.setColor(Color.gray);
if (gui.isClicked() == true && gui.getmX() > 720) {
gui.setMenu(true);
}
}
g.fillRect(x + 1, 21, 119, 29);
}
// DRAW MENU BUTTON TEXT
g.setColor(Color.BLACK);
g.drawString("Key Text", 25, 40);
g.drawString("Attunement", 125, 40);
g.drawString("Cultralia", 245, 40);
g.drawString("Navigation", 365, 40);
g.drawString("Verba", 485, 40);
g.drawString("Gramattica", 605, 40);
g.drawString("Menu", 725, 40);
// DRAW TOP MENU TEXT
g.setColor(Color.BLACK);
g.drawString(
"Name: " + character.getName() + " Hints: "
+ character.getHints() + " Points: "
+ character.getPoints() + " Level: "
+ " " + missions.getMissionName()
+ " FPS: " + fps, 5, 15);
// DRAW MAIN WINDOW
g.setColor(Color.BLACK);
g.fillRect(0, 50, 795, 495);
g.setColor(Color.GREEN);
g.drawString(functions.getOut(), 5, 65);
// DRAW BOTTOM INPUT
// g.setColor(Color.black);
// g.drawString(gui.getInput(), 5, 555);
// DRAW MENU
if (gui.isMenu() == true) {
g.setColor(Color.darkGray);
g.drawRect(300, 122, 200, 310);
g.setColor(Color.lightGray);
g.fillRect(301, 123, 199, 309);
for (int y = 140; y < 420; y += 40) {
g.setColor(Color.black);
g.drawRect(330, y, 140, 30);
if (gui.getmY() > y + 30 && gui.getmY() < y
&& gui.getmX() > 330 && gui.getmX() < 330 + 140) {
g.setColor(Color.gray);
} else {
g.setColor(Color.lightGray);
}
g.fillRect(331, y + 1, 139, 29);
}
g.setColor(Color.black);
g.drawString("Settings", 360, 160);
// ADD UPDATE CHECKER IN THE OPTIONS MENU
g.drawString("Load Game", 360, 200);
g.drawString("Save Game", 360, 240);
g.drawString("New Game", 360, 280);
g.drawString("Help", 360, 320);
g.drawString("Exit", 360, 360);
g.drawString("Back to Game", 360, 400);
}
if (messages.isShowMessage() == true) {
BufferedImage logo = null;
try {
logo = ImageIO.read(new File("src/resource/demiurge.png"));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "lol");
}
g.setColor(Color.darkGray);
g.drawRect(240, 200, 350, 180);
g.setColor(Color.lightGray);
g.fillRect(241, 201, 349, 179);
g.setColor(Color.black);
g.drawString(messages.getMessageText(), 310, 210);
g.drawImage(logo, 250, 210, 100, 100, this);
}
}
| public void paintComponent(Graphics g) {
lastTime2 = currentTime;
currentTime = (int) System.currentTimeMillis();
if (currentTime - lastTime > 500) {
lastTime = currentTime;
fps = 1000 / (currentTime - lastTime2);
}
super.paintComponent(g);
// DRAW MENU BUTTONS
for (int x = 0; x < 840; x += 120) {
g.setColor(Color.black);
g.drawRect(x, 20, 120, 30);
g.setColor(Color.lightGray);
if (gui.getmY() < 76 && gui.getmY() > 47 && gui.getmX() > x + 3
&& gui.getmX() < x + 123 && gui.isMenu() == false) {
g.setColor(Color.gray);
if (gui.isClicked() == true && gui.getmX() > 720) {
gui.setMenu(true);
} else {
gui.setMenu(false);
}
}
g.fillRect(x + 1, 21, 119, 29);
}
// DRAW MENU BUTTON TEXT
g.setColor(Color.BLACK);
g.drawString("Key Text", 25, 40);
g.drawString("Attunement", 125, 40);
g.drawString("Cultralia", 245, 40);
g.drawString("Navigation", 365, 40);
g.drawString("Verba", 485, 40);
g.drawString("Gramattica", 605, 40);
g.drawString("Menu", 725, 40);
// DRAW TOP MENU TEXT
g.setColor(Color.BLACK);
g.drawString(
"Name: " + character.getName() + " Hints: "
+ character.getHints() + " Points: "
+ character.getPoints() + " Level: "
+ " " + missions.getMissionName()
+ " FPS: " + fps, 5, 15);
// DRAW MAIN WINDOW
g.setColor(Color.BLACK);
g.fillRect(0, 50, 795, 495);
g.setColor(Color.GREEN);
g.drawString(functions.getOut(), 5, 65);
// DRAW BOTTOM INPUT
// g.setColor(Color.black);
// g.drawString(gui.getInput(), 5, 555);
// DRAW MENU
if (gui.isMenu() == true) {
g.setColor(Color.darkGray);
g.drawRect(300, 122, 200, 310);
g.setColor(Color.lightGray);
g.fillRect(301, 123, 199, 309);
for (int y = 140; y < 420; y += 40) {
g.setColor(Color.black);
g.drawRect(330, y, 140, 30);
if (gui.getmY() > y + 30 && gui.getmY() < y
&& gui.getmX() > 330 && gui.getmX() < 330 + 140) {
g.setColor(Color.gray);
} else {
g.setColor(Color.lightGray);
}
g.fillRect(331, y + 1, 139, 29);
}
g.setColor(Color.black);
g.drawString("Settings", 360, 160);
// ADD UPDATE CHECKER IN THE OPTIONS MENU
g.drawString("Load Game", 360, 200);
g.drawString("Save Game", 360, 240);
g.drawString("New Game", 360, 280);
g.drawString("Help", 360, 320);
g.drawString("Exit", 360, 360);
g.drawString("Back to Game", 360, 400);
}
if (messages.isShowMessage() == true) {
BufferedImage logo = null;
try {
logo = ImageIO.read(new File("src/resource/demiurge.png"));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "lol");
}
g.setColor(Color.darkGray);
g.drawRect(240, 200, 350, 180);
g.setColor(Color.lightGray);
g.fillRect(241, 201, 349, 179);
g.setColor(Color.black);
g.drawString(messages.getMessageText(), 310, 210);
g.drawImage(logo, 250, 210, 100, 100, this);
}
}
|
diff --git a/server/src/org/bedework/caldav/server/CaldavCalNode.java b/server/src/org/bedework/caldav/server/CaldavCalNode.java
index 1096209..50c1c1f 100644
--- a/server/src/org/bedework/caldav/server/CaldavCalNode.java
+++ b/server/src/org/bedework/caldav/server/CaldavCalNode.java
@@ -1,730 +1,732 @@
/*
Copyright (c) 2000-2005 University of Washington. All rights reserved.
Redistribution and use of this distribution in source and binary forms,
with or without modification, are permitted provided that:
The above copyright notice and this permission notice appear in
all copies and supporting documentation;
The name, identifiers, and trademarks of the University of Washington
are not used in advertising or publicity without the express prior
written permission of the University of Washington;
Recipients acknowledge that this distribution is made available as a
research courtesy, "as is", potentially with defects, without
any obligation on the part of the University of Washington to
provide support, services, or repair;
THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR
IMPLIED, WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE, AND IN NO EVENT SHALL THE UNIVERSITY OF
WASHINGTON BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT (INCLUDING
NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION WITH
THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* **********************************************************************
Copyright 2005 Rensselaer Polytechnic Institute. All worldwide rights reserved.
Redistribution and use of this distribution in source and binary forms,
with or without modification, are permitted provided that:
The above copyright notice and this permission notice appear in all
copies and supporting documentation;
The name, identifiers, and trademarks of Rensselaer Polytechnic
Institute are not used in advertising or publicity without the
express prior written permission of Rensselaer Polytechnic Institute;
DISCLAIMER: The software is distributed" AS IS" without any express or
implied warranty, including but not limited to, any implied warranties
of merchantability or fitness for a particular purpose or any warrant)'
of non-infringement of any current or pending patent rights. The authors
of the software make no representations about the suitability of this
software for any particular purpose. The entire risk as to the quality
and performance of the software is with the user. Should the software
prove defective, the user assumes the cost of all necessary servicing,
repair or correction. In particular, neither Rensselaer Polytechnic
Institute, nor the authors of the software are liable for any indirect,
special, consequential, or incidental damages related to the software,
to the maximum extent the law permits.
*/
package org.bedework.caldav.server;
import org.bedework.calfacade.BwCalendar;
import org.bedework.calfacade.BwEvent;
import org.bedework.calfacade.BwUser;
import org.bedework.calfacade.RecurringRetrievalMode;
import org.bedework.calfacade.RecurringRetrievalMode.Rmode;
import org.bedework.calfacade.util.DateTimeUtil;
import org.bedework.icalendar.IcalTranslator;
import org.bedework.icalendar.Icalendar;
import org.bedework.icalendar.VFreeUtil;
import edu.rpi.cct.webdav.servlet.shared.WebdavException;
import edu.rpi.cct.webdav.servlet.shared.WebdavForbidden;
import edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf;
import edu.rpi.cmt.access.PrivilegeDefs;
import edu.rpi.cmt.access.Acl.CurrentAccess;
import edu.rpi.sss.util.xml.XmlEmit;
import edu.rpi.sss.util.xml.XmlUtil;
import edu.rpi.sss.util.xml.tagdefs.AppleIcalTags;
import edu.rpi.sss.util.xml.tagdefs.AppleServerTags;
import edu.rpi.sss.util.xml.tagdefs.CaldavTags;
import edu.rpi.sss.util.xml.tagdefs.WebdavTags;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.TimeZone;
import net.fortuna.ical4j.model.component.VFreeBusy;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;
import org.w3c.dom.Element;
/** Class to represent a calendar in caldav.
*
* @author Mike Douglass [email protected]
*/
public class CaldavCalNode extends CaldavBwNode {
private Calendar ical;
private BwCalendar cal;
private BwUser owner;
private String vfreeBusyString;
private CurrentAccess currentAccess;
private final static HashMap<QName, PropertyTagEntry> propertyNames =
new HashMap<QName, PropertyTagEntry>();
static {
addPropEntry(propertyNames, CaldavTags.calendarDescription);
addPropEntry(propertyNames, CaldavTags.calendarFreeBusySet);
addPropEntry(propertyNames, CaldavTags.calendarTimezone);
addPropEntry(propertyNames, CaldavTags.maxAttendeesPerInstance);
addPropEntry(propertyNames, CaldavTags.maxDateTime);
addPropEntry(propertyNames, CaldavTags.maxInstances);
addPropEntry(propertyNames, CaldavTags.maxResourceSize);
addPropEntry(propertyNames, CaldavTags.minDateTime);
addPropEntry(propertyNames, CaldavTags.supportedCalendarComponentSet);
addPropEntry(propertyNames, CaldavTags.supportedCalendarData);
addPropEntry(propertyNames, AppleServerTags.getctag);
addPropEntry(propertyNames, AppleIcalTags.calendarColor);
}
/** Place holder for status
*
* @param sysi
* @param status
* @param uri
* @param debug
*/
public CaldavCalNode(SysIntf sysi, int status, String uri, boolean debug) {
super(true, sysi, debug);
setStatus(status);
this.uri = uri;
}
/**
* @param cdURI
* @param sysi
* @param debug
*/
public CaldavCalNode(CaldavURI cdURI, SysIntf sysi, boolean debug) {
super(cdURI, sysi, debug);
cal = cdURI.getCal();
collection = true;
allowsGet = false;
// if (!uri.endsWith("/")) {
// uri += "/";
// }
}
/**
* @return BwCalendar this node represents
*/
public BwCalendar getCalendar() throws WebdavException {
BwCalendar curCal = cal;
if ((curCal != null) &&
(curCal.getCalType() == BwCalendar.calTypeAlias)) {
curCal = cal.getAliasTarget();
if (curCal == null) {
getSysi().resolveAlias(cal);
curCal = cal.getAliasTarget();
}
}
return curCal;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getOwner()
*/
public String getOwner() throws WebdavException {
if (owner == null) {
if (cal == null) {
return null;
}
owner = cal.getOwner();
}
if (owner != null) {
return owner.getAccount();
}
return null;
}
public void init(boolean content) throws WebdavException {
if (!content) {
return;
}
}
public String getEtagValue(boolean strong) throws WebdavException {
BwCalendar c = getCalendar(); // Unalias
if (c == null) {
return null;
}
String val = c.getLastmod() + "-" + c.getSeq();
if (strong) {
return "\"" + val + "\"";
}
return "W/\"" + val + "\"";
}
/**
* @return true if scheduling allowed
* @throws WebdavException
*/
public boolean getSchedulingAllowed() throws WebdavException {
BwCalendar c = getCalendar(); // Unalias
if (c == null) {
return false;
}
int type = c.getCalType();
if (type == BwCalendar.calTypeInbox) {
return true;
}
if (type == BwCalendar.calTypeOutbox) {
return true;
}
return false;
}
public Collection getChildren() throws WebdavException {
/* For the moment we're going to do this the inefficient way.
We really need to have calendar defs that can be expressed as a search
allowing us to retrieve all the ids of objects within a calendar.
*/
try {
BwCalendar c = getCalendar(); // Unalias
if (!c.getCollectionInfo().entitiesAllowed) {
if (debug) {
debugMsg("POSSIBLE SEARCH: getChildren for cal " + c.getPath());
}
ArrayList ch = new ArrayList();
ch.addAll(getSysi().getCalendars(c));
ch.addAll(getSysi().getFiles(c));
return ch;
}
/* Otherwise, return the events in this calendar */
if (debug) {
debugMsg("Get all resources in calendar " + c.getPath());
}
RecurringRetrievalMode rrm = new RecurringRetrievalMode(
Rmode.overrides);
return getSysi().getEvents(c, null, rrm);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/**
* @param fb
* @throws WebdavException
*/
public void setFreeBusy(BwEvent fb) throws WebdavException {
try {
VFreeBusy vfreeBusy = VFreeUtil.toVFreeBusy(fb);
if (vfreeBusy != null) {
ical = IcalTranslator.newIcal(Icalendar.methodTypeNone);
ical.getComponents().add(vfreeBusy);
vfreeBusyString = ical.toString();
} else {
vfreeBusyString = null;
}
allowsGet = true;
} catch (Throwable t) {
if (debug) {
error(t);
}
throw new WebdavException(t);
}
}
public String getContentString() throws WebdavException {
init(true);
if (ical == null) {
return null;
}
return vfreeBusyString;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#update()
*/
public void update() throws WebdavException {
// ALIAS probably not unaliasing here
if (cal != null) {
getSysi().updateCalendar(cal);
}
}
/* ====================================================================
* Required webdav properties
* ==================================================================== */
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getContentLang()
*/
public String getContentLang() throws WebdavException {
return "en";
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getContentLen()
*/
public int getContentLen() throws WebdavException {
if (vfreeBusyString != null) {
return vfreeBusyString.length();
}
return 0;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getContentType()
*/
public String getContentType() throws WebdavException {
if (vfreeBusyString != null) {
return "text/calendar; charset=UTF-8";
}
return null;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getCreDate()
*/
public String getCreDate() throws WebdavException {
return null;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getDisplayname()
*/
public String getDisplayname() throws WebdavException {
if (cal == null) {
return null;
}
return cal.getName();
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getLastmodDate()
*/
public String getLastmodDate() throws WebdavException {
init(false);
if (cal == null) {
return null;
}
try {
return DateTimeUtil.fromISODateTimeUTCtoRfc822(cal.getLastmod().getTimestamp());
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* ====================================================================
* Abstract methods
* ==================================================================== */
public CurrentAccess getCurrentAccess() throws WebdavException {
if (currentAccess != null) {
return currentAccess;
}
BwCalendar c = getCalendar(); // Unalias
if (c == null) {
return null;
}
try {
currentAccess = getSysi().checkAccess(c, PrivilegeDefs.privAny, true);
} catch (Throwable t) {
throw new WebdavException(t);
}
return currentAccess;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#trailSlash()
*/
public boolean trailSlash() {
return true;
}
/* ====================================================================
* Property methods
* ==================================================================== */
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#removeProperty(org.w3c.dom.Element)
*/
public boolean removeProperty(Element val,
SetPropertyResult spr) throws WebdavException {
warn("Unimplemented - removeProperty");
return false;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#setProperty(org.w3c.dom.Element)
*/
public boolean setProperty(Element val,
SetPropertyResult spr) throws WebdavException {
if (super.setProperty(val, spr)) {
return true;
}
try {
if (XmlUtil.nodeMatches(val, WebdavTags.description)) {
if (checkCalForSetProp(spr)) {
cal.setDescription(XmlUtil.getElementContent(val));
}
return true;
}
if (XmlUtil.nodeMatches(val, CaldavTags.calendarDescription)) {
if (checkCalForSetProp(spr)) {
cal.setDescription(XmlUtil.getElementContent(val));
}
return true;
}
if (XmlUtil.nodeMatches(val, WebdavTags.displayname)) {
if (checkCalForSetProp(spr)) {
cal.setSummary(XmlUtil.getElementContent(val));
}
return true;
}
if (XmlUtil.nodeMatches(val, CaldavTags.calendarFreeBusySet)) {
// Only valid for inbox
if (cal.getCalType() != BwCalendar.calTypeInbox) {
throw new WebdavForbidden("Not on inbox");
}
spr.status = HttpServletResponse.SC_NOT_IMPLEMENTED;
spr.message = "Unimplemented - calendarFreeBusySet";
warn("Unimplemented - calendarFreeBusySet");
return true;
}
if (XmlUtil.nodeMatches(val, CaldavTags.calendarTimezone)) {
try {
StringReader sr = new StringReader(XmlUtil.getElementContent(val));
// This call automatically saves the timezone in the db
Icalendar ic = getSysi().fromIcal(cal, sr);
if ((ic == null) ||
(ic.size() != 0) || // No components other than timezones
(ic.getTimeZones().size() != 1)) {
if (debug) {
debugMsg("Not icalendar");
}
throw new WebdavForbidden(CaldavTags.validCalendarData, "Not icalendar");
}
TimeZone tz = ic.getTimeZones().iterator().next();
cal.setTimezone(tz.getID());
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavForbidden(CaldavTags.validCalendarData, "Not icalendar");
}
return true;
}
if (XmlUtil.nodeMatches(val, AppleIcalTags.calendarColor)) {
cal.setColor(XmlUtil.getElementContent(val));
return true;
}
return false;
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#knownProperty(edu.rpi.sss.util.xml.QName)
*/
public boolean knownProperty(QName tag) {
if (propertyNames.get(tag) != null) {
return true;
}
// Not ours
return super.knownProperty(tag);
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#generatePropertyValue(edu.rpi.sss.util.xml.QName, edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf, boolean)
*/
public boolean generatePropertyValue(QName tag,
WebdavNsIntf intf,
boolean allProp) throws WebdavException {
XmlEmit xml = intf.getXmlEmit();
try {
BwCalendar c = getCalendar(); // Unalias
if (tag.equals(WebdavTags.resourcetype)) {
// dav 13.9
xml.openTag(WebdavTags.resourcetype);
xml.emptyTag(WebdavTags.collection);
if (debug) {
debugMsg("generatePropResourcetype for " + cal);
}
int calType = c.getCalType();
//boolean isCollection = cal.getCalendarCollection();
if (calType == BwCalendar.calTypeInbox) {
xml.emptyTag(CaldavTags.scheduleInbox);
} else if (calType == BwCalendar.calTypeOutbox) {
xml.emptyTag(CaldavTags.scheduleOutbox);
} else if (calType == BwCalendar.calTypeCollection) {
xml.emptyTag(CaldavTags.calendar);
}
xml.closeTag(WebdavTags.resourcetype);
return true;
}
if (tag.equals(AppleServerTags.getctag)) {
xml.property(tag, cal.getLastmod().getTagValue());
return true;
}
if (tag.equals(AppleIcalTags.calendarColor)) {
String val = cal.getColor();
if (val == null) {
return false;
}
xml.property(tag, val);
return true;
}
if (tag.equals(CaldavTags.calendarDescription)) {
xml.property(tag, cal.getDescription());
return true;
}
if ((cal.getCalType() == BwCalendar.calTypeInbox) &&
(tag.equals(CaldavTags.calendarFreeBusySet))) {
xml.openTag(tag);
Collection<String> hrefs = getSysi().getFreebusySet();
for (String href: hrefs) {
xml.property(WebdavTags.href, href);
}
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.supportedCalendarComponentSet)) {
/* e.g.
* <C:supported-calendar-component-set
* xmlns:C="urn:ietf:params:xml:ns:caldav">
* <C:comp name="VEVENT"/>
* <C:comp name="VTODO"/>
* </C:supported-calendar-component-set>
*/
if (!cal.getCalendarCollection()) {
return true;
}
xml.openTag(tag);
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VEVENT");
xml.endEmptyTag();
xml.newline();
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VTODO");
xml.endEmptyTag();
xml.newline();
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.supportedCalendarData)) {
/* e.g.
* <C:supported-calendar-data
* xmlns:C="urn:ietf:params:xml:ns:caldav">
* <C:calendar-data content-type="text/calendar" version="2.0"/>
* </C:supported-calendar-data>
*/
xml.openTag(tag);
xml.startTag(CaldavTags.calendarData);
xml.attribute("content-type", "text/calendar");
xml.attribute("version", "2.0");
+ xml.endEmptyTag();
+ xml.newline();
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.calendarTimezone)) {
String tzid = cal.getTimezone();
if (tzid == null) {
return false;
}
String val = getSysi().toStringTzCalendar(tzid);
if (val == null) {
return false;
}
xml.cdataProperty(tag, val);
return true;
}
// Not known - try higher
return super.generatePropertyValue(tag, intf, allProp);
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/** Return a set of PropertyTagEntry defining properties this node supports.
*
* @return Collection of PropertyTagEntry
* @throws WebdavException
*/
public Collection<PropertyTagEntry> getPropertyNames()throws WebdavException {
Collection<PropertyTagEntry> res = new ArrayList<PropertyTagEntry>();
res.addAll(super.getPropertyNames());
res.addAll(propertyNames.values());
return res;
}
/** Return a set of Qname defining reports this node supports.
*
* @return Collection of QName
* @throws WebdavException
*/
public Collection<QName> getSupportedReports() throws WebdavException {
Collection<QName> res = new ArrayList<QName>();
BwCalendar c = getCalendar(); // Unalias
res.addAll(super.getSupportedReports());
/* Cannot do free-busy on in and outbox */
if (c.getCollectionInfo().allowFreeBusy) {
res.add(CaldavTags.freeBusyQuery); // Calendar access
}
return res;
}
/* ====================================================================
* Object methods
* ==================================================================== */
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("CaldavCalNode{cduri=");
sb.append("path=");
sb.append(getPath());
sb.append(", isCalendarCollection()=");
try {
sb.append(isCalendarCollection());
} catch (Throwable t) {
sb.append("exception(" + t.getMessage() + ")");
}
sb.append("}");
return sb.toString();
}
/* ====================================================================
* Private methods
* ==================================================================== */
private boolean checkCalForSetProp(SetPropertyResult spr) {
if (cal != null) {
return true;
}
spr.status = HttpServletResponse.SC_NOT_FOUND;
spr.message = "Not found";
return false;
}
}
| true | true | public boolean generatePropertyValue(QName tag,
WebdavNsIntf intf,
boolean allProp) throws WebdavException {
XmlEmit xml = intf.getXmlEmit();
try {
BwCalendar c = getCalendar(); // Unalias
if (tag.equals(WebdavTags.resourcetype)) {
// dav 13.9
xml.openTag(WebdavTags.resourcetype);
xml.emptyTag(WebdavTags.collection);
if (debug) {
debugMsg("generatePropResourcetype for " + cal);
}
int calType = c.getCalType();
//boolean isCollection = cal.getCalendarCollection();
if (calType == BwCalendar.calTypeInbox) {
xml.emptyTag(CaldavTags.scheduleInbox);
} else if (calType == BwCalendar.calTypeOutbox) {
xml.emptyTag(CaldavTags.scheduleOutbox);
} else if (calType == BwCalendar.calTypeCollection) {
xml.emptyTag(CaldavTags.calendar);
}
xml.closeTag(WebdavTags.resourcetype);
return true;
}
if (tag.equals(AppleServerTags.getctag)) {
xml.property(tag, cal.getLastmod().getTagValue());
return true;
}
if (tag.equals(AppleIcalTags.calendarColor)) {
String val = cal.getColor();
if (val == null) {
return false;
}
xml.property(tag, val);
return true;
}
if (tag.equals(CaldavTags.calendarDescription)) {
xml.property(tag, cal.getDescription());
return true;
}
if ((cal.getCalType() == BwCalendar.calTypeInbox) &&
(tag.equals(CaldavTags.calendarFreeBusySet))) {
xml.openTag(tag);
Collection<String> hrefs = getSysi().getFreebusySet();
for (String href: hrefs) {
xml.property(WebdavTags.href, href);
}
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.supportedCalendarComponentSet)) {
/* e.g.
* <C:supported-calendar-component-set
* xmlns:C="urn:ietf:params:xml:ns:caldav">
* <C:comp name="VEVENT"/>
* <C:comp name="VTODO"/>
* </C:supported-calendar-component-set>
*/
if (!cal.getCalendarCollection()) {
return true;
}
xml.openTag(tag);
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VEVENT");
xml.endEmptyTag();
xml.newline();
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VTODO");
xml.endEmptyTag();
xml.newline();
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.supportedCalendarData)) {
/* e.g.
* <C:supported-calendar-data
* xmlns:C="urn:ietf:params:xml:ns:caldav">
* <C:calendar-data content-type="text/calendar" version="2.0"/>
* </C:supported-calendar-data>
*/
xml.openTag(tag);
xml.startTag(CaldavTags.calendarData);
xml.attribute("content-type", "text/calendar");
xml.attribute("version", "2.0");
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.calendarTimezone)) {
String tzid = cal.getTimezone();
if (tzid == null) {
return false;
}
String val = getSysi().toStringTzCalendar(tzid);
if (val == null) {
return false;
}
xml.cdataProperty(tag, val);
return true;
}
// Not known - try higher
return super.generatePropertyValue(tag, intf, allProp);
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
| public boolean generatePropertyValue(QName tag,
WebdavNsIntf intf,
boolean allProp) throws WebdavException {
XmlEmit xml = intf.getXmlEmit();
try {
BwCalendar c = getCalendar(); // Unalias
if (tag.equals(WebdavTags.resourcetype)) {
// dav 13.9
xml.openTag(WebdavTags.resourcetype);
xml.emptyTag(WebdavTags.collection);
if (debug) {
debugMsg("generatePropResourcetype for " + cal);
}
int calType = c.getCalType();
//boolean isCollection = cal.getCalendarCollection();
if (calType == BwCalendar.calTypeInbox) {
xml.emptyTag(CaldavTags.scheduleInbox);
} else if (calType == BwCalendar.calTypeOutbox) {
xml.emptyTag(CaldavTags.scheduleOutbox);
} else if (calType == BwCalendar.calTypeCollection) {
xml.emptyTag(CaldavTags.calendar);
}
xml.closeTag(WebdavTags.resourcetype);
return true;
}
if (tag.equals(AppleServerTags.getctag)) {
xml.property(tag, cal.getLastmod().getTagValue());
return true;
}
if (tag.equals(AppleIcalTags.calendarColor)) {
String val = cal.getColor();
if (val == null) {
return false;
}
xml.property(tag, val);
return true;
}
if (tag.equals(CaldavTags.calendarDescription)) {
xml.property(tag, cal.getDescription());
return true;
}
if ((cal.getCalType() == BwCalendar.calTypeInbox) &&
(tag.equals(CaldavTags.calendarFreeBusySet))) {
xml.openTag(tag);
Collection<String> hrefs = getSysi().getFreebusySet();
for (String href: hrefs) {
xml.property(WebdavTags.href, href);
}
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.supportedCalendarComponentSet)) {
/* e.g.
* <C:supported-calendar-component-set
* xmlns:C="urn:ietf:params:xml:ns:caldav">
* <C:comp name="VEVENT"/>
* <C:comp name="VTODO"/>
* </C:supported-calendar-component-set>
*/
if (!cal.getCalendarCollection()) {
return true;
}
xml.openTag(tag);
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VEVENT");
xml.endEmptyTag();
xml.newline();
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VTODO");
xml.endEmptyTag();
xml.newline();
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.supportedCalendarData)) {
/* e.g.
* <C:supported-calendar-data
* xmlns:C="urn:ietf:params:xml:ns:caldav">
* <C:calendar-data content-type="text/calendar" version="2.0"/>
* </C:supported-calendar-data>
*/
xml.openTag(tag);
xml.startTag(CaldavTags.calendarData);
xml.attribute("content-type", "text/calendar");
xml.attribute("version", "2.0");
xml.endEmptyTag();
xml.newline();
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.calendarTimezone)) {
String tzid = cal.getTimezone();
if (tzid == null) {
return false;
}
String val = getSysi().toStringTzCalendar(tzid);
if (val == null) {
return false;
}
xml.cdataProperty(tag, val);
return true;
}
// Not known - try higher
return super.generatePropertyValue(tag, intf, allProp);
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
|
diff --git a/src/master/src/org/drftpd/master/BaseFtpConnection.java b/src/master/src/org/drftpd/master/BaseFtpConnection.java
index 018ac5e7..8ebce6dc 100644
--- a/src/master/src/org/drftpd/master/BaseFtpConnection.java
+++ b/src/master/src/org/drftpd/master/BaseFtpConnection.java
@@ -1,640 +1,641 @@
/*
* This file is part of DrFTPD, Distributed FTP Daemon.
*
* DrFTPD 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.
*
* DrFTPD 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 DrFTPD; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.drftpd.master;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLSocket;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.drftpd.GlobalContext;
import org.drftpd.Time;
import org.drftpd.commandmanager.CommandManagerInterface;
import org.drftpd.commandmanager.CommandRequestInterface;
import org.drftpd.commandmanager.CommandResponseInterface;
import org.drftpd.dynamicdata.Key;
import org.drftpd.dynamicdata.KeyNotFoundException;
import org.drftpd.event.ConnectionEvent;
import org.drftpd.io.AddAsciiOutputStream;
import org.drftpd.usermanager.NoSuchUserException;
import org.drftpd.usermanager.User;
import org.drftpd.usermanager.UserFileException;
import org.drftpd.util.FtpRequest;
import org.drftpd.vfs.DirectoryHandle;
/**
* This is a generic ftp connection handler. It delegates the request to
* appropriate methods in subclasses.
*
* @author <a href="mailto:[email protected]">Rana Bhattacharyya</a>
* @author mog
* @version $Id$
*/
@SuppressWarnings("serial")
public class BaseFtpConnection extends Session implements Runnable {
private static final Logger debuglogger = Logger.getLogger(BaseFtpConnection.class.getName() + ".service");
private static final Logger logger = Logger.getLogger(BaseFtpConnection.class);
public static final Key<InetAddress> ADDRESS = new Key<InetAddress>(BaseFtpConnection.class, "address");
public static final Key<String> IDENT = new Key<String>(BaseFtpConnection.class, "ident");
public static final Key<Boolean> FAILEDLOGIN = new Key<Boolean>(BaseFtpConnection.class, "failedlogin");
public static final Key<String> FAILEDREASON = new Key<String>(BaseFtpConnection.class, "failedreason");
public static final String NEWLINE = "\r\n";
/**
* Is the current password authenticated?
*/
protected boolean _authenticated = false;
private CommandManagerInterface _commandManager;
protected Socket _controlSocket;
public TransferState getTransferState() {
TransferState ts;
try {
ts = getObject(TransferState.TRANSFERSTATE);
} catch (KeyNotFoundException e) {
ts = new TransferState();
setObject(TransferState.TRANSFERSTATE,ts);
}
return ts;
}
protected DirectoryHandle _currentDirectory;
private BufferedReader _in;
/**
* time when last command from the client finished execution
*/
protected long _lastActive;
protected PrintWriter _out;
protected FtpRequest _request;
/**
* Should this thread stop insted of continue looping?
*/
protected boolean _stopRequest = false;
protected String _stopRequestMessage;
protected Thread _thread;
protected String _user;
private ThreadPoolExecutor _pool;
private boolean _authDone = false;
private AtomicInteger _commandCount = new AtomicInteger(0);
protected BaseFtpConnection() {
}
public BaseFtpConnection(Socket soc) {
setControlSocket(soc);
}
/**
* Get client address
*/
public InetAddress getClientAddress() {
return _controlSocket.getInetAddress();
}
public GlobalContext getGlobalContext() {
return GlobalContext.getGlobalContext();
}
public BufferedReader getControlReader() {
return _in;
}
public Socket getControlSocket() {
return _controlSocket;
}
public PrintWriter getControlWriter() {
return _out;
}
public DirectoryHandle getCurrentDirectory() {
return _currentDirectory;
}
/*
* Returns thread id number
*/
public long getThreadID() {
return _thread.getId();
}
/**
* Returns the "currentTimeMillis" when last command finished executing.
*/
public long getLastActive() {
return _lastActive;
}
/**
* Returns the FtpRequest of current or last command executed.
*/
public FtpRequest getRequest() {
return _request;
}
/**
* Get user object
*/
public User getUser() throws NoSuchUserException {
if ((_user == null) || !isAuthenticated()) {
throw new NoSuchUserException("no user logged in for connection");
}
try {
return getGlobalContext().getUserManager().getUserByNameUnchecked(
_user);
} catch (UserFileException e) {
throw new NoSuchUserException(e);
}
}
public User getUserNull() {
if (_user == null || !isAuthenticated()) {
return null;
}
try {
return getGlobalContext().getUserManager().getUserByNameUnchecked(
_user);
} catch (NoSuchUserException e) {
return null;
} catch (UserFileException e) {
return null;
}
}
public User getUserNullUnchecked() {
if (_user == null) {
return null;
}
try {
return getGlobalContext().getUserManager().getUserByNameUnchecked(
_user);
} catch (NoSuchUserException e) {
return null;
} catch (UserFileException e) {
return null;
}
}
/**
* @return the username (string).
*/
public String getUsername() {
if (isAuthenticated()) {
return _user;
}
return null;
}
public boolean isAuthenticated() {
return _authenticated;
}
/**
* Returns true if client is executing a command.
*/
public boolean isExecuting() {
return _pool.getActiveCount() > 0;
}
public boolean isSecure() {
return _controlSocket instanceof SSLSocket;
}
public String jprintf(Class<?> baseName, String key) {
return jprintf(baseName, key, null, getUserNull());
}
/**
* Server one FTP connection.
*/
public void run() {
_commandManager = GlobalContext.getConnectionManager().getCommandManager();
setCommands(GlobalContext.getConnectionManager().getCommands());
_lastActive = System.currentTimeMillis();
setCurrentDirectory(getGlobalContext().getRoot());
_thread = Thread.currentThread();
GlobalContext.getConnectionManager().dumpThreadPool();
_lastActive = System.currentTimeMillis();
if (!GlobalContext.getConfig().getHideIps()) {
logger.info("Handling new request from "
+ getClientAddress().getHostAddress());
_thread.setName("FtpConn thread " + _thread.getId() + " from "
+ getClientAddress().getHostAddress());
} else {
logger.info("Handling new request from <iphidden>");
_thread.setName("FtpConn thread " + _thread.getId()
+ " from <iphidden>");
}
_pool = new ThreadPoolExecutor(1, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
new CommandThreadFactory(_thread.getName()));
try {
_controlSocket.setSoTimeout(1000);
if (GlobalContext.getGlobalContext().isShutdown()) {
stop(GlobalContext.getGlobalContext().getShutdownMessage());
} else {
FtpReply response = new FtpReply(220, GlobalContext.getConfig().getLoginPrompt());
_out.print(response);
}
while (!_stopRequest) {
_out.flush();
String commandLine = null;
try {
commandLine = _in.readLine();
// will block for a maximum of _controlSocket.getSoTimeout()
// milliseconds
} catch (InterruptedIOException ex) {
if (_controlSocket == null) {
stop("Control socket is null");
break;
}
if (!_controlSocket.isConnected()) {
stop("Socket unexpectedly closed");
break;
}
int idleTime;
try {
idleTime = getUser().getIdleTime();
if (idleTime > 0) {
_pool.setKeepAliveTime(idleTime, TimeUnit.SECONDS);
}
} catch (NoSuchUserException e) {
idleTime = 60;
// user not logged in yet
}
if (idleTime > 0
&& ((System.currentTimeMillis() - _lastActive) / 1000 >= idleTime)
&& !isExecuting()) {
stop("IdleTimeout");
break;
}
continue;
}
if (_stopRequest) {
break;
}
// test command line
if (commandLine == null) {
break;
}
if (commandLine.equals("")) {
continue;
}
_request = new FtpRequest(commandLine);
if (!_request.getCommand().equals("PASS")) {
debuglogger.debug("<< " + _request.getCommandLine());
}
// execute command
_pool.execute(new CommandThread(_request, this));
if (_request.getCommand().equalsIgnoreCase("AUTH")) {
while(!_authDone && !_stopRequest) {
Thread.sleep(100);
}
}
poolStatus();
_lastActive = System.currentTimeMillis();
}
if (_stopRequestMessage != null) {
_out.print(new FtpReply(421, _stopRequestMessage));
} else {
_out.println("421 Connection closing");
}
_out.flush();
} catch (SocketException ex) {
logger.log(Level.INFO, ex.getMessage() + ", closing for user "
+ ((_user == null) ? "<not logged in>" : _user), ex);
} catch (Exception ex) {
logger.log(Level.INFO, "Exception, closing", ex);
} finally {
shutdownSocket();
if (isAuthenticated()) {
try {
getUser().updateLastAccessTime();
} catch (NoSuchUserException e) {
logger.error("User does not exist, yet user is authenticated, this is a bug");
}
GlobalContext.getEventService().publishAsync(new ConnectionEvent(getUserNull(), "LOGOUT"));
}
if (isExecuting()) {
super.abortCommand();
}
+ getTransferState().reset();
_pool.shutdown();
GlobalContext.getConnectionManager().remove(this);
GlobalContext.getConnectionManager().dumpThreadPool();
Thread t = Thread.currentThread();
t.setName(ConnectionThreadFactory.getIdleThreadName(t.getId()));
}
}
public void setAuthenticated(boolean authenticated) {
_authenticated = authenticated;
if (isAuthenticated()) {
try {
// If hideips is on, hide ip but not user/group
if (GlobalContext.getConfig().getHideIps()) {
_thread.setName("FtpConn thread " + _thread.getId()
+ " servicing " + _user + "/"
+ getUser().getGroup());
} else {
_thread.setName("FtpConn thread " + _thread.getId()
+ " from " + getClientAddress().getHostAddress()
+ " " + _user + "/" + getUser().getGroup());
}
} catch (NoSuchUserException e) {
logger
.error("User does not exist, yet user is authenticated, this is a bug");
}
}
}
public void setControlSocket(Socket socket) {
try {
_controlSocket = socket;
_in = new BufferedReader(new InputStreamReader(_controlSocket
.getInputStream(), "ISO-8859-1"));
_out = new PrintWriter(new OutputStreamWriter(
new AddAsciiOutputStream(new BufferedOutputStream(
_controlSocket.getOutputStream())), "ISO-8859-1"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void setCurrentDirectory(DirectoryHandle path) {
_currentDirectory = path;
}
public void setUser(String user) {
_user = user;
}
/**
* returns a two-line status
*/
public String status() {
return jprintf(BaseFtpConnection.class, "statusline");
}
/**
* User logout and stop this thread.
*/
public void stop() {
getTransferState().abort("Your connection is being shutdown");
_stopRequest = true;
}
public void stop(String message) {
_stopRequestMessage = message;
stop();
}
public String toString() {
StringBuffer buf = new StringBuffer("[BaseFtpConnection");
if (_user != null) {
buf.append("[user: " + _user + "]");
}
if (_request != null) {
buf.append("[command: " + _request.getCommand() + "]");
}
if (isExecuting()) {
buf.append("[executing]");
} else {
buf.append("[idle: "
+ Time.formatTime(System.currentTimeMillis()
- getLastActive()));
}
buf.append("]");
return buf.toString();
}
public OutputStream getOutputStream() throws IOException {
return _controlSocket.getOutputStream();
}
public static int countTransfersForUser(User user, char transferDirection) {
int count = 0;
for (BaseFtpConnection conn : GlobalContext.getConnectionManager().getConnections()) {
if (conn.getUserNull() == user) {
if (conn.getTransferState().getDirection() == transferDirection) {
count++;
} // else we dont need to process it.
}
}
return count;
}
/**
* When a user is renamed the control connection looses its owner since the reference to the User
* is actually made thru a String containing the username.<br>
* This methods iterates thru all control connections trying to match connections owned by 'oldUsername'
* and re-sets it to 'newUsername'.
* @param oldUsername
* @param newUsername
*/
public static void fixBaseFtpConnUser(String oldUsername, String newUsername) {
for (BaseFtpConnection conn : GlobalContext.getConnectionManager().getConnections()) {
if (conn.getUsername() == null) {
// User authentication not completed yet for this connection
continue;
} else if (conn.getUsername().equals(oldUsername)) {
conn.setUser(newUsername);
}
}
}
public synchronized void printOutput(Object o) {
_out.print(o);
_out.flush();
}
public synchronized void printOutput(int code, Object o) {
_out.print(code+"- "+o.toString()+"\n");
_out.flush();
}
public void authDone() {
_authDone = true;
}
public void poolStatus() {
//logger.debug("pool size: "+_pool.getPoolSize());
//logger.debug("active threads: "+_pool.getActiveCount());
}
@Override
public void abortCommand() {
super.abortCommand();
if (getTransferState().abort("Transfer aborted")) {
printOutput(new FtpReply(426, "Connection closed; transfer aborted."));
}
}
protected void shutdownSocket() {
try {
if (_in != null) {
_in.close();
}
} catch (Exception ex) {
// Already closed
}
try {
if (_out != null) {
_out.close();
}
} catch (Exception ex) {
// Already closed
}
try {
if (_controlSocket != null) {
_controlSocket.close();
}
} catch (Exception ex) {
// Already closed
}
}
/**
* This is required because otherwise the superclass Hashtable.equals() will be
* used which treats two maps as equal if the contents/size of the maps are equal
* including for empty maps. For connections we only want equality to be true if
* the objects being compared truly are the same connection.
*/
@Override
public boolean equals(Object o) {
return o == this;
}
class CommandThread implements Runnable {
private FtpRequest _ftpRequest;
private BaseFtpConnection _conn;
private CommandThread(FtpRequest ftpRequest, BaseFtpConnection conn) {
_ftpRequest = ftpRequest;
_conn = conn;
}
public void run() {
if (_commandCount.get() > 0 && !_ftpRequest.getCommand().equalsIgnoreCase("ABOR")) {
return;
}
_commandCount.incrementAndGet();
clearAborted();
CommandRequestInterface cmdRequest = _commandManager.newRequest(
_ftpRequest.getCommand(), _ftpRequest.getArgument(),
_currentDirectory, _conn.getUsername(), _conn, _conn.getCommands().get(_ftpRequest.getCommand()));
CommandResponseInterface cmdResponse = _commandManager
.execute(cmdRequest);
if (cmdResponse != null) {
if (!isAborted() || _ftpRequest.getCommand().equalsIgnoreCase("ABOR")) {
if (cmdResponse.getCurrentDirectory() != null) {
_currentDirectory = cmdResponse.getCurrentDirectory();
}
if (cmdResponse.getUser() != null) {
_user = cmdResponse.getUser();
}
printOutput(new FtpReply(cmdResponse));
}
}
if (cmdRequest.getSession().getObject(BaseFtpConnection.FAILEDLOGIN,false)) {
_conn.stop("Closing Connection");
}
_commandCount.decrementAndGet();
}
}
static class CommandThreadFactory implements ThreadFactory {
String _parentName;
private CommandThreadFactory(String parentName) {
_parentName = parentName;
}
public Thread newThread(Runnable r) {
Thread ret = Executors.defaultThreadFactory().newThread(r);
ret.setName(_parentName + " - " + ret.getName());
return ret;
}
}
}
| true | true | public void run() {
_commandManager = GlobalContext.getConnectionManager().getCommandManager();
setCommands(GlobalContext.getConnectionManager().getCommands());
_lastActive = System.currentTimeMillis();
setCurrentDirectory(getGlobalContext().getRoot());
_thread = Thread.currentThread();
GlobalContext.getConnectionManager().dumpThreadPool();
_lastActive = System.currentTimeMillis();
if (!GlobalContext.getConfig().getHideIps()) {
logger.info("Handling new request from "
+ getClientAddress().getHostAddress());
_thread.setName("FtpConn thread " + _thread.getId() + " from "
+ getClientAddress().getHostAddress());
} else {
logger.info("Handling new request from <iphidden>");
_thread.setName("FtpConn thread " + _thread.getId()
+ " from <iphidden>");
}
_pool = new ThreadPoolExecutor(1, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
new CommandThreadFactory(_thread.getName()));
try {
_controlSocket.setSoTimeout(1000);
if (GlobalContext.getGlobalContext().isShutdown()) {
stop(GlobalContext.getGlobalContext().getShutdownMessage());
} else {
FtpReply response = new FtpReply(220, GlobalContext.getConfig().getLoginPrompt());
_out.print(response);
}
while (!_stopRequest) {
_out.flush();
String commandLine = null;
try {
commandLine = _in.readLine();
// will block for a maximum of _controlSocket.getSoTimeout()
// milliseconds
} catch (InterruptedIOException ex) {
if (_controlSocket == null) {
stop("Control socket is null");
break;
}
if (!_controlSocket.isConnected()) {
stop("Socket unexpectedly closed");
break;
}
int idleTime;
try {
idleTime = getUser().getIdleTime();
if (idleTime > 0) {
_pool.setKeepAliveTime(idleTime, TimeUnit.SECONDS);
}
} catch (NoSuchUserException e) {
idleTime = 60;
// user not logged in yet
}
if (idleTime > 0
&& ((System.currentTimeMillis() - _lastActive) / 1000 >= idleTime)
&& !isExecuting()) {
stop("IdleTimeout");
break;
}
continue;
}
if (_stopRequest) {
break;
}
// test command line
if (commandLine == null) {
break;
}
if (commandLine.equals("")) {
continue;
}
_request = new FtpRequest(commandLine);
if (!_request.getCommand().equals("PASS")) {
debuglogger.debug("<< " + _request.getCommandLine());
}
// execute command
_pool.execute(new CommandThread(_request, this));
if (_request.getCommand().equalsIgnoreCase("AUTH")) {
while(!_authDone && !_stopRequest) {
Thread.sleep(100);
}
}
poolStatus();
_lastActive = System.currentTimeMillis();
}
if (_stopRequestMessage != null) {
_out.print(new FtpReply(421, _stopRequestMessage));
} else {
_out.println("421 Connection closing");
}
_out.flush();
} catch (SocketException ex) {
logger.log(Level.INFO, ex.getMessage() + ", closing for user "
+ ((_user == null) ? "<not logged in>" : _user), ex);
} catch (Exception ex) {
logger.log(Level.INFO, "Exception, closing", ex);
} finally {
shutdownSocket();
if (isAuthenticated()) {
try {
getUser().updateLastAccessTime();
} catch (NoSuchUserException e) {
logger.error("User does not exist, yet user is authenticated, this is a bug");
}
GlobalContext.getEventService().publishAsync(new ConnectionEvent(getUserNull(), "LOGOUT"));
}
if (isExecuting()) {
super.abortCommand();
}
_pool.shutdown();
GlobalContext.getConnectionManager().remove(this);
GlobalContext.getConnectionManager().dumpThreadPool();
Thread t = Thread.currentThread();
t.setName(ConnectionThreadFactory.getIdleThreadName(t.getId()));
}
}
| public void run() {
_commandManager = GlobalContext.getConnectionManager().getCommandManager();
setCommands(GlobalContext.getConnectionManager().getCommands());
_lastActive = System.currentTimeMillis();
setCurrentDirectory(getGlobalContext().getRoot());
_thread = Thread.currentThread();
GlobalContext.getConnectionManager().dumpThreadPool();
_lastActive = System.currentTimeMillis();
if (!GlobalContext.getConfig().getHideIps()) {
logger.info("Handling new request from "
+ getClientAddress().getHostAddress());
_thread.setName("FtpConn thread " + _thread.getId() + " from "
+ getClientAddress().getHostAddress());
} else {
logger.info("Handling new request from <iphidden>");
_thread.setName("FtpConn thread " + _thread.getId()
+ " from <iphidden>");
}
_pool = new ThreadPoolExecutor(1, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
new CommandThreadFactory(_thread.getName()));
try {
_controlSocket.setSoTimeout(1000);
if (GlobalContext.getGlobalContext().isShutdown()) {
stop(GlobalContext.getGlobalContext().getShutdownMessage());
} else {
FtpReply response = new FtpReply(220, GlobalContext.getConfig().getLoginPrompt());
_out.print(response);
}
while (!_stopRequest) {
_out.flush();
String commandLine = null;
try {
commandLine = _in.readLine();
// will block for a maximum of _controlSocket.getSoTimeout()
// milliseconds
} catch (InterruptedIOException ex) {
if (_controlSocket == null) {
stop("Control socket is null");
break;
}
if (!_controlSocket.isConnected()) {
stop("Socket unexpectedly closed");
break;
}
int idleTime;
try {
idleTime = getUser().getIdleTime();
if (idleTime > 0) {
_pool.setKeepAliveTime(idleTime, TimeUnit.SECONDS);
}
} catch (NoSuchUserException e) {
idleTime = 60;
// user not logged in yet
}
if (idleTime > 0
&& ((System.currentTimeMillis() - _lastActive) / 1000 >= idleTime)
&& !isExecuting()) {
stop("IdleTimeout");
break;
}
continue;
}
if (_stopRequest) {
break;
}
// test command line
if (commandLine == null) {
break;
}
if (commandLine.equals("")) {
continue;
}
_request = new FtpRequest(commandLine);
if (!_request.getCommand().equals("PASS")) {
debuglogger.debug("<< " + _request.getCommandLine());
}
// execute command
_pool.execute(new CommandThread(_request, this));
if (_request.getCommand().equalsIgnoreCase("AUTH")) {
while(!_authDone && !_stopRequest) {
Thread.sleep(100);
}
}
poolStatus();
_lastActive = System.currentTimeMillis();
}
if (_stopRequestMessage != null) {
_out.print(new FtpReply(421, _stopRequestMessage));
} else {
_out.println("421 Connection closing");
}
_out.flush();
} catch (SocketException ex) {
logger.log(Level.INFO, ex.getMessage() + ", closing for user "
+ ((_user == null) ? "<not logged in>" : _user), ex);
} catch (Exception ex) {
logger.log(Level.INFO, "Exception, closing", ex);
} finally {
shutdownSocket();
if (isAuthenticated()) {
try {
getUser().updateLastAccessTime();
} catch (NoSuchUserException e) {
logger.error("User does not exist, yet user is authenticated, this is a bug");
}
GlobalContext.getEventService().publishAsync(new ConnectionEvent(getUserNull(), "LOGOUT"));
}
if (isExecuting()) {
super.abortCommand();
}
getTransferState().reset();
_pool.shutdown();
GlobalContext.getConnectionManager().remove(this);
GlobalContext.getConnectionManager().dumpThreadPool();
Thread t = Thread.currentThread();
t.setName(ConnectionThreadFactory.getIdleThreadName(t.getId()));
}
}
|
diff --git a/activemq-tooling/maven-activemq-perf-plugin/src/main/java/org/apache/activemq/tool/JmsConsumerClient.java b/activemq-tooling/maven-activemq-perf-plugin/src/main/java/org/apache/activemq/tool/JmsConsumerClient.java
index 0f6c475ce..ff887fe4b 100644
--- a/activemq-tooling/maven-activemq-perf-plugin/src/main/java/org/apache/activemq/tool/JmsConsumerClient.java
+++ b/activemq-tooling/maven-activemq-perf-plugin/src/main/java/org/apache/activemq/tool/JmsConsumerClient.java
@@ -1,235 +1,239 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.tool;
import java.util.concurrent.atomic.AtomicInteger;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Topic;
import org.apache.activemq.tool.properties.JmsClientProperties;
import org.apache.activemq.tool.properties.JmsConsumerProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JmsConsumerClient extends AbstractJmsMeasurableClient {
private static final Logger LOG = LoggerFactory.getLogger(JmsConsumerClient.class);
protected MessageConsumer jmsConsumer;
protected JmsConsumerProperties client;
public JmsConsumerClient(ConnectionFactory factory) {
this(new JmsConsumerProperties(), factory);
}
public JmsConsumerClient(JmsConsumerProperties clientProps, ConnectionFactory factory) {
super(factory);
client = clientProps;
}
public void receiveMessages() throws JMSException {
if (client.isAsyncRecv()) {
if (client.getRecvType().equalsIgnoreCase(JmsConsumerProperties.TIME_BASED_RECEIVING)) {
receiveAsyncTimeBasedMessages(client.getRecvDuration());
} else {
receiveAsyncCountBasedMessages(client.getRecvCount());
}
} else {
if (client.getRecvType().equalsIgnoreCase(JmsConsumerProperties.TIME_BASED_RECEIVING)) {
receiveSyncTimeBasedMessages(client.getRecvDuration());
} else {
receiveSyncCountBasedMessages(client.getRecvCount());
}
}
}
public void receiveMessages(int destCount) throws JMSException {
this.destCount = destCount;
receiveMessages();
}
public void receiveMessages(int destIndex, int destCount) throws JMSException {
this.destIndex = destIndex;
receiveMessages(destCount);
}
public void receiveSyncTimeBasedMessages(long duration) throws JMSException {
if (getJmsConsumer() == null) {
createJmsConsumer();
}
try {
getConnection().start();
LOG.info("Starting to synchronously receive messages for " + duration + " ms...");
long endTime = System.currentTimeMillis() + duration;
while (System.currentTimeMillis() < endTime) {
getJmsConsumer().receive();
incThroughput();
}
} finally {
if (client.isDurable() && client.isUnsubscribe()) {
LOG.info("Unsubscribing durable subscriber: " + getClientName());
getJmsConsumer().close();
getSession().unsubscribe(getClientName());
}
getConnection().close();
}
}
public void receiveSyncCountBasedMessages(long count) throws JMSException {
if (getJmsConsumer() == null) {
createJmsConsumer();
}
try {
getConnection().start();
LOG.info("Starting to synchronously receive " + count + " messages...");
int recvCount = 0;
while (recvCount < count) {
getJmsConsumer().receive();
incThroughput();
recvCount++;
}
} finally {
if (client.isDurable() && client.isUnsubscribe()) {
LOG.info("Unsubscribing durable subscriber: " + getClientName());
getJmsConsumer().close();
getSession().unsubscribe(getClientName());
}
getConnection().close();
}
}
public void receiveAsyncTimeBasedMessages(long duration) throws JMSException {
if (getJmsConsumer() == null) {
createJmsConsumer();
}
getJmsConsumer().setMessageListener(new MessageListener() {
public void onMessage(Message msg) {
incThroughput();
}
});
try {
getConnection().start();
LOG.info("Starting to asynchronously receive messages for " + duration + " ms...");
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
throw new JMSException("JMS consumer thread sleep has been interrupted. Message: " + e.getMessage());
}
} finally {
if (client.isDurable() && client.isUnsubscribe()) {
LOG.info("Unsubscribing durable subscriber: " + getClientName());
getJmsConsumer().close();
getSession().unsubscribe(getClientName());
}
getConnection().close();
}
}
public void receiveAsyncCountBasedMessages(long count) throws JMSException {
if (getJmsConsumer() == null) {
createJmsConsumer();
}
final AtomicInteger recvCount = new AtomicInteger(0);
getJmsConsumer().setMessageListener(new MessageListener() {
public void onMessage(Message msg) {
incThroughput();
recvCount.incrementAndGet();
- recvCount.notify();
+ synchronized (recvCount) {
+ recvCount.notify();
+ }
}
});
try {
getConnection().start();
LOG.info("Starting to asynchronously receive " + client.getRecvCount() + " messages...");
try {
while (recvCount.get() < count) {
- recvCount.wait();
+ synchronized (recvCount) {
+ recvCount.wait();
+ }
}
} catch (InterruptedException e) {
throw new JMSException("JMS consumer thread wait has been interrupted. Message: " + e.getMessage());
}
} finally {
if (client.isDurable() && client.isUnsubscribe()) {
LOG.info("Unsubscribing durable subscriber: " + getClientName());
getJmsConsumer().close();
getSession().unsubscribe(getClientName());
}
getConnection().close();
}
}
public MessageConsumer createJmsConsumer() throws JMSException {
Destination[] dest = createDestination(destIndex, destCount);
return createJmsConsumer(dest[0]);
}
public MessageConsumer createJmsConsumer(Destination dest) throws JMSException {
if (client.isDurable()) {
String clientName = getClientName();
if (clientName == null) {
clientName = "JmsConsumer";
setClientName(clientName);
}
LOG.info("Creating durable subscriber (" + clientName + ") to: " + dest.toString());
jmsConsumer = getSession().createDurableSubscriber((Topic) dest, clientName);
} else {
LOG.info("Creating non-durable consumer to: " + dest.toString());
jmsConsumer = getSession().createConsumer(dest);
}
return jmsConsumer;
}
public MessageConsumer createJmsConsumer(Destination dest, String selector, boolean noLocal) throws JMSException {
if (client.isDurable()) {
String clientName = getClientName();
if (clientName == null) {
clientName = "JmsConsumer";
setClientName(clientName);
}
LOG.info("Creating durable subscriber (" + clientName + ") to: " + dest.toString());
jmsConsumer = getSession().createDurableSubscriber((Topic) dest, clientName, selector, noLocal);
} else {
LOG.info("Creating non-durable consumer to: " + dest.toString());
jmsConsumer = getSession().createConsumer(dest, selector, noLocal);
}
return jmsConsumer;
}
public MessageConsumer getJmsConsumer() {
return jmsConsumer;
}
public JmsClientProperties getClient() {
return client;
}
public void setClient(JmsClientProperties clientProps) {
client = (JmsConsumerProperties)clientProps;
}
}
| false | true | public void receiveAsyncCountBasedMessages(long count) throws JMSException {
if (getJmsConsumer() == null) {
createJmsConsumer();
}
final AtomicInteger recvCount = new AtomicInteger(0);
getJmsConsumer().setMessageListener(new MessageListener() {
public void onMessage(Message msg) {
incThroughput();
recvCount.incrementAndGet();
recvCount.notify();
}
});
try {
getConnection().start();
LOG.info("Starting to asynchronously receive " + client.getRecvCount() + " messages...");
try {
while (recvCount.get() < count) {
recvCount.wait();
}
} catch (InterruptedException e) {
throw new JMSException("JMS consumer thread wait has been interrupted. Message: " + e.getMessage());
}
} finally {
if (client.isDurable() && client.isUnsubscribe()) {
LOG.info("Unsubscribing durable subscriber: " + getClientName());
getJmsConsumer().close();
getSession().unsubscribe(getClientName());
}
getConnection().close();
}
}
| public void receiveAsyncCountBasedMessages(long count) throws JMSException {
if (getJmsConsumer() == null) {
createJmsConsumer();
}
final AtomicInteger recvCount = new AtomicInteger(0);
getJmsConsumer().setMessageListener(new MessageListener() {
public void onMessage(Message msg) {
incThroughput();
recvCount.incrementAndGet();
synchronized (recvCount) {
recvCount.notify();
}
}
});
try {
getConnection().start();
LOG.info("Starting to asynchronously receive " + client.getRecvCount() + " messages...");
try {
while (recvCount.get() < count) {
synchronized (recvCount) {
recvCount.wait();
}
}
} catch (InterruptedException e) {
throw new JMSException("JMS consumer thread wait has been interrupted. Message: " + e.getMessage());
}
} finally {
if (client.isDurable() && client.isUnsubscribe()) {
LOG.info("Unsubscribing durable subscriber: " + getClientName());
getJmsConsumer().close();
getSession().unsubscribe(getClientName());
}
getConnection().close();
}
}
|
diff --git a/src/main/java/net/pms/encoders/MEncoderVideo.java b/src/main/java/net/pms/encoders/MEncoderVideo.java
index bd36fe2c..09d9910c 100644
--- a/src/main/java/net/pms/encoders/MEncoderVideo.java
+++ b/src/main/java/net/pms/encoders/MEncoderVideo.java
@@ -1,2578 +1,2578 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* 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; version 2
* of the License only.
*
* 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 net.pms.encoders;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import net.pms.Messages;
import net.pms.PMS;
import net.pms.configuration.PmsConfiguration;
import net.pms.configuration.RendererConfiguration;
import net.pms.dlna.DLNAMediaAudio;
import net.pms.dlna.DLNAMediaInfo;
import net.pms.dlna.DLNAMediaSubtitle;
import net.pms.dlna.DLNAResource;
import net.pms.dlna.FileTranscodeVirtualFolder;
import net.pms.dlna.InputFile;
import net.pms.formats.Format;
import net.pms.io.OutputParams;
import net.pms.io.PipeIPCProcess;
import net.pms.io.PipeProcess;
import net.pms.io.ProcessWrapper;
import net.pms.io.ProcessWrapperImpl;
import net.pms.io.StreamModifier;
import net.pms.network.HTTPResource;
import net.pms.newgui.FontFileFilter;
import net.pms.newgui.LooksFrame;
import net.pms.newgui.MyComboBoxModel;
import net.pms.newgui.RestrictedFileSystemView;
import net.pms.util.CodecUtil;
import net.pms.util.FormLayoutUtil;
import net.pms.util.ProcessUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bsh.EvalError;
import bsh.Interpreter;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.Borders;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.sun.jna.Platform;
public class MEncoderVideo extends Player {
private static final Logger LOGGER = LoggerFactory.getLogger(MEncoderVideo.class);
private static final String COL_SPEC = "left:pref, 3dlu, p:grow, 3dlu, right:p:grow, 3dlu, p:grow, 3dlu, right:p:grow,3dlu, p:grow, 3dlu, right:p:grow,3dlu, pref:grow";
private static final String ROW_SPEC = "p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu,p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 9dlu, p, 2dlu, p, 2dlu, p , 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p";
private JTextField mencoder_ass_scale;
private JTextField mencoder_ass_margin;
private JTextField mencoder_ass_outline;
private JTextField mencoder_ass_shadow;
private JTextField mencoder_noass_scale;
private JTextField mencoder_noass_subpos;
private JTextField mencoder_noass_blur;
private JTextField mencoder_noass_outline;
private JTextField mencoder_custom_options;
private JTextField langs;
private JTextField defaultsubs;
private JTextField forcedsub;
private JTextField forcedtags;
private JTextField defaultaudiosubs;
private JTextField defaultfont;
private JComboBox subcp;
private JTextField subq;
private JCheckBox forcefps;
private JCheckBox yadif;
private JCheckBox scaler;
private JTextField scaleX;
private JTextField scaleY;
private JCheckBox assdefaultstyle;
private JCheckBox fc;
private JCheckBox ass;
private JCheckBox checkBox;
private JCheckBox mencodermt;
private JCheckBox videoremux;
private JCheckBox noskip;
private JCheckBox intelligentsync;
private JTextField alternateSubFolder;
private JButton subColor;
private JTextField ocw;
private JTextField och;
private JCheckBox subs;
private JCheckBox fribidi;
private final PmsConfiguration configuration;
private static final String[] INVALID_CUSTOM_OPTIONS = {
"-of",
"-oac",
"-ovc",
"-mpegopts"
};
private static final String INVALID_CUSTOM_OPTIONS_LIST = Arrays.toString(INVALID_CUSTOM_OPTIONS);
public static final int MENCODER_MAX_THREADS = 8;
public static final String ID = "mencoder";
// TODO (breaking change): most (probably all) of these
// protected fields should be private. And at least two
// shouldn't be fields
@Deprecated
protected boolean dvd;
@Deprecated
protected String overriddenMainArgs[];
protected boolean dts;
protected boolean pcm;
protected boolean mux;
protected boolean ovccopy;
protected boolean oaccopy;
protected boolean mpegts;
protected boolean wmv;
public static final String DEFAULT_CODEC_CONF_SCRIPT =
Messages.getString("MEncoderVideo.68")
+ Messages.getString("MEncoderVideo.69")
+ Messages.getString("MEncoderVideo.70")
+ Messages.getString("MEncoderVideo.71")
+ Messages.getString("MEncoderVideo.72")
+ Messages.getString("MEncoderVideo.73")
+ Messages.getString("MEncoderVideo.75")
+ Messages.getString("MEncoderVideo.76")
+ Messages.getString("MEncoderVideo.77")
+ Messages.getString("MEncoderVideo.78")
+ Messages.getString("MEncoderVideo.79")
+ "#\n"
+ Messages.getString("MEncoderVideo.80")
+ "container == iso :: -nosync\n"
+ "(container == avi || container == matroska) && vcodec == mpeg4 && acodec == mp3 :: -mc 0.1\n"
+ "container == flv :: -mc 0.1\n"
+ "container == mov :: -mc 0.1\n"
+ "container == rm :: -mc 0.1\n"
+ "container == matroska && framerate == 29.97 :: -nomux -mc 0\n"
+ "container == mp4 && vcodec == h264 :: -mc 0.1\n"
+ "\n"
+ Messages.getString("MEncoderVideo.87")
+ Messages.getString("MEncoderVideo.88")
+ Messages.getString("MEncoderVideo.89")
+ Messages.getString("MEncoderVideo.91");
public JCheckBox getCheckBox() {
return checkBox;
}
public JCheckBox getNoskip() {
return noskip;
}
public JCheckBox getSubs() {
return subs;
}
public MEncoderVideo(PmsConfiguration configuration) {
this.configuration = configuration;
}
@Override
public JComponent config() {
// Apply the orientation for the locale
Locale locale = new Locale(configuration.getLanguage());
ComponentOrientation orientation = ComponentOrientation.getOrientation(locale);
String colSpec = FormLayoutUtil.getColSpec(COL_SPEC, orientation);
FormLayout layout = new FormLayout(colSpec, ROW_SPEC);
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.EMPTY_BORDER);
builder.setOpaque(false);
CellConstraints cc = new CellConstraints();
checkBox = new JCheckBox(Messages.getString("MEncoderVideo.0"));
checkBox.setContentAreaFilled(false);
if (configuration.getSkipLoopFilterEnabled()) {
checkBox.setSelected(true);
}
checkBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setSkipLoopFilterEnabled((e.getStateChange() == ItemEvent.SELECTED));
}
});
JComponent cmp = builder.addSeparator(Messages.getString("MEncoderVideo.1"), FormLayoutUtil.flip(cc.xyw(1, 1, 15), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
mencodermt = new JCheckBox(Messages.getString("MEncoderVideo.35"));
mencodermt.setContentAreaFilled(false);
if (configuration.getMencoderMT()) {
mencodermt.setSelected(true);
}
mencodermt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configuration.setMencoderMT(mencodermt.isSelected());
}
});
mencodermt.setEnabled(Platform.isWindows() || Platform.isMac());
builder.add(mencodermt, FormLayoutUtil.flip(cc.xy(1, 3), colSpec, orientation));
builder.add(checkBox, FormLayoutUtil.flip(cc.xyw(3, 3, 12), colSpec, orientation));
noskip = new JCheckBox(Messages.getString("MEncoderVideo.2"));
noskip.setContentAreaFilled(false);
if (configuration.isMencoderNoOutOfSync()) {
noskip.setSelected(true);
}
noskip.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderNoOutOfSync((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(noskip, FormLayoutUtil.flip(cc.xy(1, 5), colSpec, orientation));
JButton button = new JButton(Messages.getString("MEncoderVideo.29"));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPanel codecPanel = new JPanel(new BorderLayout());
final JTextArea textArea = new JTextArea();
textArea.setText(configuration.getCodecSpecificConfig());
textArea.setFont(new Font("Courier", Font.PLAIN, 12));
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new java.awt.Dimension(900, 100));
final JTextArea textAreaDefault = new JTextArea();
textAreaDefault.setText(DEFAULT_CODEC_CONF_SCRIPT);
textAreaDefault.setBackground(Color.WHITE);
textAreaDefault.setFont(new Font("Courier", Font.PLAIN, 12));
textAreaDefault.setEditable(false);
textAreaDefault.setEnabled(configuration.isMencoderIntelligentSync());
JScrollPane scrollPaneDefault = new JScrollPane(textAreaDefault);
scrollPaneDefault.setPreferredSize(new java.awt.Dimension(900, 450));
JPanel customPanel = new JPanel(new BorderLayout());
intelligentsync = new JCheckBox(Messages.getString("MEncoderVideo.3"));
intelligentsync.setContentAreaFilled(false);
if (configuration.isMencoderIntelligentSync()) {
intelligentsync.setSelected(true);
}
intelligentsync.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderIntelligentSync((e.getStateChange() == ItemEvent.SELECTED));
textAreaDefault.setEnabled(configuration.isMencoderIntelligentSync());
}
});
JLabel label = new JLabel(Messages.getString("MEncoderVideo.33"));
customPanel.add(label, BorderLayout.NORTH);
customPanel.add(scrollPane, BorderLayout.SOUTH);
codecPanel.add(intelligentsync, BorderLayout.NORTH);
codecPanel.add(scrollPaneDefault, BorderLayout.CENTER);
codecPanel.add(customPanel, BorderLayout.SOUTH);
while (JOptionPane.showOptionDialog((JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
codecPanel, Messages.getString("MEncoderVideo.34"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null) == JOptionPane.OK_OPTION) {
String newCodecparam = textArea.getText();
DLNAMediaInfo fakemedia = new DLNAMediaInfo();
DLNAMediaAudio audio = new DLNAMediaAudio();
audio.setCodecA("ac3");
fakemedia.setCodecV("mpeg4");
fakemedia.setContainer("matroska");
fakemedia.setDuration(45d*60);
audio.setNrAudioChannels(2);
fakemedia.setWidth(1280);
fakemedia.setHeight(720);
audio.setSampleFrequency("48000");
fakemedia.setFrameRate("23.976");
fakemedia.getAudioCodes().add(audio);
String result[] = getSpecificCodecOptions(newCodecparam, fakemedia, new OutputParams(configuration), "dummy.mpg", "dummy.srt", false, true);
if (result.length > 0 && result[0].startsWith("@@")) {
String errorMessage = result[0].substring(2);
JOptionPane.showMessageDialog((JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())), errorMessage);
} else {
configuration.setCodecSpecificConfig(newCodecparam);
break;
}
}
}
});
builder.add(button, FormLayoutUtil.flip(cc.xyw(1, 11, 2), colSpec, orientation));
forcefps = new JCheckBox(Messages.getString("MEncoderVideo.4"));
forcefps.setContentAreaFilled(false);
if (configuration.isMencoderForceFps()) {
forcefps.setSelected(true);
}
forcefps.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderForceFps(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(forcefps, FormLayoutUtil.flip(cc.xyw(1, 7, 2), colSpec, orientation));
yadif = new JCheckBox(Messages.getString("MEncoderVideo.26"));
yadif.setContentAreaFilled(false);
if (configuration.isMencoderYadif()) {
yadif.setSelected(true);
}
yadif.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderYadif(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(yadif, FormLayoutUtil.flip(cc.xyw(3, 7, 7), colSpec, orientation));
scaler = new JCheckBox(Messages.getString("MEncoderVideo.27"));
scaler.setContentAreaFilled(false);
scaler.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderScaler(e.getStateChange() == ItemEvent.SELECTED);
scaleX.setEnabled(configuration.isMencoderScaler());
scaleY.setEnabled(configuration.isMencoderScaler());
}
});
builder.add(scaler, FormLayoutUtil.flip(cc.xyw(3, 5, 7), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.28"), FormLayoutUtil.flip(cc.xyw(10, 5, 3, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
scaleX = new JTextField("" + configuration.getMencoderScaleX());
scaleX.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
try {
configuration.setMencoderScaleX(Integer.parseInt(scaleX.getText()));
} catch (NumberFormatException nfe) {
LOGGER.debug("Could not parse scaleX from \"" + scaleX.getText() + "\"");
}
}
});
builder.add(scaleX, FormLayoutUtil.flip(cc.xyw(13, 5, 3), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.30"), FormLayoutUtil.flip(cc.xyw(10, 7, 3, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
scaleY = new JTextField("" + configuration.getMencoderScaleY());
scaleY.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
try {
configuration.setMencoderScaleY(Integer.parseInt(scaleY.getText()));
} catch (NumberFormatException nfe) {
LOGGER.debug("Could not parse scaleY from \"" + scaleY.getText() + "\"");
}
}
});
builder.add(scaleY, FormLayoutUtil.flip(cc.xyw(13, 7, 3), colSpec, orientation));
if (configuration.isMencoderScaler()) {
scaler.setSelected(true);
} else {
scaleX.setEnabled(false);
scaleY.setEnabled(false);
}
videoremux = new JCheckBox("<html>" + Messages.getString("MEncoderVideo.38") + "</html>");
videoremux.setContentAreaFilled(false);
if (configuration.isMencoderMuxWhenCompatible()) {
videoremux.setSelected(true);
}
videoremux.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderMuxWhenCompatible((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(videoremux, FormLayoutUtil.flip(cc.xyw(1, 9, 13), colSpec, orientation));
cmp = builder.addSeparator(Messages.getString("MEncoderVideo.5"), FormLayoutUtil.flip(cc.xyw(1, 19, 15), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.addLabel(Messages.getString("MEncoderVideo.6"), FormLayoutUtil.flip(cc.xy(1, 21), colSpec, orientation));
mencoder_custom_options = new JTextField(configuration.getMencoderCustomOptions());
mencoder_custom_options.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderCustomOptions(mencoder_custom_options.getText());
}
});
builder.add(mencoder_custom_options, FormLayoutUtil.flip(cc.xyw(3, 21, 13), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.7"), FormLayoutUtil.flip(cc.xyw(1, 23, 15), colSpec, orientation));
langs = new JTextField(configuration.getMencoderAudioLanguages());
langs.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAudioLanguages(langs.getText());
}
});
builder.add(langs, FormLayoutUtil.flip(cc.xyw(3, 23, 8), colSpec, orientation));
cmp = builder.addSeparator(Messages.getString("MEncoderVideo.8"), FormLayoutUtil.flip(cc.xyw(1, 25, 15), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.addLabel(Messages.getString("MEncoderVideo.9"), FormLayoutUtil.flip(cc.xy(1, 27), colSpec, orientation));
defaultsubs = new JTextField(configuration.getMencoderSubLanguages());
defaultsubs.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderSubLanguages(defaultsubs.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.94"), FormLayoutUtil.flip(cc.xy(5, 27), colSpec, orientation));
forcedsub = new JTextField(configuration.getMencoderForcedSubLanguage());
forcedsub.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderForcedSubLanguage(forcedsub.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.95"), FormLayoutUtil.flip(cc.xy(9, 27), colSpec, orientation));
forcedtags = new JTextField(configuration.getMencoderForcedSubTags());
forcedtags.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderForcedSubTags(forcedtags.getText());
}
});
builder.add(defaultsubs, FormLayoutUtil.flip(cc.xyw(3, 27, 2), colSpec, orientation));
builder.add(forcedsub, FormLayoutUtil.flip(cc.xy(7, 27), colSpec, orientation));
builder.add(forcedtags, FormLayoutUtil.flip(cc.xyw(11, 27, 5), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.10"), FormLayoutUtil.flip(cc.xy(1, 29), colSpec, orientation));
defaultaudiosubs = new JTextField(configuration.getMencoderAudioSubLanguages());
defaultaudiosubs.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAudioSubLanguages(defaultaudiosubs.getText());
}
});
builder.add(defaultaudiosubs, FormLayoutUtil.flip(cc.xyw(3, 29, 8), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.11"), FormLayoutUtil.flip(cc.xy(1, 31), colSpec, orientation));
Object data[] = new Object[]{
configuration.getMencoderSubCp(),
Messages.getString("MEncoderVideo.96"),
Messages.getString("MEncoderVideo.97"),
Messages.getString("MEncoderVideo.98"),
Messages.getString("MEncoderVideo.99"),
Messages.getString("MEncoderVideo.100"),
Messages.getString("MEncoderVideo.101"),
Messages.getString("MEncoderVideo.102"),
Messages.getString("MEncoderVideo.103"),
Messages.getString("MEncoderVideo.104"),
Messages.getString("MEncoderVideo.105"),
Messages.getString("MEncoderVideo.106"),
Messages.getString("MEncoderVideo.107"),
Messages.getString("MEncoderVideo.108"),
Messages.getString("MEncoderVideo.109"),
Messages.getString("MEncoderVideo.110"),
Messages.getString("MEncoderVideo.111"),
Messages.getString("MEncoderVideo.112"),
Messages.getString("MEncoderVideo.113"),
Messages.getString("MEncoderVideo.114"),
Messages.getString("MEncoderVideo.115"),
Messages.getString("MEncoderVideo.116"),
Messages.getString("MEncoderVideo.117"),
Messages.getString("MEncoderVideo.118"),
Messages.getString("MEncoderVideo.119"),
Messages.getString("MEncoderVideo.120"),
Messages.getString("MEncoderVideo.121"),
Messages.getString("MEncoderVideo.122"),
Messages.getString("MEncoderVideo.123"),
Messages.getString("MEncoderVideo.124")
};
MyComboBoxModel cbm = new MyComboBoxModel(data);
subcp = new JComboBox(cbm);
subcp.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String s = (String) e.getItem();
int offset = s.indexOf("/*");
if (offset > -1) {
s = s.substring(0, offset).trim();
}
configuration.setMencoderSubCp(s);
}
}
});
subcp.setEditable(true);
builder.add(subcp, FormLayoutUtil.flip(cc.xyw(3, 31, 7), colSpec, orientation));
fribidi = new JCheckBox(Messages.getString("MEncoderVideo.23"));
fribidi.setContentAreaFilled(false);
if (configuration.isMencoderSubFribidi()) {
fribidi.setSelected(true);
}
fribidi.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderSubFribidi(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(fribidi, FormLayoutUtil.flip(cc.xyw(11, 31, 4), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.24"), FormLayoutUtil.flip(cc.xy(1, 33), colSpec, orientation));
defaultfont = new JTextField(configuration.getMencoderFont());
defaultfont.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderFont(defaultfont.getText());
}
});
builder.add(defaultfont, FormLayoutUtil.flip(cc.xyw(3, 33, 8), colSpec, orientation));
JButton fontselect = new JButton("...");
fontselect.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FontFileFilter());
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("MEncoderVideo.25"));
if (returnVal == JFileChooser.APPROVE_OPTION) {
defaultfont.setText(chooser.getSelectedFile().getAbsolutePath());
configuration.setMencoderFont(chooser.getSelectedFile().getAbsolutePath());
}
}
});
builder.add(fontselect, FormLayoutUtil.flip(cc.xyw(11, 33, 2), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.37"), FormLayoutUtil.flip(cc.xyw(1, 35, 3), colSpec, orientation));
alternateSubFolder = new JTextField(configuration.getAlternateSubsFolder());
alternateSubFolder.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setAlternateSubsFolder(alternateSubFolder.getText());
}
});
builder.add(alternateSubFolder, FormLayoutUtil.flip(cc.xyw(3, 35, 8), colSpec, orientation));
JButton select = new JButton("...");
select.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = null;
try {
chooser = new JFileChooser();
} catch (Exception ee) {
chooser = new JFileChooser(new RestrictedFileSystemView());
}
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.28"));
if (returnVal == JFileChooser.APPROVE_OPTION) {
alternateSubFolder.setText(chooser.getSelectedFile().getAbsolutePath());
configuration.setAlternateSubsFolder(chooser.getSelectedFile().getAbsolutePath());
}
}
});
builder.add(select, FormLayoutUtil.flip(cc.xyw(11, 35, 2), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.12"), FormLayoutUtil.flip(cc.xy(1, 39, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
mencoder_ass_scale = new JTextField(configuration.getMencoderAssScale());
mencoder_ass_scale.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAssScale(mencoder_ass_scale.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.13"), FormLayoutUtil.flip(cc.xy(5, 39), colSpec, orientation));
mencoder_ass_outline = new JTextField(configuration.getMencoderAssOutline());
mencoder_ass_outline.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAssOutline(mencoder_ass_outline.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.14"), FormLayoutUtil.flip(cc.xy(9, 39), colSpec, orientation));
mencoder_ass_shadow = new JTextField(configuration.getMencoderAssShadow());
mencoder_ass_shadow.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAssShadow(mencoder_ass_shadow.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.15"), FormLayoutUtil.flip(cc.xy(13, 39), colSpec, orientation));
mencoder_ass_margin = new JTextField(configuration.getMencoderAssMargin());
mencoder_ass_margin.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAssMargin(mencoder_ass_margin.getText());
}
});
builder.add(mencoder_ass_scale, FormLayoutUtil.flip(cc.xy(3, 39), colSpec, orientation));
builder.add(mencoder_ass_outline, FormLayoutUtil.flip(cc.xy(7, 39), colSpec, orientation));
builder.add(mencoder_ass_shadow, FormLayoutUtil.flip(cc.xy(11, 39), colSpec, orientation));
builder.add(mencoder_ass_margin, FormLayoutUtil.flip(cc.xy(15, 39), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.16"), FormLayoutUtil.flip(cc.xy(1, 41, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
mencoder_noass_scale = new JTextField(configuration.getMencoderNoAssScale());
mencoder_noass_scale.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderNoAssScale(mencoder_noass_scale.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.17"), FormLayoutUtil.flip(cc.xy(5, 41), colSpec, orientation));
mencoder_noass_outline = new JTextField(configuration.getMencoderNoAssOutline());
mencoder_noass_outline.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderNoAssOutline(mencoder_noass_outline.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.18"), FormLayoutUtil.flip(cc.xy(9, 41), colSpec, orientation));
mencoder_noass_blur = new JTextField(configuration.getMencoderNoAssBlur());
mencoder_noass_blur.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderNoAssBlur(mencoder_noass_blur.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.19"), FormLayoutUtil.flip(cc.xy(13, 41), colSpec, orientation));
mencoder_noass_subpos = new JTextField(configuration.getMencoderNoAssSubPos());
mencoder_noass_subpos.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderNoAssSubPos(mencoder_noass_subpos.getText());
}
});
builder.add(mencoder_noass_scale, FormLayoutUtil.flip(cc.xy(3, 41), colSpec, orientation));
builder.add(mencoder_noass_outline, FormLayoutUtil.flip(cc.xy(7, 41), colSpec, orientation));
builder.add(mencoder_noass_blur, FormLayoutUtil.flip(cc.xy(11, 41), colSpec, orientation));
builder.add(mencoder_noass_subpos, FormLayoutUtil.flip(cc.xy(15, 41), colSpec, orientation));
ass = new JCheckBox(Messages.getString("MEncoderVideo.20"));
ass.setContentAreaFilled(false);
ass.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e != null) {
configuration.setMencoderAss(e.getStateChange() == ItemEvent.SELECTED);
}
}
});
builder.add(ass, FormLayoutUtil.flip(cc.xy(1, 37), colSpec, orientation));
ass.setSelected(configuration.isMencoderAss());
ass.getItemListeners()[0].itemStateChanged(null);
fc = new JCheckBox(Messages.getString("MEncoderVideo.21"));
fc.setContentAreaFilled(false);
fc.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderFontConfig(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(fc, FormLayoutUtil.flip(cc.xyw(3, 37, 5), colSpec, orientation));
fc.setSelected(configuration.isMencoderFontConfig());
assdefaultstyle = new JCheckBox(Messages.getString("MEncoderVideo.36"));
assdefaultstyle.setContentAreaFilled(false);
assdefaultstyle.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderAssDefaultStyle(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(assdefaultstyle, FormLayoutUtil.flip(cc.xyw(8, 37, 4), colSpec, orientation));
assdefaultstyle.setSelected(configuration.isMencoderAssDefaultStyle());
subs = new JCheckBox(Messages.getString("MEncoderVideo.22"));
subs.setContentAreaFilled(false);
if (configuration.getUseSubtitles()) {
subs.setSelected(true);
}
subs.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setUseSubtitles((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(subs, FormLayoutUtil.flip(cc.xyw(1, 43, 15), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.92"), FormLayoutUtil.flip(cc.xy(1, 45), colSpec, orientation));
subq = new JTextField(configuration.getMencoderVobsubSubtitleQuality());
subq.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderVobsubSubtitleQuality(subq.getText());
}
});
builder.add(subq, FormLayoutUtil.flip(cc.xyw(3, 45, 1), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.93"), FormLayoutUtil.flip(cc.xyw(1, 47, 6), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.28") + "% ", FormLayoutUtil.flip(cc.xy(1, 49, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
ocw = new JTextField(configuration.getMencoderOverscanCompensationWidth());
ocw.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderOverscanCompensationWidth(ocw.getText());
}
});
builder.add(ocw, FormLayoutUtil.flip(cc.xyw(3, 49, 1), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.30") + "% ", FormLayoutUtil.flip(cc.xy(5, 49), colSpec, orientation));
och = new JTextField(configuration.getMencoderOverscanCompensationHeight());
och.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderOverscanCompensationHeight(och.getText());
}
});
builder.add(och, FormLayoutUtil.flip(cc.xyw(7, 49, 1), colSpec, orientation));
subColor = new JButton();
subColor.setText(Messages.getString("MEncoderVideo.31"));
subColor.setBackground(new Color(configuration.getSubsColor()));
subColor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Color newColor = JColorChooser.showDialog(
(JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("MEncoderVideo.125"),
subColor.getBackground()
);
if (newColor != null) {
subColor.setBackground(newColor);
configuration.setSubsColor(newColor.getRGB());
}
}
});
builder.add(subColor, FormLayoutUtil.flip(cc.xyw(12, 37, 4), colSpec, orientation));
JCheckBox disableSubs = ((LooksFrame) PMS.get().getFrame()).getTr().getDisableSubs();
disableSubs.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderDisableSubs(e.getStateChange() == ItemEvent.SELECTED);
subs.setEnabled(!configuration.isMencoderDisableSubs());
subq.setEnabled(!configuration.isMencoderDisableSubs());
defaultsubs.setEnabled(!configuration.isMencoderDisableSubs());
subcp.setEnabled(!configuration.isMencoderDisableSubs());
ass.setEnabled(!configuration.isMencoderDisableSubs());
assdefaultstyle.setEnabled(!configuration.isMencoderDisableSubs());
fribidi.setEnabled(!configuration.isMencoderDisableSubs());
fc.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_ass_scale.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_ass_outline.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_ass_shadow.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_ass_margin.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_noass_scale.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_noass_outline.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_noass_blur.setEnabled(!configuration.isMencoderDisableSubs());
mencoder_noass_subpos.setEnabled(!configuration.isMencoderDisableSubs());
if (!configuration.isMencoderDisableSubs()) {
ass.getItemListeners()[0].itemStateChanged(null);
}
}
});
if (configuration.isMencoderDisableSubs()) {
disableSubs.setSelected(true);
}
JPanel panel = builder.getPanel();
// Apply the orientation to the panel and all components in it
panel.applyComponentOrientation(orientation);
return panel;
}
@Override
public int purpose() {
return VIDEO_SIMPLEFILE_PLAYER;
}
@Override
public String id() {
return ID;
}
@Override
public boolean avisynth() {
return false;
}
@Override
public boolean isTimeSeekable() {
return true;
}
protected String[] getDefaultArgs() {
return new String[]{
"-quiet",
"-oac", oaccopy ? "copy" : (pcm ? "pcm" : "lavc"),
"-of", (wmv || mpegts) ? "lavf" : (pcm && avisynth()) ? "avi" : (((pcm || dts || mux) ? "rawvideo" : "mpeg")),
(wmv || mpegts) ? "-lavfopts" : "-quiet",
wmv ? "format=asf" : (mpegts ? "format=mpegts" : "-quiet"),
"-mpegopts", "format=mpeg2:muxrate=500000:vbuf_size=1194:abuf_size=64",
"-ovc", (mux || ovccopy) ? "copy" : "lavc"
};
}
private String[] sanitizeArgs(String[] args) {
List<String> sanitized = new ArrayList<String>();
int i = 0;
while (i < args.length) {
String name = args[i];
String value = null;
for (String option : INVALID_CUSTOM_OPTIONS) {
if (option.equals(name)) {
if ((i + 1) < args.length) {
value = " " + args[i + 1];
++i;
} else {
value = "";
}
LOGGER.warn(
"Ignoring custom MEncoder option: {}{}; the following options cannot be changed: " + INVALID_CUSTOM_OPTIONS_LIST,
name,
value
);
break;
}
}
if (value == null) {
sanitized.add(args[i]);
}
++i;
}
return sanitized.toArray(new String[sanitized.size()]);
}
@Override
public String[] args() {
String args[] = null;
String defaultArgs[] = getDefaultArgs();
if (overriddenMainArgs != null) {
// add the sanitized custom MEncoder options.
// not cached because they may be changed on the fly in the GUI
// TODO if/when we upgrade to org.apache.commons.lang3:
// args = ArrayUtils.addAll(defaultArgs, sanitizeArgs(overriddenMainArgs))
String[] sanitizedCustomArgs = sanitizeArgs(overriddenMainArgs);
args = new String[defaultArgs.length + sanitizedCustomArgs.length];
System.arraycopy(defaultArgs, 0, args, 0, defaultArgs.length);
System.arraycopy(sanitizedCustomArgs, 0, args, defaultArgs.length, sanitizedCustomArgs.length);
} else {
args = defaultArgs;
}
return args;
}
@Override
public String executable() {
return configuration.getMencoderPath();
}
private int[] getVideoBitrateConfig(String bitrate) {
int bitrates[] = new int[2];
if (bitrate.contains("(") && bitrate.contains(")")) {
bitrates[1] = Integer.parseInt(bitrate.substring(bitrate.indexOf("(") + 1, bitrate.indexOf(")")));
}
if (bitrate.contains("(")) {
bitrate = bitrate.substring(0, bitrate.indexOf("(")).trim();
}
if (StringUtils.isBlank(bitrate)) {
bitrate = "0";
}
bitrates[0] = (int) Double.parseDouble(bitrate);
return bitrates;
}
/**
* Note: This is not exact, the bitrate can go above this but it is generally pretty good.
* @return The maximum bitrate the video should be along with the buffer size using MEncoder vars
*/
private String addMaximumBitrateConstraints(String encodeSettings, DLNAMediaInfo media, String quality, RendererConfiguration mediaRenderer, String audioType) {
int defaultMaxBitrates[] = getVideoBitrateConfig(configuration.getMaximumBitrate());
int rendererMaxBitrates[] = new int[2];
if (mediaRenderer.getMaxVideoBitrate() != null) {
rendererMaxBitrates = getVideoBitrateConfig(mediaRenderer.getMaxVideoBitrate());
}
if ((defaultMaxBitrates[0] == 0 && rendererMaxBitrates[0] > 0) || rendererMaxBitrates[0] < defaultMaxBitrates[0] && rendererMaxBitrates[0] > 0) {
defaultMaxBitrates = rendererMaxBitrates;
}
if (mediaRenderer.getCBRVideoBitrate() == 0 && defaultMaxBitrates[0] > 0 && !quality.contains("vrc_buf_size") && !quality.contains("vrc_maxrate") && !quality.contains("vbitrate")) {
// Convert value from Mb to Kb
defaultMaxBitrates[0] = 1000 * defaultMaxBitrates[0];
// Halve it since it seems to send up to 1 second of video in advance
defaultMaxBitrates[0] = defaultMaxBitrates[0] / 2;
int bufSize = 1835;
if (media.isHDVideo()) {
bufSize = defaultMaxBitrates[0] / 3;
}
if (bufSize > 7000) {
bufSize = 7000;
}
if (defaultMaxBitrates[1] > 0) {
bufSize = defaultMaxBitrates[1];
}
if (mediaRenderer.isDefaultVBVSize() && rendererMaxBitrates[1] == 0) {
bufSize = 1835;
}
// Make room for audio
// If audio is PCM, subtract 4600kb/s
if ("pcm".equals(audioType)) {
defaultMaxBitrates[0] = defaultMaxBitrates[0] - 4600;
}
// If audio is DTS, subtract 1510kb/s
else if ("dts".equals(audioType)) {
defaultMaxBitrates[0] = defaultMaxBitrates[0] - 1510;
}
// If audio is AC3, subtract 640kb/s to be safe
else if ("ac3".equals(audioType)) {
defaultMaxBitrates[0] = defaultMaxBitrates[0] - 640;
}
// Round down to the nearest Mb
defaultMaxBitrates[0] = defaultMaxBitrates[0] / 1000 * 1000;
encodeSettings += ":vrc_maxrate=" + defaultMaxBitrates[0] + ":vrc_buf_size=" + bufSize;
}
return encodeSettings;
}
@Override
public ProcessWrapper launchTranscode(
String fileName,
DLNAResource dlna,
DLNAMediaInfo media,
OutputParams params
) throws IOException {
params.manageFastStart();
boolean avisynth = avisynth();
setAudioAndSubs(fileName, media, params, configuration);
String subString = null;
if (params.sid != null && params.sid.getPlayableFile() != null) {
subString = ProcessUtil.getShortFileNameIfWideChars(params.sid.getPlayableFile().getAbsolutePath());
}
InputFile newInput = new InputFile();
newInput.setFilename(fileName);
newInput.setPush(params.stdin);
dvd = false;
if (media != null && media.getDvdtrack() > 0) {
dvd = true;
}
// don't honour "Switch to tsMuxeR..." if the resource is being streamed via an MEncoder entry in
// the #--TRANSCODE--# folder
boolean forceMencoder = !configuration.getHideTranscodeEnabled()
&& dlna.isNoName() // XXX remove this? http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12149
&& (dlna.getParent() instanceof FileTranscodeVirtualFolder);
ovccopy = false;
int intOCW = 0;
int intOCH = 0;
try {
intOCW = Integer.parseInt(configuration.getMencoderOverscanCompensationWidth());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation width: \"{}\"", configuration.getMencoderOverscanCompensationWidth());
}
try {
intOCH = Integer.parseInt(configuration.getMencoderOverscanCompensationHeight());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation height: \"{}\"", configuration.getMencoderOverscanCompensationHeight());
}
if (
!forceMencoder &&
params.sid == null &&
!dvd &&
!avisynth() &&
media != null && (
media.isVideoPS3Compatible(newInput) ||
!params.mediaRenderer.isH264Level41Limited()
) &&
media.isMuxable(params.mediaRenderer) &&
configuration.isMencoderMuxWhenCompatible() &&
params.mediaRenderer.isMuxH264MpegTS() && (
intOCW == 0 &&
intOCH == 0
)
) {
String sArgs[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
subString,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : sArgs) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
TSMuxerVideo tv = new TSMuxerVideo(configuration);
params.forceFps = media.getValidFps(false);
if (media.getCodecV().equals("h264")) {
params.forceType = "V_MPEG4/ISO/AVC";
} else if (media.getCodecV().startsWith("mpeg2")) {
params.forceType = "V_MPEG-2";
} else if (media.getCodecV().equals("vc1")) {
params.forceType = "V_MS/VFW/WVC1";
}
return tv.launchTranscode(fileName, dlna, media, params);
}
} else if (params.sid == null && dvd && configuration.isMencoderRemuxMPEG2() && params.mediaRenderer.isMpeg2Supported()) {
String sArgs[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
subString,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : sArgs) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
ovccopy = true;
}
}
String vcodec = "mpeg2video";
wmv = false;
if (params.mediaRenderer.isTranscodeToWMV()) {
wmv = true;
vcodec = "wmv2"; // http://wiki.megaframe.org/wiki/Ubuntu_XBOX_360#MEncoder not usable in streaming
}
mpegts = false;
if (params.mediaRenderer.isTranscodeToMPEGTSAC3()) {
mpegts = true;
}
oaccopy = false;
// disable AC3 remux for stereo tracks with 384 kbits bitrate and PS3 renderer (PS3 FW bug?)
- boolean ps3_and_stereo_and_384_kbits = (params.mediaRenderer.getRendererName().equalsIgnoreCase("Playstation 3") && params.aid.getNrAudioChannels() == 2) && (params.aid.getBitRate() > 370000 && params.aid.getBitRate() < 400000);
+ boolean ps3_and_stereo_and_384_kbits = params.aid != null && (params.mediaRenderer.getRendererName().equalsIgnoreCase("Playstation 3") && params.aid.getNrAudioChannels() == 2) && (params.aid.getBitRate() > 370000 && params.aid.getBitRate() < 400000);
if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && !ps3_and_stereo_and_384_kbits && !avisynth() && params.mediaRenderer.isTranscodeToAC3()) {
// AC3 remux takes priority
oaccopy = true;
} else {
// now check for DTS remux and LPCM streaming
dts = configuration.isDTSEmbedInPCM() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
) && params.aid != null &&
params.aid.isDTS() &&
!avisynth() &&
params.mediaRenderer.isDTSPlayable();
pcm = configuration.isMencoderUsePcm() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
)
// disable LPCM transcoding for MP4 container with non-H264 video as workaround for mencoder's A/V sync bug
&& !(media.getContainer().equals("mp4") && !media.getCodecV().equals("h264"))
&& params.aid != null &&
(
(params.aid.isDTS() && params.aid.getNrAudioChannels() <= 6) || // disable 7.1 DTS-HD => LPCM because of channels mapping bug
params.aid.isLossless() ||
params.aid.isTrueHD() ||
(
!configuration.isMencoderUsePcmForHQAudioOnly() &&
(
params.aid.isAC3() ||
params.aid.isMP3() ||
params.aid.isAAC() ||
params.aid.isVorbis() ||
// disable WMA to LPCM transcoding because of mencoder's channel mapping bug
// (see CodecUtil.getMixerOutput)
// params.aid.isWMA() ||
params.aid.isMpegAudio()
)
)
) && params.mediaRenderer.isLPCMPlayable();
}
if (dts || pcm) {
if (dts) {
oaccopy = true;
}
params.losslessaudio = true;
params.forceFps = media.getValidFps(false);
}
// mpeg2 remux still buggy with mencoder :\
if (!pcm && !dts && !mux && ovccopy) {
ovccopy = false;
}
if (pcm && avisynth()) {
params.avidemux = true;
}
String add = "";
String rendererMencoderOptions = params.mediaRenderer.getCustomMencoderOptions(); // default: empty string
String mencoderCustomOptions = configuration.getMencoderCustomOptions(); // default: empty string
String combinedCustomOptions = StringUtils.defaultString(mencoderCustomOptions)
+ " "
+ StringUtils.defaultString(rendererMencoderOptions);
if (!combinedCustomOptions.contains("-lavdopts")) {
add = " -lavdopts debug=0";
}
int channels = wmv ? 2 : configuration.getAudioChannelCount();
if (media != null && params.aid != null) {
channels = wmv ? 2 : CodecUtil.getRealChannelCount(configuration, params.aid);
}
LOGGER.trace("channels=" + channels);
if (StringUtils.isNotBlank(rendererMencoderOptions)) {
/*
* ignore the renderer's custom MEncoder options if a) we're streaming a DVD (i.e. via dvd://)
* or b) the renderer's MEncoder options contain overscan settings (those are handled
* separately)
*/
// XXX we should weed out the unused/unwanted settings and keep the rest
// (see sanitizeArgs()) rather than ignoring the options entirely
if (rendererMencoderOptions.contains("expand=") || dvd) {
rendererMencoderOptions = null;
}
}
StringTokenizer st = new StringTokenizer(
"-channels " + channels
+ (StringUtils.isNotBlank(mencoderCustomOptions) ? " " + mencoderCustomOptions : "")
+ (StringUtils.isNotBlank(rendererMencoderOptions) ? " " + rendererMencoderOptions : "")
+ add,
" "
);
// XXX why does this field (which is used to populate the array returned by args(),
// called below) store the renderer-specific (i.e. not global) MEncoder options?
overriddenMainArgs = new String[st.countTokens()];
int i = 0;
boolean handleToken = false;
int nThreads = (dvd || fileName.toLowerCase().endsWith("dvr-ms")) ?
1 :
configuration.getMencoderMaxThreads();
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (handleToken) {
token += ":threads=" + nThreads;
if (configuration.getSkipLoopFilterEnabled() && !avisynth()) {
token += ":skiploopfilter=all";
}
handleToken = false;
}
if (token.toLowerCase().contains("lavdopts")) {
handleToken = true;
}
overriddenMainArgs[i++] = token;
}
if (configuration.getMencoderMainSettings() != null) {
String mainConfig = configuration.getMencoderMainSettings();
String customSettings = params.mediaRenderer.getCustomMencoderQualitySettings();
// Custom settings in PMS may override the settings of the saved configuration
if (StringUtils.isNotBlank(customSettings)) {
mainConfig = customSettings;
}
if (mainConfig.contains("/*")) {
mainConfig = mainConfig.substring(mainConfig.indexOf("/*"));
}
// Ditlew - WDTV Live (+ other byte asking clients), CBR. This probably ought to be placed in addMaximumBitrateConstraints(..)
int cbr_bitrate = params.mediaRenderer.getCBRVideoBitrate();
String cbr_settings = (cbr_bitrate > 0) ? ":vrc_buf_size=5000:vrc_minrate=" + cbr_bitrate + ":vrc_maxrate=" + cbr_bitrate + ":vbitrate=" + ((cbr_bitrate > 16000) ? cbr_bitrate * 1000 : cbr_bitrate) : "";
String encodeSettings = "-lavcopts autoaspect=1:vcodec=" + vcodec +
(wmv ? ":acodec=wmav2:abitrate=448" : (cbr_settings + ":acodec=" + (configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3") +
":abitrate=" + CodecUtil.getAC3Bitrate(configuration, params.aid))) +
":threads=" + (wmv ? 1 : configuration.getMencoderMaxThreads()) +
("".equals(mainConfig) ? "" : ":" + mainConfig);
String audioType = "ac3";
if (dts) {
audioType = "dts";
} else if (pcm) {
audioType = "pcm";
}
encodeSettings = addMaximumBitrateConstraints(encodeSettings, media, mainConfig, params.mediaRenderer, audioType);
st = new StringTokenizer(encodeSettings, " ");
int oldc = overriddenMainArgs.length;
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
i = oldc;
while (st.hasMoreTokens()) {
overriddenMainArgs[i++] = st.nextToken();
}
}
boolean foundNoassParam = false;
if (media != null) {
String sArgs [] = getSpecificCodecOptions(configuration.getCodecSpecificConfig(), media, params, fileName, subString, configuration.isMencoderIntelligentSync(), false);
for (String s : sArgs) {
if (s.equals("-noass")) {
foundNoassParam = true;
}
}
}
StringBuilder sb = new StringBuilder();
// Set subtitles options
if (!configuration.isMencoderDisableSubs() && !avisynth() && params.sid != null) {
int subtitleMargin = 0;
int userMargin = 0;
// Use ASS flag (and therefore ASS font styles) for all subtitled files except vobsub, embedded, dvd and mp4 container with srt
// Note: The MP4 container with SRT rule is a workaround for MEncoder r30369. If there is ever a later version of MEncoder that supports external srt subs we should use that. As of r32848 that isn't the case
if (
(
(
params.sid.isFileUtf8() &&
params.sid.getType() == DLNAMediaSubtitle.EMBEDDED
) ||
params.sid.getType() != DLNAMediaSubtitle.EMBEDDED
) &&
params.sid.getType() != DLNAMediaSubtitle.VOBSUB &&
!(
params.sid.getType() == DLNAMediaSubtitle.SUBRIP &&
media.getContainer().equals("mp4")
) &&
configuration.isMencoderAss() && // GUI: enable subtitles formating
!foundNoassParam && // GUI: codec specific options
!dvd
) {
sb.append("-ass ");
// GUI: Override ASS subtitles style if requested (always for SRT subtitles)
if (
!configuration.isMencoderAssDefaultStyle() ||
params.sid.getType() == DLNAMediaSubtitle.SUBRIP ||
params.sid.getType() == DLNAMediaSubtitle.EMBEDDED
) {
String assSubColor = "ffffff00";
if (configuration.getSubsColor() != 0) {
assSubColor = Integer.toHexString(configuration.getSubsColor());
if (assSubColor.length() > 2) {
assSubColor = assSubColor.substring(2) + "00";
}
}
sb.append("-ass-color ").append(assSubColor).append(" -ass-border-color 00000000 -ass-font-scale ").append(configuration.getMencoderAssScale());
// set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
// set font with -font option, workaround for
// https://github.com/Happy-Neko/ps3mediaserver/commit/52e62203ea12c40628de1869882994ce1065446a#commitcomment-990156 bug
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
sb.append(" -ass-force-style FontName=").append(configuration.getMencoderFont()).append(",");
} else {
String font = CodecUtil.getDefaultFontPath();
if (StringUtils.isNotBlank(font)) {
// Variable "font" contains a font path instead of a font name.
// Does "-ass-force-style" support font paths? In tests on OSX
// the font path is ignored (Outline, Shadow and MarginV are
// used, though) and the "-font" definition is used instead.
// See: https://github.com/ps3mediaserver/ps3mediaserver/pull/14
sb.append(" -font ").append(font).append(" ");
sb.append(" -ass-force-style FontName=").append(font).append(",");
} else {
sb.append(" -font Arial ");
sb.append(" -ass-force-style FontName=Arial,");
}
}
// Add to the subtitle margin if overscan compensation is being used
// This keeps the subtitle text inside the frame instead of in the border
if (intOCH > 0) {
subtitleMargin = (media.getHeight() / 100) * intOCH;
}
sb.append("Outline=").append(configuration.getMencoderAssOutline()).append(",Shadow=").append(configuration.getMencoderAssShadow());
try {
userMargin = Integer.parseInt(configuration.getMencoderAssMargin());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse SSA margin from \"" + configuration.getMencoderAssMargin() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(",MarginV=").append(subtitleMargin).append(" ");
} else if (intOCH > 0) {
sb.append("-ass-force-style MarginV=").append(subtitleMargin).append(" ");
}
if (params.sid.getType() != DLNAMediaSubtitle.EMBEDDED) {
// Workaround for MPlayer #2041, remove when that bug is fixed
sb.append("-noflip-hebrew ");
}
// use PLAINTEXT formating
} else {
// set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
} else {
String font = CodecUtil.getDefaultFontPath();
if (StringUtils.isNotBlank(font)) {
sb.append(" -font ").append(font).append(" ");
}
}
sb.append(" -subfont-text-scale ").append(configuration.getMencoderNoAssScale());
sb.append(" -subfont-outline ").append(configuration.getMencoderNoAssOutline());
sb.append(" -subfont-blur ").append(configuration.getMencoderNoAssBlur());
// Add to the subtitle margin if overscan compensation is being used
// This keeps the subtitle text inside the frame instead of in the border
if (intOCH > 0) {
subtitleMargin = intOCH;
}
try {
userMargin = Integer.parseInt(configuration.getMencoderNoAssSubPos());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse subpos from \"" + configuration.getMencoderNoAssSubPos() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(" -subpos ").append(100 - subtitleMargin).append(" ");
}
// Common subtitle options
// Use fontconfig if enabled
sb.append("-").append(configuration.isMencoderFontConfig() ? "" : "no").append("fontconfig ");
// Apply DVD/VOBsub subtitle quality
if (params.sid.getType() == DLNAMediaSubtitle.VOBSUB && configuration.getMencoderVobsubSubtitleQuality() != null) {
String subtitleQuality = configuration.getMencoderVobsubSubtitleQuality();
sb.append("-spuaa ").append(subtitleQuality).append(" ");
}
if (!params.sid.isFileUtf8() && !configuration.isMencoderDisableSubs() && configuration.getMencoderSubCp() != null && configuration.getMencoderSubCp().length() > 0) {
sb.append("-subcp ").append(configuration.getMencoderSubCp()).append(" ");
if (configuration.isMencoderSubFribidi()) {
sb.append("-fribidi-charset ").append(configuration.getMencoderSubCp()).append(" ");
}
}
}
st = new StringTokenizer(sb.toString(), " ");
int oldc = overriddenMainArgs.length;
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
i = oldc;
handleToken = false;
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (handleToken) {
s = "-quiet";
handleToken = false;
}
if ((!configuration.isMencoderAss() || dvd) && s.contains("-ass")) {
s = "-quiet";
handleToken = true;
}
overriddenMainArgs[i++] = s;
}
String cmdArray[] = new String[18 + args().length];
cmdArray[0] = executable();
// Choose which time to seek to
cmdArray[1] = "-ss";
if (params.timeseek > 0) {
cmdArray[2] = "" + params.timeseek;
} else {
cmdArray[2] = "0";
}
if (dvd) {
cmdArray[3] = "-dvd-device";
} else {
cmdArray[3] = "-quiet";
}
if (avisynth && !fileName.toLowerCase().endsWith(".iso")) {
File avsFile = FFMpegVideo.getAVSScript(fileName, params.sid, params.fromFrame, params.toFrame);
cmdArray[4] = ProcessUtil.getShortFileNameIfWideChars(avsFile.getAbsolutePath());
} else {
cmdArray[4] = fileName;
if (params.stdin != null) {
cmdArray[4] = "-";
}
}
if (dvd) {
cmdArray[5] = "dvd://" + media.getDvdtrack();
} else {
cmdArray[5] = "-quiet";
}
String arguments[] = args();
for (i = 0; i < arguments.length; i++) {
cmdArray[6 + i] = arguments[i];
if (arguments[i].contains("format=mpeg2") && media.getAspect() != null && media.getValidAspect(true) != null) {
cmdArray[6 + i] += ":vaspect=" + media.getValidAspect(true);
}
}
cmdArray[cmdArray.length - 12] = "-quiet";
cmdArray[cmdArray.length - 11] = "-quiet";
cmdArray[cmdArray.length - 10] = "-quiet";
cmdArray[cmdArray.length - 9] = "-quiet";
if (!dts && !pcm && !avisynth() && params.aid != null && media.getAudioCodes().size() > 1) {
cmdArray[cmdArray.length - 12] = "-aid";
boolean lavf = false; // Need to add support for LAVF demuxing
cmdArray[cmdArray.length - 11] = "" + (lavf ? params.aid.getId() + 1 : params.aid.getId());
}
/*
* TODO: Move the following block up with the rest of the
* subtitle stuff
*/
if (subString == null && params.sid != null) {
cmdArray[cmdArray.length - 10] = "-sid";
cmdArray[cmdArray.length - 9] = "" + params.sid.getId();
} else if (subString != null && !avisynth()) { // Trick necessary for MEncoder to skip the internal embedded track ?
cmdArray[cmdArray.length - 10] = "-sid";
cmdArray[cmdArray.length - 9] = "100";
} else if (subString == null) { // Trick necessary for MEncoder to not display the internal embedded track
cmdArray[cmdArray.length - 10] = "-subdelay";
cmdArray[cmdArray.length - 9] = "20000";
}
cmdArray[cmdArray.length - 8] = "-quiet";
cmdArray[cmdArray.length - 7] = "-quiet";
if (configuration.isMencoderForceFps() && !configuration.isFix25FPSAvMismatch()) {
cmdArray[cmdArray.length - 8] = "-fps";
cmdArray[cmdArray.length - 7] = "24000/1001";
}
cmdArray[cmdArray.length - 6] = "-ofps";
cmdArray[cmdArray.length - 5] = "24000/1001";
String frameRate = null;
if (media != null) {
frameRate = media.getValidFps(true);
}
if (frameRate != null) {
cmdArray[cmdArray.length - 5] = frameRate;
if (configuration.isMencoderForceFps()) {
if (configuration.isFix25FPSAvMismatch()) {
cmdArray[cmdArray.length - 8] = "-mc";
cmdArray[cmdArray.length - 7] = "0.005";
cmdArray[cmdArray.length - 5] = "25";
} else {
cmdArray[cmdArray.length - 7] = cmdArray[cmdArray.length - 5];
}
}
}
/*
* TODO: Move the following block up with the rest of the
* subtitle stuff
*/
if (subString != null && !configuration.isMencoderDisableSubs() && !avisynth()) {
if (params.sid.getType() == DLNAMediaSubtitle.VOBSUB) {
cmdArray[cmdArray.length - 4] = "-vobsub";
cmdArray[cmdArray.length - 3] = subString.substring(0, subString.length() - 4);
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-slang";
cmdArray[cmdArray.length - 3] = "" + params.sid.getLang();
} else {
cmdArray[cmdArray.length - 4] = "-sub";
cmdArray[cmdArray.length - 3] = subString.replace(",", "\\,"); // Commas in MEncoder separate multiple subtitle files
if (params.sid.isFileUtf8() && params.sid.getPlayableFile() != null) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 1);
cmdArray[cmdArray.length - 3] = "-utf8";
}
}
} else {
cmdArray[cmdArray.length - 4] = "-quiet";
cmdArray[cmdArray.length - 3] = "-quiet";
}
if (fileName.toLowerCase().endsWith(".evo")) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-psprobe";
cmdArray[cmdArray.length - 3] = "10000";
}
boolean deinterlace = configuration.isMencoderYadif();
// Check if the media renderer supports this resolution
boolean isResolutionTooHighForRenderer = params.mediaRenderer.isVideoRescale()
&& media != null
&& (
(media.getWidth() > params.mediaRenderer.getMaxVideoWidth())
||
(media.getHeight() > params.mediaRenderer.getMaxVideoHeight())
);
// Video scaler and overscan compensation
boolean scaleBool = isResolutionTooHighForRenderer
|| (configuration.isMencoderScaler() && (configuration.getMencoderScaleX() != 0 || configuration.getMencoderScaleY() != 0))
|| (intOCW > 0 || intOCH > 0);
if ((deinterlace || scaleBool) && !avisynth()) {
StringBuilder vfValueOverscanPrepend = new StringBuilder();
StringBuilder vfValueOverscanMiddle = new StringBuilder();
StringBuilder vfValueVS = new StringBuilder();
StringBuilder vfValueComplete = new StringBuilder();
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-vf";
String deinterlaceComma = "";
int scaleWidth = 0;
int scaleHeight = 0;
double rendererAspectRatio;
// Set defaults
if (media != null && media.getWidth() > 0 && media.getHeight() > 0) {
scaleWidth = media.getWidth();
scaleHeight = media.getHeight();
}
/*
* Implement overscan compensation settings
*
* This feature takes into account aspect ratio,
* making it less blunt than the Video Scaler option
*/
if (intOCW > 0 || intOCH > 0) {
int intOCWPixels = (media.getWidth() / 100) * intOCW;
int intOCHPixels = (media.getHeight() / 100) * intOCH;
scaleWidth = scaleWidth + intOCWPixels;
scaleHeight = scaleHeight + intOCHPixels;
// See if the video needs to be scaled down
if (
(scaleWidth > params.mediaRenderer.getMaxVideoWidth()) ||
(scaleHeight > params.mediaRenderer.getMaxVideoHeight())
) {
double overscannedAspectRatio = scaleWidth / scaleHeight;
rendererAspectRatio = params.mediaRenderer.getMaxVideoWidth() / params.mediaRenderer.getMaxVideoHeight();
if (overscannedAspectRatio > rendererAspectRatio) {
// Limit video by width
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / overscannedAspectRatio);
} else {
// Limit video by height
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * overscannedAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
vfValueOverscanPrepend.append("softskip,expand=-").append(intOCWPixels).append(":-").append(intOCHPixels);
vfValueOverscanMiddle.append(",scale=").append(scaleWidth).append(":").append(scaleHeight);
}
/*
* Video Scaler and renderer-specific resolution-limiter
*/
if (configuration.isMencoderScaler()) {
// Use the manual, user-controlled scaler
if (configuration.getMencoderScaleX() != 0) {
if (configuration.getMencoderScaleX() <= params.mediaRenderer.getMaxVideoWidth()) {
scaleWidth = configuration.getMencoderScaleX();
} else {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
}
}
if (configuration.getMencoderScaleY() != 0) {
if (configuration.getMencoderScaleY() <= params.mediaRenderer.getMaxVideoHeight()) {
scaleHeight = configuration.getMencoderScaleY();
} else {
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", your Video Scaler setting");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
/*
* The video resolution is too big for the renderer so we need to scale it down
*/
} else if (
media != null &&
media.getWidth() > 0 &&
media.getHeight() > 0 &&
(
media.getWidth() > params.mediaRenderer.getMaxVideoWidth() ||
media.getHeight() > params.mediaRenderer.getMaxVideoHeight()
)
) {
double videoAspectRatio = (double) media.getWidth() / (double) media.getHeight();
rendererAspectRatio = (double) params.mediaRenderer.getMaxVideoWidth() / (double) params.mediaRenderer.getMaxVideoHeight();
/*
* First we deal with some exceptions, then if they are not matched we will
* let the renderer limits work.
*
* This is so, for example, we can still define a maximum resolution of
* 1920x1080 in the renderer config file but still support 1920x1088 when
* it's needed, otherwise we would either resize 1088 to 1080, meaning the
* ugly (unused) bottom 8 pixels would be displayed, or we would limit all
* videos to 1088 causing the bottom 8 meaningful pixels to be cut off.
*/
if (media.getWidth() == 3840 && media.getHeight() == 1080) {
// Full-SBS
scaleWidth = 1920;
scaleHeight = 1080;
} else if (media.getWidth() == 1920 && media.getHeight() == 2160) {
// Full-OU
scaleWidth = 1920;
scaleHeight = 1080;
} else if (media.getWidth() == 1920 && media.getHeight() == 1088) {
// SAT capture
scaleWidth = 1920;
scaleHeight = 1088;
} else {
// Passed the exceptions, now we allow the renderer to define the limits
if (videoAspectRatio > rendererAspectRatio) {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / videoAspectRatio);
} else {
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * videoAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", the maximum your renderer supports");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
}
// Put the string together taking into account overscan compensation and video scaler
if (intOCW > 0 || intOCH > 0) {
vfValueComplete.append(vfValueOverscanPrepend).append(vfValueOverscanMiddle).append(",harddup");
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", to fit your overscan compensation");
} else {
vfValueComplete.append(vfValueVS);
}
if (deinterlace) {
deinterlaceComma = ",";
}
cmdArray[cmdArray.length - 3] = (deinterlace ? "yadif" : "") + (scaleBool ? deinterlaceComma + vfValueComplete : "");
}
/*
* The PS3 and possibly other renderers display videos incorrectly
* if the dimensions aren't divisible by 4, so if that is the
* case we scale it down to the nearest 4.
* This fixes the long-time bug of videos displaying in black and
* white with diagonal strips of colour, weird one.
*
* TODO: Integrate this with the other stuff so that "scale" only
* ever appears once in the MEncoder CMD.
*/
if (media != null && (media.getWidth() % 4 != 0) || media.getHeight() % 4 != 0) {
int newWidth;
int newHeight;
newWidth = (media.getWidth() / 4) * 4;
newHeight = (media.getHeight() / 4) * 4;
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-vf";
cmdArray[cmdArray.length - 3] = "softskip,scale=" + newWidth + ":" + newHeight;
}
if (configuration.getMencoderMT() && !avisynth && !dvd && !(media.getCodecV() != null && (media.getCodecV().equals("mpeg2video")))) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-lavdopts";
cmdArray[cmdArray.length - 3] = "fast";
}
boolean noMC0NoSkip = false;
if (media != null) {
String sArgs[] = getSpecificCodecOptions(configuration.getCodecSpecificConfig(), media, params, fileName, subString, configuration.isMencoderIntelligentSync(), false);
if (sArgs != null && sArgs.length > 0) {
boolean vfConsumed = false;
boolean afConsumed = false;
for (int s = 0; s < sArgs.length; s++) {
if (sArgs[s].equals("-noass")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-ass")) {
cmdArray[c] = "-quiet";
}
}
} else if (sArgs[s].equals("-ofps")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-ofps")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-fps")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-fps")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-ovc")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-ovc")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-channels")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-channels")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-oac")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-oac")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-quality")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-lavcopts")) {
cmdArray[c + 1] = "autoaspect=1:vcodec=" + vcodec +
":acodec=" + (configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3") +
":abitrate=" + CodecUtil.getAC3Bitrate(configuration, params.aid) +
":threads=" + configuration.getMencoderMaxThreads() + ":" + sArgs[s + 1];
addMaximumBitrateConstraints(cmdArray[c + 1], media, cmdArray[c + 1], params.mediaRenderer, "");
sArgs[s + 1] = "-quality";
s++;
}
}
} else if (sArgs[s].equals("-mpegopts")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-mpegopts")) {
cmdArray[c + 1] += ":" + sArgs[s + 1];
sArgs[s + 1] = "-mpegopts";
s++;
}
}
} else if (sArgs[s].equals("-vf")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-vf")) {
cmdArray[c + 1] += "," + sArgs[s + 1];
sArgs[s + 1] = "-vf";
s++;
vfConsumed = true;
}
}
} else if (sArgs[s].equals("-af")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-af")) {
cmdArray[c + 1] += "," + sArgs[s + 1];
sArgs[s + 1] = "-af";
s++;
afConsumed = true;
}
}
} else if (sArgs[s].equals("-nosync")) {
noMC0NoSkip = true;
} else if (sArgs[s].equals("-mc")) {
noMC0NoSkip = true;
}
}
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + sArgs.length);
for (int s = 0; s < sArgs.length; s++) {
if (sArgs[s].equals("-noass") || sArgs[s].equals("-nomux") || sArgs[s].equals("-mpegopts") || (sArgs[s].equals("-vf") & vfConsumed) || (sArgs[s].equals("-af") && afConsumed) || sArgs[s].equals("-quality") || sArgs[s].equals("-nosync") || sArgs[s].equals("-mt")) {
cmdArray[cmdArray.length - sArgs.length - 2 + s] = "-quiet";
} else {
cmdArray[cmdArray.length - sArgs.length - 2 + s] = sArgs[s];
}
}
}
}
if ((pcm || dts || mux) || (configuration.isMencoderNoOutOfSync() && !noMC0NoSkip)) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 3);
cmdArray[cmdArray.length - 5] = "-mc";
cmdArray[cmdArray.length - 4] = "0";
cmdArray[cmdArray.length - 3] = "-noskip";
if (configuration.isFix25FPSAvMismatch()) {
cmdArray[cmdArray.length - 4] = "0.005";
cmdArray[cmdArray.length - 3] = "-quiet";
}
}
if (params.timeend > 0) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-endpos";
cmdArray[cmdArray.length - 3] = "" + params.timeend;
}
String rate = "48000";
if (params.mediaRenderer.isXBOX()) {
rate = "44100";
}
// force srate -> cause ac3's mencoder doesn't like anything other than 48khz
if (media != null && !pcm && !dts && !mux) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 4);
cmdArray[cmdArray.length - 6] = "-af";
cmdArray[cmdArray.length - 5] = "lavcresample=" + rate;
cmdArray[cmdArray.length - 4] = "-srate";
cmdArray[cmdArray.length - 3] = rate;
}
// add a -cache option for piped media (e.g. rar/zip file entries):
// https://code.google.com/p/ps3mediaserver/issues/detail?id=911
if (params.stdin != null) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-cache";
cmdArray[cmdArray.length - 3] = "8192";
}
PipeProcess pipe = null;
cmdArray[cmdArray.length - 2] = "-o";
ProcessWrapperImpl pw = null;
if (pcm || dts || mux) {
boolean channels_filter_present = false;
for (String s : cmdArray) {
if (StringUtils.isNotBlank(s) && s.startsWith("channels")) {
channels_filter_present = true;
break;
}
}
if (params.avidemux) {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dts || mux) ? null : params);
params.input_pipes[0] = pipe;
cmdArray[cmdArray.length - 1] = pipe.getInputPipe();
if (pcm && !channels_filter_present) {
String mixer = CodecUtil.getMixerOutput(true, configuration.getAudioChannelCount(), configuration.getAudioChannelCount());
if (StringUtils.isNotBlank(mixer)) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 2] = "-af";
cmdArray[cmdArray.length - 1] = mixer;
}
}
pw = new ProcessWrapperImpl(cmdArray, params);
PipeProcess videoPipe = new PipeProcess("videoPipe" + System.currentTimeMillis(), "out", "reconnect");
PipeProcess audioPipe = new PipeProcess("audioPipe" + System.currentTimeMillis(), "out", "reconnect");
ProcessWrapper videoPipeProcess = videoPipe.getPipeProcess();
ProcessWrapper audioPipeProcess = audioPipe.getPipeProcess();
params.output_pipes[0] = videoPipe;
params.output_pipes[1] = audioPipe;
pw.attachProcess(videoPipeProcess);
pw.attachProcess(audioPipeProcess);
videoPipeProcess.runInNewThread();
audioPipeProcess.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
videoPipe.deleteLater();
audioPipe.deleteLater();
} else {
// remove the -oac switch, otherwise too many video packets errors appears again
for (int s = 0; s < cmdArray.length; s++) {
if (cmdArray[s].equals("-oac")) {
cmdArray[s] = "-nosound";
cmdArray[s + 1] = "-nosound";
break;
}
}
pipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts");
TSMuxerVideo ts = new TSMuxerVideo(configuration);
File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta");
String cmd[] = new String[]{ts.executable(), f.getAbsolutePath(), pipe.getInputPipe()};
pw = new ProcessWrapperImpl(cmd, params);
PipeIPCProcess ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true);
cmdArray[cmdArray.length - 1] = ffVideoPipe.getInputPipe();
OutputParams ffparams = new OutputParams(configuration);
ffparams.maxBufferSize = 1;
ffparams.stdin = params.stdin;
ProcessWrapperImpl ffVideo = new ProcessWrapperImpl(cmdArray, ffparams);
ProcessWrapper ff_video_pipe_process = ffVideoPipe.getPipeProcess();
pw.attachProcess(ff_video_pipe_process);
ff_video_pipe_process.runInNewThread();
ffVideoPipe.deleteLater();
pw.attachProcess(ffVideo);
ffVideo.runInNewThread();
String aid = null;
if (media != null && media.getAudioCodes().size() > 1 && params.aid != null) {
aid = params.aid.getId() + "";
}
PipeIPCProcess ffAudioPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true);
StreamModifier sm = new StreamModifier();
sm.setPcm(pcm);
sm.setDtsembed(dts);
sm.setNbchannels(sm.isDtsembed() ? 2 : CodecUtil.getRealChannelCount(configuration, params.aid));
sm.setSampleFrequency(48000);
sm.setBitspersample(16);
String mixer = CodecUtil.getMixerOutput(!sm.isDtsembed(), sm.getNbchannels(), configuration.getAudioChannelCount());
// it seems the -really-quiet prevents mencoder to stop the pipe output after some time...
// -mc 0.1 make the DTS-HD extraction works better with latest mencoder builds, and makes no impact on the regular DTS one
String ffmpegLPCMextract[] = new String[]{
executable(),
"-ss", "0",
fileName,
"-really-quiet",
"-msglevel", "statusline=2",
"-channels", "" + sm.getNbchannels(),
"-ovc", "copy",
"-of", "rawaudio",
"-mc", dts ? "0.1" : "0",
"-noskip",
(aid == null) ? "-quiet" : "-aid", (aid == null) ? "-quiet" : aid,
"-oac", sm.isDtsembed() ? "copy" : "pcm",
(StringUtils.isNotBlank(mixer) && !channels_filter_present) ? "-af" : "-quiet", (StringUtils.isNotBlank(mixer) && !channels_filter_present) ? mixer : "-quiet",
"-srate", "48000",
"-o", ffAudioPipe.getInputPipe()
};
if (!params.mediaRenderer.isMuxDTSToMpeg()) { // no need to use the PCM trick when media renderer supports DTS
ffAudioPipe.setModifier(sm);
}
if (media != null && media.getDvdtrack() > 0) {
ffmpegLPCMextract[3] = "-dvd-device";
ffmpegLPCMextract[4] = fileName;
ffmpegLPCMextract[5] = "dvd://" + media.getDvdtrack();
} else if (params.stdin != null) {
ffmpegLPCMextract[3] = "-";
}
if (fileName.toLowerCase().endsWith(".evo")) {
ffmpegLPCMextract[4] = "-psprobe";
ffmpegLPCMextract[5] = "1000000";
}
if (params.timeseek > 0) {
ffmpegLPCMextract[2] = "" + params.timeseek;
}
OutputParams ffaudioparams = new OutputParams(configuration);
ffaudioparams.maxBufferSize = 1;
ffaudioparams.stdin = params.stdin;
ProcessWrapperImpl ffAudio = new ProcessWrapperImpl(ffmpegLPCMextract, ffaudioparams);
params.stdin = null;
PrintWriter pwMux = new PrintWriter(f);
pwMux.println("MUXOPT --no-pcr-on-video-pid --no-asyncio --new-audio-pes --vbr --vbv-len=500");
String videoType = "V_MPEG-2";
if (params.no_videoencode && params.forceType != null) {
videoType = params.forceType;
}
String fps = "";
if (params.forceFps != null) {
fps = "fps=" + params.forceFps + ", ";
}
String audioType = "A_LPCM";
if (params.mediaRenderer.isMuxDTSToMpeg()) {
audioType = "A_DTS";
}
if (params.lossyaudio) {
audioType = "A_AC3";
}
pwMux.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + fps + "level=4.1, insertSEI, contSPS, track=1");
pwMux.println(audioType + ", \"" + ffAudioPipe.getOutputPipe() + "\", track=2");
pwMux.close();
ProcessWrapper pipe_process = pipe.getPipeProcess();
pw.attachProcess(pipe_process);
pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
params.input_pipes[0] = pipe;
ProcessWrapper ff_pipe_process = ffAudioPipe.getPipeProcess();
pw.attachProcess(ff_pipe_process);
ff_pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
ffAudioPipe.deleteLater();
pw.attachProcess(ffAudio);
ffAudio.runInNewThread();
}
} else {
boolean directpipe = Platform.isMac() || Platform.isFreeBSD();
if (directpipe) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 3);
cmdArray[cmdArray.length - 3] = "-really-quiet";
cmdArray[cmdArray.length - 2] = "-msglevel";
cmdArray[cmdArray.length - 1] = "statusline=2";
cmdArray[cmdArray.length - 4] = "-";
params.input_pipes = new PipeProcess[2];
} else {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dts || mux) ? null : params);
params.input_pipes[0] = pipe;
cmdArray[cmdArray.length - 1] = pipe.getInputPipe();
}
cmdArray = finalizeTranscoderArgs(
this,
fileName,
dlna,
media,
params,
cmdArray
);
pw = new ProcessWrapperImpl(cmdArray, params);
if (!directpipe) {
ProcessWrapper mkfifo_process = pipe.getPipeProcess();
pw.attachProcess(mkfifo_process);
mkfifo_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
}
}
pw.runInNewThread();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
return pw;
}
@Override
public String mimeType() {
return HTTPResource.VIDEO_TRANSCODE;
}
@Override
public String name() {
return "MEncoder";
}
@Override
public int type() {
return Format.VIDEO;
}
private String[] getSpecificCodecOptions(String codecParam, DLNAMediaInfo media, OutputParams params, String filename, String srtFileName, boolean enable, boolean verifyOnly) {
StringBuilder sb = new StringBuilder();
String codecs = enable ? DEFAULT_CODEC_CONF_SCRIPT : "";
codecs += "\n" + codecParam;
StringTokenizer stLines = new StringTokenizer(codecs, "\n");
try {
Interpreter interpreter = new Interpreter();
interpreter.setStrictJava(true);
ArrayList<String> types = CodecUtil.getPossibleCodecs();
int rank = 1;
if (types != null) {
for (String type : types) {
int r = rank++;
interpreter.set("" + type, r);
String secondaryType = "dummy";
if ("matroska".equals(type)) {
secondaryType = "mkv";
interpreter.set(secondaryType, r);
} else if ("rm".equals(type)) {
secondaryType = "rmvb";
interpreter.set(secondaryType, r);
} else if ("mpeg2video".equals(type)) {
secondaryType = "mpeg2";
interpreter.set(secondaryType, r);
} else if ("mpeg1video".equals(type)) {
secondaryType = "mpeg1";
interpreter.set(secondaryType, r);
}
if (media.getContainer() != null && (media.getContainer().equals(type) || media.getContainer().equals(secondaryType))) {
interpreter.set("container", r);
} else if (media.getCodecV() != null && (media.getCodecV().equals(type) || media.getCodecV().equals(secondaryType))) {
interpreter.set("vcodec", r);
} else if (params.aid != null && params.aid.getCodecA() != null && params.aid.getCodecA().equals(type)) {
interpreter.set("acodec", r);
}
}
} else {
return null;
}
interpreter.set("filename", filename);
interpreter.set("audio", params.aid != null);
interpreter.set("subtitles", params.sid != null);
interpreter.set("srtfile", srtFileName);
if (params.aid != null) {
interpreter.set("samplerate", params.aid.getSampleRate());
}
String framerate = media.getValidFps(false);
try {
if (framerate != null) {
interpreter.set("framerate", Double.parseDouble(framerate));
}
} catch (NumberFormatException e) {
LOGGER.debug("Could not parse framerate from \"" + framerate + "\"");
}
interpreter.set("duration", media.getDurationInSeconds());
if (params.aid != null) {
interpreter.set("channels", params.aid.getNrAudioChannels());
}
interpreter.set("height", media.getHeight());
interpreter.set("width", media.getWidth());
while (stLines.hasMoreTokens()) {
String line = stLines.nextToken();
if (!line.startsWith("#") && line.trim().length() > 0) {
int separator = line.indexOf("::");
if (separator > -1) {
String key = null;
try {
key = line.substring(0, separator).trim();
String value = line.substring(separator + 2).trim();
if (value.length() > 0) {
if (key.length() == 0) {
key = "1 == 1";
}
Object result = interpreter.eval(key);
if (result != null && result instanceof Boolean && ((Boolean) result).booleanValue()) {
sb.append(" ");
sb.append(value);
}
}
} catch (Throwable e) {
LOGGER.debug("Error while executing: " + key + " : " + e.getMessage());
if (verifyOnly) {
return new String[]{"@@Error while parsing: " + e.getMessage()};
}
}
} else if (verifyOnly) {
return new String[]{"@@Malformatted line: " + line};
}
}
}
} catch (EvalError e) {
LOGGER.debug("BeanShell error: " + e.getMessage());
}
String completeLine = sb.toString();
ArrayList<String> args = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(completeLine, " ");
while (st.hasMoreTokens()) {
String arg = st.nextToken().trim();
if (arg.length() > 0) {
args.add(arg);
}
}
String definitiveArgs[] = new String[args.size()];
args.toArray(definitiveArgs);
return definitiveArgs;
}
}
| true | true | public ProcessWrapper launchTranscode(
String fileName,
DLNAResource dlna,
DLNAMediaInfo media,
OutputParams params
) throws IOException {
params.manageFastStart();
boolean avisynth = avisynth();
setAudioAndSubs(fileName, media, params, configuration);
String subString = null;
if (params.sid != null && params.sid.getPlayableFile() != null) {
subString = ProcessUtil.getShortFileNameIfWideChars(params.sid.getPlayableFile().getAbsolutePath());
}
InputFile newInput = new InputFile();
newInput.setFilename(fileName);
newInput.setPush(params.stdin);
dvd = false;
if (media != null && media.getDvdtrack() > 0) {
dvd = true;
}
// don't honour "Switch to tsMuxeR..." if the resource is being streamed via an MEncoder entry in
// the #--TRANSCODE--# folder
boolean forceMencoder = !configuration.getHideTranscodeEnabled()
&& dlna.isNoName() // XXX remove this? http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12149
&& (dlna.getParent() instanceof FileTranscodeVirtualFolder);
ovccopy = false;
int intOCW = 0;
int intOCH = 0;
try {
intOCW = Integer.parseInt(configuration.getMencoderOverscanCompensationWidth());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation width: \"{}\"", configuration.getMencoderOverscanCompensationWidth());
}
try {
intOCH = Integer.parseInt(configuration.getMencoderOverscanCompensationHeight());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation height: \"{}\"", configuration.getMencoderOverscanCompensationHeight());
}
if (
!forceMencoder &&
params.sid == null &&
!dvd &&
!avisynth() &&
media != null && (
media.isVideoPS3Compatible(newInput) ||
!params.mediaRenderer.isH264Level41Limited()
) &&
media.isMuxable(params.mediaRenderer) &&
configuration.isMencoderMuxWhenCompatible() &&
params.mediaRenderer.isMuxH264MpegTS() && (
intOCW == 0 &&
intOCH == 0
)
) {
String sArgs[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
subString,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : sArgs) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
TSMuxerVideo tv = new TSMuxerVideo(configuration);
params.forceFps = media.getValidFps(false);
if (media.getCodecV().equals("h264")) {
params.forceType = "V_MPEG4/ISO/AVC";
} else if (media.getCodecV().startsWith("mpeg2")) {
params.forceType = "V_MPEG-2";
} else if (media.getCodecV().equals("vc1")) {
params.forceType = "V_MS/VFW/WVC1";
}
return tv.launchTranscode(fileName, dlna, media, params);
}
} else if (params.sid == null && dvd && configuration.isMencoderRemuxMPEG2() && params.mediaRenderer.isMpeg2Supported()) {
String sArgs[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
subString,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : sArgs) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
ovccopy = true;
}
}
String vcodec = "mpeg2video";
wmv = false;
if (params.mediaRenderer.isTranscodeToWMV()) {
wmv = true;
vcodec = "wmv2"; // http://wiki.megaframe.org/wiki/Ubuntu_XBOX_360#MEncoder not usable in streaming
}
mpegts = false;
if (params.mediaRenderer.isTranscodeToMPEGTSAC3()) {
mpegts = true;
}
oaccopy = false;
// disable AC3 remux for stereo tracks with 384 kbits bitrate and PS3 renderer (PS3 FW bug?)
boolean ps3_and_stereo_and_384_kbits = (params.mediaRenderer.getRendererName().equalsIgnoreCase("Playstation 3") && params.aid.getNrAudioChannels() == 2) && (params.aid.getBitRate() > 370000 && params.aid.getBitRate() < 400000);
if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && !ps3_and_stereo_and_384_kbits && !avisynth() && params.mediaRenderer.isTranscodeToAC3()) {
// AC3 remux takes priority
oaccopy = true;
} else {
// now check for DTS remux and LPCM streaming
dts = configuration.isDTSEmbedInPCM() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
) && params.aid != null &&
params.aid.isDTS() &&
!avisynth() &&
params.mediaRenderer.isDTSPlayable();
pcm = configuration.isMencoderUsePcm() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
)
// disable LPCM transcoding for MP4 container with non-H264 video as workaround for mencoder's A/V sync bug
&& !(media.getContainer().equals("mp4") && !media.getCodecV().equals("h264"))
&& params.aid != null &&
(
(params.aid.isDTS() && params.aid.getNrAudioChannels() <= 6) || // disable 7.1 DTS-HD => LPCM because of channels mapping bug
params.aid.isLossless() ||
params.aid.isTrueHD() ||
(
!configuration.isMencoderUsePcmForHQAudioOnly() &&
(
params.aid.isAC3() ||
params.aid.isMP3() ||
params.aid.isAAC() ||
params.aid.isVorbis() ||
// disable WMA to LPCM transcoding because of mencoder's channel mapping bug
// (see CodecUtil.getMixerOutput)
// params.aid.isWMA() ||
params.aid.isMpegAudio()
)
)
) && params.mediaRenderer.isLPCMPlayable();
}
if (dts || pcm) {
if (dts) {
oaccopy = true;
}
params.losslessaudio = true;
params.forceFps = media.getValidFps(false);
}
// mpeg2 remux still buggy with mencoder :\
if (!pcm && !dts && !mux && ovccopy) {
ovccopy = false;
}
if (pcm && avisynth()) {
params.avidemux = true;
}
String add = "";
String rendererMencoderOptions = params.mediaRenderer.getCustomMencoderOptions(); // default: empty string
String mencoderCustomOptions = configuration.getMencoderCustomOptions(); // default: empty string
String combinedCustomOptions = StringUtils.defaultString(mencoderCustomOptions)
+ " "
+ StringUtils.defaultString(rendererMencoderOptions);
if (!combinedCustomOptions.contains("-lavdopts")) {
add = " -lavdopts debug=0";
}
int channels = wmv ? 2 : configuration.getAudioChannelCount();
if (media != null && params.aid != null) {
channels = wmv ? 2 : CodecUtil.getRealChannelCount(configuration, params.aid);
}
LOGGER.trace("channels=" + channels);
if (StringUtils.isNotBlank(rendererMencoderOptions)) {
/*
* ignore the renderer's custom MEncoder options if a) we're streaming a DVD (i.e. via dvd://)
* or b) the renderer's MEncoder options contain overscan settings (those are handled
* separately)
*/
// XXX we should weed out the unused/unwanted settings and keep the rest
// (see sanitizeArgs()) rather than ignoring the options entirely
if (rendererMencoderOptions.contains("expand=") || dvd) {
rendererMencoderOptions = null;
}
}
StringTokenizer st = new StringTokenizer(
"-channels " + channels
+ (StringUtils.isNotBlank(mencoderCustomOptions) ? " " + mencoderCustomOptions : "")
+ (StringUtils.isNotBlank(rendererMencoderOptions) ? " " + rendererMencoderOptions : "")
+ add,
" "
);
// XXX why does this field (which is used to populate the array returned by args(),
// called below) store the renderer-specific (i.e. not global) MEncoder options?
overriddenMainArgs = new String[st.countTokens()];
int i = 0;
boolean handleToken = false;
int nThreads = (dvd || fileName.toLowerCase().endsWith("dvr-ms")) ?
1 :
configuration.getMencoderMaxThreads();
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (handleToken) {
token += ":threads=" + nThreads;
if (configuration.getSkipLoopFilterEnabled() && !avisynth()) {
token += ":skiploopfilter=all";
}
handleToken = false;
}
if (token.toLowerCase().contains("lavdopts")) {
handleToken = true;
}
overriddenMainArgs[i++] = token;
}
if (configuration.getMencoderMainSettings() != null) {
String mainConfig = configuration.getMencoderMainSettings();
String customSettings = params.mediaRenderer.getCustomMencoderQualitySettings();
// Custom settings in PMS may override the settings of the saved configuration
if (StringUtils.isNotBlank(customSettings)) {
mainConfig = customSettings;
}
if (mainConfig.contains("/*")) {
mainConfig = mainConfig.substring(mainConfig.indexOf("/*"));
}
// Ditlew - WDTV Live (+ other byte asking clients), CBR. This probably ought to be placed in addMaximumBitrateConstraints(..)
int cbr_bitrate = params.mediaRenderer.getCBRVideoBitrate();
String cbr_settings = (cbr_bitrate > 0) ? ":vrc_buf_size=5000:vrc_minrate=" + cbr_bitrate + ":vrc_maxrate=" + cbr_bitrate + ":vbitrate=" + ((cbr_bitrate > 16000) ? cbr_bitrate * 1000 : cbr_bitrate) : "";
String encodeSettings = "-lavcopts autoaspect=1:vcodec=" + vcodec +
(wmv ? ":acodec=wmav2:abitrate=448" : (cbr_settings + ":acodec=" + (configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3") +
":abitrate=" + CodecUtil.getAC3Bitrate(configuration, params.aid))) +
":threads=" + (wmv ? 1 : configuration.getMencoderMaxThreads()) +
("".equals(mainConfig) ? "" : ":" + mainConfig);
String audioType = "ac3";
if (dts) {
audioType = "dts";
} else if (pcm) {
audioType = "pcm";
}
encodeSettings = addMaximumBitrateConstraints(encodeSettings, media, mainConfig, params.mediaRenderer, audioType);
st = new StringTokenizer(encodeSettings, " ");
int oldc = overriddenMainArgs.length;
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
i = oldc;
while (st.hasMoreTokens()) {
overriddenMainArgs[i++] = st.nextToken();
}
}
boolean foundNoassParam = false;
if (media != null) {
String sArgs [] = getSpecificCodecOptions(configuration.getCodecSpecificConfig(), media, params, fileName, subString, configuration.isMencoderIntelligentSync(), false);
for (String s : sArgs) {
if (s.equals("-noass")) {
foundNoassParam = true;
}
}
}
StringBuilder sb = new StringBuilder();
// Set subtitles options
if (!configuration.isMencoderDisableSubs() && !avisynth() && params.sid != null) {
int subtitleMargin = 0;
int userMargin = 0;
// Use ASS flag (and therefore ASS font styles) for all subtitled files except vobsub, embedded, dvd and mp4 container with srt
// Note: The MP4 container with SRT rule is a workaround for MEncoder r30369. If there is ever a later version of MEncoder that supports external srt subs we should use that. As of r32848 that isn't the case
if (
(
(
params.sid.isFileUtf8() &&
params.sid.getType() == DLNAMediaSubtitle.EMBEDDED
) ||
params.sid.getType() != DLNAMediaSubtitle.EMBEDDED
) &&
params.sid.getType() != DLNAMediaSubtitle.VOBSUB &&
!(
params.sid.getType() == DLNAMediaSubtitle.SUBRIP &&
media.getContainer().equals("mp4")
) &&
configuration.isMencoderAss() && // GUI: enable subtitles formating
!foundNoassParam && // GUI: codec specific options
!dvd
) {
sb.append("-ass ");
// GUI: Override ASS subtitles style if requested (always for SRT subtitles)
if (
!configuration.isMencoderAssDefaultStyle() ||
params.sid.getType() == DLNAMediaSubtitle.SUBRIP ||
params.sid.getType() == DLNAMediaSubtitle.EMBEDDED
) {
String assSubColor = "ffffff00";
if (configuration.getSubsColor() != 0) {
assSubColor = Integer.toHexString(configuration.getSubsColor());
if (assSubColor.length() > 2) {
assSubColor = assSubColor.substring(2) + "00";
}
}
sb.append("-ass-color ").append(assSubColor).append(" -ass-border-color 00000000 -ass-font-scale ").append(configuration.getMencoderAssScale());
// set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
// set font with -font option, workaround for
// https://github.com/Happy-Neko/ps3mediaserver/commit/52e62203ea12c40628de1869882994ce1065446a#commitcomment-990156 bug
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
sb.append(" -ass-force-style FontName=").append(configuration.getMencoderFont()).append(",");
} else {
String font = CodecUtil.getDefaultFontPath();
if (StringUtils.isNotBlank(font)) {
// Variable "font" contains a font path instead of a font name.
// Does "-ass-force-style" support font paths? In tests on OSX
// the font path is ignored (Outline, Shadow and MarginV are
// used, though) and the "-font" definition is used instead.
// See: https://github.com/ps3mediaserver/ps3mediaserver/pull/14
sb.append(" -font ").append(font).append(" ");
sb.append(" -ass-force-style FontName=").append(font).append(",");
} else {
sb.append(" -font Arial ");
sb.append(" -ass-force-style FontName=Arial,");
}
}
// Add to the subtitle margin if overscan compensation is being used
// This keeps the subtitle text inside the frame instead of in the border
if (intOCH > 0) {
subtitleMargin = (media.getHeight() / 100) * intOCH;
}
sb.append("Outline=").append(configuration.getMencoderAssOutline()).append(",Shadow=").append(configuration.getMencoderAssShadow());
try {
userMargin = Integer.parseInt(configuration.getMencoderAssMargin());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse SSA margin from \"" + configuration.getMencoderAssMargin() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(",MarginV=").append(subtitleMargin).append(" ");
} else if (intOCH > 0) {
sb.append("-ass-force-style MarginV=").append(subtitleMargin).append(" ");
}
if (params.sid.getType() != DLNAMediaSubtitle.EMBEDDED) {
// Workaround for MPlayer #2041, remove when that bug is fixed
sb.append("-noflip-hebrew ");
}
// use PLAINTEXT formating
} else {
// set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
} else {
String font = CodecUtil.getDefaultFontPath();
if (StringUtils.isNotBlank(font)) {
sb.append(" -font ").append(font).append(" ");
}
}
sb.append(" -subfont-text-scale ").append(configuration.getMencoderNoAssScale());
sb.append(" -subfont-outline ").append(configuration.getMencoderNoAssOutline());
sb.append(" -subfont-blur ").append(configuration.getMencoderNoAssBlur());
// Add to the subtitle margin if overscan compensation is being used
// This keeps the subtitle text inside the frame instead of in the border
if (intOCH > 0) {
subtitleMargin = intOCH;
}
try {
userMargin = Integer.parseInt(configuration.getMencoderNoAssSubPos());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse subpos from \"" + configuration.getMencoderNoAssSubPos() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(" -subpos ").append(100 - subtitleMargin).append(" ");
}
// Common subtitle options
// Use fontconfig if enabled
sb.append("-").append(configuration.isMencoderFontConfig() ? "" : "no").append("fontconfig ");
// Apply DVD/VOBsub subtitle quality
if (params.sid.getType() == DLNAMediaSubtitle.VOBSUB && configuration.getMencoderVobsubSubtitleQuality() != null) {
String subtitleQuality = configuration.getMencoderVobsubSubtitleQuality();
sb.append("-spuaa ").append(subtitleQuality).append(" ");
}
if (!params.sid.isFileUtf8() && !configuration.isMencoderDisableSubs() && configuration.getMencoderSubCp() != null && configuration.getMencoderSubCp().length() > 0) {
sb.append("-subcp ").append(configuration.getMencoderSubCp()).append(" ");
if (configuration.isMencoderSubFribidi()) {
sb.append("-fribidi-charset ").append(configuration.getMencoderSubCp()).append(" ");
}
}
}
st = new StringTokenizer(sb.toString(), " ");
int oldc = overriddenMainArgs.length;
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
i = oldc;
handleToken = false;
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (handleToken) {
s = "-quiet";
handleToken = false;
}
if ((!configuration.isMencoderAss() || dvd) && s.contains("-ass")) {
s = "-quiet";
handleToken = true;
}
overriddenMainArgs[i++] = s;
}
String cmdArray[] = new String[18 + args().length];
cmdArray[0] = executable();
// Choose which time to seek to
cmdArray[1] = "-ss";
if (params.timeseek > 0) {
cmdArray[2] = "" + params.timeseek;
} else {
cmdArray[2] = "0";
}
if (dvd) {
cmdArray[3] = "-dvd-device";
} else {
cmdArray[3] = "-quiet";
}
if (avisynth && !fileName.toLowerCase().endsWith(".iso")) {
File avsFile = FFMpegVideo.getAVSScript(fileName, params.sid, params.fromFrame, params.toFrame);
cmdArray[4] = ProcessUtil.getShortFileNameIfWideChars(avsFile.getAbsolutePath());
} else {
cmdArray[4] = fileName;
if (params.stdin != null) {
cmdArray[4] = "-";
}
}
if (dvd) {
cmdArray[5] = "dvd://" + media.getDvdtrack();
} else {
cmdArray[5] = "-quiet";
}
String arguments[] = args();
for (i = 0; i < arguments.length; i++) {
cmdArray[6 + i] = arguments[i];
if (arguments[i].contains("format=mpeg2") && media.getAspect() != null && media.getValidAspect(true) != null) {
cmdArray[6 + i] += ":vaspect=" + media.getValidAspect(true);
}
}
cmdArray[cmdArray.length - 12] = "-quiet";
cmdArray[cmdArray.length - 11] = "-quiet";
cmdArray[cmdArray.length - 10] = "-quiet";
cmdArray[cmdArray.length - 9] = "-quiet";
if (!dts && !pcm && !avisynth() && params.aid != null && media.getAudioCodes().size() > 1) {
cmdArray[cmdArray.length - 12] = "-aid";
boolean lavf = false; // Need to add support for LAVF demuxing
cmdArray[cmdArray.length - 11] = "" + (lavf ? params.aid.getId() + 1 : params.aid.getId());
}
/*
* TODO: Move the following block up with the rest of the
* subtitle stuff
*/
if (subString == null && params.sid != null) {
cmdArray[cmdArray.length - 10] = "-sid";
cmdArray[cmdArray.length - 9] = "" + params.sid.getId();
} else if (subString != null && !avisynth()) { // Trick necessary for MEncoder to skip the internal embedded track ?
cmdArray[cmdArray.length - 10] = "-sid";
cmdArray[cmdArray.length - 9] = "100";
} else if (subString == null) { // Trick necessary for MEncoder to not display the internal embedded track
cmdArray[cmdArray.length - 10] = "-subdelay";
cmdArray[cmdArray.length - 9] = "20000";
}
cmdArray[cmdArray.length - 8] = "-quiet";
cmdArray[cmdArray.length - 7] = "-quiet";
if (configuration.isMencoderForceFps() && !configuration.isFix25FPSAvMismatch()) {
cmdArray[cmdArray.length - 8] = "-fps";
cmdArray[cmdArray.length - 7] = "24000/1001";
}
cmdArray[cmdArray.length - 6] = "-ofps";
cmdArray[cmdArray.length - 5] = "24000/1001";
String frameRate = null;
if (media != null) {
frameRate = media.getValidFps(true);
}
if (frameRate != null) {
cmdArray[cmdArray.length - 5] = frameRate;
if (configuration.isMencoderForceFps()) {
if (configuration.isFix25FPSAvMismatch()) {
cmdArray[cmdArray.length - 8] = "-mc";
cmdArray[cmdArray.length - 7] = "0.005";
cmdArray[cmdArray.length - 5] = "25";
} else {
cmdArray[cmdArray.length - 7] = cmdArray[cmdArray.length - 5];
}
}
}
/*
* TODO: Move the following block up with the rest of the
* subtitle stuff
*/
if (subString != null && !configuration.isMencoderDisableSubs() && !avisynth()) {
if (params.sid.getType() == DLNAMediaSubtitle.VOBSUB) {
cmdArray[cmdArray.length - 4] = "-vobsub";
cmdArray[cmdArray.length - 3] = subString.substring(0, subString.length() - 4);
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-slang";
cmdArray[cmdArray.length - 3] = "" + params.sid.getLang();
} else {
cmdArray[cmdArray.length - 4] = "-sub";
cmdArray[cmdArray.length - 3] = subString.replace(",", "\\,"); // Commas in MEncoder separate multiple subtitle files
if (params.sid.isFileUtf8() && params.sid.getPlayableFile() != null) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 1);
cmdArray[cmdArray.length - 3] = "-utf8";
}
}
} else {
cmdArray[cmdArray.length - 4] = "-quiet";
cmdArray[cmdArray.length - 3] = "-quiet";
}
if (fileName.toLowerCase().endsWith(".evo")) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-psprobe";
cmdArray[cmdArray.length - 3] = "10000";
}
boolean deinterlace = configuration.isMencoderYadif();
// Check if the media renderer supports this resolution
boolean isResolutionTooHighForRenderer = params.mediaRenderer.isVideoRescale()
&& media != null
&& (
(media.getWidth() > params.mediaRenderer.getMaxVideoWidth())
||
(media.getHeight() > params.mediaRenderer.getMaxVideoHeight())
);
// Video scaler and overscan compensation
boolean scaleBool = isResolutionTooHighForRenderer
|| (configuration.isMencoderScaler() && (configuration.getMencoderScaleX() != 0 || configuration.getMencoderScaleY() != 0))
|| (intOCW > 0 || intOCH > 0);
if ((deinterlace || scaleBool) && !avisynth()) {
StringBuilder vfValueOverscanPrepend = new StringBuilder();
StringBuilder vfValueOverscanMiddle = new StringBuilder();
StringBuilder vfValueVS = new StringBuilder();
StringBuilder vfValueComplete = new StringBuilder();
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-vf";
String deinterlaceComma = "";
int scaleWidth = 0;
int scaleHeight = 0;
double rendererAspectRatio;
// Set defaults
if (media != null && media.getWidth() > 0 && media.getHeight() > 0) {
scaleWidth = media.getWidth();
scaleHeight = media.getHeight();
}
/*
* Implement overscan compensation settings
*
* This feature takes into account aspect ratio,
* making it less blunt than the Video Scaler option
*/
if (intOCW > 0 || intOCH > 0) {
int intOCWPixels = (media.getWidth() / 100) * intOCW;
int intOCHPixels = (media.getHeight() / 100) * intOCH;
scaleWidth = scaleWidth + intOCWPixels;
scaleHeight = scaleHeight + intOCHPixels;
// See if the video needs to be scaled down
if (
(scaleWidth > params.mediaRenderer.getMaxVideoWidth()) ||
(scaleHeight > params.mediaRenderer.getMaxVideoHeight())
) {
double overscannedAspectRatio = scaleWidth / scaleHeight;
rendererAspectRatio = params.mediaRenderer.getMaxVideoWidth() / params.mediaRenderer.getMaxVideoHeight();
if (overscannedAspectRatio > rendererAspectRatio) {
// Limit video by width
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / overscannedAspectRatio);
} else {
// Limit video by height
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * overscannedAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
vfValueOverscanPrepend.append("softskip,expand=-").append(intOCWPixels).append(":-").append(intOCHPixels);
vfValueOverscanMiddle.append(",scale=").append(scaleWidth).append(":").append(scaleHeight);
}
/*
* Video Scaler and renderer-specific resolution-limiter
*/
if (configuration.isMencoderScaler()) {
// Use the manual, user-controlled scaler
if (configuration.getMencoderScaleX() != 0) {
if (configuration.getMencoderScaleX() <= params.mediaRenderer.getMaxVideoWidth()) {
scaleWidth = configuration.getMencoderScaleX();
} else {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
}
}
if (configuration.getMencoderScaleY() != 0) {
if (configuration.getMencoderScaleY() <= params.mediaRenderer.getMaxVideoHeight()) {
scaleHeight = configuration.getMencoderScaleY();
} else {
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", your Video Scaler setting");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
/*
* The video resolution is too big for the renderer so we need to scale it down
*/
} else if (
media != null &&
media.getWidth() > 0 &&
media.getHeight() > 0 &&
(
media.getWidth() > params.mediaRenderer.getMaxVideoWidth() ||
media.getHeight() > params.mediaRenderer.getMaxVideoHeight()
)
) {
double videoAspectRatio = (double) media.getWidth() / (double) media.getHeight();
rendererAspectRatio = (double) params.mediaRenderer.getMaxVideoWidth() / (double) params.mediaRenderer.getMaxVideoHeight();
/*
* First we deal with some exceptions, then if they are not matched we will
* let the renderer limits work.
*
* This is so, for example, we can still define a maximum resolution of
* 1920x1080 in the renderer config file but still support 1920x1088 when
* it's needed, otherwise we would either resize 1088 to 1080, meaning the
* ugly (unused) bottom 8 pixels would be displayed, or we would limit all
* videos to 1088 causing the bottom 8 meaningful pixels to be cut off.
*/
if (media.getWidth() == 3840 && media.getHeight() == 1080) {
// Full-SBS
scaleWidth = 1920;
scaleHeight = 1080;
} else if (media.getWidth() == 1920 && media.getHeight() == 2160) {
// Full-OU
scaleWidth = 1920;
scaleHeight = 1080;
} else if (media.getWidth() == 1920 && media.getHeight() == 1088) {
// SAT capture
scaleWidth = 1920;
scaleHeight = 1088;
} else {
// Passed the exceptions, now we allow the renderer to define the limits
if (videoAspectRatio > rendererAspectRatio) {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / videoAspectRatio);
} else {
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * videoAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", the maximum your renderer supports");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
}
// Put the string together taking into account overscan compensation and video scaler
if (intOCW > 0 || intOCH > 0) {
vfValueComplete.append(vfValueOverscanPrepend).append(vfValueOverscanMiddle).append(",harddup");
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", to fit your overscan compensation");
} else {
vfValueComplete.append(vfValueVS);
}
if (deinterlace) {
deinterlaceComma = ",";
}
cmdArray[cmdArray.length - 3] = (deinterlace ? "yadif" : "") + (scaleBool ? deinterlaceComma + vfValueComplete : "");
}
/*
* The PS3 and possibly other renderers display videos incorrectly
* if the dimensions aren't divisible by 4, so if that is the
* case we scale it down to the nearest 4.
* This fixes the long-time bug of videos displaying in black and
* white with diagonal strips of colour, weird one.
*
* TODO: Integrate this with the other stuff so that "scale" only
* ever appears once in the MEncoder CMD.
*/
if (media != null && (media.getWidth() % 4 != 0) || media.getHeight() % 4 != 0) {
int newWidth;
int newHeight;
newWidth = (media.getWidth() / 4) * 4;
newHeight = (media.getHeight() / 4) * 4;
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-vf";
cmdArray[cmdArray.length - 3] = "softskip,scale=" + newWidth + ":" + newHeight;
}
if (configuration.getMencoderMT() && !avisynth && !dvd && !(media.getCodecV() != null && (media.getCodecV().equals("mpeg2video")))) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-lavdopts";
cmdArray[cmdArray.length - 3] = "fast";
}
boolean noMC0NoSkip = false;
if (media != null) {
String sArgs[] = getSpecificCodecOptions(configuration.getCodecSpecificConfig(), media, params, fileName, subString, configuration.isMencoderIntelligentSync(), false);
if (sArgs != null && sArgs.length > 0) {
boolean vfConsumed = false;
boolean afConsumed = false;
for (int s = 0; s < sArgs.length; s++) {
if (sArgs[s].equals("-noass")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-ass")) {
cmdArray[c] = "-quiet";
}
}
} else if (sArgs[s].equals("-ofps")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-ofps")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-fps")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-fps")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-ovc")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-ovc")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-channels")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-channels")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-oac")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-oac")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-quality")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-lavcopts")) {
cmdArray[c + 1] = "autoaspect=1:vcodec=" + vcodec +
":acodec=" + (configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3") +
":abitrate=" + CodecUtil.getAC3Bitrate(configuration, params.aid) +
":threads=" + configuration.getMencoderMaxThreads() + ":" + sArgs[s + 1];
addMaximumBitrateConstraints(cmdArray[c + 1], media, cmdArray[c + 1], params.mediaRenderer, "");
sArgs[s + 1] = "-quality";
s++;
}
}
} else if (sArgs[s].equals("-mpegopts")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-mpegopts")) {
cmdArray[c + 1] += ":" + sArgs[s + 1];
sArgs[s + 1] = "-mpegopts";
s++;
}
}
} else if (sArgs[s].equals("-vf")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-vf")) {
cmdArray[c + 1] += "," + sArgs[s + 1];
sArgs[s + 1] = "-vf";
s++;
vfConsumed = true;
}
}
} else if (sArgs[s].equals("-af")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-af")) {
cmdArray[c + 1] += "," + sArgs[s + 1];
sArgs[s + 1] = "-af";
s++;
afConsumed = true;
}
}
} else if (sArgs[s].equals("-nosync")) {
noMC0NoSkip = true;
} else if (sArgs[s].equals("-mc")) {
noMC0NoSkip = true;
}
}
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + sArgs.length);
for (int s = 0; s < sArgs.length; s++) {
if (sArgs[s].equals("-noass") || sArgs[s].equals("-nomux") || sArgs[s].equals("-mpegopts") || (sArgs[s].equals("-vf") & vfConsumed) || (sArgs[s].equals("-af") && afConsumed) || sArgs[s].equals("-quality") || sArgs[s].equals("-nosync") || sArgs[s].equals("-mt")) {
cmdArray[cmdArray.length - sArgs.length - 2 + s] = "-quiet";
} else {
cmdArray[cmdArray.length - sArgs.length - 2 + s] = sArgs[s];
}
}
}
}
if ((pcm || dts || mux) || (configuration.isMencoderNoOutOfSync() && !noMC0NoSkip)) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 3);
cmdArray[cmdArray.length - 5] = "-mc";
cmdArray[cmdArray.length - 4] = "0";
cmdArray[cmdArray.length - 3] = "-noskip";
if (configuration.isFix25FPSAvMismatch()) {
cmdArray[cmdArray.length - 4] = "0.005";
cmdArray[cmdArray.length - 3] = "-quiet";
}
}
if (params.timeend > 0) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-endpos";
cmdArray[cmdArray.length - 3] = "" + params.timeend;
}
String rate = "48000";
if (params.mediaRenderer.isXBOX()) {
rate = "44100";
}
// force srate -> cause ac3's mencoder doesn't like anything other than 48khz
if (media != null && !pcm && !dts && !mux) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 4);
cmdArray[cmdArray.length - 6] = "-af";
cmdArray[cmdArray.length - 5] = "lavcresample=" + rate;
cmdArray[cmdArray.length - 4] = "-srate";
cmdArray[cmdArray.length - 3] = rate;
}
// add a -cache option for piped media (e.g. rar/zip file entries):
// https://code.google.com/p/ps3mediaserver/issues/detail?id=911
if (params.stdin != null) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-cache";
cmdArray[cmdArray.length - 3] = "8192";
}
PipeProcess pipe = null;
cmdArray[cmdArray.length - 2] = "-o";
ProcessWrapperImpl pw = null;
if (pcm || dts || mux) {
boolean channels_filter_present = false;
for (String s : cmdArray) {
if (StringUtils.isNotBlank(s) && s.startsWith("channels")) {
channels_filter_present = true;
break;
}
}
if (params.avidemux) {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dts || mux) ? null : params);
params.input_pipes[0] = pipe;
cmdArray[cmdArray.length - 1] = pipe.getInputPipe();
if (pcm && !channels_filter_present) {
String mixer = CodecUtil.getMixerOutput(true, configuration.getAudioChannelCount(), configuration.getAudioChannelCount());
if (StringUtils.isNotBlank(mixer)) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 2] = "-af";
cmdArray[cmdArray.length - 1] = mixer;
}
}
pw = new ProcessWrapperImpl(cmdArray, params);
PipeProcess videoPipe = new PipeProcess("videoPipe" + System.currentTimeMillis(), "out", "reconnect");
PipeProcess audioPipe = new PipeProcess("audioPipe" + System.currentTimeMillis(), "out", "reconnect");
ProcessWrapper videoPipeProcess = videoPipe.getPipeProcess();
ProcessWrapper audioPipeProcess = audioPipe.getPipeProcess();
params.output_pipes[0] = videoPipe;
params.output_pipes[1] = audioPipe;
pw.attachProcess(videoPipeProcess);
pw.attachProcess(audioPipeProcess);
videoPipeProcess.runInNewThread();
audioPipeProcess.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
videoPipe.deleteLater();
audioPipe.deleteLater();
} else {
// remove the -oac switch, otherwise too many video packets errors appears again
for (int s = 0; s < cmdArray.length; s++) {
if (cmdArray[s].equals("-oac")) {
cmdArray[s] = "-nosound";
cmdArray[s + 1] = "-nosound";
break;
}
}
pipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts");
TSMuxerVideo ts = new TSMuxerVideo(configuration);
File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta");
String cmd[] = new String[]{ts.executable(), f.getAbsolutePath(), pipe.getInputPipe()};
pw = new ProcessWrapperImpl(cmd, params);
PipeIPCProcess ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true);
cmdArray[cmdArray.length - 1] = ffVideoPipe.getInputPipe();
OutputParams ffparams = new OutputParams(configuration);
ffparams.maxBufferSize = 1;
ffparams.stdin = params.stdin;
ProcessWrapperImpl ffVideo = new ProcessWrapperImpl(cmdArray, ffparams);
ProcessWrapper ff_video_pipe_process = ffVideoPipe.getPipeProcess();
pw.attachProcess(ff_video_pipe_process);
ff_video_pipe_process.runInNewThread();
ffVideoPipe.deleteLater();
pw.attachProcess(ffVideo);
ffVideo.runInNewThread();
String aid = null;
if (media != null && media.getAudioCodes().size() > 1 && params.aid != null) {
aid = params.aid.getId() + "";
}
PipeIPCProcess ffAudioPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true);
StreamModifier sm = new StreamModifier();
sm.setPcm(pcm);
sm.setDtsembed(dts);
sm.setNbchannels(sm.isDtsembed() ? 2 : CodecUtil.getRealChannelCount(configuration, params.aid));
sm.setSampleFrequency(48000);
sm.setBitspersample(16);
String mixer = CodecUtil.getMixerOutput(!sm.isDtsembed(), sm.getNbchannels(), configuration.getAudioChannelCount());
// it seems the -really-quiet prevents mencoder to stop the pipe output after some time...
// -mc 0.1 make the DTS-HD extraction works better with latest mencoder builds, and makes no impact on the regular DTS one
String ffmpegLPCMextract[] = new String[]{
executable(),
"-ss", "0",
fileName,
"-really-quiet",
"-msglevel", "statusline=2",
"-channels", "" + sm.getNbchannels(),
"-ovc", "copy",
"-of", "rawaudio",
"-mc", dts ? "0.1" : "0",
"-noskip",
(aid == null) ? "-quiet" : "-aid", (aid == null) ? "-quiet" : aid,
"-oac", sm.isDtsembed() ? "copy" : "pcm",
(StringUtils.isNotBlank(mixer) && !channels_filter_present) ? "-af" : "-quiet", (StringUtils.isNotBlank(mixer) && !channels_filter_present) ? mixer : "-quiet",
"-srate", "48000",
"-o", ffAudioPipe.getInputPipe()
};
if (!params.mediaRenderer.isMuxDTSToMpeg()) { // no need to use the PCM trick when media renderer supports DTS
ffAudioPipe.setModifier(sm);
}
if (media != null && media.getDvdtrack() > 0) {
ffmpegLPCMextract[3] = "-dvd-device";
ffmpegLPCMextract[4] = fileName;
ffmpegLPCMextract[5] = "dvd://" + media.getDvdtrack();
} else if (params.stdin != null) {
ffmpegLPCMextract[3] = "-";
}
if (fileName.toLowerCase().endsWith(".evo")) {
ffmpegLPCMextract[4] = "-psprobe";
ffmpegLPCMextract[5] = "1000000";
}
if (params.timeseek > 0) {
ffmpegLPCMextract[2] = "" + params.timeseek;
}
OutputParams ffaudioparams = new OutputParams(configuration);
ffaudioparams.maxBufferSize = 1;
ffaudioparams.stdin = params.stdin;
ProcessWrapperImpl ffAudio = new ProcessWrapperImpl(ffmpegLPCMextract, ffaudioparams);
params.stdin = null;
PrintWriter pwMux = new PrintWriter(f);
pwMux.println("MUXOPT --no-pcr-on-video-pid --no-asyncio --new-audio-pes --vbr --vbv-len=500");
String videoType = "V_MPEG-2";
if (params.no_videoencode && params.forceType != null) {
videoType = params.forceType;
}
String fps = "";
if (params.forceFps != null) {
fps = "fps=" + params.forceFps + ", ";
}
String audioType = "A_LPCM";
if (params.mediaRenderer.isMuxDTSToMpeg()) {
audioType = "A_DTS";
}
if (params.lossyaudio) {
audioType = "A_AC3";
}
pwMux.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + fps + "level=4.1, insertSEI, contSPS, track=1");
pwMux.println(audioType + ", \"" + ffAudioPipe.getOutputPipe() + "\", track=2");
pwMux.close();
ProcessWrapper pipe_process = pipe.getPipeProcess();
pw.attachProcess(pipe_process);
pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
params.input_pipes[0] = pipe;
ProcessWrapper ff_pipe_process = ffAudioPipe.getPipeProcess();
pw.attachProcess(ff_pipe_process);
ff_pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
ffAudioPipe.deleteLater();
pw.attachProcess(ffAudio);
ffAudio.runInNewThread();
}
} else {
boolean directpipe = Platform.isMac() || Platform.isFreeBSD();
if (directpipe) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 3);
cmdArray[cmdArray.length - 3] = "-really-quiet";
cmdArray[cmdArray.length - 2] = "-msglevel";
cmdArray[cmdArray.length - 1] = "statusline=2";
cmdArray[cmdArray.length - 4] = "-";
params.input_pipes = new PipeProcess[2];
} else {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dts || mux) ? null : params);
params.input_pipes[0] = pipe;
cmdArray[cmdArray.length - 1] = pipe.getInputPipe();
}
cmdArray = finalizeTranscoderArgs(
this,
fileName,
dlna,
media,
params,
cmdArray
);
pw = new ProcessWrapperImpl(cmdArray, params);
if (!directpipe) {
ProcessWrapper mkfifo_process = pipe.getPipeProcess();
pw.attachProcess(mkfifo_process);
mkfifo_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
}
}
pw.runInNewThread();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
return pw;
}
| public ProcessWrapper launchTranscode(
String fileName,
DLNAResource dlna,
DLNAMediaInfo media,
OutputParams params
) throws IOException {
params.manageFastStart();
boolean avisynth = avisynth();
setAudioAndSubs(fileName, media, params, configuration);
String subString = null;
if (params.sid != null && params.sid.getPlayableFile() != null) {
subString = ProcessUtil.getShortFileNameIfWideChars(params.sid.getPlayableFile().getAbsolutePath());
}
InputFile newInput = new InputFile();
newInput.setFilename(fileName);
newInput.setPush(params.stdin);
dvd = false;
if (media != null && media.getDvdtrack() > 0) {
dvd = true;
}
// don't honour "Switch to tsMuxeR..." if the resource is being streamed via an MEncoder entry in
// the #--TRANSCODE--# folder
boolean forceMencoder = !configuration.getHideTranscodeEnabled()
&& dlna.isNoName() // XXX remove this? http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12149
&& (dlna.getParent() instanceof FileTranscodeVirtualFolder);
ovccopy = false;
int intOCW = 0;
int intOCH = 0;
try {
intOCW = Integer.parseInt(configuration.getMencoderOverscanCompensationWidth());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation width: \"{}\"", configuration.getMencoderOverscanCompensationWidth());
}
try {
intOCH = Integer.parseInt(configuration.getMencoderOverscanCompensationHeight());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation height: \"{}\"", configuration.getMencoderOverscanCompensationHeight());
}
if (
!forceMencoder &&
params.sid == null &&
!dvd &&
!avisynth() &&
media != null && (
media.isVideoPS3Compatible(newInput) ||
!params.mediaRenderer.isH264Level41Limited()
) &&
media.isMuxable(params.mediaRenderer) &&
configuration.isMencoderMuxWhenCompatible() &&
params.mediaRenderer.isMuxH264MpegTS() && (
intOCW == 0 &&
intOCH == 0
)
) {
String sArgs[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
subString,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : sArgs) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
TSMuxerVideo tv = new TSMuxerVideo(configuration);
params.forceFps = media.getValidFps(false);
if (media.getCodecV().equals("h264")) {
params.forceType = "V_MPEG4/ISO/AVC";
} else if (media.getCodecV().startsWith("mpeg2")) {
params.forceType = "V_MPEG-2";
} else if (media.getCodecV().equals("vc1")) {
params.forceType = "V_MS/VFW/WVC1";
}
return tv.launchTranscode(fileName, dlna, media, params);
}
} else if (params.sid == null && dvd && configuration.isMencoderRemuxMPEG2() && params.mediaRenderer.isMpeg2Supported()) {
String sArgs[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
subString,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : sArgs) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
ovccopy = true;
}
}
String vcodec = "mpeg2video";
wmv = false;
if (params.mediaRenderer.isTranscodeToWMV()) {
wmv = true;
vcodec = "wmv2"; // http://wiki.megaframe.org/wiki/Ubuntu_XBOX_360#MEncoder not usable in streaming
}
mpegts = false;
if (params.mediaRenderer.isTranscodeToMPEGTSAC3()) {
mpegts = true;
}
oaccopy = false;
// disable AC3 remux for stereo tracks with 384 kbits bitrate and PS3 renderer (PS3 FW bug?)
boolean ps3_and_stereo_and_384_kbits = params.aid != null && (params.mediaRenderer.getRendererName().equalsIgnoreCase("Playstation 3") && params.aid.getNrAudioChannels() == 2) && (params.aid.getBitRate() > 370000 && params.aid.getBitRate() < 400000);
if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && !ps3_and_stereo_and_384_kbits && !avisynth() && params.mediaRenderer.isTranscodeToAC3()) {
// AC3 remux takes priority
oaccopy = true;
} else {
// now check for DTS remux and LPCM streaming
dts = configuration.isDTSEmbedInPCM() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
) && params.aid != null &&
params.aid.isDTS() &&
!avisynth() &&
params.mediaRenderer.isDTSPlayable();
pcm = configuration.isMencoderUsePcm() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
)
// disable LPCM transcoding for MP4 container with non-H264 video as workaround for mencoder's A/V sync bug
&& !(media.getContainer().equals("mp4") && !media.getCodecV().equals("h264"))
&& params.aid != null &&
(
(params.aid.isDTS() && params.aid.getNrAudioChannels() <= 6) || // disable 7.1 DTS-HD => LPCM because of channels mapping bug
params.aid.isLossless() ||
params.aid.isTrueHD() ||
(
!configuration.isMencoderUsePcmForHQAudioOnly() &&
(
params.aid.isAC3() ||
params.aid.isMP3() ||
params.aid.isAAC() ||
params.aid.isVorbis() ||
// disable WMA to LPCM transcoding because of mencoder's channel mapping bug
// (see CodecUtil.getMixerOutput)
// params.aid.isWMA() ||
params.aid.isMpegAudio()
)
)
) && params.mediaRenderer.isLPCMPlayable();
}
if (dts || pcm) {
if (dts) {
oaccopy = true;
}
params.losslessaudio = true;
params.forceFps = media.getValidFps(false);
}
// mpeg2 remux still buggy with mencoder :\
if (!pcm && !dts && !mux && ovccopy) {
ovccopy = false;
}
if (pcm && avisynth()) {
params.avidemux = true;
}
String add = "";
String rendererMencoderOptions = params.mediaRenderer.getCustomMencoderOptions(); // default: empty string
String mencoderCustomOptions = configuration.getMencoderCustomOptions(); // default: empty string
String combinedCustomOptions = StringUtils.defaultString(mencoderCustomOptions)
+ " "
+ StringUtils.defaultString(rendererMencoderOptions);
if (!combinedCustomOptions.contains("-lavdopts")) {
add = " -lavdopts debug=0";
}
int channels = wmv ? 2 : configuration.getAudioChannelCount();
if (media != null && params.aid != null) {
channels = wmv ? 2 : CodecUtil.getRealChannelCount(configuration, params.aid);
}
LOGGER.trace("channels=" + channels);
if (StringUtils.isNotBlank(rendererMencoderOptions)) {
/*
* ignore the renderer's custom MEncoder options if a) we're streaming a DVD (i.e. via dvd://)
* or b) the renderer's MEncoder options contain overscan settings (those are handled
* separately)
*/
// XXX we should weed out the unused/unwanted settings and keep the rest
// (see sanitizeArgs()) rather than ignoring the options entirely
if (rendererMencoderOptions.contains("expand=") || dvd) {
rendererMencoderOptions = null;
}
}
StringTokenizer st = new StringTokenizer(
"-channels " + channels
+ (StringUtils.isNotBlank(mencoderCustomOptions) ? " " + mencoderCustomOptions : "")
+ (StringUtils.isNotBlank(rendererMencoderOptions) ? " " + rendererMencoderOptions : "")
+ add,
" "
);
// XXX why does this field (which is used to populate the array returned by args(),
// called below) store the renderer-specific (i.e. not global) MEncoder options?
overriddenMainArgs = new String[st.countTokens()];
int i = 0;
boolean handleToken = false;
int nThreads = (dvd || fileName.toLowerCase().endsWith("dvr-ms")) ?
1 :
configuration.getMencoderMaxThreads();
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (handleToken) {
token += ":threads=" + nThreads;
if (configuration.getSkipLoopFilterEnabled() && !avisynth()) {
token += ":skiploopfilter=all";
}
handleToken = false;
}
if (token.toLowerCase().contains("lavdopts")) {
handleToken = true;
}
overriddenMainArgs[i++] = token;
}
if (configuration.getMencoderMainSettings() != null) {
String mainConfig = configuration.getMencoderMainSettings();
String customSettings = params.mediaRenderer.getCustomMencoderQualitySettings();
// Custom settings in PMS may override the settings of the saved configuration
if (StringUtils.isNotBlank(customSettings)) {
mainConfig = customSettings;
}
if (mainConfig.contains("/*")) {
mainConfig = mainConfig.substring(mainConfig.indexOf("/*"));
}
// Ditlew - WDTV Live (+ other byte asking clients), CBR. This probably ought to be placed in addMaximumBitrateConstraints(..)
int cbr_bitrate = params.mediaRenderer.getCBRVideoBitrate();
String cbr_settings = (cbr_bitrate > 0) ? ":vrc_buf_size=5000:vrc_minrate=" + cbr_bitrate + ":vrc_maxrate=" + cbr_bitrate + ":vbitrate=" + ((cbr_bitrate > 16000) ? cbr_bitrate * 1000 : cbr_bitrate) : "";
String encodeSettings = "-lavcopts autoaspect=1:vcodec=" + vcodec +
(wmv ? ":acodec=wmav2:abitrate=448" : (cbr_settings + ":acodec=" + (configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3") +
":abitrate=" + CodecUtil.getAC3Bitrate(configuration, params.aid))) +
":threads=" + (wmv ? 1 : configuration.getMencoderMaxThreads()) +
("".equals(mainConfig) ? "" : ":" + mainConfig);
String audioType = "ac3";
if (dts) {
audioType = "dts";
} else if (pcm) {
audioType = "pcm";
}
encodeSettings = addMaximumBitrateConstraints(encodeSettings, media, mainConfig, params.mediaRenderer, audioType);
st = new StringTokenizer(encodeSettings, " ");
int oldc = overriddenMainArgs.length;
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
i = oldc;
while (st.hasMoreTokens()) {
overriddenMainArgs[i++] = st.nextToken();
}
}
boolean foundNoassParam = false;
if (media != null) {
String sArgs [] = getSpecificCodecOptions(configuration.getCodecSpecificConfig(), media, params, fileName, subString, configuration.isMencoderIntelligentSync(), false);
for (String s : sArgs) {
if (s.equals("-noass")) {
foundNoassParam = true;
}
}
}
StringBuilder sb = new StringBuilder();
// Set subtitles options
if (!configuration.isMencoderDisableSubs() && !avisynth() && params.sid != null) {
int subtitleMargin = 0;
int userMargin = 0;
// Use ASS flag (and therefore ASS font styles) for all subtitled files except vobsub, embedded, dvd and mp4 container with srt
// Note: The MP4 container with SRT rule is a workaround for MEncoder r30369. If there is ever a later version of MEncoder that supports external srt subs we should use that. As of r32848 that isn't the case
if (
(
(
params.sid.isFileUtf8() &&
params.sid.getType() == DLNAMediaSubtitle.EMBEDDED
) ||
params.sid.getType() != DLNAMediaSubtitle.EMBEDDED
) &&
params.sid.getType() != DLNAMediaSubtitle.VOBSUB &&
!(
params.sid.getType() == DLNAMediaSubtitle.SUBRIP &&
media.getContainer().equals("mp4")
) &&
configuration.isMencoderAss() && // GUI: enable subtitles formating
!foundNoassParam && // GUI: codec specific options
!dvd
) {
sb.append("-ass ");
// GUI: Override ASS subtitles style if requested (always for SRT subtitles)
if (
!configuration.isMencoderAssDefaultStyle() ||
params.sid.getType() == DLNAMediaSubtitle.SUBRIP ||
params.sid.getType() == DLNAMediaSubtitle.EMBEDDED
) {
String assSubColor = "ffffff00";
if (configuration.getSubsColor() != 0) {
assSubColor = Integer.toHexString(configuration.getSubsColor());
if (assSubColor.length() > 2) {
assSubColor = assSubColor.substring(2) + "00";
}
}
sb.append("-ass-color ").append(assSubColor).append(" -ass-border-color 00000000 -ass-font-scale ").append(configuration.getMencoderAssScale());
// set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
// set font with -font option, workaround for
// https://github.com/Happy-Neko/ps3mediaserver/commit/52e62203ea12c40628de1869882994ce1065446a#commitcomment-990156 bug
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
sb.append(" -ass-force-style FontName=").append(configuration.getMencoderFont()).append(",");
} else {
String font = CodecUtil.getDefaultFontPath();
if (StringUtils.isNotBlank(font)) {
// Variable "font" contains a font path instead of a font name.
// Does "-ass-force-style" support font paths? In tests on OSX
// the font path is ignored (Outline, Shadow and MarginV are
// used, though) and the "-font" definition is used instead.
// See: https://github.com/ps3mediaserver/ps3mediaserver/pull/14
sb.append(" -font ").append(font).append(" ");
sb.append(" -ass-force-style FontName=").append(font).append(",");
} else {
sb.append(" -font Arial ");
sb.append(" -ass-force-style FontName=Arial,");
}
}
// Add to the subtitle margin if overscan compensation is being used
// This keeps the subtitle text inside the frame instead of in the border
if (intOCH > 0) {
subtitleMargin = (media.getHeight() / 100) * intOCH;
}
sb.append("Outline=").append(configuration.getMencoderAssOutline()).append(",Shadow=").append(configuration.getMencoderAssShadow());
try {
userMargin = Integer.parseInt(configuration.getMencoderAssMargin());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse SSA margin from \"" + configuration.getMencoderAssMargin() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(",MarginV=").append(subtitleMargin).append(" ");
} else if (intOCH > 0) {
sb.append("-ass-force-style MarginV=").append(subtitleMargin).append(" ");
}
if (params.sid.getType() != DLNAMediaSubtitle.EMBEDDED) {
// Workaround for MPlayer #2041, remove when that bug is fixed
sb.append("-noflip-hebrew ");
}
// use PLAINTEXT formating
} else {
// set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
} else {
String font = CodecUtil.getDefaultFontPath();
if (StringUtils.isNotBlank(font)) {
sb.append(" -font ").append(font).append(" ");
}
}
sb.append(" -subfont-text-scale ").append(configuration.getMencoderNoAssScale());
sb.append(" -subfont-outline ").append(configuration.getMencoderNoAssOutline());
sb.append(" -subfont-blur ").append(configuration.getMencoderNoAssBlur());
// Add to the subtitle margin if overscan compensation is being used
// This keeps the subtitle text inside the frame instead of in the border
if (intOCH > 0) {
subtitleMargin = intOCH;
}
try {
userMargin = Integer.parseInt(configuration.getMencoderNoAssSubPos());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse subpos from \"" + configuration.getMencoderNoAssSubPos() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(" -subpos ").append(100 - subtitleMargin).append(" ");
}
// Common subtitle options
// Use fontconfig if enabled
sb.append("-").append(configuration.isMencoderFontConfig() ? "" : "no").append("fontconfig ");
// Apply DVD/VOBsub subtitle quality
if (params.sid.getType() == DLNAMediaSubtitle.VOBSUB && configuration.getMencoderVobsubSubtitleQuality() != null) {
String subtitleQuality = configuration.getMencoderVobsubSubtitleQuality();
sb.append("-spuaa ").append(subtitleQuality).append(" ");
}
if (!params.sid.isFileUtf8() && !configuration.isMencoderDisableSubs() && configuration.getMencoderSubCp() != null && configuration.getMencoderSubCp().length() > 0) {
sb.append("-subcp ").append(configuration.getMencoderSubCp()).append(" ");
if (configuration.isMencoderSubFribidi()) {
sb.append("-fribidi-charset ").append(configuration.getMencoderSubCp()).append(" ");
}
}
}
st = new StringTokenizer(sb.toString(), " ");
int oldc = overriddenMainArgs.length;
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
i = oldc;
handleToken = false;
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (handleToken) {
s = "-quiet";
handleToken = false;
}
if ((!configuration.isMencoderAss() || dvd) && s.contains("-ass")) {
s = "-quiet";
handleToken = true;
}
overriddenMainArgs[i++] = s;
}
String cmdArray[] = new String[18 + args().length];
cmdArray[0] = executable();
// Choose which time to seek to
cmdArray[1] = "-ss";
if (params.timeseek > 0) {
cmdArray[2] = "" + params.timeseek;
} else {
cmdArray[2] = "0";
}
if (dvd) {
cmdArray[3] = "-dvd-device";
} else {
cmdArray[3] = "-quiet";
}
if (avisynth && !fileName.toLowerCase().endsWith(".iso")) {
File avsFile = FFMpegVideo.getAVSScript(fileName, params.sid, params.fromFrame, params.toFrame);
cmdArray[4] = ProcessUtil.getShortFileNameIfWideChars(avsFile.getAbsolutePath());
} else {
cmdArray[4] = fileName;
if (params.stdin != null) {
cmdArray[4] = "-";
}
}
if (dvd) {
cmdArray[5] = "dvd://" + media.getDvdtrack();
} else {
cmdArray[5] = "-quiet";
}
String arguments[] = args();
for (i = 0; i < arguments.length; i++) {
cmdArray[6 + i] = arguments[i];
if (arguments[i].contains("format=mpeg2") && media.getAspect() != null && media.getValidAspect(true) != null) {
cmdArray[6 + i] += ":vaspect=" + media.getValidAspect(true);
}
}
cmdArray[cmdArray.length - 12] = "-quiet";
cmdArray[cmdArray.length - 11] = "-quiet";
cmdArray[cmdArray.length - 10] = "-quiet";
cmdArray[cmdArray.length - 9] = "-quiet";
if (!dts && !pcm && !avisynth() && params.aid != null && media.getAudioCodes().size() > 1) {
cmdArray[cmdArray.length - 12] = "-aid";
boolean lavf = false; // Need to add support for LAVF demuxing
cmdArray[cmdArray.length - 11] = "" + (lavf ? params.aid.getId() + 1 : params.aid.getId());
}
/*
* TODO: Move the following block up with the rest of the
* subtitle stuff
*/
if (subString == null && params.sid != null) {
cmdArray[cmdArray.length - 10] = "-sid";
cmdArray[cmdArray.length - 9] = "" + params.sid.getId();
} else if (subString != null && !avisynth()) { // Trick necessary for MEncoder to skip the internal embedded track ?
cmdArray[cmdArray.length - 10] = "-sid";
cmdArray[cmdArray.length - 9] = "100";
} else if (subString == null) { // Trick necessary for MEncoder to not display the internal embedded track
cmdArray[cmdArray.length - 10] = "-subdelay";
cmdArray[cmdArray.length - 9] = "20000";
}
cmdArray[cmdArray.length - 8] = "-quiet";
cmdArray[cmdArray.length - 7] = "-quiet";
if (configuration.isMencoderForceFps() && !configuration.isFix25FPSAvMismatch()) {
cmdArray[cmdArray.length - 8] = "-fps";
cmdArray[cmdArray.length - 7] = "24000/1001";
}
cmdArray[cmdArray.length - 6] = "-ofps";
cmdArray[cmdArray.length - 5] = "24000/1001";
String frameRate = null;
if (media != null) {
frameRate = media.getValidFps(true);
}
if (frameRate != null) {
cmdArray[cmdArray.length - 5] = frameRate;
if (configuration.isMencoderForceFps()) {
if (configuration.isFix25FPSAvMismatch()) {
cmdArray[cmdArray.length - 8] = "-mc";
cmdArray[cmdArray.length - 7] = "0.005";
cmdArray[cmdArray.length - 5] = "25";
} else {
cmdArray[cmdArray.length - 7] = cmdArray[cmdArray.length - 5];
}
}
}
/*
* TODO: Move the following block up with the rest of the
* subtitle stuff
*/
if (subString != null && !configuration.isMencoderDisableSubs() && !avisynth()) {
if (params.sid.getType() == DLNAMediaSubtitle.VOBSUB) {
cmdArray[cmdArray.length - 4] = "-vobsub";
cmdArray[cmdArray.length - 3] = subString.substring(0, subString.length() - 4);
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-slang";
cmdArray[cmdArray.length - 3] = "" + params.sid.getLang();
} else {
cmdArray[cmdArray.length - 4] = "-sub";
cmdArray[cmdArray.length - 3] = subString.replace(",", "\\,"); // Commas in MEncoder separate multiple subtitle files
if (params.sid.isFileUtf8() && params.sid.getPlayableFile() != null) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 1);
cmdArray[cmdArray.length - 3] = "-utf8";
}
}
} else {
cmdArray[cmdArray.length - 4] = "-quiet";
cmdArray[cmdArray.length - 3] = "-quiet";
}
if (fileName.toLowerCase().endsWith(".evo")) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-psprobe";
cmdArray[cmdArray.length - 3] = "10000";
}
boolean deinterlace = configuration.isMencoderYadif();
// Check if the media renderer supports this resolution
boolean isResolutionTooHighForRenderer = params.mediaRenderer.isVideoRescale()
&& media != null
&& (
(media.getWidth() > params.mediaRenderer.getMaxVideoWidth())
||
(media.getHeight() > params.mediaRenderer.getMaxVideoHeight())
);
// Video scaler and overscan compensation
boolean scaleBool = isResolutionTooHighForRenderer
|| (configuration.isMencoderScaler() && (configuration.getMencoderScaleX() != 0 || configuration.getMencoderScaleY() != 0))
|| (intOCW > 0 || intOCH > 0);
if ((deinterlace || scaleBool) && !avisynth()) {
StringBuilder vfValueOverscanPrepend = new StringBuilder();
StringBuilder vfValueOverscanMiddle = new StringBuilder();
StringBuilder vfValueVS = new StringBuilder();
StringBuilder vfValueComplete = new StringBuilder();
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-vf";
String deinterlaceComma = "";
int scaleWidth = 0;
int scaleHeight = 0;
double rendererAspectRatio;
// Set defaults
if (media != null && media.getWidth() > 0 && media.getHeight() > 0) {
scaleWidth = media.getWidth();
scaleHeight = media.getHeight();
}
/*
* Implement overscan compensation settings
*
* This feature takes into account aspect ratio,
* making it less blunt than the Video Scaler option
*/
if (intOCW > 0 || intOCH > 0) {
int intOCWPixels = (media.getWidth() / 100) * intOCW;
int intOCHPixels = (media.getHeight() / 100) * intOCH;
scaleWidth = scaleWidth + intOCWPixels;
scaleHeight = scaleHeight + intOCHPixels;
// See if the video needs to be scaled down
if (
(scaleWidth > params.mediaRenderer.getMaxVideoWidth()) ||
(scaleHeight > params.mediaRenderer.getMaxVideoHeight())
) {
double overscannedAspectRatio = scaleWidth / scaleHeight;
rendererAspectRatio = params.mediaRenderer.getMaxVideoWidth() / params.mediaRenderer.getMaxVideoHeight();
if (overscannedAspectRatio > rendererAspectRatio) {
// Limit video by width
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / overscannedAspectRatio);
} else {
// Limit video by height
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * overscannedAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
vfValueOverscanPrepend.append("softskip,expand=-").append(intOCWPixels).append(":-").append(intOCHPixels);
vfValueOverscanMiddle.append(",scale=").append(scaleWidth).append(":").append(scaleHeight);
}
/*
* Video Scaler and renderer-specific resolution-limiter
*/
if (configuration.isMencoderScaler()) {
// Use the manual, user-controlled scaler
if (configuration.getMencoderScaleX() != 0) {
if (configuration.getMencoderScaleX() <= params.mediaRenderer.getMaxVideoWidth()) {
scaleWidth = configuration.getMencoderScaleX();
} else {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
}
}
if (configuration.getMencoderScaleY() != 0) {
if (configuration.getMencoderScaleY() <= params.mediaRenderer.getMaxVideoHeight()) {
scaleHeight = configuration.getMencoderScaleY();
} else {
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", your Video Scaler setting");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
/*
* The video resolution is too big for the renderer so we need to scale it down
*/
} else if (
media != null &&
media.getWidth() > 0 &&
media.getHeight() > 0 &&
(
media.getWidth() > params.mediaRenderer.getMaxVideoWidth() ||
media.getHeight() > params.mediaRenderer.getMaxVideoHeight()
)
) {
double videoAspectRatio = (double) media.getWidth() / (double) media.getHeight();
rendererAspectRatio = (double) params.mediaRenderer.getMaxVideoWidth() / (double) params.mediaRenderer.getMaxVideoHeight();
/*
* First we deal with some exceptions, then if they are not matched we will
* let the renderer limits work.
*
* This is so, for example, we can still define a maximum resolution of
* 1920x1080 in the renderer config file but still support 1920x1088 when
* it's needed, otherwise we would either resize 1088 to 1080, meaning the
* ugly (unused) bottom 8 pixels would be displayed, or we would limit all
* videos to 1088 causing the bottom 8 meaningful pixels to be cut off.
*/
if (media.getWidth() == 3840 && media.getHeight() == 1080) {
// Full-SBS
scaleWidth = 1920;
scaleHeight = 1080;
} else if (media.getWidth() == 1920 && media.getHeight() == 2160) {
// Full-OU
scaleWidth = 1920;
scaleHeight = 1080;
} else if (media.getWidth() == 1920 && media.getHeight() == 1088) {
// SAT capture
scaleWidth = 1920;
scaleHeight = 1088;
} else {
// Passed the exceptions, now we allow the renderer to define the limits
if (videoAspectRatio > rendererAspectRatio) {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / videoAspectRatio);
} else {
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * videoAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", the maximum your renderer supports");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
}
// Put the string together taking into account overscan compensation and video scaler
if (intOCW > 0 || intOCH > 0) {
vfValueComplete.append(vfValueOverscanPrepend).append(vfValueOverscanMiddle).append(",harddup");
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", to fit your overscan compensation");
} else {
vfValueComplete.append(vfValueVS);
}
if (deinterlace) {
deinterlaceComma = ",";
}
cmdArray[cmdArray.length - 3] = (deinterlace ? "yadif" : "") + (scaleBool ? deinterlaceComma + vfValueComplete : "");
}
/*
* The PS3 and possibly other renderers display videos incorrectly
* if the dimensions aren't divisible by 4, so if that is the
* case we scale it down to the nearest 4.
* This fixes the long-time bug of videos displaying in black and
* white with diagonal strips of colour, weird one.
*
* TODO: Integrate this with the other stuff so that "scale" only
* ever appears once in the MEncoder CMD.
*/
if (media != null && (media.getWidth() % 4 != 0) || media.getHeight() % 4 != 0) {
int newWidth;
int newHeight;
newWidth = (media.getWidth() / 4) * 4;
newHeight = (media.getHeight() / 4) * 4;
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-vf";
cmdArray[cmdArray.length - 3] = "softskip,scale=" + newWidth + ":" + newHeight;
}
if (configuration.getMencoderMT() && !avisynth && !dvd && !(media.getCodecV() != null && (media.getCodecV().equals("mpeg2video")))) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-lavdopts";
cmdArray[cmdArray.length - 3] = "fast";
}
boolean noMC0NoSkip = false;
if (media != null) {
String sArgs[] = getSpecificCodecOptions(configuration.getCodecSpecificConfig(), media, params, fileName, subString, configuration.isMencoderIntelligentSync(), false);
if (sArgs != null && sArgs.length > 0) {
boolean vfConsumed = false;
boolean afConsumed = false;
for (int s = 0; s < sArgs.length; s++) {
if (sArgs[s].equals("-noass")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-ass")) {
cmdArray[c] = "-quiet";
}
}
} else if (sArgs[s].equals("-ofps")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-ofps")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-fps")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-fps")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-ovc")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-ovc")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-channels")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-channels")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-oac")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-oac")) {
cmdArray[c] = "-quiet";
cmdArray[c + 1] = "-quiet";
s++;
}
}
} else if (sArgs[s].equals("-quality")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-lavcopts")) {
cmdArray[c + 1] = "autoaspect=1:vcodec=" + vcodec +
":acodec=" + (configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3") +
":abitrate=" + CodecUtil.getAC3Bitrate(configuration, params.aid) +
":threads=" + configuration.getMencoderMaxThreads() + ":" + sArgs[s + 1];
addMaximumBitrateConstraints(cmdArray[c + 1], media, cmdArray[c + 1], params.mediaRenderer, "");
sArgs[s + 1] = "-quality";
s++;
}
}
} else if (sArgs[s].equals("-mpegopts")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-mpegopts")) {
cmdArray[c + 1] += ":" + sArgs[s + 1];
sArgs[s + 1] = "-mpegopts";
s++;
}
}
} else if (sArgs[s].equals("-vf")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-vf")) {
cmdArray[c + 1] += "," + sArgs[s + 1];
sArgs[s + 1] = "-vf";
s++;
vfConsumed = true;
}
}
} else if (sArgs[s].equals("-af")) {
for (int c = 0; c < cmdArray.length; c++) {
if (cmdArray[c] != null && cmdArray[c].equals("-af")) {
cmdArray[c + 1] += "," + sArgs[s + 1];
sArgs[s + 1] = "-af";
s++;
afConsumed = true;
}
}
} else if (sArgs[s].equals("-nosync")) {
noMC0NoSkip = true;
} else if (sArgs[s].equals("-mc")) {
noMC0NoSkip = true;
}
}
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + sArgs.length);
for (int s = 0; s < sArgs.length; s++) {
if (sArgs[s].equals("-noass") || sArgs[s].equals("-nomux") || sArgs[s].equals("-mpegopts") || (sArgs[s].equals("-vf") & vfConsumed) || (sArgs[s].equals("-af") && afConsumed) || sArgs[s].equals("-quality") || sArgs[s].equals("-nosync") || sArgs[s].equals("-mt")) {
cmdArray[cmdArray.length - sArgs.length - 2 + s] = "-quiet";
} else {
cmdArray[cmdArray.length - sArgs.length - 2 + s] = sArgs[s];
}
}
}
}
if ((pcm || dts || mux) || (configuration.isMencoderNoOutOfSync() && !noMC0NoSkip)) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 3);
cmdArray[cmdArray.length - 5] = "-mc";
cmdArray[cmdArray.length - 4] = "0";
cmdArray[cmdArray.length - 3] = "-noskip";
if (configuration.isFix25FPSAvMismatch()) {
cmdArray[cmdArray.length - 4] = "0.005";
cmdArray[cmdArray.length - 3] = "-quiet";
}
}
if (params.timeend > 0) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-endpos";
cmdArray[cmdArray.length - 3] = "" + params.timeend;
}
String rate = "48000";
if (params.mediaRenderer.isXBOX()) {
rate = "44100";
}
// force srate -> cause ac3's mencoder doesn't like anything other than 48khz
if (media != null && !pcm && !dts && !mux) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 4);
cmdArray[cmdArray.length - 6] = "-af";
cmdArray[cmdArray.length - 5] = "lavcresample=" + rate;
cmdArray[cmdArray.length - 4] = "-srate";
cmdArray[cmdArray.length - 3] = rate;
}
// add a -cache option for piped media (e.g. rar/zip file entries):
// https://code.google.com/p/ps3mediaserver/issues/detail?id=911
if (params.stdin != null) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 4] = "-cache";
cmdArray[cmdArray.length - 3] = "8192";
}
PipeProcess pipe = null;
cmdArray[cmdArray.length - 2] = "-o";
ProcessWrapperImpl pw = null;
if (pcm || dts || mux) {
boolean channels_filter_present = false;
for (String s : cmdArray) {
if (StringUtils.isNotBlank(s) && s.startsWith("channels")) {
channels_filter_present = true;
break;
}
}
if (params.avidemux) {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dts || mux) ? null : params);
params.input_pipes[0] = pipe;
cmdArray[cmdArray.length - 1] = pipe.getInputPipe();
if (pcm && !channels_filter_present) {
String mixer = CodecUtil.getMixerOutput(true, configuration.getAudioChannelCount(), configuration.getAudioChannelCount());
if (StringUtils.isNotBlank(mixer)) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 2);
cmdArray[cmdArray.length - 2] = "-af";
cmdArray[cmdArray.length - 1] = mixer;
}
}
pw = new ProcessWrapperImpl(cmdArray, params);
PipeProcess videoPipe = new PipeProcess("videoPipe" + System.currentTimeMillis(), "out", "reconnect");
PipeProcess audioPipe = new PipeProcess("audioPipe" + System.currentTimeMillis(), "out", "reconnect");
ProcessWrapper videoPipeProcess = videoPipe.getPipeProcess();
ProcessWrapper audioPipeProcess = audioPipe.getPipeProcess();
params.output_pipes[0] = videoPipe;
params.output_pipes[1] = audioPipe;
pw.attachProcess(videoPipeProcess);
pw.attachProcess(audioPipeProcess);
videoPipeProcess.runInNewThread();
audioPipeProcess.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
videoPipe.deleteLater();
audioPipe.deleteLater();
} else {
// remove the -oac switch, otherwise too many video packets errors appears again
for (int s = 0; s < cmdArray.length; s++) {
if (cmdArray[s].equals("-oac")) {
cmdArray[s] = "-nosound";
cmdArray[s + 1] = "-nosound";
break;
}
}
pipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts");
TSMuxerVideo ts = new TSMuxerVideo(configuration);
File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta");
String cmd[] = new String[]{ts.executable(), f.getAbsolutePath(), pipe.getInputPipe()};
pw = new ProcessWrapperImpl(cmd, params);
PipeIPCProcess ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true);
cmdArray[cmdArray.length - 1] = ffVideoPipe.getInputPipe();
OutputParams ffparams = new OutputParams(configuration);
ffparams.maxBufferSize = 1;
ffparams.stdin = params.stdin;
ProcessWrapperImpl ffVideo = new ProcessWrapperImpl(cmdArray, ffparams);
ProcessWrapper ff_video_pipe_process = ffVideoPipe.getPipeProcess();
pw.attachProcess(ff_video_pipe_process);
ff_video_pipe_process.runInNewThread();
ffVideoPipe.deleteLater();
pw.attachProcess(ffVideo);
ffVideo.runInNewThread();
String aid = null;
if (media != null && media.getAudioCodes().size() > 1 && params.aid != null) {
aid = params.aid.getId() + "";
}
PipeIPCProcess ffAudioPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true);
StreamModifier sm = new StreamModifier();
sm.setPcm(pcm);
sm.setDtsembed(dts);
sm.setNbchannels(sm.isDtsembed() ? 2 : CodecUtil.getRealChannelCount(configuration, params.aid));
sm.setSampleFrequency(48000);
sm.setBitspersample(16);
String mixer = CodecUtil.getMixerOutput(!sm.isDtsembed(), sm.getNbchannels(), configuration.getAudioChannelCount());
// it seems the -really-quiet prevents mencoder to stop the pipe output after some time...
// -mc 0.1 make the DTS-HD extraction works better with latest mencoder builds, and makes no impact on the regular DTS one
String ffmpegLPCMextract[] = new String[]{
executable(),
"-ss", "0",
fileName,
"-really-quiet",
"-msglevel", "statusline=2",
"-channels", "" + sm.getNbchannels(),
"-ovc", "copy",
"-of", "rawaudio",
"-mc", dts ? "0.1" : "0",
"-noskip",
(aid == null) ? "-quiet" : "-aid", (aid == null) ? "-quiet" : aid,
"-oac", sm.isDtsembed() ? "copy" : "pcm",
(StringUtils.isNotBlank(mixer) && !channels_filter_present) ? "-af" : "-quiet", (StringUtils.isNotBlank(mixer) && !channels_filter_present) ? mixer : "-quiet",
"-srate", "48000",
"-o", ffAudioPipe.getInputPipe()
};
if (!params.mediaRenderer.isMuxDTSToMpeg()) { // no need to use the PCM trick when media renderer supports DTS
ffAudioPipe.setModifier(sm);
}
if (media != null && media.getDvdtrack() > 0) {
ffmpegLPCMextract[3] = "-dvd-device";
ffmpegLPCMextract[4] = fileName;
ffmpegLPCMextract[5] = "dvd://" + media.getDvdtrack();
} else if (params.stdin != null) {
ffmpegLPCMextract[3] = "-";
}
if (fileName.toLowerCase().endsWith(".evo")) {
ffmpegLPCMextract[4] = "-psprobe";
ffmpegLPCMextract[5] = "1000000";
}
if (params.timeseek > 0) {
ffmpegLPCMextract[2] = "" + params.timeseek;
}
OutputParams ffaudioparams = new OutputParams(configuration);
ffaudioparams.maxBufferSize = 1;
ffaudioparams.stdin = params.stdin;
ProcessWrapperImpl ffAudio = new ProcessWrapperImpl(ffmpegLPCMextract, ffaudioparams);
params.stdin = null;
PrintWriter pwMux = new PrintWriter(f);
pwMux.println("MUXOPT --no-pcr-on-video-pid --no-asyncio --new-audio-pes --vbr --vbv-len=500");
String videoType = "V_MPEG-2";
if (params.no_videoencode && params.forceType != null) {
videoType = params.forceType;
}
String fps = "";
if (params.forceFps != null) {
fps = "fps=" + params.forceFps + ", ";
}
String audioType = "A_LPCM";
if (params.mediaRenderer.isMuxDTSToMpeg()) {
audioType = "A_DTS";
}
if (params.lossyaudio) {
audioType = "A_AC3";
}
pwMux.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + fps + "level=4.1, insertSEI, contSPS, track=1");
pwMux.println(audioType + ", \"" + ffAudioPipe.getOutputPipe() + "\", track=2");
pwMux.close();
ProcessWrapper pipe_process = pipe.getPipeProcess();
pw.attachProcess(pipe_process);
pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
params.input_pipes[0] = pipe;
ProcessWrapper ff_pipe_process = ffAudioPipe.getPipeProcess();
pw.attachProcess(ff_pipe_process);
ff_pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
ffAudioPipe.deleteLater();
pw.attachProcess(ffAudio);
ffAudio.runInNewThread();
}
} else {
boolean directpipe = Platform.isMac() || Platform.isFreeBSD();
if (directpipe) {
cmdArray = Arrays.copyOf(cmdArray, cmdArray.length + 3);
cmdArray[cmdArray.length - 3] = "-really-quiet";
cmdArray[cmdArray.length - 2] = "-msglevel";
cmdArray[cmdArray.length - 1] = "statusline=2";
cmdArray[cmdArray.length - 4] = "-";
params.input_pipes = new PipeProcess[2];
} else {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dts || mux) ? null : params);
params.input_pipes[0] = pipe;
cmdArray[cmdArray.length - 1] = pipe.getInputPipe();
}
cmdArray = finalizeTranscoderArgs(
this,
fileName,
dlna,
media,
params,
cmdArray
);
pw = new ProcessWrapperImpl(cmdArray, params);
if (!directpipe) {
ProcessWrapper mkfifo_process = pipe.getPipeProcess();
pw.attachProcess(mkfifo_process);
mkfifo_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
}
}
pw.runInNewThread();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
return pw;
}
|
diff --git a/src/main/java/com/tinkerpop/furnace/generators/CommunityGenerator.java b/src/main/java/com/tinkerpop/furnace/generators/CommunityGenerator.java
index a71bf82..6edf33b 100644
--- a/src/main/java/com/tinkerpop/furnace/generators/CommunityGenerator.java
+++ b/src/main/java/com/tinkerpop/furnace/generators/CommunityGenerator.java
@@ -1,163 +1,168 @@
package com.tinkerpop.furnace.generators;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.Vertex;
import java.util.*;
/**
* Generates a synthetic network with a community structure, that is, several densely connected
* sub-networks that are loosely connected with one another.
*
* (c) Matthias Broecheler ([email protected])
*/
public class CommunityGenerator extends AbstractGenerator {
/**
* Default value used if {@link #setCrossCommunityPercentage(double)} is not called.
*/
public static final double DEFAULT_CROSS_COMMUNITY_PERCENTAGE = 0.1;
private Distribution communitySize=null;
private Distribution edgeDegree=null;
private double crossCommunityPercentage = DEFAULT_CROSS_COMMUNITY_PERCENTAGE;
private final Random random = new Random();
/**
*
* @param label
* @param annotator
* @see AbstractGenerator#AbstractGenerator(String, EdgeAnnotator)
*/
public CommunityGenerator(String label, EdgeAnnotator annotator) {
super(label, annotator);
}
/**
*
* @param label
* @see AbstractGenerator#AbstractGenerator(String)
*/
public CommunityGenerator(String label) {
super(label);
}
/**
* Sets the distribution to be used to generate the sizes of communities.
*
* @param community
*/
public void setCommunityDistribution(Distribution community) {
this.communitySize=community;
}
/**
* Sets the distribution to be used to generate the out-degrees of vertices
*
* @param degree
*/
public void setDegreeDistribution(Distribution degree) {
this.edgeDegree=degree;
}
/**
* Sets the percentage of edges that cross a community, i.e. connect a vertex to a vertex in
* another community. The lower this value, the higher the modularity of the generated communities.
*
* @param percentage Percentage of community crossing edges. Must be in [0,1]
*/
public void setCrossCommunityPercentage(double percentage) {
if (percentage<0.0 || percentage>1.0) throw new IllegalArgumentException("Percentage must be between 0 and 1");
this.crossCommunityPercentage=percentage;
}
/**
* Returns the configured cross community percentage.
*
* @return
*/
public double getCrossCommunityPercentage() {
return crossCommunityPercentage;
}
/**
* Generates a synthetic network for all vertices in the given graph such that the provided expected number
* of communities are generated with the specified expected number of edges.
*
* @param graph
* @param expectedNumCommunities
* @param expectedNumEdges
* @return The actual number of edges generated. May be different from the expected number.
*/
public int generate(Graph graph, int expectedNumCommunities, int expectedNumEdges) {
return generate(graph,graph.getVertices(),expectedNumCommunities,expectedNumEdges);
}
/**
* Generates a synthetic network for provided vertices in the given graphh such that the provided expected number
* of communities are generated with the specified expected number of edges.
*
* @param graph
* @param vertices
* @param expectedNumCommunities
* @param expectedNumEdges
* @return The actual number of edges generated. May be different from the expected number.
*/
public int generate(Graph graph, Iterable<Vertex> vertices, int expectedNumCommunities, int expectedNumEdges) {
if (communitySize==null) throw new IllegalStateException("Need to initialize community size distribution");
if (edgeDegree==null) throw new IllegalStateException("Need to initialize degree distribution");
int numVertices = SizableIterable.sizeOf(vertices);
Iterator<Vertex> iter = vertices.iterator();
ArrayList<ArrayList<Vertex>> communities = new ArrayList<ArrayList<Vertex>>(expectedNumCommunities);
Distribution communityDist = communitySize.initialize(expectedNumCommunities,numVertices);
while (iter.hasNext()) {
int nextSize = communityDist.nextValue(random);
ArrayList<Vertex> community = new ArrayList<Vertex>(nextSize);
for (int i=0;i<nextSize && iter.hasNext();i++) {
community.add(iter.next());
}
if (!community.isEmpty()) communities.add(community);
}
double inCommunityPercentage = 1.0-crossCommunityPercentage;
Distribution degreeDist = edgeDegree.initialize(numVertices,expectedNumEdges);
if (crossCommunityPercentage>0 && communities.size()<2) throw new IllegalArgumentException("Cannot have cross links with only one community");
int addedEdges = 0;
//System.out.println("Generating links on communities: "+communities.size());
for (ArrayList<Vertex> community : communities) {
for (Vertex v : community) {
int degree = degreeDist.nextValue(random);
degree = Math.min(degree,(int)Math.ceil((community.size() - 1) / inCommunityPercentage)-1);
Set<Vertex> inlinks = new HashSet<Vertex>();
+ Set<Vertex> outlinks = new HashSet<Vertex>();
for (int i=0;i<degree;i++) {
Vertex selected = null;
if (random.nextDouble()<crossCommunityPercentage || (community.size()-1<=inlinks.size()) ) {
//Cross community
ArrayList<Vertex> othercomm = null;
- while (othercomm==null) {
- othercomm = communities.get(random.nextInt(communities.size()));
- if (othercomm.equals(community)) othercomm=null;
+ while (selected == null) {
+ while (othercomm==null) {
+ othercomm = communities.get(random.nextInt(communities.size()));
+ if (othercomm.equals(community)) othercomm=null;
+ }
+ selected = othercomm.get(random.nextInt(othercomm.size()));
+ if (outlinks.contains(selected)) selected = null;
}
- selected=othercomm.get(random.nextInt(othercomm.size()));
+ outlinks.add(selected);
} else {
//In community
while (selected==null) {
selected=community.get(random.nextInt(community.size()));
if (v.equals(selected) || inlinks.contains(selected)) selected=null;
}
inlinks.add(selected);
}
addEdge(graph,v,selected);
addedEdges++;
}
}
}
return addedEdges;
}
}
| false | true | public int generate(Graph graph, Iterable<Vertex> vertices, int expectedNumCommunities, int expectedNumEdges) {
if (communitySize==null) throw new IllegalStateException("Need to initialize community size distribution");
if (edgeDegree==null) throw new IllegalStateException("Need to initialize degree distribution");
int numVertices = SizableIterable.sizeOf(vertices);
Iterator<Vertex> iter = vertices.iterator();
ArrayList<ArrayList<Vertex>> communities = new ArrayList<ArrayList<Vertex>>(expectedNumCommunities);
Distribution communityDist = communitySize.initialize(expectedNumCommunities,numVertices);
while (iter.hasNext()) {
int nextSize = communityDist.nextValue(random);
ArrayList<Vertex> community = new ArrayList<Vertex>(nextSize);
for (int i=0;i<nextSize && iter.hasNext();i++) {
community.add(iter.next());
}
if (!community.isEmpty()) communities.add(community);
}
double inCommunityPercentage = 1.0-crossCommunityPercentage;
Distribution degreeDist = edgeDegree.initialize(numVertices,expectedNumEdges);
if (crossCommunityPercentage>0 && communities.size()<2) throw new IllegalArgumentException("Cannot have cross links with only one community");
int addedEdges = 0;
//System.out.println("Generating links on communities: "+communities.size());
for (ArrayList<Vertex> community : communities) {
for (Vertex v : community) {
int degree = degreeDist.nextValue(random);
degree = Math.min(degree,(int)Math.ceil((community.size() - 1) / inCommunityPercentage)-1);
Set<Vertex> inlinks = new HashSet<Vertex>();
for (int i=0;i<degree;i++) {
Vertex selected = null;
if (random.nextDouble()<crossCommunityPercentage || (community.size()-1<=inlinks.size()) ) {
//Cross community
ArrayList<Vertex> othercomm = null;
while (othercomm==null) {
othercomm = communities.get(random.nextInt(communities.size()));
if (othercomm.equals(community)) othercomm=null;
}
selected=othercomm.get(random.nextInt(othercomm.size()));
} else {
//In community
while (selected==null) {
selected=community.get(random.nextInt(community.size()));
if (v.equals(selected) || inlinks.contains(selected)) selected=null;
}
inlinks.add(selected);
}
addEdge(graph,v,selected);
addedEdges++;
}
}
}
return addedEdges;
}
| public int generate(Graph graph, Iterable<Vertex> vertices, int expectedNumCommunities, int expectedNumEdges) {
if (communitySize==null) throw new IllegalStateException("Need to initialize community size distribution");
if (edgeDegree==null) throw new IllegalStateException("Need to initialize degree distribution");
int numVertices = SizableIterable.sizeOf(vertices);
Iterator<Vertex> iter = vertices.iterator();
ArrayList<ArrayList<Vertex>> communities = new ArrayList<ArrayList<Vertex>>(expectedNumCommunities);
Distribution communityDist = communitySize.initialize(expectedNumCommunities,numVertices);
while (iter.hasNext()) {
int nextSize = communityDist.nextValue(random);
ArrayList<Vertex> community = new ArrayList<Vertex>(nextSize);
for (int i=0;i<nextSize && iter.hasNext();i++) {
community.add(iter.next());
}
if (!community.isEmpty()) communities.add(community);
}
double inCommunityPercentage = 1.0-crossCommunityPercentage;
Distribution degreeDist = edgeDegree.initialize(numVertices,expectedNumEdges);
if (crossCommunityPercentage>0 && communities.size()<2) throw new IllegalArgumentException("Cannot have cross links with only one community");
int addedEdges = 0;
//System.out.println("Generating links on communities: "+communities.size());
for (ArrayList<Vertex> community : communities) {
for (Vertex v : community) {
int degree = degreeDist.nextValue(random);
degree = Math.min(degree,(int)Math.ceil((community.size() - 1) / inCommunityPercentage)-1);
Set<Vertex> inlinks = new HashSet<Vertex>();
Set<Vertex> outlinks = new HashSet<Vertex>();
for (int i=0;i<degree;i++) {
Vertex selected = null;
if (random.nextDouble()<crossCommunityPercentage || (community.size()-1<=inlinks.size()) ) {
//Cross community
ArrayList<Vertex> othercomm = null;
while (selected == null) {
while (othercomm==null) {
othercomm = communities.get(random.nextInt(communities.size()));
if (othercomm.equals(community)) othercomm=null;
}
selected = othercomm.get(random.nextInt(othercomm.size()));
if (outlinks.contains(selected)) selected = null;
}
outlinks.add(selected);
} else {
//In community
while (selected==null) {
selected=community.get(random.nextInt(community.size()));
if (v.equals(selected) || inlinks.contains(selected)) selected=null;
}
inlinks.add(selected);
}
addEdge(graph,v,selected);
addedEdges++;
}
}
}
return addedEdges;
}
|
diff --git a/src/com/flaptor/util/sort/MergeSort.java b/src/com/flaptor/util/sort/MergeSort.java
index 27de6a6..49cbd71 100644
--- a/src/com/flaptor/util/sort/MergeSort.java
+++ b/src/com/flaptor/util/sort/MergeSort.java
@@ -1,213 +1,218 @@
/*
Copyright 2008 Flaptor (flaptor.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.flaptor.util.sort;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Vector;
/**
* This class sorts a file that doesn't fit in available memory using the mergeSort algorithm.
*/
public final class MergeSort {
/**
* The sort operation
* @param filein the name of the input unsorted file
* @param fileout the name of the output sorted file
* @param rInfo the RecordInformation object
*/
public static void sort (File filein, File fileout, RecordInformation rInfo) throws FileNotFoundException, IOException {
// Get whatever tmp files may be left from an interrupted sort operation.
File parent = filein.getParentFile();
Vector<File> tmpFiles = new Vector<File>(Arrays.asList(parent.listFiles(new TmpFilesFilter())));
// If the original unsorted file exists, it means this is a fresh sort
// or an interrupted sort where the block distribution didn't finish.
if (filein.exists()) {
// if there are leftover blocks, delete them.
if (tmpFiles.size() > 0) {
cleanUpTmp (tmpFiles);
}
// Perform the initial dispersion into sorted files.
tmpFiles = distributeSortedBlocks (filein, fileout.getParentFile(), rInfo);
// Delete original file, it is no longer needed and uses up space.
filein.delete();
}
// if there is something to merge...
if (tmpFiles.size() > 0) {
// If the output file is there, it was interrupted during merge.
// In that case, delete the output file before merging.
if (fileout.exists()) {
fileout.delete();
}
// Merge the sorted files.
mergeSortedBlocks (tmpFiles, fileout, rInfo);
// Cleanup.
cleanUpTmp (tmpFiles);
}
}
/**
* Determine if the sort needs to be completed.
* This does not look into the file to see if it is sorted,
* it only detects situations in which the sort was interrupted.
*/
public static boolean sortIsIncomplete (File filein) {
if (filein.exists()) return true;
if (filein.getParentFile().listFiles(new TmpFilesFilter()).length > 0) return true;
return false;
}
/**
* Delete the temporary files.
*/
private static void cleanUpTmp (Vector<File> tmpFiles) {
for (int i = 0; i < tmpFiles.size(); i++) {
tmpFiles.elementAt(i).delete();
}
}
/**
* This filter accepts only temporary files.
*/
private static class TmpFilesFilter implements FilenameFilter {
public boolean accept (File dir, String name) {
return name.startsWith("tmp_");
}
}
/**
* Perform the initial dispersion of the data.
*/
private static Vector<File> distributeSortedBlocks (File from, File tmpDir, RecordInformation rInfo) throws FileNotFoundException, IOException {
RecordReader reader = rInfo.newRecordReader(from);
Vector<File> files = new Vector<File>();
Runtime.getRuntime().gc(); // free memory
long startingMem = Runtime.getRuntime().freeMemory();
//System.out.println("startingMem = " + Math.round(startingMem/1024/102.4f)/10.0f + " MB");
boolean allDone = false;
for (int i = 0; ! allDone; i++) {
// Pull in a few records, put them into the Vector
// that is where we are performing the internal sort
// that creates the sorted blocks.
Vector<Record> rec = new Vector<Record>();
boolean memoryAvailable = true;
while (memoryAvailable && ! allDone) {
- Record r = reader.readRecord();
+ Record r = null;
+ try {
+ r = reader.readRecord();
+ } catch (java.io.StreamCorruptedException e) {
+ System.out.println("Error reading records: "+e);
+ }
if (r == null) {
allDone = true;
break;
}
rec.addElement(r);
long remainingMem = Runtime.getRuntime().freeMemory();
memoryAvailable = (remainingMem > startingMem * 0.5f); // use up to 50% of available memory.
//if (!memoryAvailable) System.out.println("remainingMem = " + Math.round(remainingMem/1024/102.4f)/10.0f + " MB; records = " + rec.size());
}
// Sort the vector
QuicksortVector.sort(rec, rInfo.getComparator());
// Write out the sorted vector.
File tmpFile = new File(tmpDir, "tmp_" + i);
files.addElement(tmpFile);
RecordWriter writer = rInfo.newRecordWriter(tmpFile);
for (int j = 0; j < rec.size(); j++) {
writer.writeRecord(rec.elementAt(j));
}
writer.close();
// free memory
rec.clear();
rec = null;
Runtime.getRuntime().gc();
}
reader.close();
return files;
}
/**
* Undertake a round of merging.
*/
private static void mergeSortedBlocks (Vector filesIn, File fileOut, RecordInformation rInfo) throws FileNotFoundException, IOException {
// Open up the set of Readers and the Writer.
RecordReader[] readers = new RecordReader[filesIn.size()];
for (int i = 0 ; i < readers.length ; i++) {
readers[i] = rInfo.newRecordReader((File)filesIn.elementAt(i));
}
RecordWriter writer = rInfo.newRecordWriter(fileOut);
// Initialize the records array holding the next record from each of the files.
Record[] rec = new Record[readers.length];
for (int j = 0; j < readers.length; j++) {
rec[j] = readers[j].readRecord();
}
while (true) {
// Determine which is the next Record to add to the output stream.
int index = findAppropriate(rec, rInfo.getComparator());
// If there isn't one then we get a negative index and we can terminate the loop.
if (index < 0) break;
// Write the record to the destination file
writer.writeRecord(rec[index]);
// Draw a new Record from the file whose Record was chosen
rec[index] = readers[index].readRecord();
}
// Cleanup.
writer.close();
for (int i = 0; i < readers.length; i++) {
readers[i].close();
}
}
/**
* Determine which Record is the one to be output next.
*
* @param items the array of <code>Records</code> from which to
* select the next according to the order relation defined bu
* <code>c</code>.
*
* @param c the <code>Comparator</code> defining the required
* order relation on the <code>Record</code>s.
*
* @return the index in the array of the item that should be
* chosen next.
*/
private static int findAppropriate(final Record[] items, final Comparator c) {
// Find first non-empty entry.
int index = -1;
for (int i = 0; i < items.length; i++) {
if (items[i] != null) {
index = i;
break;
}
}
// If there still are non-empty entries then do a linear search
// through the items to see which is the next one to select.
if (index >= 0) {
Record value = items[index];
for (int i = index+1; i < items.length; i++) {
if (items[i] != null) {
if (c.compare(items[i], value) < 0) {
index = i;
value = items[i];
}
}
}
}
return index;
}
}
| true | true | private static Vector<File> distributeSortedBlocks (File from, File tmpDir, RecordInformation rInfo) throws FileNotFoundException, IOException {
RecordReader reader = rInfo.newRecordReader(from);
Vector<File> files = new Vector<File>();
Runtime.getRuntime().gc(); // free memory
long startingMem = Runtime.getRuntime().freeMemory();
//System.out.println("startingMem = " + Math.round(startingMem/1024/102.4f)/10.0f + " MB");
boolean allDone = false;
for (int i = 0; ! allDone; i++) {
// Pull in a few records, put them into the Vector
// that is where we are performing the internal sort
// that creates the sorted blocks.
Vector<Record> rec = new Vector<Record>();
boolean memoryAvailable = true;
while (memoryAvailable && ! allDone) {
Record r = reader.readRecord();
if (r == null) {
allDone = true;
break;
}
rec.addElement(r);
long remainingMem = Runtime.getRuntime().freeMemory();
memoryAvailable = (remainingMem > startingMem * 0.5f); // use up to 50% of available memory.
//if (!memoryAvailable) System.out.println("remainingMem = " + Math.round(remainingMem/1024/102.4f)/10.0f + " MB; records = " + rec.size());
}
// Sort the vector
QuicksortVector.sort(rec, rInfo.getComparator());
// Write out the sorted vector.
File tmpFile = new File(tmpDir, "tmp_" + i);
files.addElement(tmpFile);
RecordWriter writer = rInfo.newRecordWriter(tmpFile);
for (int j = 0; j < rec.size(); j++) {
writer.writeRecord(rec.elementAt(j));
}
writer.close();
// free memory
rec.clear();
rec = null;
Runtime.getRuntime().gc();
}
reader.close();
return files;
}
| private static Vector<File> distributeSortedBlocks (File from, File tmpDir, RecordInformation rInfo) throws FileNotFoundException, IOException {
RecordReader reader = rInfo.newRecordReader(from);
Vector<File> files = new Vector<File>();
Runtime.getRuntime().gc(); // free memory
long startingMem = Runtime.getRuntime().freeMemory();
//System.out.println("startingMem = " + Math.round(startingMem/1024/102.4f)/10.0f + " MB");
boolean allDone = false;
for (int i = 0; ! allDone; i++) {
// Pull in a few records, put them into the Vector
// that is where we are performing the internal sort
// that creates the sorted blocks.
Vector<Record> rec = new Vector<Record>();
boolean memoryAvailable = true;
while (memoryAvailable && ! allDone) {
Record r = null;
try {
r = reader.readRecord();
} catch (java.io.StreamCorruptedException e) {
System.out.println("Error reading records: "+e);
}
if (r == null) {
allDone = true;
break;
}
rec.addElement(r);
long remainingMem = Runtime.getRuntime().freeMemory();
memoryAvailable = (remainingMem > startingMem * 0.5f); // use up to 50% of available memory.
//if (!memoryAvailable) System.out.println("remainingMem = " + Math.round(remainingMem/1024/102.4f)/10.0f + " MB; records = " + rec.size());
}
// Sort the vector
QuicksortVector.sort(rec, rInfo.getComparator());
// Write out the sorted vector.
File tmpFile = new File(tmpDir, "tmp_" + i);
files.addElement(tmpFile);
RecordWriter writer = rInfo.newRecordWriter(tmpFile);
for (int j = 0; j < rec.size(); j++) {
writer.writeRecord(rec.elementAt(j));
}
writer.close();
// free memory
rec.clear();
rec = null;
Runtime.getRuntime().gc();
}
reader.close();
return files;
}
|
diff --git a/src/org/xbmc/api/object/TvShow.java b/src/org/xbmc/api/object/TvShow.java
index 39450c6..1533f75 100644
--- a/src/org/xbmc/api/object/TvShow.java
+++ b/src/org/xbmc/api/object/TvShow.java
@@ -1,122 +1,122 @@
package org.xbmc.api.object;
import java.net.URLDecoder;
import java.util.List;
import org.xbmc.android.util.Crc32;
import org.xbmc.api.type.MediaType;
public class TvShow implements ICoverArt, INamedResource {
public final static String TAG = "TvShow";
/**
* Points to where the movie thumbs are stored
*/
public final static String THUMB_PREFIX = "special://profile/Thumbnails/";
/**
* Save this once it's calculated
*/
public long thumbID = 0L;
public List<Season> seasons = null;
public List<Actor> actors = null;
public TvShow(int id, String title, String summary, double rating, String firstAired,
String genre, String contentRating, String network, String path, int numEpisodes, int watchedEpisodes, boolean watched, String artUrl) {
this.id = id;
this.title = title;
this.summary = summary;
this.rating = rating;
this.firstAired = firstAired;
this.contentRating = contentRating;
this.network = network;
this.genre = genre;
this.path = path;
this.numEpisodes = numEpisodes;
this.watchedEpisodes = watchedEpisodes;
this.watched = watched;
- this.artUrl = URLDecoder.decode(artUrl.replaceAll("image://", ""));
+ this.artUrl = artUrl;
}
public String getShortName() {
return title;
}
/**
* Composes the complete path to the album's thumbnail
* @return Path to thumbnail
*/
public String getThumbUri() {
return getThumbUri(this);
}
public static String getThumbUri(ICoverArt cover) {
return cover.getThumbUrl();
}
public static String getFallbackThumbUri(ICoverArt cover) {
final String hex;
if (cover.getMediaType() == MediaType.VIDEO_TVEPISODE) {
hex = Crc32.formatAsHexLowerCase(cover.getFallbackCrc());
} else {
hex = Crc32.formatAsHexLowerCase(cover.getCrc());
}
return THUMB_PREFIX + hex.charAt(0) + "/" + hex + ".jpg";
}
public long getCrc() {
if (thumbID == 0L) {
thumbID = Crc32.computeLowerCase(artUrl);
}
return thumbID;
}
public int getFallbackCrc() {
return 0;
}
public int getId() {
return id;
}
public int getMediaType() {
return MediaType.VIDEO_TVSHOW;
}
public String getName() {
return title;
}
public String getPath() {
return path;
}
public String getThumbUrl() {
return artUrl;
}
/**
* Something descriptive
*/
public String toString() {
return "[" + id + "] " + title;
}
public int id;
public String title;
public String summary;
public double rating = 0.0;
public String firstAired;
public String contentRating;
public String network;
public String genre;
public String path;
public int numEpisodes;
public int watchedEpisodes;
public boolean watched;
public String artUrl;
private static final long serialVersionUID = -902152099894950269L;
}
| true | true | public TvShow(int id, String title, String summary, double rating, String firstAired,
String genre, String contentRating, String network, String path, int numEpisodes, int watchedEpisodes, boolean watched, String artUrl) {
this.id = id;
this.title = title;
this.summary = summary;
this.rating = rating;
this.firstAired = firstAired;
this.contentRating = contentRating;
this.network = network;
this.genre = genre;
this.path = path;
this.numEpisodes = numEpisodes;
this.watchedEpisodes = watchedEpisodes;
this.watched = watched;
this.artUrl = URLDecoder.decode(artUrl.replaceAll("image://", ""));
}
| public TvShow(int id, String title, String summary, double rating, String firstAired,
String genre, String contentRating, String network, String path, int numEpisodes, int watchedEpisodes, boolean watched, String artUrl) {
this.id = id;
this.title = title;
this.summary = summary;
this.rating = rating;
this.firstAired = firstAired;
this.contentRating = contentRating;
this.network = network;
this.genre = genre;
this.path = path;
this.numEpisodes = numEpisodes;
this.watchedEpisodes = watchedEpisodes;
this.watched = watched;
this.artUrl = artUrl;
}
|
diff --git a/plugins/email_sender/src/test/java/com/rabbitmq/streams/plugins/email/EmailSenderTest.java b/plugins/email_sender/src/test/java/com/rabbitmq/streams/plugins/email/EmailSenderTest.java
index 304ea27..a823a78 100644
--- a/plugins/email_sender/src/test/java/com/rabbitmq/streams/plugins/email/EmailSenderTest.java
+++ b/plugins/email_sender/src/test/java/com/rabbitmq/streams/plugins/email/EmailSenderTest.java
@@ -1,67 +1,67 @@
package com.rabbitmq.streams.plugins.email;
import junit.framework.TestCase;
import com.rabbitmq.streams.harness.testsupport.MockMessageChannel;
import com.rabbitmq.streams.harness.*;
import static org.mockito.Mockito.*;
import net.sf.json.JSONObject;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;
public class EmailSenderTest extends TestCase {
private JSONObject config;
public void setUp() {
config = new JSONObject();
config.put("host", "0.0.0.0");
config.put("username", "username");
config.put("password", "password");
config.put("transportProtocol", "smtp");
}
public void testNotification() throws IOException {
InputMessage message = mock(InputMessage.class);
when(message.routingKey()).thenReturn("bang");
when(message.body()).thenReturn("bang".getBytes());
MockMessageChannel messageChannel = new MockMessageChannel();
EmailSender emailSender = new EmailSender();
emailSender.setMessageChannel(messageChannel);
Notifier notifier = mock(Notifier.class);
emailSender.setNotifier(notifier);
Logger log = mock(Logger.class);
emailSender.setLog(log);
DatabaseResource database = mock(DatabaseResource.class);
when(database.getDocument(anyString())).thenReturn(new JSONObject());
emailSender.setTerminalsDatabase(database);
String destination = "{\"destination\":{\"to\":[\"[email protected]\"],\"subject\":\"simple test\"}}";
JSONObject terminal = JSONObject.fromObject(destination);
List<JSONObject> terminalConfigs = new ArrayList<JSONObject>();
terminalConfigs.add(terminal);
try {
emailSender.configure(config);
emailSender.terminalStatusChange("bang", terminalConfigs, true);
}
catch (PluginBuildException e) {
e.printStackTrace();
}
try {
messageChannel.inject("input", message);
fail();
}
catch (PluginException ignore) {
}
- verify(notifier).notify(NotificationType.Unavailable, "Could not deliver email 501 5.1.7 Bad sender address syntax");
+ verify(notifier).notify(eq(NotificationType.Unavailable), anyString());
}
}
| true | true | public void testNotification() throws IOException {
InputMessage message = mock(InputMessage.class);
when(message.routingKey()).thenReturn("bang");
when(message.body()).thenReturn("bang".getBytes());
MockMessageChannel messageChannel = new MockMessageChannel();
EmailSender emailSender = new EmailSender();
emailSender.setMessageChannel(messageChannel);
Notifier notifier = mock(Notifier.class);
emailSender.setNotifier(notifier);
Logger log = mock(Logger.class);
emailSender.setLog(log);
DatabaseResource database = mock(DatabaseResource.class);
when(database.getDocument(anyString())).thenReturn(new JSONObject());
emailSender.setTerminalsDatabase(database);
String destination = "{\"destination\":{\"to\":[\"[email protected]\"],\"subject\":\"simple test\"}}";
JSONObject terminal = JSONObject.fromObject(destination);
List<JSONObject> terminalConfigs = new ArrayList<JSONObject>();
terminalConfigs.add(terminal);
try {
emailSender.configure(config);
emailSender.terminalStatusChange("bang", terminalConfigs, true);
}
catch (PluginBuildException e) {
e.printStackTrace();
}
try {
messageChannel.inject("input", message);
fail();
}
catch (PluginException ignore) {
}
verify(notifier).notify(NotificationType.Unavailable, "Could not deliver email 501 5.1.7 Bad sender address syntax");
}
| public void testNotification() throws IOException {
InputMessage message = mock(InputMessage.class);
when(message.routingKey()).thenReturn("bang");
when(message.body()).thenReturn("bang".getBytes());
MockMessageChannel messageChannel = new MockMessageChannel();
EmailSender emailSender = new EmailSender();
emailSender.setMessageChannel(messageChannel);
Notifier notifier = mock(Notifier.class);
emailSender.setNotifier(notifier);
Logger log = mock(Logger.class);
emailSender.setLog(log);
DatabaseResource database = mock(DatabaseResource.class);
when(database.getDocument(anyString())).thenReturn(new JSONObject());
emailSender.setTerminalsDatabase(database);
String destination = "{\"destination\":{\"to\":[\"[email protected]\"],\"subject\":\"simple test\"}}";
JSONObject terminal = JSONObject.fromObject(destination);
List<JSONObject> terminalConfigs = new ArrayList<JSONObject>();
terminalConfigs.add(terminal);
try {
emailSender.configure(config);
emailSender.terminalStatusChange("bang", terminalConfigs, true);
}
catch (PluginBuildException e) {
e.printStackTrace();
}
try {
messageChannel.inject("input", message);
fail();
}
catch (PluginException ignore) {
}
verify(notifier).notify(eq(NotificationType.Unavailable), anyString());
}
|
diff --git a/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/mutable/mysql/impl/MySQLForeignKeyMetaDataBuilderImpl.java b/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/mutable/mysql/impl/MySQLForeignKeyMetaDataBuilderImpl.java
index 03420b5..b516ecd 100644
--- a/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/mutable/mysql/impl/MySQLForeignKeyMetaDataBuilderImpl.java
+++ b/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/mutable/mysql/impl/MySQLForeignKeyMetaDataBuilderImpl.java
@@ -1,127 +1,127 @@
package net.madz.db.core.meta.mutable.mysql.impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.madz.db.core.meta.immutable.ForeignKeyMetaData;
import net.madz.db.core.meta.immutable.IndexMetaData;
import net.madz.db.core.meta.immutable.mysql.MySQLColumnMetaData;
import net.madz.db.core.meta.immutable.mysql.MySQLForeignKeyMetaData;
import net.madz.db.core.meta.immutable.mysql.MySQLIndexMetaData;
import net.madz.db.core.meta.immutable.mysql.MySQLSchemaMetaData;
import net.madz.db.core.meta.immutable.mysql.MySQLTableMetaData;
import net.madz.db.core.meta.immutable.mysql.impl.MySQLForeignKeyMetaDataImpl;
import net.madz.db.core.meta.immutable.types.CascadeRule;
import net.madz.db.core.meta.mutable.impl.BaseForeignKeyMetaDataBuilder;
import net.madz.db.core.meta.mutable.mysql.MySQLColumnMetaDataBuilder;
import net.madz.db.core.meta.mutable.mysql.MySQLForeignKeyMetaDataBuilder;
import net.madz.db.core.meta.mutable.mysql.MySQLIndexMetaDataBuilder;
import net.madz.db.core.meta.mutable.mysql.MySQLSchemaMetaDataBuilder;
import net.madz.db.core.meta.mutable.mysql.MySQLTableMetaDataBuilder;
import net.madz.db.utils.MessageConsts;
import net.madz.db.utils.ResourceManagementUtils;
public class MySQLForeignKeyMetaDataBuilderImpl
extends
BaseForeignKeyMetaDataBuilder<MySQLSchemaMetaDataBuilder, MySQLTableMetaDataBuilder, MySQLColumnMetaDataBuilder, MySQLForeignKeyMetaDataBuilder, MySQLIndexMetaDataBuilder, MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>
implements MySQLForeignKeyMetaDataBuilder {
public MySQLForeignKeyMetaDataBuilderImpl(MySQLTableMetaDataBuilder table, String name) {
this.fkTable = table;
this.foreignKeyPath = table.getTablePath().append(name);
}
@Override
public MySQLForeignKeyMetaDataBuilder build(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = null;
try {
rs = stmt.executeQuery("SELECT * FROM referential_constraints WHERE constraint_schema='" + this.fkTable.getTablePath().getParent().getName()
+ "' AND constraint_name='" + this.foreignKeyPath.getName() + "';");
while ( rs.next() ) {
this.updateRule = CascadeRule.getRule(rs.getString("update_rule"));
this.deleteRule = CascadeRule.getRule(rs.getString("delete_rule"));
// [ToDo] [Tracy] about how to get pkTable
// Below code suppose the referenced table is in the same
// schema,
// but actually, the referenced table could be in another
// schema.
this.pkTable = this.fkTable.getSchema().getTableBuilder(rs.getString("referenced_table_name"));
// Note: some times unique_constraint_name is null
this.pkIndex = this.pkTable.getIndexBuilder(rs.getString("unique_constraint_name"));
this.fkIndex = this.fkTable.getIndexBuilder(rs.getString("constraint_name"));
}
} finally {
ResourceManagementUtils.closeResultSet(rs);
}
try {
rs = stmt.executeQuery("SELECT * FROM key_column_usage WHERE constraint_schema='" + this.fkTable.getSchema().getSchemaPath().getName()
+ "' AND constraint_name = '" + this.foreignKeyPath.getName() + "';");
while ( rs.next() ) {
final String columnName = rs.getString("column_name");
final String referencedColumnName = rs.getString("referenced_column_name");
final MySQLColumnMetaData fkColumn = this.fkTable.getColumnBuilder(columnName);
final MySQLColumnMetaData pkColumn = this.pkTable.getColumnBuilder(referencedColumnName);
final Short seq = rs.getShort("ordinal_position");
final BaseForeignKeyMetaDataBuilder<MySQLSchemaMetaDataBuilder,MySQLTableMetaDataBuilder,MySQLColumnMetaDataBuilder,MySQLForeignKeyMetaDataBuilder,MySQLIndexMetaDataBuilder,MySQLSchemaMetaData,MySQLTableMetaData,MySQLColumnMetaData,MySQLForeignKeyMetaData,MySQLIndexMetaData>.Entry entry = new BaseForeignKeyMetaDataBuilder.Entry(fkColumn, pkColumn, this, seq);
final MySQLColumnMetaDataBuilder columnBuilder = this.fkTable.getColumnBuilder(columnName);
columnBuilder.appendForeignKeyEntry(entry);
this.addEntry(entry);
}
} finally {
ResourceManagementUtils.closeResultSet(rs);
}
// Handle the situation that fkIndex is null, which will be happend when
// creating fk without a constraint name. The name of index
// auto-generated doesn't match the constraint name.
if ( null == this.fkIndex ) {
final Map<Short, MySQLColumnMetaData> fkColumns = new HashMap<Short, MySQLColumnMetaData>();
List<ForeignKeyMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> fkEntrySet = this.entryList;
for ( ForeignKeyMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : fkEntrySet ) {
fkColumns.put(entry.getSeq(), entry.getForeignKeyColumn());
}
Collection<MySQLIndexMetaDataBuilder> indexSet = this.fkTable.getIndexBuilderSet();
Map<Short, MySQLColumnMetaData> indexColumns = null;
for ( MySQLIndexMetaDataBuilder index : indexSet ) {
indexColumns = new HashMap<Short, MySQLColumnMetaData>();
final Collection<IndexMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> entrySet = index
.getEntrySet();
for ( IndexMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : entrySet ) {
indexColumns.put(entry.getPosition(), entry.getColumn());
}
// if ( fkColumns.size() != indexColumns.size() ) {
// continue;
// }
boolean matched = true;
for ( Short key : fkColumns.keySet() ) {
MySQLColumnMetaData pkColumn = fkColumns.get(key);
MySQLColumnMetaData indexColumn = indexColumns.get(key);
if ( !pkColumn.getColumnPath().equals(indexColumn.getColumnPath()) ) {
matched = false;
break;
}
}
- if ( matched ) {
+ if ( matched && !index.getIndexName().equalsIgnoreCase("PRIMARY")) {
this.fkIndex = this.fkTable.getIndexBuilder(index.getIndexName());
break;
}
}
// if (null == this.fkIndex) {
// throw new IllegalStateException(MessageConsts.FK_INDEX_SHOULD_NOT_BE_NULL);
// }
}
return this;
}
@Override
public MySQLForeignKeyMetaData createMetaData() {
this.constructedMetaData = new MySQLForeignKeyMetaDataImpl(this.fkTable.getMetaData(), this);
return constructedMetaData;
}
}
| true | true | public MySQLForeignKeyMetaDataBuilder build(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = null;
try {
rs = stmt.executeQuery("SELECT * FROM referential_constraints WHERE constraint_schema='" + this.fkTable.getTablePath().getParent().getName()
+ "' AND constraint_name='" + this.foreignKeyPath.getName() + "';");
while ( rs.next() ) {
this.updateRule = CascadeRule.getRule(rs.getString("update_rule"));
this.deleteRule = CascadeRule.getRule(rs.getString("delete_rule"));
// [ToDo] [Tracy] about how to get pkTable
// Below code suppose the referenced table is in the same
// schema,
// but actually, the referenced table could be in another
// schema.
this.pkTable = this.fkTable.getSchema().getTableBuilder(rs.getString("referenced_table_name"));
// Note: some times unique_constraint_name is null
this.pkIndex = this.pkTable.getIndexBuilder(rs.getString("unique_constraint_name"));
this.fkIndex = this.fkTable.getIndexBuilder(rs.getString("constraint_name"));
}
} finally {
ResourceManagementUtils.closeResultSet(rs);
}
try {
rs = stmt.executeQuery("SELECT * FROM key_column_usage WHERE constraint_schema='" + this.fkTable.getSchema().getSchemaPath().getName()
+ "' AND constraint_name = '" + this.foreignKeyPath.getName() + "';");
while ( rs.next() ) {
final String columnName = rs.getString("column_name");
final String referencedColumnName = rs.getString("referenced_column_name");
final MySQLColumnMetaData fkColumn = this.fkTable.getColumnBuilder(columnName);
final MySQLColumnMetaData pkColumn = this.pkTable.getColumnBuilder(referencedColumnName);
final Short seq = rs.getShort("ordinal_position");
final BaseForeignKeyMetaDataBuilder<MySQLSchemaMetaDataBuilder,MySQLTableMetaDataBuilder,MySQLColumnMetaDataBuilder,MySQLForeignKeyMetaDataBuilder,MySQLIndexMetaDataBuilder,MySQLSchemaMetaData,MySQLTableMetaData,MySQLColumnMetaData,MySQLForeignKeyMetaData,MySQLIndexMetaData>.Entry entry = new BaseForeignKeyMetaDataBuilder.Entry(fkColumn, pkColumn, this, seq);
final MySQLColumnMetaDataBuilder columnBuilder = this.fkTable.getColumnBuilder(columnName);
columnBuilder.appendForeignKeyEntry(entry);
this.addEntry(entry);
}
} finally {
ResourceManagementUtils.closeResultSet(rs);
}
// Handle the situation that fkIndex is null, which will be happend when
// creating fk without a constraint name. The name of index
// auto-generated doesn't match the constraint name.
if ( null == this.fkIndex ) {
final Map<Short, MySQLColumnMetaData> fkColumns = new HashMap<Short, MySQLColumnMetaData>();
List<ForeignKeyMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> fkEntrySet = this.entryList;
for ( ForeignKeyMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : fkEntrySet ) {
fkColumns.put(entry.getSeq(), entry.getForeignKeyColumn());
}
Collection<MySQLIndexMetaDataBuilder> indexSet = this.fkTable.getIndexBuilderSet();
Map<Short, MySQLColumnMetaData> indexColumns = null;
for ( MySQLIndexMetaDataBuilder index : indexSet ) {
indexColumns = new HashMap<Short, MySQLColumnMetaData>();
final Collection<IndexMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> entrySet = index
.getEntrySet();
for ( IndexMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : entrySet ) {
indexColumns.put(entry.getPosition(), entry.getColumn());
}
// if ( fkColumns.size() != indexColumns.size() ) {
// continue;
// }
boolean matched = true;
for ( Short key : fkColumns.keySet() ) {
MySQLColumnMetaData pkColumn = fkColumns.get(key);
MySQLColumnMetaData indexColumn = indexColumns.get(key);
if ( !pkColumn.getColumnPath().equals(indexColumn.getColumnPath()) ) {
matched = false;
break;
}
}
if ( matched ) {
this.fkIndex = this.fkTable.getIndexBuilder(index.getIndexName());
break;
}
}
// if (null == this.fkIndex) {
// throw new IllegalStateException(MessageConsts.FK_INDEX_SHOULD_NOT_BE_NULL);
// }
}
return this;
}
| public MySQLForeignKeyMetaDataBuilder build(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = null;
try {
rs = stmt.executeQuery("SELECT * FROM referential_constraints WHERE constraint_schema='" + this.fkTable.getTablePath().getParent().getName()
+ "' AND constraint_name='" + this.foreignKeyPath.getName() + "';");
while ( rs.next() ) {
this.updateRule = CascadeRule.getRule(rs.getString("update_rule"));
this.deleteRule = CascadeRule.getRule(rs.getString("delete_rule"));
// [ToDo] [Tracy] about how to get pkTable
// Below code suppose the referenced table is in the same
// schema,
// but actually, the referenced table could be in another
// schema.
this.pkTable = this.fkTable.getSchema().getTableBuilder(rs.getString("referenced_table_name"));
// Note: some times unique_constraint_name is null
this.pkIndex = this.pkTable.getIndexBuilder(rs.getString("unique_constraint_name"));
this.fkIndex = this.fkTable.getIndexBuilder(rs.getString("constraint_name"));
}
} finally {
ResourceManagementUtils.closeResultSet(rs);
}
try {
rs = stmt.executeQuery("SELECT * FROM key_column_usage WHERE constraint_schema='" + this.fkTable.getSchema().getSchemaPath().getName()
+ "' AND constraint_name = '" + this.foreignKeyPath.getName() + "';");
while ( rs.next() ) {
final String columnName = rs.getString("column_name");
final String referencedColumnName = rs.getString("referenced_column_name");
final MySQLColumnMetaData fkColumn = this.fkTable.getColumnBuilder(columnName);
final MySQLColumnMetaData pkColumn = this.pkTable.getColumnBuilder(referencedColumnName);
final Short seq = rs.getShort("ordinal_position");
final BaseForeignKeyMetaDataBuilder<MySQLSchemaMetaDataBuilder,MySQLTableMetaDataBuilder,MySQLColumnMetaDataBuilder,MySQLForeignKeyMetaDataBuilder,MySQLIndexMetaDataBuilder,MySQLSchemaMetaData,MySQLTableMetaData,MySQLColumnMetaData,MySQLForeignKeyMetaData,MySQLIndexMetaData>.Entry entry = new BaseForeignKeyMetaDataBuilder.Entry(fkColumn, pkColumn, this, seq);
final MySQLColumnMetaDataBuilder columnBuilder = this.fkTable.getColumnBuilder(columnName);
columnBuilder.appendForeignKeyEntry(entry);
this.addEntry(entry);
}
} finally {
ResourceManagementUtils.closeResultSet(rs);
}
// Handle the situation that fkIndex is null, which will be happend when
// creating fk without a constraint name. The name of index
// auto-generated doesn't match the constraint name.
if ( null == this.fkIndex ) {
final Map<Short, MySQLColumnMetaData> fkColumns = new HashMap<Short, MySQLColumnMetaData>();
List<ForeignKeyMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> fkEntrySet = this.entryList;
for ( ForeignKeyMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : fkEntrySet ) {
fkColumns.put(entry.getSeq(), entry.getForeignKeyColumn());
}
Collection<MySQLIndexMetaDataBuilder> indexSet = this.fkTable.getIndexBuilderSet();
Map<Short, MySQLColumnMetaData> indexColumns = null;
for ( MySQLIndexMetaDataBuilder index : indexSet ) {
indexColumns = new HashMap<Short, MySQLColumnMetaData>();
final Collection<IndexMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> entrySet = index
.getEntrySet();
for ( IndexMetaData.Entry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : entrySet ) {
indexColumns.put(entry.getPosition(), entry.getColumn());
}
// if ( fkColumns.size() != indexColumns.size() ) {
// continue;
// }
boolean matched = true;
for ( Short key : fkColumns.keySet() ) {
MySQLColumnMetaData pkColumn = fkColumns.get(key);
MySQLColumnMetaData indexColumn = indexColumns.get(key);
if ( !pkColumn.getColumnPath().equals(indexColumn.getColumnPath()) ) {
matched = false;
break;
}
}
if ( matched && !index.getIndexName().equalsIgnoreCase("PRIMARY")) {
this.fkIndex = this.fkTable.getIndexBuilder(index.getIndexName());
break;
}
}
// if (null == this.fkIndex) {
// throw new IllegalStateException(MessageConsts.FK_INDEX_SHOULD_NOT_BE_NULL);
// }
}
return this;
}
|
diff --git a/GpsMidGraph/de/ueller/midlet/gps/data/Way.java b/GpsMidGraph/de/ueller/midlet/gps/data/Way.java
index dd5bc95d..7abf4ef2 100644
--- a/GpsMidGraph/de/ueller/midlet/gps/data/Way.java
+++ b/GpsMidGraph/de/ueller/midlet/gps/data/Way.java
@@ -1,2325 +1,2334 @@
/*
* GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net
* Copyright (c) 2008 sk750 at users dot sourceforge dot net
* See COPYING
*/
package de.ueller.midlet.gps.data;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Vector;
import de.enough.polish.util.Locale;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import net.sourceforge.jmicropolygon.PolygonGraphics;
import de.ueller.gps.data.Legend;
import de.ueller.gps.data.Configuration;
import de.ueller.gpsMid.mapData.SingleTile;
import de.ueller.gpsMid.mapData.Tile;
import de.ueller.midlet.gps.Logger;
import de.ueller.midlet.gps.RouteInstructions;
import de.ueller.midlet.gps.RouteLineProducer;
import de.ueller.midlet.gps.routing.Connection;
import de.ueller.midlet.gps.routing.ConnectionWithNode;
import de.ueller.midlet.gps.routing.TravelMode;
import de.ueller.midlet.gps.Trace;
import de.ueller.midlet.gps.tile.PaintContext;
import de.ueller.midlet.gps.tile.WayDescription;
/**
* handle Ways and arrays. Be careful, all paint parts useing static vars so painting
* is NOT thread save, because of Imagecollector is a single Thread which is the only one that
* uses painting of obects, its assured that one Way will be painted after the other.
* @author hmu
*
*/
/* Questions:
* - What classes are involved for getting the necessary Way data from the Jar?
* QueueDataReader read the whole tile, and calls this constructor to read the way details
* - Which region is covered by a SingleTile, does it always contain all Nodes of the complete way?
* Yes/No ;-) from the GpsMid data perspective a way is complete within a tile.
* from OSM Perspective ways are splited into two ways if they are to large
* - Where are the way nodes combined if a tile was split in Osm2GpsMid?
* in case of a split way, we have one part in one tile and a other part in an other tile.
* so the endpoint of one way is the same as the start point of the other way. In this case
* both tiles contains its own copy of this Node.
*/
public class Way extends Entity {
public static final byte WAY_FLAG_NAME = 1;
public static final byte WAY_FLAG_MAXSPEED = 2;
public static final byte WAY_FLAG_LAYER = 4;
public static final byte WAY_FLAG_RESERVED_FLAG = 8;
public static final byte WAY_FLAG_ONEWAY = 16;
// public static final byte WAY_FLAG_MULTIPATH = 4;
public static final byte WAY_FLAG_NAMEHIGH = 32;
public static final byte WAY_FLAG_AREA = 64;
// public static final byte WAY_FLAG_ISINHIGH = 64;
public static final int WAY_FLAG_ADDITIONALFLAG = 128;
public static final byte WAY_FLAG2_ROUNDABOUT = 1;
public static final byte WAY_FLAG2_TUNNEL = 2;
public static final byte WAY_FLAG2_BRIDGE = 4;
public static final byte WAY_FLAG2_CYCLE_OPPOSITE = 8;
public static final byte WAY_FLAG2_LONGWAY = 16;
public static final byte WAY_FLAG2_MAXSPEED_WINTER = 32;
/** http://wiki.openstreetmap.org/wiki/WikiProject_Haiti */
public static final byte WAY_FLAG2_DAMAGED = 64;
public static final int WAY_FLAG2_ADDITIONALFLAG = 128;
public static final byte WAY_FLAG3_URL = 1;
public static final byte WAY_FLAG3_URLHIGH = 2;
public static final byte WAY_FLAG3_PHONE = 4;
public static final byte WAY_FLAG3_PHONEHIGH = 8;
public static final byte WAY_FLAG3_NAMEASFORAREA = 16;
public static final byte WAY_FLAG3_HAS_HOUSENUMBERS = 32;
public static final byte WAY_FLAG3_LONGHOUSENUMBERS = 64;
public static final byte DRAW_BORDER=1;
public static final byte DRAW_AREA=2;
public static final byte DRAW_FULL=3;
private static final int MaxSpeedMask = 0xff;
private static final int MaxSpeedShift = 0;
//private static final int ModMask = 0xff00;
private static final int ModShift = 8;
public static final int WAY_ONEWAY = 1 << ModShift;
public static final int WAY_AREA = 2 << ModShift;
public static final int WAY_ROUNDABOUT = 4 << ModShift;
public static final int WAY_TUNNEL = 8 << ModShift;
public static final int WAY_BRIDGE = 16 << ModShift;
public static final int WAY_CYCLE_OPPOSITE = 32 << ModShift;
/** http://wiki.openstreetmap.org/wiki/WikiProject_Haiti */
public static final int WAY_DAMAGED = 64 << ModShift;
public static final int WAY_NAMEASFORAREA = 128 << ModShift;
public static final byte PAINTMODE_COUNTFITTINGCHARS = 0;
public static final byte PAINTMODE_DRAWCHARS = 1;
public static final byte INDENT_PATHNAME = 2;
private static final int PATHSEG_DO_NOT_HIGHLIGHT = -1;
private static final int PATHSEG_DO_NOT_DRAW = -2;
private static final int HIGHLIGHT_NONE = 0;
private static final int HIGHLIGHT_DEST = 1;
private static final int HIGHLIGHT_ROUTEPATH_CONTAINED = 2;
protected static final Logger logger = Logger.getInstance(Way.class, Logger.TRACE);
public int flags = 0;
private int flagswinter = 0;
/** indicate by which route modes this way can be used (motorcar, bicycle, etc.)
* Each bit represents one of the route modes in the midlet, with bit 0 being the first route mode.
* The routeability of the way in each route mode is determined by Osm2GpsMid,
* which derives it from the accessible flag of the wValue of way type's description
* and the routeAccess specifications in the style file
* Higher bits (bit 4 to 7 are used for the same flags like in Connection)
*/
private byte wayRouteModes = 0;
public short[] path;
public short minLat;
public short minLon;
public short maxLat;
public short maxLon;
public short wayNrInFile = 0;
public int nameIdx = -1;
public int urlIdx = -1;
public int phoneIdx = -1;
/**
* This is a buffer for the drawing routines
* so that we don't have to allocate new
* memory at each time we draw a way. This
* saves some time on memory management
* too.
*
* This makes this function thread unsafe,
* so make sure we only have a single thread
* drawing a way at a time
*/
private static int [] x = new int[100];
private static int [] y = new int[100];
/**
* contains either PATHSEG_DO_NOT_HIGHLIGHT, PATHSEG_DO_NOT_DRAW
* or if this way's segment is part of the route path,
* the index of the corresponding ConnectionWithNode in the route
*/
private static int [] hl = new int[100];
private static Font areaFont;
private static int areaFontHeight;
private static Font pathFont;
private static int pathFontHeight;
private static int pathFontMaxCharWidth;
private static int pathFontBaseLinePos;
/** Point Line 1 begin; note: Line 1 and Line 2 form a waysegment (read as Line1Begin) */
static final IntPoint l1b = new IntPoint();
/** Point Line 1 begin; note: Line 1 and Line 2 form a waysegment (read as Line1End) */
static final IntPoint l1e = new IntPoint();
/** Point Line 2 begin; note: Line 1 and Line 2 form a waysegment (read as Line2Begin) */
static final IntPoint l2b = new IntPoint();
/** Point Line 2 begin; note: Line 1 and Line 2 form a waysegment (read as Line2End) */
static final IntPoint l2e = new IntPoint();
/** Point Line 3 begin; note: Line 3 and Line 4 form a waysegment (read as Line3Begin) */
static final IntPoint l3b = new IntPoint();
/** Point Line 3 begin; note: Line 3 and Line 4 form a waysegment (read as Line3End) */
static final IntPoint l3e = new IntPoint();
/** Point Line 4 begin; note: Line 3 and Line 4 form a waysegment (read as Line4Begin) */
static final IntPoint l4b = new IntPoint();
/** Point Line 5 begin; note: Line 3 and Line 4 form a waysegment (read as Line4End) */
static final IntPoint l4e = new IntPoint();
/** stores the intersection-point of the inner turn */
static final IntPoint intersecP = new IntPoint();
/** Enables or disables the match travelling direction for actual way calculation heuristic */
private static boolean addDirectionalPenalty = false;
/** Sets the scale of the directional penalty dependent on the projection used. */
private static float scalePen = 0;
/*
* Precalculated normalised vector for the direction of current travel,
* used in the the directional penalty heuristic
*/
private static float courseVecX = 0;
private static float courseVecY = 0;
private static WaySegment waySegment = new WaySegment();
// private final static Logger logger = Logger.getInstance(Way.class,
// Logger.TRACE);
public Way() {
super();
}
/**
* The flag should be read by caller. If FLAGS == 128 this is a dummy way
* and can be ignored.
*
* @param is Tile inputstream
* @param f flags this is read by the caller
* @param t Tile
* @param layers: this is somewhat awkward. We need to get the layer information back out to
* the caller, so use a kind of call by reference
* @param idx index into the layers array where to store the layer info.
* @param nodes
* @throws IOException
*/
public Way(DataInputStream is, byte f, Tile t, byte[] layers, int idx) throws IOException {
minLat = is.readShort();
minLon = is.readShort();
maxLat = is.readShort();
maxLon = is.readShort();
type = is.readByte();
setWayRouteModes(is.readByte());
if ((f & WAY_FLAG_NAME) == WAY_FLAG_NAME) {
if ((f & WAY_FLAG_NAMEHIGH) == WAY_FLAG_NAMEHIGH) {
nameIdx = is.readInt();
//System.out.println("Name_High " + f );
} else {
nameIdx = is.readShort();
}
}
if ((f & WAY_FLAG_MAXSPEED) == WAY_FLAG_MAXSPEED) {
// logger.debug("read maxspeed");
flags = is.readByte() & 0xff; // apply an 8 bit mask to the maxspeed byte read so values >127 won't result in a negative integer with wrong bits set for the flags
}
byte f2=0;
byte f3=0;
if ( (f & WAY_FLAG_ADDITIONALFLAG) > 0 ) {
f2 = is.readByte();
if ( (f2 & WAY_FLAG2_ROUNDABOUT) > 0 ) {
flags += WAY_ROUNDABOUT;
}
if ( (f2 & WAY_FLAG2_TUNNEL) > 0 ) {
flags += WAY_TUNNEL;
}
if ( (f2 & WAY_FLAG2_BRIDGE) > 0 ) {
flags += WAY_BRIDGE;
}
if ( (f2 & WAY_FLAG2_DAMAGED) > 0 ) {
flags += WAY_DAMAGED;
}
if ( (f2 & WAY_FLAG2_CYCLE_OPPOSITE) > 0 ) {
flags += WAY_CYCLE_OPPOSITE;
}
if ( (f2 & WAY_FLAG2_ADDITIONALFLAG) == WAY_FLAG2_ADDITIONALFLAG ) {
f3 = is.readByte();
if ( (f3 & WAY_FLAG3_NAMEASFORAREA) > 0) {
flags += WAY_NAMEASFORAREA;
}
if ( (f3 & WAY_FLAG3_URL) > 0 ) {
if ( (f3 & WAY_FLAG3_URLHIGH) > 0 ) {
urlIdx = is.readInt();
} else {
urlIdx = is.readShort();
}
}
if ( (f3 & WAY_FLAG3_PHONE) > 0 ) {
if ( (f3 & WAY_FLAG3_PHONEHIGH) > 0 ) {
phoneIdx = is.readInt();
} else {
phoneIdx = is.readShort();
}
}
if ( (f3 & WAY_FLAG3_HAS_HOUSENUMBERS) > 0 ) {
int hcount;
// Ignore the data for now
if ( (f3 & WAY_FLAG3_LONGHOUSENUMBERS) > 0 ) {
hcount = is.readShort();
if (hcount < 0) {
hcount += 65536;
}
} else {
hcount = is.readByte();
if (hcount < 0) {
hcount += 256;
}
}
logger.debug("expecting " + hcount + " housenumber nodes");
for (short i = 0; i < hcount; i++) {
is.readLong();
}
}
}
}
if ((f2 & WAY_FLAG2_MAXSPEED_WINTER) == WAY_FLAG2_MAXSPEED_WINTER) {
setFlagswinter(is.readByte());
}
layers[idx] = 0;
if ((f & WAY_FLAG_LAYER) == WAY_FLAG_LAYER) {
/**
* TODO: We are currently ignoring the layer info
* Please implement proper support for this when rendering
*/
layers[idx] = is.readByte();
}
if ((f & WAY_FLAG_ONEWAY) == WAY_FLAG_ONEWAY) {
flags += WAY_ONEWAY;
}
if ((f & WAY_FLAG_AREA) > 0){
flags += WAY_AREA;
logger.debug("Area = true");
}
// if (((f & WAY_FLAG_AREA) == WAY_FLAG_AREA) || Legend.getWayDescription(type).isArea) {
// if ((f & WAY_FLAG_AREA) == WAY_FLAG_AREA) {
// //#debug debug
// logger.debug("Loading explicit Area: " + this);
// }
// flags += WAY_AREA;
// }
boolean longWays = false;
if ((f2 & WAY_FLAG2_LONGWAY) > 0) {
longWays = true;
logger.debug("longway = true");
}
int count;
if (longWays) {
count = is.readShort();
if (count < 0) {
count += 65536;
}
} else {
count = is.readByte();
if (count < 0) {
count += 256;
}
}
path = new short[count];
logger.debug("expecting " + count + " nodes");
for (short i = 0; i < count; i++) {
path[i] = is.readShort();
}
}
private void readVerify(byte expect,String msg,DataInputStream is){
try {
byte next=is.readByte();
if (next == expect) {
logger.debug("Verify Way " + expect + " OK" +msg);
return;
}
logger.debug("Error while verify Way " + msg + " expect " + expect + " got " + next);
for (int l=0; l<10 ; l++){
logger.debug(" " + is.readByte());
}
System.exit(-1);
} catch (IOException e) {
logger.error(Locale.get("way.ErrorWhileVerify")/*Error while verify */ + msg + " " + e.getMessage());
}
}
public boolean isRoutableWay() {
return (getWayRouteModes() & Configuration.getTravelMask()) != 0;
}
/**
* Precalculate parameters to quickly test the the directional overlap between
* a way and the current direction of travelling. This is used in processWay
* to calculate the most likely way we are currently travelling on.
*
* @param pc
* @param speed
*/
public static void setupDirectionalPenalty(PaintContext pc, int speed, boolean gpsRecenter) {
//Only use this heuristic if we are travelling faster than 6 km/h, as otherwise
//the direction estimate is too bad to be of much use. Also, only use the direction
//if we are actually using the gps to center the map and not manually panning around.
if ((speed < 7) || !gpsRecenter) {
addDirectionalPenalty = false;
scalePen = 0;
return;
}
addDirectionalPenalty = true;
Projection p = pc.getP();
float lat1 = pc.center.radlat;
float lon1 = pc.center.radlon;
IntPoint lineP1 = new IntPoint();
IntPoint lineP2 = new IntPoint();
float lat2 = pc.center.radlat + (float) (0.00001 * Math.cos(pc.course * MoreMath.FAC_DECTORAD));
float lon2 = pc.center.radlon + (float) (0.00001 * Math.sin(pc.course * MoreMath.FAC_DECTORAD));
p.forward(lat1, lon1, lineP1);
p.forward(lat2, lon2, lineP2);
courseVecX = lineP1.x - lineP2.x;
courseVecY = lineP1.y - lineP2.y;
float norm = (float)Math.sqrt(courseVecX * courseVecX + courseVecY * courseVecY);
courseVecX /= norm; courseVecY /= norm;
//Calculate the lat and lon coordinates of two
//points that are 35 pixels apart
Node n1 = new Node();
Node n2 = new Node();
pc.getP().inverse(10, 10, n1);
pc.getP().inverse(45, 10, n2);
//Calculate the distance between them in meters
float d = ProjMath.getDistance(n1, n2);
//Set the scale of the direction penalty to roughly
//match that of a penalty of 100m at a 90 degree angle
scalePen = 35.0f / d * 100.0f;
}
public boolean isOnScreen( short pcLDlat, short pcLDlon, short pcRUlat, short pcRUlon) {
if ((maxLat < pcLDlat) || (minLat > pcRUlat)) {
return false;
}
if ((maxLon < pcLDlon) || (minLon > pcRUlon)) {
return false;
}
return true;
}
public float wayBearing(SingleTile t) {
return (float) MoreMath.bearing_int(
t.nodeLat[path[0]] * MoreMath.FIXPT_MULT_INV + t.centerLat,
t.nodeLon[path[0]] * MoreMath.FIXPT_MULT_INV + t.centerLon,
t.nodeLat[path[path.length - 1]] * MoreMath.FIXPT_MULT_INV + t.centerLat,
t.nodeLon[path[path.length - 1]] * MoreMath.FIXPT_MULT_INV + t.centerLon);
}
public void paintAsPath(PaintContext pc, SingleTile t, byte layer) {
processPath(pc,t,Tile.OPT_PAINT, layer);
}
public void paintHighlightPath(PaintContext pc, SingleTile t, byte layer) {
processPath(pc,t,Tile.OPT_PAINT | Tile.OPT_HIGHLIGHT, layer);
}
private void changeCountNameIdx(PaintContext pc, int diff) {
if (nameIdx >= 0) {
Integer oCount = (Integer) pc.conWayNameIdxs.get(nameIdx);
int nCount = 0;
if (oCount != null) {
nCount = oCount.intValue();
}
pc.conWayNameIdxs.put(nameIdx, new Integer(nCount + diff) );
}
}
/* check if the way contains the nodes searchCon1 and searchCon2
* if it does, but we already have a matching way,
* only take this way if it has the shortest path from searchCon1 to searchCon2
**/
public void connections2WayMatch(PaintContext pc, SingleTile t) {
boolean containsCon1 = false;
boolean containsCon2 = false;
short containsCon1At = 0;
short containsCon2At = 0;
short searchCon1Lat = (short) ((pc.searchCon1Lat - t.centerLat) * MoreMath.FIXPT_MULT);
short searchCon1Lon = (short) ((pc.searchCon1Lon - t.centerLon) * MoreMath.FIXPT_MULT);
short searchCon2Lat = (short) ((pc.searchCon2Lat - t.centerLat) * MoreMath.FIXPT_MULT);
short searchCon2Lon = (short) ((pc.searchCon2Lon - t.centerLon) * MoreMath.FIXPT_MULT);
boolean isCircleway = isCircleway(t);
byte bearingForward = 0;
byte bearingBackward = 0;
// check if way contains both search connections
// System.out.println("search path nodes: " + path.length);
for (short i = 0; i < path.length; i++) {
int idx = path[i];
// System.out.println("lat:" + t.nodeLat[idx] + "/" + searchCon1Lat);
if ( (Math.abs(t.nodeLat[idx] - searchCon1Lat) < 2)
&&
(Math.abs(t.nodeLon[idx] - searchCon1Lon) < 2)
) {
if (
this.isRoutableWay()
// count in roundabouts only once (search connection could match at start and end node)
&& !containsCon1
// count only if it's not a oneway ending at this connection (and no against oneway rule applies)
&& !(isOneDirectionOnly() && (i == path.length - 1 && !isCircleway) )
) {
// remember bearings of the ways at this connection, so we can later check out if we have multiple straight-ons requiring a bearing instruction
// we do this twice for each found way to add the bearings for forward and backward
for (int d = -1 ; d <= 1; d += 2) {
// do not add bearings against direction if this is a oneway (and no against oneway rule applies)
if (d == -1 && isOneDirectionOnly()) {
continue;
}
if ( (i + d) < path.length && (i + d) >= 0) {
short rfCurr = (short) Legend.getWayDescription(this.type).routeFlags;
// count bearings for entering / leaving the motorway. We don't need to give bearing instructions if there's only one motorway alternative at the connection
if (RouteInstructions.isEnterMotorway(pc.searchConPrevWayRouteFlags, rfCurr)
||
RouteInstructions.isLeaveMotorway(pc.searchConPrevWayRouteFlags, rfCurr)
) {
pc.conWayNumMotorways++;
}
if (pc.conWayBearingsCount < 8) {
pc.conWayBearingHasName[pc.conWayBearingsCount] = (nameIdx >= 0);
pc.conWayBearingWayType[pc.conWayBearingsCount] = this.type;
int idxC = path[i + d];
/* if the route node and the next node on the way are very close together, use one node later on the way for the bearing calculation:
* this especially prevents issues with almost identical coordinates from the start point to the next node on the way like
* http://www.openstreetmap.org/browse/node/429201917 and http://www.openstreetmap.org/browse/node/21042290
* (as we can't distinguish them exactly enough with fix point coordinates)
*/
int iAfterNext = i + d + d;
if (
MoreMath.dist(
pc.searchCon1Lat,
pc.searchCon1Lon,
t.centerLat + t.nodeLat[idxC] * MoreMath.FIXPT_MULT_INV,
t.centerLon + t.nodeLon[idxC] * MoreMath.FIXPT_MULT_INV
)
< 3
&&
// FIXME: It might even make sense to take the next way into account if there's no next node on this way
iAfterNext < path.length
&&
iAfterNext >= 0)
{
idxC = path [iAfterNext];
//System.out.println("EXAMINE AFTER NEXT");
}
pc.conWayBearings[pc.conWayBearingsCount] =
MoreMath.bearing_start(
(pc.searchCon1Lat),
(pc.searchCon1Lon),
(t.centerLat + t.nodeLat[idxC] * MoreMath.FIXPT_MULT_INV),
(t.centerLon + t.nodeLon[idxC] * MoreMath.FIXPT_MULT_INV)
);
if (d == 1) {
bearingForward = pc.conWayBearings[pc.conWayBearingsCount];
} else {
bearingBackward = pc.conWayBearings[pc.conWayBearingsCount];
}
// System.out.println("Bearing: " + pc.conWayBearings[pc.conWayBearingsCount] + new Node(t.centerLat+ t.nodeLat[idxC] * MoreMath.FIXPT_MULT_INV, t.centerLon + t.nodeLon[idxC] * MoreMath.FIXPT_MULT_INV, true).toString());
pc.conWayBearingsCount++;
} else {
// System.out.println("Bearing count is > 8");
}
}
}
// remember nameIdx's leading away from the connection, so we can later on check if multiple ways lead to the same street name
changeCountNameIdx(pc, 1);
//System.out.println("add 1 " + "con1At: " + i + " pathlen - 1: " + (path.length - 1) );
pc.conWayNumToRoutableWays++;
// if we are in the middle of the way, count the way once more (if no against oneway rule applies)
if (i != 0 && i != path.length - 1 && !isOneDirectionOnly()) {
pc.conWayNumToRoutableWays++;
changeCountNameIdx(pc, 1);
//System.out.println("add middle 1 " + "con1At: " + i + " pathlen - 1: " + (path.length - 1) );
}
}
containsCon1 = true;
containsCon1At = i;
// System.out.println("con1 match");
if (containsCon1 && containsCon2) break;
}
if ( (Math.abs(t.nodeLat[idx] - searchCon2Lat) < 2)
&&
(Math.abs(t.nodeLon[idx] - searchCon2Lon) < 2)
) {
containsCon2 = true;
containsCon2At = i;
// System.out.println("con2 match");
if (containsCon1 && containsCon2) break;
}
}
// we've got a match
if (containsCon1 && containsCon2) {
WayDescription wayDesc = Legend.getWayDescription(this.type);
float conWayRealDistance = 0;
short from = containsCon1At;
short to = containsCon2At;
int direction = 1;
if (from > to && !(isRoundAbout() || isCircleway) ) {
// if this is a oneway but not a roundabout or circle way it can't be
// the route path as we would go against the oneway's direction (if no against oneway rule applies)
if (isOneDirectionOnly()) {
return;
}
// swap direction
from = to;
to = containsCon1At;
direction = -1;
}
int idx1 = path[from];
int idx2;
// sum up the distance of the segments between searchCon1 and searchCon2
for (short i = from; i != to; i++) {
if ( (isRoundAbout() || isCircleway) && i >= (path.length - 2)) {
i=-1; // if in roundabout at end of path continue at first node
if (to == (path.length - 1) ) {
break;
}
}
idx2 = path[i+1];
float dist = ProjMath.getDistance(
(t.centerLat + t.nodeLat[idx1] * MoreMath.FIXPT_MULT_INV),
(t.centerLon + t.nodeLon[idx1] * MoreMath.FIXPT_MULT_INV),
(t.centerLat + t.nodeLat[idx2] * MoreMath.FIXPT_MULT_INV),
(t.centerLon + t.nodeLon[idx2] * MoreMath.FIXPT_MULT_INV));
conWayRealDistance += dist;
idx1 = idx2;
}
/* check if this is a better match than a maybe previous one:
if the distance is closer than the already matching one
this way contains a better path between the connections
*/
if (conWayRealDistance < pc.conWayDistanceToNext &&
/* check if way is routable
* (there are situations where 2 ways have the same nodes, e.g. a tram and a highway)
*/
this.isRoutableWay()
) {
// if (pc.conWayDistanceToNext != Float.MAX_VALUE) {
// String name1=null, name2=null;
// if (pc.conWayNameIdx != -1) name1=Trace.getInstance().getName(pc.conWayNameIdx);
// if (this.nameIdx != -1) name2=Trace.getInstance().getName(this.nameIdx);
// System.out.println("REPLACE " + pc.conWayDistanceToNext + "m (" + Legend.getWayDescription(pc.conWayType).description + " " + (name1==null?"":name1) + ")");
// System.out.println("WITH " + conWayRealDistance + "m (" + Legend.getWayDescription(this.type).description + " " + (name2==null?"":name2) + ")");
// }
// this is currently the best path between searchCon1 and searchCon2
pc.conWayDistanceToNext = conWayRealDistance;
pc.conWayMaxSpeed = (short) getMaxSpeed();
if (getMaxSpeedWinter() != 0 && Configuration.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER)) {
pc.conWayMaxSpeed = (short) getMaxSpeedWinter();
}
pc.conWayCombinedFileAndWayNr = getWayId(t);
pc.conWayFromAt = containsCon1At;
pc.conWayToAt = containsCon2At;
pc.conWayNameIdx= this.nameIdx;
pc.conWayType = this.type;
short routeFlags = (short) wayDesc.routeFlags;
if (isRoundAbout()) routeFlags += Legend.ROUTE_FLAG_ROUNDABOUT;
if (isTunnel()) routeFlags += Legend.ROUTE_FLAG_TUNNEL;
if (isBridge()) routeFlags += Legend.ROUTE_FLAG_BRIDGE;
if (isOneDirectionOnly()) routeFlags += Legend.ROUTE_FLAG_ONEDIRECTION_ONLY;
pc.conWayRouteFlags = routeFlags;
// substract way we are coming from from turn options with same name
changeCountNameIdx(pc, -1);
//System.out.println("sub 1");
// calculate bearings
if ( (direction == 1 && containsCon1At < (path.length - 1))
||
(direction == -1 && containsCon1At > 0)
) {
pc.conWayStartBearing = (direction==1) ? bearingForward : bearingBackward;
// pc.conWayStartBearing = MoreMath.bearing_start(
// (pc.searchCon1Lat),
// (pc.searchCon1Lon),
// (t.centerLat + t.nodeLat[idxC] * MoreMath.FIXPT_MULT_INV),
// (t.centerLon + t.nodeLon[idxC] * MoreMath.FIXPT_MULT_INV)
// );
}
// System.out.println("pc.conWayStartBearing: " + pc.conWayStartBearing);
if (
containsCon2At - direction >= 0
&&
containsCon2At - direction < path.length
) {
int idxC = path[containsCon2At - direction];
/* if the route node and the previous node on the way are very close together, use one node before on the way for the bearing calculation:
* this especially prevents issues with almost identical coordinates from the previous node on the way and the route node
* (as we can't distinguish them exactly enough with fix point coordinates)
*/
int iBeforePrevious = containsCon2At - direction - direction;
if (
MoreMath.dist(
t.centerLat + t.nodeLat[idxC] * MoreMath.FIXPT_MULT_INV,
t.centerLon + t.nodeLon[idxC] * MoreMath.FIXPT_MULT_INV,
pc.searchCon2Lat,
pc.searchCon2Lon
)
< 3
// FIXME: It might even make sense to take the previous way into account if there's no previous node on this way
&&
iBeforePrevious >= 0
&&
iBeforePrevious < path.length
) {
idxC = path [iBeforePrevious];
}
pc.conWayEndBearing = MoreMath.bearing_start(
(t.centerLat + t.nodeLat[idxC] * MoreMath.FIXPT_MULT_INV),
(t.centerLon + t.nodeLon[idxC] * MoreMath.FIXPT_MULT_INV),
(pc.searchCon2Lat),
(pc.searchCon2Lon)
);
}
}
}
}
private int getWayId(SingleTile t) {
return (t.fileId << 16) + wayNrInFile;
}
/**
* check if the area contains the nodes searchCon1 and searchCon2
**/
public void connections2AreaMatch(PaintContext pc, SingleTile t) {
boolean containsCon1 = false;
boolean containsCon2 = false;
short searchCon1Lat = (short)((pc.searchCon1Lat - t.centerLat) * MoreMath.FIXPT_MULT);
short searchCon1Lon = (short)((pc.searchCon1Lon - t.centerLon) * MoreMath.FIXPT_MULT);
short searchCon2Lat = (short)((pc.searchCon2Lat - t.centerLat) * MoreMath.FIXPT_MULT);
short searchCon2Lon = (short)((pc.searchCon2Lon - t.centerLon) * MoreMath.FIXPT_MULT);
// check if area way contains both search connections
// System.out.println("search area nodes: " + path.length);
for (short i = 0; i < path.length; i++) {
int idx = path[i];
// System.out.println("lat:" + t.nodeLat[idx] + "/" + searchCon1Lat);
if ( (Math.abs(t.nodeLat[idx] - searchCon1Lat) < 2)
&&
(Math.abs(t.nodeLon[idx] - searchCon1Lon) < 2)
) {
containsCon1 = true;
// System.out.println("con1 match");
if (containsCon1 && containsCon2) break;
}
if ( (Math.abs(t.nodeLat[idx] - searchCon2Lat) < 2)
&&
(Math.abs(t.nodeLon[idx] - searchCon2Lon) < 2)
) {
containsCon2 = true;
// System.out.println("con2 match");
if (containsCon1 && containsCon2) break;
}
}
// we've got a match
if (containsCon1 && containsCon2) {
pc.conWayDistanceToNext = 0; // must be filled in later
pc.conWayNameIdx= this.nameIdx;
pc.conWayType = this.type;
short routeFlags = (short) Legend.getWayDescription(this.type).routeFlags;
routeFlags |= Legend.ROUTE_FLAG_AREA;
pc.conWayRouteFlags = routeFlags;
}
}
public void processPath(PaintContext pc, SingleTile t, int mode, byte layer) {
WayDescription wayDesc = Legend.getWayDescription(type);
/** width of the way to be painted */
int w = 0;
byte highlight=HIGHLIGHT_NONE;
/**
* If the static array is not large enough, increase it
*/
if (x.length < path.length) {
x = new int[path.length];
y = new int[path.length];
hl = new int[path.length];
}
// initialize with default draw states for the path's segments
int hlDefault = PATHSEG_DO_NOT_HIGHLIGHT;
if ( (mode & Tile.OPT_HIGHLIGHT) != 0) {
hlDefault = PATHSEG_DO_NOT_DRAW;
}
for (int i1 = 0; i1 < path.length; i1++) {
hl[i1] = hlDefault;
}
if ((mode & Tile.OPT_PAINT) > 0) {
byte om = Legend.getWayOverviewMode(type);
switch (om & Legend.OM_MODE_MASK) {
case Legend.OM_SHOWNORMAL:
// if not in Overview Mode check for scale
if (pc.scale > wayDesc.maxScale * Configuration.getDetailBoostMultiplier()) {
return;
}
break;
case Legend.OM_HIDE:
if (wayDesc.hideable) {
return;
}
break;
}
switch (om & Legend.OM_NAME_MASK) {
case Legend.OM_WITH_NAMEPART:
if (nameIdx == -1) {
return;
}
String name = pc.trace.getName(nameIdx);
String url = pc.trace.getUrl(urlIdx);
if (name == null) {
return;
} else {
if (url != null) {
name = name + url;
}
}
/**
* The overview filter mode allows you to restrict showing ways if their name
* does not match a substring. So check if this condition is fulfilled.
*/
if (name.toUpperCase().indexOf(Legend.get0Poi1Area2WayNamePart((byte) 2).toUpperCase()) == -1) {
return;
}
break;
case Legend.OM_WITH_NAME:
if (nameIdx == -1) {
return;
}
break;
case Legend.OM_NO_NAME:
if (nameIdx != -1) {
return;
}
break;
}
/**
* check if way matches to one or more route connections,
* so we can highlight the route line parts
*/
// TODO: Refactor this to a method of its own to avoid the many levels
// of indentation here. This will also make the code easier to understand
// as the method name can describe what is being done.
if (RouteLineProducer.isWayIdUsedByRouteLine(getWayId(t)) ) {
Vector route=pc.trace.getRoute();
ConnectionWithNode c;
if (route!=null && route.size()!=0) {
for (int i = 0; i < route.size() - 1; i++) {
c = (ConnectionWithNode) route.elementAt(i);
if (c.wayNameIdx == this.nameIdx) {
if (path.length > c.wayFromConAt && path.length > c.wayToConAt) {
int idx = path[c.wayFromConAt];
short searchCon1Lat = (short) ((c.to.lat - t.centerLat) * MoreMath.FIXPT_MULT);
if ( (Math.abs(t.nodeLat[idx] - searchCon1Lat) < 2) ) {
short searchCon1Lon = (short) ((c.to.lon - t.centerLon) * MoreMath.FIXPT_MULT);
if ( (Math.abs(t.nodeLon[idx] - searchCon1Lon) < 2) ) {
idx = path[c.wayToConAt];
ConnectionWithNode c2 = (ConnectionWithNode) route.elementAt(i + 1);
searchCon1Lat = (short) ((c2.to.lat - t.centerLat) * MoreMath.FIXPT_MULT);
if ( (Math.abs(t.nodeLat[idx] - searchCon1Lat) < 2) ) {
searchCon1Lon = (short) ((c2.to.lon - t.centerLon) * MoreMath.FIXPT_MULT);
if ( (Math.abs(t.nodeLon[idx] - searchCon1Lon) < 2) ) {
// if we are not in highlight mode, flag that this layer contains a path segment to highlight
if ((mode & Tile.OPT_HIGHLIGHT) == 0) {
pc.hlLayers |= (1<<layer);
}
// set way highlight flag so we can quickly determine if this way contains a route line part
highlight = HIGHLIGHT_ROUTEPATH_CONTAINED;
/*
* flag the parts of the way as to be highlighted
* by putting in the index of the corresponding connection
*/
short from = c.wayFromConAt;
short to = c.wayToConAt;
boolean isCircleway = isCircleway(t);
if (from > to && !(isRoundAbout() || isCircleway) ) {
// swap direction
to = from;
from = c.wayToConAt;
}
for (int n = from; n != to; n++) {
hl[n] = i;
if ( ( isRoundAbout() || isCircleway ) && n >= (path.length - 1) ) {
// if in roundabout at end of path continue at first node
n = -1;
if (to == (path.length - 1) ) {
break;
}
}
}
}
}
}
}
}
}
}
}
}
}
/**
* If this way is not to be highlighted but we are in highlight mode,
* skip the rest of the processing of this way
*/
if (highlight == HIGHLIGHT_NONE && (mode & Tile.OPT_HIGHLIGHT) != 0) {
return;
}
/**
* We go through the way segment by segment
* (a segment is a line between two consecutive points on the path).
* lineP1 is first node of the segment, lineP2 is the second.
*/
IntPoint lineP1 = pc.lineP1;
IntPoint lineP2 = pc.lineP2;
IntPoint swapLineP = pc.swapLineP;
Projection p = pc.getP();
boolean orthogonal=p.isOrthogonal();
int pi=0;
for (int i1 = 0; i1 < path.length; i1++) {
int idx = path[i1];
p.forward(t.nodeLat[idx], t.nodeLon[idx], lineP2,t);
if (lineP1 == null) {
/**
* This is the first segment of the path, so we don't have a lineP1 yet
*/
lineP1 = lineP2;
lineP2 = swapLineP;
x[pi] = lineP1.x;
y[pi++] = lineP1.y;
} else {
/**
* We save some rendering time, by doing a line simplification on the fly.
* If two nodes are very close by, then we can simply drop one of the nodes
* and draw the line between the other points. If the way is highlighted,
* we can't do any simplification, as we need to determine the index of the segment
* that is closest to the center (= map center) of the PaintContext
*/
if (highlight == HIGHLIGHT_ROUTEPATH_CONTAINED || ! lineP1.approximatelyEquals(lineP2)){
/**
* calculate closest distance to specific ways
*/
IntPoint center = pc.getP().getImageCenter();
float dst = MoreMath.ptSegDistSq(lineP1.x, lineP1.y,
lineP2.x, lineP2.y, center.x, center.y);
// String name = pc.trace.getName(nameIdx);
// if (dst < pc.squareDstToWay){
// System.out.println(" Way " + name + " dst=" + dst);
// }
// let see where the imageCenter is at this point
// TODO: hmu comment out
// try {
// pc.g.drawLine(center.x-5, center.y-7, center.x+5, center.y+7);
// pc.g.drawLine(center.x-5, center.y+7, center.x+5, center.y-7);
// } catch(Exception e){
//
// }
if (dst < pc.squareDstToWay || dst < pc.squareDstToActualRoutableWay || dst < pc.squareDstToRoutePath) {
float pen = 0;
/**
* Add a heuristic so that the direction of travel and the direction
* of the way should more or less match if we are travelling on this way
*/
if (addDirectionalPenalty) {
int segDirVecX = lineP1.x - lineP2.x;
int segDirVecY = lineP1.y - lineP2.y;
float norm = (float) Math.sqrt((double)(segDirVecX * segDirVecX + segDirVecY * segDirVecY));
//This is a hack to use a linear approximation to keep computational requirements down
pen = scalePen * (1.0f - Math.abs((segDirVecX * courseVecX + segDirVecY * courseVecY) / norm));
pen *= pen;
}
float dstWithPen = dst + pen;
// if this way is closer including penalty than the old one set it as new actualWay
if (dstWithPen < pc.squareDstToWay) {
pc.squareDstToWay = dst + pen;
pc.actualWay = this;
pc.actualSingleTile = t;
}
if (this.isRoutableWay()) {
// if this routable way is closer including penalty than the old one set it as new actualRoutableWay
if (dstWithPen < pc.squareDstToActualRoutableWay) {
pc.squareDstToActualRoutableWay = dst + pen;
pc.actualRoutableWay = this;
}
// if this is a highlighted path seg and it's closer than the old one including penalty set it as new one
if ((hl[i1 - 1] > PATHSEG_DO_NOT_HIGHLIGHT) && (dstWithPen < pc.squareDstWithPenToRoutePath)) {
pc.squareDstWithPenToRoutePath = dst + pen;
pc.squareDstToRoutePath = dst;
pc.routePathConnection = hl[i1 - 1];
pc.pathIdxInRoutePathConnection = pi;
}
}
}
x[pi] = lineP2.x;
y[pi++] = lineP2.y;
swapLineP = lineP1;
lineP1 = lineP2;
lineP2 = swapLineP;
} else if ((i1+1) == path.length) {
/**
* This is an endpoint, so we can't simply drop it, as the lines would potentially look disconnected
*/
//System.out.println(" endpoint " + lineP2.x + "/" + lineP2.y+ " " + pc.trace.getName(nameIdx));
if (!lineP1.equals(lineP2)) {
x[pi] = lineP2.x;
y[pi++] = lineP2.y;
} else {
//System.out.println(" discarding never the less");
}
} else {
/**
* Drop this point, it is redundant
*/
//System.out.println(" discard " + lineP2.x + "/" + lineP2.y+ " " +pc.trace.getName(nameIdx));
}
}
}
swapLineP = lineP1;
lineP1 = null;
/**
* TODO: Can we remove this call and do it the same way as with actualWay and introduce a
* pc.actualRoutableWaySingleTile and only calculate the entity and position mark when we need them?
*/
if ((pc.actualRoutableWay == this) && ((pc.currentPos == null) || (pc.currentPos.entity != this))) {
pc.currentPos = new RoutePositionMark(pc.center.radlat, pc.center.radlon);
pc.currentPos.setEntity(this, getNodesLatLon(t, true), getNodesLatLon(t, false));
}
if ((mode & Tile.OPT_PAINT) > 0) {
/**
* Calculate the width of the path to be drawn. A width of 1
* corresponds to it being draw as a thin line rather than as a
* street
*/
if (Configuration
.getCfgBitState(Configuration.CFGBIT_STREETRENDERMODE)
&& wayDesc.wayWidth > 1) {
w = (int) (pc.ppm * wayDesc.wayWidth / 2 + 0.5);
}
if (highlight != HIGHLIGHT_ROUTEPATH_CONTAINED && pc.dest != null
&& this.equals(pc.dest.entity)) {
highlight = HIGHLIGHT_DEST;
}
// if render as lines and no part of the way is highlighted
if (w == 0 && highlight == HIGHLIGHT_NONE) {
setColor(pc);
PolygonGraphics.drawOpenPolygon(pc.g, x, y, pi - 1);
if (isOneway()) {
// Loop through all waysegments for painting the OnewayArrows as overlay
// TODO: Maybe, we can integrate this one day in the main loop. Currently, we have troubles
// with "not completely fitting arrows" getting painted over by the next waysegment.
paintPathOnewayArrows(pi - 1, wayDesc, pc);
}
// if render as streets or a part of the way is highlighted
} else {
draw(pc, t, (w == 0) ? 1 : w, x, y, hl, pi - 1, highlight,orthogonal);
}
paintPathName(pc, t);
}
}
public void paintPathName(PaintContext pc, SingleTile t) {
//boolean info=false;
// exit if not zoomed in enough
WayDescription wayDesc = Legend.getWayDescription(type);
if (pc.scale > wayDesc.maxTextScale * Configuration.getDetailBoostMultiplier() ) {
return;
}
if ( !Configuration.getCfgBitState(Configuration.CFGBIT_WAYTEXTS)) {
return;
}
//remember previous font
Font originalFont = pc.g.getFont();
if (pathFont == null) {
pathFont = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL);
pathFontHeight = pathFont.getHeight();
pathFontMaxCharWidth = pathFont.charWidth('W');
pathFontBaseLinePos = pathFont.getBaselinePosition();
}
// At least the half font height must fit to the on-screen-width of the way
// (is calculation of w correct???)
int w = (int)(pc.ppm * wayDesc.wayWidth);
if (pathFontHeight / 4 > w) {
return;
}
String name = null;
String url = null;
if ( Configuration.getCfgBitState(Configuration.CFGBIT_SHOWWAYPOITYPE)) {
name = (this.isRoundAbout() ? "rab " : "") + wayDesc.description;
} else {
if (nameIdx != -1) {
name = Trace.getInstance().getName(nameIdx);
}
}
if (urlIdx != -1) {
url=Trace.getInstance().getUrl(urlIdx);
}
if (name == null) {
return;
}
if (url != null) {
name = name + url;
}
// determine region in which chars can be drawn
int minCharScreenX = pc.g.getClipX() - pathFontMaxCharWidth;
int minCharScreenY = pc.g.getClipY() - pathFontBaseLinePos - (w / 2);
int maxCharScreenX = minCharScreenX + pc.g.getClipWidth() + pathFontMaxCharWidth;
int maxCharScreenY = minCharScreenY + pc.g.getClipHeight() + pathFontBaseLinePos * 2;
StringBuffer sbName= new StringBuffer();
pc.g.setFont(pathFont);
char letter = ' ';
short charsDrawable = 0;
Projection p = pc.getP();
//if(info)System.out.println("Draw " + name + " from " + path.length + " points");
boolean abbreviated = false;
int iNameRepeatable = 0;
int iNameRepeated = 0;
// 2 passes:
// - 1st pass only counts fitting chars, so we can correctly
// abbreviate reversed strings
// - 2nd pass actually draws
for (byte mode = PAINTMODE_COUNTFITTINGCHARS; mode <= PAINTMODE_DRAWCHARS; mode++) {
double posChar_x = 0;
double posChar_y = 0;
double slope_x = 0;
double slope_y = 0;
double nextDeltaSub = 0;
int delta = 0;
IntPoint lineP1 = pc.lineP1;
IntPoint lineP2 = pc.lineP2;
IntPoint swapLineP = pc.swapLineP;
// do indent because first letter position would often
// be covered by other connecting streets
short streetNameCharIndex = -INDENT_PATHNAME;
// draw name again and again until end of path
for (int i1 = 0; i1 < path.length; i1++) {
// get the next line point coordinates into lineP2
int idx = this.path[i1];
// forward() is in Mercator.java
p.forward(t.nodeLat[idx], t.nodeLon[idx], lineP2, t);
// if we got only one line point, get a second one
if (lineP1 == null) {
lineP1 = lineP2;
lineP2 = swapLineP;
continue;
}
// calculate the slope of the new line
double distance = Math.sqrt( ((double)lineP2.y - (double)lineP1.y) * ((double)lineP2.y - (double)lineP1.y) +
((double)lineP2.x - (double)lineP1.x) * ((double)lineP2.x - (double)lineP1.x) );
if (distance != 0) {
slope_x = ((double)lineP2.x - (double)lineP1.x) / distance;
slope_y = ((double)lineP2.y - (double)lineP1.y) / distance;
} else {
//logger.debug("ZERO distance in path segment " + i1 + "/" + path.length + " of " + name);
break;
}
// new char position is first line point position
// minus the delta we've drawn over the previous
// line point
posChar_x = lineP1.x - nextDeltaSub * slope_x;
posChar_y = lineP1.y - nextDeltaSub * slope_y;
// as long as we have not passed the next line point
while( (
(slope_x <= 0 && posChar_x >= lineP2.x) ||
(slope_x >= 0 && posChar_x <= lineP2.x)
) && (
(slope_y <= 0 && posChar_y >= lineP2.y) ||
(slope_y >= 0 && posChar_y <= lineP2.y)
)
) {
// get the street name into the buffer
if (streetNameCharIndex == -INDENT_PATHNAME) {
// use full name to count fitting chars
sbName.setLength(0);
sbName.append(name);
abbreviated = false;
if (mode == PAINTMODE_DRAWCHARS) {
if (
iNameRepeated >= iNameRepeatable &&
charsDrawable > 0 &&
charsDrawable < name.length()
) {
//if(info)System.out.println(sbName.toString() + " i1: " + i1 + " lastFitI1 " + lastFittingI1 + " charsdrawable: " + charsDrawable );
sbName.setLength(charsDrawable - 1);
abbreviated = true;
if (sbName.length() == 0) {
sbName.append(".");
}
}
// always begin drawing street names
// left to right
if (lineP1.x > lineP2.x) {
sbName.reverse();
}
}
}
// draw letter
if (streetNameCharIndex >= 0) {
// char to draw
letter = sbName.charAt(streetNameCharIndex);
if (mode == PAINTMODE_DRAWCHARS) {
// draw char only if it's at least partly on-screen
if ( (int)posChar_x >= minCharScreenX &&
(int)posChar_x <= maxCharScreenX &&
(int)posChar_y >= minCharScreenX &&
(int)posChar_y <= maxCharScreenY
) {
if (abbreviated) {
pc.g.setColor(Legend.COLORS[Legend.COLOR_WAY_LABEL_TEXT_ABBREVIATED]);
} else {
pc.g.setColor(Legend.COLORS[Legend.COLOR_WAY_LABEL_TEXT]);
}
pc.g.drawChar(
letter,
(int)posChar_x, (int)(posChar_y + (w / 2)),
Graphics.BASELINE | Graphics.HCENTER
);
}
}
// if (mode == PAINTMODE_COUNTFITTINGCHARS ) {
// pc.g.setColor(150, 150, 150);
// pc.g.drawChar(letter,
// (int)posChar_x, (int)(posChar_y + (w / 2)),
// Graphics.BASELINE | Graphics.HCENTER);
// }
// delta calculation should be improved
if (Math.abs(slope_x) > Math.abs(slope_y)) {
delta = (pathFont.charWidth(letter) + pathFontHeight ) /2;
} else {
delta = pathFontHeight * 3 / 4;
}
} else {
// delta for indent
delta = pathFontHeight;
}
streetNameCharIndex++;
if (mode == PAINTMODE_COUNTFITTINGCHARS) {
charsDrawable = streetNameCharIndex;
}
// if at end of name
if (streetNameCharIndex >= sbName.length()) {
streetNameCharIndex = -INDENT_PATHNAME;
if (mode == PAINTMODE_COUNTFITTINGCHARS) {
// increase number of times the name fitted completely
iNameRepeatable++;
} else {
iNameRepeated++;
}
}
// add slope to char position
posChar_x += slope_x * delta;
posChar_y += slope_y * delta;
// how much would we start to draw the next char over the end point
if (slope_x != 0) {
nextDeltaSub = (lineP2.x - posChar_x) / slope_x;
} else {
nextDeltaSub = 0;
}
} // end while loop
// continue in next path segment
swapLineP = lineP1;
lineP1 = lineP2;
lineP2 = swapLineP;
} // end segment for-loop
} // end mode for-loop
pc.g.setFont(originalFont);
}
public void paintPathOnewayArrows(int count, WayDescription wayDesc, PaintContext pc) {
// exit if not zoomed in enough
if (pc.scale > wayDesc.maxOnewayArrowScale /* * pc.config.getDetailBoostMultiplier() */ ) {
return;
}
// Exit if user configured to not display OnewayArrows
if ( !Configuration.getCfgBitState(Configuration.CFGBIT_ONEWAY_ARROWS)) {
return;
}
// calculate on-screen-width of the way
float w = (int)(pc.ppm * wayDesc.wayWidth + 1);
// if arrow would get too small do not draw
if (w < 3) {
return;
}
// if arrow would be very small make it a bit larger
if (w < 5) {
w = 5;
}
// limit maximum arrow width
if (w > 10) {
w = 10;
}
// calculate arrow length
int lenTriangle = (int) ((w * 5) / 4);
int lenLine = (int) ((w * 4) / 3);
int completeLen = lenTriangle + lenLine;
int sumTooSmallLen = 0;
// determine region in which arrows can be drawn
int minArrowScreenX = pc.g.getClipX() - completeLen;
int minArrowScreenY = pc.g.getClipY() - completeLen;
int maxArrowScreenX = minArrowScreenX + pc.g.getClipWidth() + completeLen;
int maxArrowScreenY = minArrowScreenY + pc.g.getClipHeight() + completeLen;
float posArrow_x = 0;
float posArrow_y = 0;
float slope_x = 0;
float slope_y = 0;
// cache i + 1 to i2
int i2 = 0;
// draw arrow in each segment of path
for (int i = 0; i < count; i++) {
i2 = i + 1;
// calculate the slope of the new line
float distance = (float) Math.sqrt( (y[i2] - y[i]) * (y[i2] - y[i]) +
(x[i2] - x[i]) * (x[i2] - x[i]) );
if (distance > completeLen || sumTooSmallLen > completeLen) {
if (sumTooSmallLen > completeLen) {
sumTooSmallLen = 0;
// special color for not completely fitting arrows
pc.g.setColor(Legend.COLORS[Legend.COLOR_ONEWAY_ARROW_NON_FITTING]);
} else {
// normal color
pc.g.setColor(Legend.COLORS[Legend.COLOR_ONEWAY_ARROW]);
}
if (distance!=0) {
slope_x = (x[i2] - x[i]) / distance;
slope_y = (y[i2] - y[i]) / distance;
}
// new arrow position is middle of way segment
posArrow_x = x[i] + slope_x * (distance - completeLen) / 2;
posArrow_y = y[i] + slope_y * (distance - completeLen) / 2;
// draw arrow only if it's at least partly on-screen
if ( (int)posArrow_x >= minArrowScreenX &&
(int)posArrow_x <= maxArrowScreenX &&
(int)posArrow_y >= minArrowScreenX &&
(int)posArrow_y <= maxArrowScreenY
) {
drawArrow(pc,
posArrow_x, posArrow_y,
slope_x, slope_y,
w, lenLine, lenTriangle
);
}
// // delta calculation should be improved
// delta = completeLen * 3;
// // add slope to arrow position
// posArrow_x += slope_x * delta;
// posArrow_y += slope_y * delta;
// if (slope_x == 0 && slope_y == 0) {
// break;
// }
//
// // how much would we start to draw the next arrow over the end point
// if (slope_x != 0) {
// nextDeltaSub=(x[i1 + 1] - posArrow_x) / slope_x;
// }
} else {
sumTooSmallLen += distance;
}
} // End For: continue in next path segment, if there is any
}
private void drawArrow( PaintContext pc,
double x, double y,
double slopeX, double slopeY,
double w, int lenLine, int lenTriangle)
{
double x2 = x + slopeX * (double) lenLine;
double y2 = y + slopeY * (double) lenLine;
pc.g.drawLine((int) x, (int) y, (int) x2, (int) y2);
pc.g.fillTriangle(
(int)(x2 + slopeY * w / 2), (int)(y2 - slopeX * w / 2),
(int)(x2 - slopeY * w / 2), (int)(y2 + slopeX * w / 2),
(int)(x2 + slopeX * lenTriangle), (int)(y2 + slopeY * lenTriangle)
);
}
/** Calculates the turn 2 vectors make (left, right, straight)
* @return s < 0 for right turn, s > 0 for left turn. 0 for straight
*/
public int getVectorTurn(int ax, int ay, int bx, int by, int cx, int cy) {
// s < 0 Legend is left of AB
// s > 0 Legend is right of AB
// s = 0 Legend is on AB
return (ay - cy) * (bx - ax) - (ax - cx) * (by - ay);
}
/** Calculate the end points for 2 paralell lines with distance w which
* has the origin line (Xpoint[i]/Ypoint[i]) to (Xpoint[i+1]/Ypoint[i+1])
* as centre line
* @param xPoints list off all XPoints for this Way
* @param yPoints list off all YPoints for this Way
* @param i the index out of (X/Y) Point for the line segement we looking for
* @param w the width of the segment out of the way
* @param p1 left start point
* @param p2 right start point
* @param p3 left end point
* @param p4 right end point
* @return the angle of the line in radians ( -Pi .. +Pi )
*/
private float getParLines(int xPoints[], int yPoints[], int i, int w,
IntPoint p1, IntPoint p2, IntPoint p3, IntPoint p4) {
int i1 = i + 1;
int dx = xPoints[i1] - xPoints[i];
int dy = yPoints[i1] - yPoints[i];
int l2 = dx * dx + dy * dy;
float l2f = (float) Math.sqrt(l2);
float lf = w / l2f;
int xb = (int) ((Math.abs(lf * dy)) + 0.5f);
int yb = (int) ((Math.abs(lf * dx)) + 0.5f);
int rfx = 1;
int rfy = 1;
if (dy < 0) {
rfx = -1;
}
if (dx > 0) {
rfy = -1;
}
int xd = rfx * xb;
int yd = rfy * yb;
p1.x = xPoints[i] + xd;
p1.y = yPoints[i] + yd;
p2.x = xPoints[i] - xd;
p2.y = yPoints[i] - yd;
p3.x = xPoints[i1] + xd;
p3.y = yPoints[i1] + yd;
p4.x = xPoints[i1] - xd;
p4.y = yPoints[i1] - yd;
if (dx != 0) {
return (MoreMath.atan(1f * dy / dx));
} else {
if (dy > 0) {
return MoreMath.PiDiv2;
} else {
return -MoreMath.PiDiv2;
}
}
}
private void draw(PaintContext pc, SingleTile t, int w, int xPoints[], int yPoints[],
int hl[], int count, byte highlight,boolean ortho /*, byte mode*/) {
IntPoint closestP = new IntPoint();
int wClosest = 0;
boolean dividedSeg = false;
boolean dividedHighlight = true;
+ IntPoint closestDestP = new IntPoint();
boolean dividedFinalRouteSeg = false;
boolean dividedFinalDone = false;
int originalFinalRouteSegX = 0;
int originalFinalRouteSegY = 0;
int pathIndexOfNewSeg = 0;
boolean routeIsForwardOnWay = false;
int originalX = 0;
int originalY = 0;
int wOriginal = w;
if (w <1) w=1;
int wDraw = w;
int turn = 0;
WayDescription wayDesc = Legend.getWayDescription(type);
Vector route = pc.trace.getRoute();
for (int i = 0; i < count; i++) {
wDraw = w;
// draw route line wider
if (
highlight == HIGHLIGHT_ROUTEPATH_CONTAINED
&& hl[i] >= 0
&& wDraw < Configuration.getMinRouteLineWidth()
) {
wDraw = Configuration.getMinRouteLineWidth();
}
if (dividedSeg) {
// if this is a divided seg, draw second part of it
xPoints[i] = xPoints[i + 1];
yPoints[i] = yPoints[i + 1];
xPoints[i + 1] = originalX;
yPoints[i + 1] = originalY;
dividedHighlight = !dividedHighlight;
} else {
// if not turn off the highlight
dividedHighlight = false;
if (dividedFinalRouteSeg) {
//System.out.println ("restore i " + i);
xPoints[i] = xPoints[i + 1];
yPoints[i] = yPoints[i + 1];
xPoints[i + 1] = originalFinalRouteSegX;
yPoints[i + 1] = originalFinalRouteSegY;
if (routeIsForwardOnWay) {
hl[i] = PATHSEG_DO_NOT_HIGHLIGHT;
} else {
hl[i] = route.size() - 2;
wDraw = w;
if (wDraw < Configuration.getMinRouteLineWidth()) {
wDraw = Configuration.getMinRouteLineWidth();
}
}
dividedFinalRouteSeg = false;
dividedFinalDone = true;
}
}
// divide final segment on the route
if (
//false &&
highlight == HIGHLIGHT_ROUTEPATH_CONTAINED
&& route != null
&& hl[i] == route.size() - 2
) {
// get direction we go on the way
ConnectionWithNode c = (ConnectionWithNode) route.elementAt(hl[i]);
routeIsForwardOnWay = (c.wayFromConAt < c.wayToConAt);
pathIndexOfNewSeg = (routeIsForwardOnWay ? c.wayToConAt - 1 : c.wayToConAt);
//System.out.println ("waytoconat: " + c.wayToConAt + " wayfromconat: " + c.wayFromConAt + " i: " + i);
if (
i == pathIndexOfNewSeg
&& !dividedFinalDone
) {
- IntPoint closestDestP = new IntPoint();
pc.getP().forward(RouteInstructions.getClosestPointOnDestWay(), closestDestP);
originalFinalRouteSegX = xPoints[i + 1];
originalFinalRouteSegY = yPoints[i + 1];
xPoints[i + 1] = closestDestP.x;
yPoints[i + 1] = closestDestP.y;
if (routeIsForwardOnWay) {
;
} else {
hl[i] = PATHSEG_DO_NOT_HIGHLIGHT;
wDraw = w;
}
//pc.g.setColor(0x00ff00);
//pc.g.drawString("closest:" + i, closestDestP.x, closestDestP.y, Graphics.TOP | Graphics.LEFT);
//System.out.println("Insert closest point at " + (i + 1) );
dividedFinalRouteSeg = true;
}
} else {
dividedFinalRouteSeg = false;
}
if (hl[i] >= 0
// if this is the closest segment of the closest connection
&& RouteInstructions.routePathConnection == hl[i]
&& i == RouteInstructions.pathIdxInRoutePathConnection - 1
&& !dividedSeg
) {
IntPoint centerP = new IntPoint();
// this is a divided seg (partly prior route line, partly current route line)
dividedSeg = true;
centerP=pc.getP().getImageCenter();
/** centerP is now provided by Projection implementation */
// pc.getP().forward(
// (short)(MoreMath.FIXPT_MULT * (pc.center.radlat - t.centerLat)),
// (short)(MoreMath.FIXPT_MULT * (pc.center.radlon - t.centerLon)), centerP, t);
// get point dividing the seg
closestP = MoreMath.closestPointOnLine(xPoints[i], yPoints[i], xPoints[i + 1], yPoints[i + 1], centerP.x, centerP.y);
// remember original next point
originalX = xPoints[i + 1];
originalY = yPoints[i + 1];
// replace next point with closest point
xPoints[i + 1] = closestP.x;
yPoints[i + 1] = closestP.y;
// remember width for drawing the closest point
wClosest = wDraw;
// get direction we go on the way
ConnectionWithNode c = (ConnectionWithNode) route.elementAt(hl[i]);
dividedHighlight = (c.wayFromConAt > c.wayToConAt);
+ // fix dstToRoutePath on way part of divided final route seg for off route display
+ if ( (dividedFinalDone || dividedFinalRouteSeg)
+ &&closestP.equals(closestDestP)
+ ) {
+ pc.squareDstToRoutePath = MoreMath.ptSegDistSq( closestDestP.x, closestDestP.y,
+ closestDestP.x, closestDestP.y,
+ centerP.x, centerP.y
+ );
+ }
} else {
dividedSeg = false;
}
// if (hl[i] >= 0) {
// pc.g.setColor(0xffff80);
// pc.g.drawString("i:" + i, xPoints[i], yPoints[i],Graphics.TOP | Graphics.LEFT);
// }
// Get the four outer points of the wDraw-wide waysegment
if (ortho){
getParLines(xPoints, yPoints, i , wDraw, l1b, l2b, l1e, l2e);
} else {
pc.getP().getParLines(xPoints, yPoints, i , wDraw, l1b, l2b, l1e, l2e);
}
if (hl[i] != PATHSEG_DO_NOT_DRAW) {
// if (mode == DRAW_AREA) {
setColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
int xbcentre = (l2b.x + l1b.x) / 2;
int xecentre = (l2e.x + l1e.x) / 2;
int ybcentre = (l2b.y + l1b.y) / 2;
int yecentre = (l2e.y + l1e.y) / 2;
int xbdiameter = Math.abs(l2b.x - l1b.x);
int xediameter = Math.abs(l2e.x - l1e.x);
int ybdiameter = Math.abs(l2b.y - l1b.y);
int yediameter = Math.abs(l2e.y - l1e.y);
// FIXME we would need rotated ellipsis for clean rounded endings,
// but lacking that we can apply some heuristics
if (xbdiameter/3 > ybdiameter) {
ybdiameter = xbdiameter/3;
}
if (ybdiameter/3 > xbdiameter) {
xbdiameter = ybdiameter/3;
}
if (xediameter/3 > yediameter) {
yediameter = xediameter/3;
}
if (yediameter/3 > xediameter) {
xediameter = yediameter/3;
}
// when this is not render as lines (for the non-highlighted part of the way) or it is a highlighted part, draw as area
if (wOriginal != 0 || hl[i] >= 0) {
pc.g.fillTriangle(l2b.x, l2b.y, l1b.x, l1b.y, l1e.x, l1e.y);
pc.g.fillTriangle(l1e.x, l1e.y, l2e.x, l2e.y, l2b.x, l2b.y);
if (i == 0) { // if this is the first segment, draw the lines
// draw circular endings
if (Configuration.getCfgBitState(Configuration.CFGBIT_ROUND_WAY_ENDS) && wDraw > 2) {
if (ortho) {
circleWayEnd(pc, xbcentre, ybcentre, wDraw);
circleWayEnd(pc, xecentre, yecentre, wDraw);
} else {
// ellipse is close, but rotation is missing
// FIXME fix the bad appearance for eagle projection
pc.g.fillArc(xbcentre - xbdiameter/2, ybcentre - ybdiameter/2, xbdiameter, ybdiameter, 0, 360);
pc.g.fillArc(xecentre - xediameter/2, yecentre - yediameter/2, xediameter, yediameter, 0, 360);
}
}
setBorderColor(pc, wayDesc,(hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (! Configuration.getCfgBitState(Configuration.CFGBIT_NOSTREETBORDERS) || isCurrentRoutePath(pc, i)) {
pc.g.drawLine(l2b.x, l2b.y, l2e.x, l2e.y);
pc.g.drawLine(l1b.x, l1b.y, l1e.x, l1e.y);
}
}
// Now look at the turns(corners) of the waysegment and fill them if necessary.
// We always look back to the turn between current and previous waysegment.
if (i > 0) {
// as we look back, there is no turn at the first segment
turn = getVectorTurn(xPoints[i - 1], yPoints[i - 1], xPoints[i],
yPoints[i], xPoints[i + 1], yPoints[i + 1] );
if (turn < 0 ) {
// turn right
intersectionPoint(l4b, l4e, l2b, l2e, intersecP, 1);
setColor(pc, wayDesc,(hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
// Fills the gap of the corner with a small triangle
pc.g.fillTriangle(xPoints[i], yPoints[i] , l3e.x, l3e.y, l1b.x,l1b.y);
if (Configuration.getCfgBitState(Configuration.CFGBIT_ROUND_WAY_ENDS) && wDraw > 2) {
if (ortho) {
circleWayEnd(pc, xbcentre, ybcentre, wDraw);
circleWayEnd(pc, xecentre, yecentre, wDraw
);
} else {
// ellipse is close, but rotation is missing
// FIXME fix the bad appearance for eagle projection
pc.g.fillArc(xbcentre - xbdiameter/2, ybcentre - ybdiameter/2, xbdiameter, ybdiameter, 0, 360);
pc.g.fillArc(xecentre - xediameter/2, yecentre - yediameter/2, xediameter, yediameter, 0, 360);
}
}
setBorderColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (! Configuration.getCfgBitState(Configuration.CFGBIT_NOSTREETBORDERS) || isCurrentRoutePath(pc, i)) {
if (highlight == HIGHLIGHT_NONE) {
//paint the inner turn border to the intersection point between old and current waysegment
pc.g.drawLine(intersecP.x, intersecP.y, l2e.x, l2e.y);
} else {
//painting full border of the inner turn while routing
pc.g.drawLine(l2b.x, l2b.y, l2e.x, l2e.y);
}
// paint the full outer turn border
pc.g.drawLine(l1b.x, l1b.y, l1e.x, l1e.y);
// paint the full outer turn border
pc.g.drawLine(l1b.x, l1b.y, l3e.x, l3e.y);
}
}
else if (turn > 0 ) {
// turn left
intersectionPoint(l3b,l3e,l1b,l1e,intersecP,1);
setColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
// Fills the gap of the corner with a small triangle
pc.g.fillTriangle(xPoints[i], yPoints[i] , l4e.x, l4e.y, l2b.x,l2b.y);
if (Configuration.getCfgBitState(Configuration.CFGBIT_ROUND_WAY_ENDS) && wDraw > 2) {
if (ortho) {
circleWayEnd(pc, xbcentre, ybcentre, wDraw);
circleWayEnd(pc, xecentre, yecentre, wDraw);
} else {
// ellipse is close, but rotation is missing
// FIXME fix the bad appearance for eagle projection
pc.g.fillArc(xbcentre - xbdiameter/2, ybcentre - ybdiameter/2, xbdiameter, ybdiameter, 0, 360);
pc.g.fillArc(xecentre - xediameter/2, yecentre - yediameter/2, xediameter, yediameter, 0, 360);
}
}
setBorderColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (! Configuration.getCfgBitState(Configuration.CFGBIT_NOSTREETBORDERS) || isCurrentRoutePath(pc, i)) {
if (highlight == HIGHLIGHT_NONE) {
//see comments above
pc.g.drawLine(intersecP.x, intersecP.y, l1e.x, l1e.y);
} else {
pc.g.drawLine(l1b.x, l1b.y, l1e.x, l1e.y);
}
pc.g.drawLine(l2b.x, l2b.y, l2e.x, l2e.y);
//corner
pc.g.drawLine(l2b.x, l2b.y, l4e.x, l4e.y);
}
}
else {
//no turn, way is straight
setColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (Configuration.getCfgBitState(Configuration.CFGBIT_ROUND_WAY_ENDS) && wDraw > 2) {
if (ortho) {
circleWayEnd(pc, xbcentre, ybcentre, wDraw);
circleWayEnd(pc, xecentre, yecentre, wDraw);
} else {
// ellipse is close, but rotation is missing
// FIXME fix the bad appearance for eagle projection
pc.g.fillArc(xbcentre - xbdiameter/2, ybcentre - ybdiameter/2, xbdiameter, ybdiameter, 0, 360);
pc.g.fillArc(xecentre - xediameter/2, yecentre - yediameter/2, xediameter, yediameter, 0, 360);
}
}
setBorderColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (! Configuration.getCfgBitState(Configuration.CFGBIT_NOSTREETBORDERS) || isCurrentRoutePath(pc, i)) {
pc.g.drawLine(l2b.x, l2b.y, l2e.x, l2e.y);
// paint the full outer turn border
pc.g.drawLine(l1b.x, l1b.y, l1e.x, l1e.y);
}
}
}
} else {
// Draw streets as lines (only 1px wide)
setColor(pc,wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
pc.g.drawLine(xPoints[i], yPoints[i], xPoints[i + 1], yPoints[i + 1]);
}
if (isBridge()) {
waySegment.drawBridge(pc, xPoints, yPoints, i, count - 1, w,
l1b, l1e, l2b, l2e);
}
if (isTunnel()) {
waySegment.drawTunnel(pc, xPoints, yPoints, i, count - 1, w,
l1b, l1e, l2b, l2e);
}
if (isTollRoad()) {
waySegment.drawTollRoad(pc, xPoints, yPoints, i, count - 1, w,
l1b, l1e, l2b, l2e);
}
if (isDamaged()) {
waySegment.drawDamage(pc, xPoints, yPoints, i, count - 1, w,
l1b, l1e, l2b, l2e);
}
}
//Save the way-corners for the next loop to fill segment-gaps
l3b.set(l1b);
l4b.set(l2b);
l3e.set(l1e);
l4e.set(l2e);
if (dividedSeg || dividedFinalRouteSeg) {
// if this is a divided seg, in the next step draw the second part
i--;
}
}
if (isOneway()) {
// Loop through all waysegments for painting the OnewayArrows as overlay
// TODO: Maybe, we can integrate this one day in the main loop. Currently, we have troubles
// with "not completely fitting arrows" getting overpainted by the next waysegment.
paintPathOnewayArrows(count, wayDesc, pc);
}
//now as we painted all ways, do the things we should only do once
if (wClosest != 0) {
// if we got a closest seg, draw closest point to the center in it
RouteInstructions.drawRouteDot(pc.g, closestP, wClosest);
}
if (nameAsForArea()) {
paintAreaName(pc,t);
}
}
/**
* @param pc
* @param i - segment idx in the way's path to check
* @return true, if the current segment in the way's path is not reached yet, else false
*/
private boolean isCurrentRoutePath(PaintContext pc, int i) {
if (RouteInstructions.routePathConnection != hl[i]) {
return (RouteInstructions.routePathConnection < hl[i]);
}
ConnectionWithNode c = (ConnectionWithNode) pc.trace.getRoute().elementAt(RouteInstructions.routePathConnection);
return (
(c.wayFromConAt < c.wayToConAt)
?RouteInstructions.pathIdxInRoutePathConnection <= i
:RouteInstructions.pathIdxInRoutePathConnection > i+1
);
}
private void intersectionPoint(IntPoint p1, IntPoint p2, IntPoint p3,
IntPoint p4, IntPoint ret, int aprox) {
if (p2.approximatelyEquals(p3, aprox)) {
// as p2 and p3 are (approx) equal, the intersectionpoint is infinite
ret.x = p3.x; // returning p3 as this is the best solution
ret.y = p3.y;
}
else {
intersectionPointCalc(p1, p2,p3,p4,ret);
}
}
// private void intersectionPoint(IntPoint p1, IntPoint p2, IntPoint p3,
// IntPoint p4, IntPoint ret) {
//
// if (p2.equals(p3)) {
// // as p2 and p3 are (approx) equal, the intersectionpoint is infinite
// ret.x = p3.x; // returning p3 as this is the best solution
// ret.y = p3.y;
// } else {
// intersectionPointCalc(p1, p2,p3,p4,ret);
// }
// }
private void intersectionPointCalc(IntPoint p1, IntPoint p2, IntPoint p3,
IntPoint p4, IntPoint ret) {
int dx1 = p2.x - p1.x;
int dx2 = p4.x - p3.x;
int dx3 = p1.x - p3.x;
int dy1 = p2.y - p1.y;
int dy2 = p1.y - p3.y;
int dy3 = p4.y - p3.y;
float r = dx1 * dy3 - dy1 * dx2;
if (r != 0f) {
r = (1f * (dy2 * (p4.x - p3.x) - dx3 * dy3)) / r;
ret.x = (int) ((p1.x + r * dx1) + 0.5);
ret.y = (int) ((p1.y + r * dy1) + 0.5);
} else {
if (((p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y)) == 0) {
ret.x = p3.x;
ret.y = p3.y;
} else {
ret.x = p4.x;
ret.y = p4.y;
}
}
}
/* private boolean getLineLineIntersection(IntPoint p1, IntPoint p2,
IntPoint p3, IntPoint p4, IntPoint ret) {
float x1 = p1.x;
float y1 = p1.y;
float x2 = p2.x;
float y2 = p2.y;
float x3 = p3.x;
float y3 = p3.y;
float x4 = p4.x;
float y4 = p4.y;
ret.x = (int) ((det(det(x1, y1, x2, y2), x1 - x2, det(x3, y3, x4, y4),
x3 - x4) / det(x1 - x2, y1 - y2, x3 - x4, y3 - y4)) + 0.5);
ret.y = (int) ((det(det(x1, y1, x2, y2), y1 - y2, det(x3, y3, x4, y4),
y3 - y4) / det(x1 - x2, y1 - y2, x3 - x4, y3 - y4)) + 0.5);
return true;
}
*/
/* private static float det(float a, float b, float c, float d) {
return a * d - b * c;
} */
private void circleWayEnd (PaintContext pc, int x, int y, int radius) {
pc.g.fillArc(x - radius, y - radius, radius*2, radius*2, 0, 360);
}
public void paintAsArea(PaintContext pc, SingleTile t) {
WayDescription wayDesc = Legend.getWayDescription(type);
pc.g.setColor(wayDesc.lineColor);
byte om = Legend.getWayOverviewMode(type);
switch (om & Legend.OM_MODE_MASK) {
case Legend.OM_SHOWNORMAL:
// if not in Overview Mode check for scale
if (pc.scale > wayDesc.maxScale * Configuration.getDetailBoostMultiplier()) {
return;
}
// building areas
if (wayDesc.isBuilding()) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_BUILDINGS)) {
return;
}
// non-building areas
} else {
if(wayDesc.hideable && !Configuration.getCfgBitState(Configuration.CFGBIT_AREAS)) {
return;
}
}
break;
case Legend.OM_HIDE:
if (wayDesc.hideable) {
return;
}
break;
}
switch (om & Legend.OM_NAME_MASK) {
case Legend.OM_WITH_NAMEPART:
if (nameIdx == -1) {
return;
}
String name = pc.trace.getName(nameIdx);
String url = pc.trace.getName(urlIdx);
if (name == null) {
return;
}
if (name.toUpperCase().indexOf(Legend.get0Poi1Area2WayNamePart((byte) 1).toUpperCase()) == -1) {
return;
}
break;
case Legend.OM_WITH_NAME:
if (nameIdx == -1) {
return;
}
break;
case Legend.OM_NO_NAME:
if (nameIdx != -1) {
return;
}
break;
}
Projection p = pc.getP();
IntPoint p1 = pc.lineP2;
IntPoint p2 = pc.swapLineP;
IntPoint p3 = pc.tempPoint;
pc.g.setColor(wayDesc.lineColor);
for (int i1 = 0; i1 < path.length; ){
// pc.g.setColor(wayDesc.lineColor);
int idx = path[i1++];
p.forward(t.nodeLat[idx],t.nodeLon[idx],p1,t);
idx = path[i1++];
p.forward(t.nodeLat[idx],t.nodeLon[idx],p2,t);
idx = path[i1++];
p.forward(t.nodeLat[idx],t.nodeLon[idx],p3,t);
pc.g.fillTriangle(p1.x,p1.y,p2.x,p2.y,p3.x,p3.y);
// pc.g.setColor(0);
//#if polish.android
pc.g.drawLine(p1.x,p1.y,p2.x,p2.y);
pc.g.drawLine(p2.x,p2.y,p3.x,p3.y);
pc.g.drawLine(p1.x,p1.y,p3.x,p3.y);
//#endif
}
paintAreaName(pc,t);
}
public void paintAreaName(PaintContext pc, SingleTile t) {
WayDescription wayDesc = Legend.getWayDescription(type);
if (pc.scale > wayDesc.maxTextScale * Configuration.getDetailBoostMultiplier() ) {
return;
}
// building areas
if (wayDesc.isBuilding()) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_BUILDING_LABELS)) {
return;
}
// non-building areas
} else {
if (wayDesc.hideable && !Configuration.getCfgBitState(Configuration.CFGBIT_AREATEXTS)) {
return;
}
}
String name = null;
if ( Configuration.getCfgBitState(Configuration.CFGBIT_SHOWWAYPOITYPE)) {
name = wayDesc.description;
} else {
if (nameIdx != -1) {
name = Trace.getInstance().getName(nameIdx);
}
}
// if zoomed in enough, show description
if (pc.scale < wayDesc.maxDescriptionScale) {
// show way description
if (name == null) {
name = wayDesc.description;
} else {
name = name + " (" + wayDesc.description + ")";
}
}
if (name == null) {
return;
}
IntPoint lineP2 = pc.lineP2;
Projection p = pc.getP();
int x;
int y;
// get screen clip
int clipX = pc.g.getClipX();
int clipY = pc.g.getClipY();
int clipMaxX = clipX + pc.g.getClipWidth();
int clipMaxY = clipY + pc.g.getClipHeight();;
// find center of area
int minX = clipMaxX;
int maxX = clipX;
int minY = clipMaxY;
int maxY = clipY;
for (int i1 = 0; i1 < path.length; i1++) {
int idx = path[i1];
p.forward(t.nodeLat[idx], t.nodeLon[idx], lineP2, t);
x = lineP2.x;
y = lineP2.y;
if (minX > x) {
minX = x;
}
if (minY > y) {
minY = y;
}
if (maxX < x) {
maxX = x;
}
if (maxY < y) {
maxY = y;
}
}
// System.out.println("name:" + name + " ClipX:" + clipX + " ClipMaxX:" + clipMaxX + " ClipY:" + clipY + " ClipMaxY:" + clipMaxY + " minx:" + minX + " maxX:"+maxX + " miny:"+minY+ " maxY" + maxY);
Font originalFont = pc.g.getFont();
if (areaFont == null) {
areaFont = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL);
areaFontHeight = areaFont.getHeight();
}
// find out how many chars of the name fit into the area
int i = name.length() + 1;
int w;
do {
i--;
w = areaFont.substringWidth(name, 0, i);
} while (w > (maxX - minX) && i > 1);
// is area wide enough to draw at least a dot into it?
if ((maxX - minX) >= 3 ) {
pc.g.setColor(Legend.COLORS[Legend.COLOR_AREA_LABEL_TEXT]);
// if at least two chars have fit or name is a fitting single char, draw name
if (i > 1 || (i == name.length() && w <= (maxX - minX)) ) {
pc.g.setFont(areaFont);
// center vertically in area
int y1 = (minY + maxY - areaFontHeight) / 2;
// draw centered into area
pc.g.drawSubstring(name, 0, i, (minX + maxX - w) / 2, y1, Graphics.TOP | Graphics.LEFT);
// if name fits not completely, append "..."
if (i != name.length()) {
pc.g.drawString("...", (minX + maxX + w) / 2, y1, Graphics.TOP | Graphics.LEFT);
}
pc.g.setFont(originalFont);
// else draw a dot to indicate there's a name for this area available
} else {
pc.g.drawRect((minX + maxX) / 2, (minY + maxY) / 2, 0, 0 );
}
}
}
public void setColor(PaintContext pc,WayDescription wayDesc,boolean routing,boolean isCurrentRoutePath, boolean highlight) {
if (routing) {
// set the way(area)-color
if (isCurrentRoutePath) {
// set this color if way is part of current route
pc.g.setColor(Legend.COLORS[Legend.COLOR_ROUTE_ROUTELINE]);
} else {
// set this color if way was part of current route
pc.g.setColor(Legend.COLORS[Legend.COLOR_ROUTE_PRIOR_ROUTELINE]);
}
} else if (highlight) {
// way is highlighted as destination for routing
// TODO: Shouldn't this colour be configurable too?
pc.g.setColor(255, 50, 50);
} else {
// use color from style.xml
pc.g.setStrokeStyle(wayDesc.getGraphicsLineStyle());
pc.g.setColor(wayDesc.lineColor);
}
}
public void setColor(PaintContext pc) {
WayDescription wayDesc = Legend.getWayDescription(type);
pc.g.setStrokeStyle(wayDesc.getGraphicsLineStyle());
pc.g.setColor(isDamaged() ? Legend.COLORS[Legend.COLOR_WAY_DAMAGED_DECORATION] : wayDesc.lineColor);
}
public int getWidth(PaintContext pc) {
WayDescription wayDesc = Legend.getWayDescription(type);
return wayDesc.wayWidth;
}
/**
* Advanced setting of the BorderColor
*/
public void setBorderColor(PaintContext pc, WayDescription wayDesc, boolean routing,
boolean dividedHighlight, boolean highlight) {
if (routing) {
if (dividedHighlight) {
pc.g.setColor(Legend.COLORS[Legend.COLOR_ROUTE_ROUTELINE_BORDER]);
} else {
pc.g.setColor(Legend.COLORS[Legend.COLOR_ROUTE_PRIOR_ROUTELINE_BORDER]);
}
} else if (highlight) {
// TODO: Shouldn't this colour be configurable too?
pc.g.setColor(255, 50, 50);
} else {
pc.g.setStrokeStyle(Graphics.SOLID);
pc.g.setColor(isDamaged() ? Legend.COLORS[Legend.COLOR_WAY_DAMAGED_BORDER] : wayDesc.boardedColor);
}
}
public void setBorderColor(PaintContext pc) {
pc.g.setStrokeStyle(Graphics.SOLID);
WayDescription wayDesc = Legend.getWayDescription(type);
pc.g.setColor(isDamaged() ? Legend.COLOR_WAY_DAMAGED_BORDER : wayDesc.boardedColor);
}
public boolean isOneway() {
return (flags & WAY_ONEWAY) != 0;
}
/**
* Checks if the way is a circle way (a closed way - with the same node at the start and the end)
* @return true if this way is a circle way
*/
public boolean isCircleway(SingleTile t) {
return (path[0] == path[path.length - 1]);
}
public boolean isArea() {
return ((flags & WAY_AREA) > 0);
}
public boolean nameAsForArea() {
return ((flags & WAY_NAMEASFORAREA) > 0);
}
public boolean isRoundAbout() {
return ((flags & WAY_ROUNDABOUT) > 0);
}
public boolean isOneDirectionOnly() {
return (flags & (WAY_ONEWAY + WAY_ROUNDABOUT)) != 0
&& !(
(Configuration.getTravelMode().travelModeFlags & TravelMode.AGAINST_ALL_ONEWAYS) > 0
|| ((Configuration.getTravelMode().travelModeFlags & TravelMode.BICYLE_OPPOSITE_EXCEPTIONS) > 0
&& (flags & WAY_CYCLE_OPPOSITE) != 0
)
);
}
public boolean isTunnel() {
return ((flags & WAY_TUNNEL) > 0);
}
public boolean isBridge() {
return ((flags & WAY_BRIDGE) > 0);
}
public boolean isTollRoad() {
return ((wayRouteModes & Connection.CONNTYPE_TOLLROAD) > 0);
}
public boolean isDamaged() {
return ((flags & WAY_DAMAGED) > 0);
}
public int getMaxSpeed() {
return ((flags & MaxSpeedMask) >> MaxSpeedShift);
}
public int getMaxSpeedWinter() {
return ((getFlagswinter() & MaxSpeedMask) >> MaxSpeedShift);
}
/* private float[] getFloatNodes(SingleTile t, short[] nodes, float offset) {
float [] res = new float[nodes.length];
for (int i = 0; i < nodes.length; i++) {
res[i] = nodes[i] * SingleTile.fpminv + offset;
}
return res;
}
*/
public float[] getNodesLatLon(SingleTile t, boolean latlon) {
float offset;
short [] nodes;
int len = path.length;
float [] lat = new float[len];
if (latlon) {
offset = t.centerLat;
nodes = t.nodeLat;
} else {
offset = t.centerLon;
nodes = t.nodeLon;
}
for (int i = 0; i < len; i++) {
lat[i] = nodes[path[i]] * MoreMath.FIXPT_MULT_INV + offset;
}
return lat;
}
public String toString() {
return Locale.get("way.Way")/*Way*/ + " " + Trace.getInstance().getName(nameIdx) + " " + Locale.get("way.type")/*type*/ + ": " + Legend.getWayDescription(type).description;
}
/**
* @param wayRouteModes the wayRouteModes to set
*/
public void setWayRouteModes(byte wayRouteModes) {
this.wayRouteModes = wayRouteModes;
}
/**
* @return the wayRouteModes
*/
public byte getWayRouteModes() {
return wayRouteModes;
}
/**
* @param flagswinter the flagswinter to set
*/
public void setFlagswinter(int flagswinter) {
this.flagswinter = flagswinter;
}
/**
* @return the flagswinter
*/
public int getFlagswinter() {
return flagswinter;
}
}
| false | true | private void draw(PaintContext pc, SingleTile t, int w, int xPoints[], int yPoints[],
int hl[], int count, byte highlight,boolean ortho /*, byte mode*/) {
IntPoint closestP = new IntPoint();
int wClosest = 0;
boolean dividedSeg = false;
boolean dividedHighlight = true;
boolean dividedFinalRouteSeg = false;
boolean dividedFinalDone = false;
int originalFinalRouteSegX = 0;
int originalFinalRouteSegY = 0;
int pathIndexOfNewSeg = 0;
boolean routeIsForwardOnWay = false;
int originalX = 0;
int originalY = 0;
int wOriginal = w;
if (w <1) w=1;
int wDraw = w;
int turn = 0;
WayDescription wayDesc = Legend.getWayDescription(type);
Vector route = pc.trace.getRoute();
for (int i = 0; i < count; i++) {
wDraw = w;
// draw route line wider
if (
highlight == HIGHLIGHT_ROUTEPATH_CONTAINED
&& hl[i] >= 0
&& wDraw < Configuration.getMinRouteLineWidth()
) {
wDraw = Configuration.getMinRouteLineWidth();
}
if (dividedSeg) {
// if this is a divided seg, draw second part of it
xPoints[i] = xPoints[i + 1];
yPoints[i] = yPoints[i + 1];
xPoints[i + 1] = originalX;
yPoints[i + 1] = originalY;
dividedHighlight = !dividedHighlight;
} else {
// if not turn off the highlight
dividedHighlight = false;
if (dividedFinalRouteSeg) {
//System.out.println ("restore i " + i);
xPoints[i] = xPoints[i + 1];
yPoints[i] = yPoints[i + 1];
xPoints[i + 1] = originalFinalRouteSegX;
yPoints[i + 1] = originalFinalRouteSegY;
if (routeIsForwardOnWay) {
hl[i] = PATHSEG_DO_NOT_HIGHLIGHT;
} else {
hl[i] = route.size() - 2;
wDraw = w;
if (wDraw < Configuration.getMinRouteLineWidth()) {
wDraw = Configuration.getMinRouteLineWidth();
}
}
dividedFinalRouteSeg = false;
dividedFinalDone = true;
}
}
// divide final segment on the route
if (
//false &&
highlight == HIGHLIGHT_ROUTEPATH_CONTAINED
&& route != null
&& hl[i] == route.size() - 2
) {
// get direction we go on the way
ConnectionWithNode c = (ConnectionWithNode) route.elementAt(hl[i]);
routeIsForwardOnWay = (c.wayFromConAt < c.wayToConAt);
pathIndexOfNewSeg = (routeIsForwardOnWay ? c.wayToConAt - 1 : c.wayToConAt);
//System.out.println ("waytoconat: " + c.wayToConAt + " wayfromconat: " + c.wayFromConAt + " i: " + i);
if (
i == pathIndexOfNewSeg
&& !dividedFinalDone
) {
IntPoint closestDestP = new IntPoint();
pc.getP().forward(RouteInstructions.getClosestPointOnDestWay(), closestDestP);
originalFinalRouteSegX = xPoints[i + 1];
originalFinalRouteSegY = yPoints[i + 1];
xPoints[i + 1] = closestDestP.x;
yPoints[i + 1] = closestDestP.y;
if (routeIsForwardOnWay) {
;
} else {
hl[i] = PATHSEG_DO_NOT_HIGHLIGHT;
wDraw = w;
}
//pc.g.setColor(0x00ff00);
//pc.g.drawString("closest:" + i, closestDestP.x, closestDestP.y, Graphics.TOP | Graphics.LEFT);
//System.out.println("Insert closest point at " + (i + 1) );
dividedFinalRouteSeg = true;
}
} else {
dividedFinalRouteSeg = false;
}
if (hl[i] >= 0
// if this is the closest segment of the closest connection
&& RouteInstructions.routePathConnection == hl[i]
&& i == RouteInstructions.pathIdxInRoutePathConnection - 1
&& !dividedSeg
) {
IntPoint centerP = new IntPoint();
// this is a divided seg (partly prior route line, partly current route line)
dividedSeg = true;
centerP=pc.getP().getImageCenter();
/** centerP is now provided by Projection implementation */
// pc.getP().forward(
// (short)(MoreMath.FIXPT_MULT * (pc.center.radlat - t.centerLat)),
// (short)(MoreMath.FIXPT_MULT * (pc.center.radlon - t.centerLon)), centerP, t);
// get point dividing the seg
closestP = MoreMath.closestPointOnLine(xPoints[i], yPoints[i], xPoints[i + 1], yPoints[i + 1], centerP.x, centerP.y);
// remember original next point
originalX = xPoints[i + 1];
originalY = yPoints[i + 1];
// replace next point with closest point
xPoints[i + 1] = closestP.x;
yPoints[i + 1] = closestP.y;
// remember width for drawing the closest point
wClosest = wDraw;
// get direction we go on the way
ConnectionWithNode c = (ConnectionWithNode) route.elementAt(hl[i]);
dividedHighlight = (c.wayFromConAt > c.wayToConAt);
} else {
dividedSeg = false;
}
// if (hl[i] >= 0) {
// pc.g.setColor(0xffff80);
// pc.g.drawString("i:" + i, xPoints[i], yPoints[i],Graphics.TOP | Graphics.LEFT);
// }
// Get the four outer points of the wDraw-wide waysegment
if (ortho){
getParLines(xPoints, yPoints, i , wDraw, l1b, l2b, l1e, l2e);
} else {
pc.getP().getParLines(xPoints, yPoints, i , wDraw, l1b, l2b, l1e, l2e);
}
if (hl[i] != PATHSEG_DO_NOT_DRAW) {
// if (mode == DRAW_AREA) {
setColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
int xbcentre = (l2b.x + l1b.x) / 2;
int xecentre = (l2e.x + l1e.x) / 2;
int ybcentre = (l2b.y + l1b.y) / 2;
int yecentre = (l2e.y + l1e.y) / 2;
int xbdiameter = Math.abs(l2b.x - l1b.x);
int xediameter = Math.abs(l2e.x - l1e.x);
int ybdiameter = Math.abs(l2b.y - l1b.y);
int yediameter = Math.abs(l2e.y - l1e.y);
// FIXME we would need rotated ellipsis for clean rounded endings,
// but lacking that we can apply some heuristics
if (xbdiameter/3 > ybdiameter) {
ybdiameter = xbdiameter/3;
}
if (ybdiameter/3 > xbdiameter) {
xbdiameter = ybdiameter/3;
}
if (xediameter/3 > yediameter) {
yediameter = xediameter/3;
}
if (yediameter/3 > xediameter) {
xediameter = yediameter/3;
}
// when this is not render as lines (for the non-highlighted part of the way) or it is a highlighted part, draw as area
if (wOriginal != 0 || hl[i] >= 0) {
pc.g.fillTriangle(l2b.x, l2b.y, l1b.x, l1b.y, l1e.x, l1e.y);
pc.g.fillTriangle(l1e.x, l1e.y, l2e.x, l2e.y, l2b.x, l2b.y);
if (i == 0) { // if this is the first segment, draw the lines
// draw circular endings
if (Configuration.getCfgBitState(Configuration.CFGBIT_ROUND_WAY_ENDS) && wDraw > 2) {
if (ortho) {
circleWayEnd(pc, xbcentre, ybcentre, wDraw);
circleWayEnd(pc, xecentre, yecentre, wDraw);
} else {
// ellipse is close, but rotation is missing
// FIXME fix the bad appearance for eagle projection
pc.g.fillArc(xbcentre - xbdiameter/2, ybcentre - ybdiameter/2, xbdiameter, ybdiameter, 0, 360);
pc.g.fillArc(xecentre - xediameter/2, yecentre - yediameter/2, xediameter, yediameter, 0, 360);
}
}
setBorderColor(pc, wayDesc,(hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (! Configuration.getCfgBitState(Configuration.CFGBIT_NOSTREETBORDERS) || isCurrentRoutePath(pc, i)) {
pc.g.drawLine(l2b.x, l2b.y, l2e.x, l2e.y);
pc.g.drawLine(l1b.x, l1b.y, l1e.x, l1e.y);
}
}
// Now look at the turns(corners) of the waysegment and fill them if necessary.
// We always look back to the turn between current and previous waysegment.
if (i > 0) {
// as we look back, there is no turn at the first segment
turn = getVectorTurn(xPoints[i - 1], yPoints[i - 1], xPoints[i],
yPoints[i], xPoints[i + 1], yPoints[i + 1] );
if (turn < 0 ) {
// turn right
intersectionPoint(l4b, l4e, l2b, l2e, intersecP, 1);
setColor(pc, wayDesc,(hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
// Fills the gap of the corner with a small triangle
pc.g.fillTriangle(xPoints[i], yPoints[i] , l3e.x, l3e.y, l1b.x,l1b.y);
if (Configuration.getCfgBitState(Configuration.CFGBIT_ROUND_WAY_ENDS) && wDraw > 2) {
if (ortho) {
circleWayEnd(pc, xbcentre, ybcentre, wDraw);
circleWayEnd(pc, xecentre, yecentre, wDraw
);
} else {
// ellipse is close, but rotation is missing
// FIXME fix the bad appearance for eagle projection
pc.g.fillArc(xbcentre - xbdiameter/2, ybcentre - ybdiameter/2, xbdiameter, ybdiameter, 0, 360);
pc.g.fillArc(xecentre - xediameter/2, yecentre - yediameter/2, xediameter, yediameter, 0, 360);
}
}
setBorderColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (! Configuration.getCfgBitState(Configuration.CFGBIT_NOSTREETBORDERS) || isCurrentRoutePath(pc, i)) {
if (highlight == HIGHLIGHT_NONE) {
//paint the inner turn border to the intersection point between old and current waysegment
pc.g.drawLine(intersecP.x, intersecP.y, l2e.x, l2e.y);
} else {
//painting full border of the inner turn while routing
pc.g.drawLine(l2b.x, l2b.y, l2e.x, l2e.y);
}
// paint the full outer turn border
pc.g.drawLine(l1b.x, l1b.y, l1e.x, l1e.y);
// paint the full outer turn border
pc.g.drawLine(l1b.x, l1b.y, l3e.x, l3e.y);
}
}
else if (turn > 0 ) {
// turn left
intersectionPoint(l3b,l3e,l1b,l1e,intersecP,1);
setColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
// Fills the gap of the corner with a small triangle
pc.g.fillTriangle(xPoints[i], yPoints[i] , l4e.x, l4e.y, l2b.x,l2b.y);
if (Configuration.getCfgBitState(Configuration.CFGBIT_ROUND_WAY_ENDS) && wDraw > 2) {
if (ortho) {
circleWayEnd(pc, xbcentre, ybcentre, wDraw);
circleWayEnd(pc, xecentre, yecentre, wDraw);
} else {
// ellipse is close, but rotation is missing
// FIXME fix the bad appearance for eagle projection
pc.g.fillArc(xbcentre - xbdiameter/2, ybcentre - ybdiameter/2, xbdiameter, ybdiameter, 0, 360);
pc.g.fillArc(xecentre - xediameter/2, yecentre - yediameter/2, xediameter, yediameter, 0, 360);
}
}
setBorderColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (! Configuration.getCfgBitState(Configuration.CFGBIT_NOSTREETBORDERS) || isCurrentRoutePath(pc, i)) {
if (highlight == HIGHLIGHT_NONE) {
//see comments above
pc.g.drawLine(intersecP.x, intersecP.y, l1e.x, l1e.y);
} else {
pc.g.drawLine(l1b.x, l1b.y, l1e.x, l1e.y);
}
pc.g.drawLine(l2b.x, l2b.y, l2e.x, l2e.y);
//corner
pc.g.drawLine(l2b.x, l2b.y, l4e.x, l4e.y);
}
}
else {
//no turn, way is straight
setColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (Configuration.getCfgBitState(Configuration.CFGBIT_ROUND_WAY_ENDS) && wDraw > 2) {
if (ortho) {
circleWayEnd(pc, xbcentre, ybcentre, wDraw);
circleWayEnd(pc, xecentre, yecentre, wDraw);
} else {
// ellipse is close, but rotation is missing
// FIXME fix the bad appearance for eagle projection
pc.g.fillArc(xbcentre - xbdiameter/2, ybcentre - ybdiameter/2, xbdiameter, ybdiameter, 0, 360);
pc.g.fillArc(xecentre - xediameter/2, yecentre - yediameter/2, xediameter, yediameter, 0, 360);
}
}
setBorderColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (! Configuration.getCfgBitState(Configuration.CFGBIT_NOSTREETBORDERS) || isCurrentRoutePath(pc, i)) {
pc.g.drawLine(l2b.x, l2b.y, l2e.x, l2e.y);
// paint the full outer turn border
pc.g.drawLine(l1b.x, l1b.y, l1e.x, l1e.y);
}
}
}
} else {
// Draw streets as lines (only 1px wide)
setColor(pc,wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
pc.g.drawLine(xPoints[i], yPoints[i], xPoints[i + 1], yPoints[i + 1]);
}
if (isBridge()) {
waySegment.drawBridge(pc, xPoints, yPoints, i, count - 1, w,
l1b, l1e, l2b, l2e);
}
if (isTunnel()) {
waySegment.drawTunnel(pc, xPoints, yPoints, i, count - 1, w,
l1b, l1e, l2b, l2e);
}
if (isTollRoad()) {
waySegment.drawTollRoad(pc, xPoints, yPoints, i, count - 1, w,
l1b, l1e, l2b, l2e);
}
if (isDamaged()) {
waySegment.drawDamage(pc, xPoints, yPoints, i, count - 1, w,
l1b, l1e, l2b, l2e);
}
}
//Save the way-corners for the next loop to fill segment-gaps
l3b.set(l1b);
l4b.set(l2b);
l3e.set(l1e);
l4e.set(l2e);
if (dividedSeg || dividedFinalRouteSeg) {
// if this is a divided seg, in the next step draw the second part
i--;
}
}
if (isOneway()) {
// Loop through all waysegments for painting the OnewayArrows as overlay
// TODO: Maybe, we can integrate this one day in the main loop. Currently, we have troubles
// with "not completely fitting arrows" getting overpainted by the next waysegment.
paintPathOnewayArrows(count, wayDesc, pc);
}
//now as we painted all ways, do the things we should only do once
if (wClosest != 0) {
// if we got a closest seg, draw closest point to the center in it
RouteInstructions.drawRouteDot(pc.g, closestP, wClosest);
}
if (nameAsForArea()) {
paintAreaName(pc,t);
}
}
| private void draw(PaintContext pc, SingleTile t, int w, int xPoints[], int yPoints[],
int hl[], int count, byte highlight,boolean ortho /*, byte mode*/) {
IntPoint closestP = new IntPoint();
int wClosest = 0;
boolean dividedSeg = false;
boolean dividedHighlight = true;
IntPoint closestDestP = new IntPoint();
boolean dividedFinalRouteSeg = false;
boolean dividedFinalDone = false;
int originalFinalRouteSegX = 0;
int originalFinalRouteSegY = 0;
int pathIndexOfNewSeg = 0;
boolean routeIsForwardOnWay = false;
int originalX = 0;
int originalY = 0;
int wOriginal = w;
if (w <1) w=1;
int wDraw = w;
int turn = 0;
WayDescription wayDesc = Legend.getWayDescription(type);
Vector route = pc.trace.getRoute();
for (int i = 0; i < count; i++) {
wDraw = w;
// draw route line wider
if (
highlight == HIGHLIGHT_ROUTEPATH_CONTAINED
&& hl[i] >= 0
&& wDraw < Configuration.getMinRouteLineWidth()
) {
wDraw = Configuration.getMinRouteLineWidth();
}
if (dividedSeg) {
// if this is a divided seg, draw second part of it
xPoints[i] = xPoints[i + 1];
yPoints[i] = yPoints[i + 1];
xPoints[i + 1] = originalX;
yPoints[i + 1] = originalY;
dividedHighlight = !dividedHighlight;
} else {
// if not turn off the highlight
dividedHighlight = false;
if (dividedFinalRouteSeg) {
//System.out.println ("restore i " + i);
xPoints[i] = xPoints[i + 1];
yPoints[i] = yPoints[i + 1];
xPoints[i + 1] = originalFinalRouteSegX;
yPoints[i + 1] = originalFinalRouteSegY;
if (routeIsForwardOnWay) {
hl[i] = PATHSEG_DO_NOT_HIGHLIGHT;
} else {
hl[i] = route.size() - 2;
wDraw = w;
if (wDraw < Configuration.getMinRouteLineWidth()) {
wDraw = Configuration.getMinRouteLineWidth();
}
}
dividedFinalRouteSeg = false;
dividedFinalDone = true;
}
}
// divide final segment on the route
if (
//false &&
highlight == HIGHLIGHT_ROUTEPATH_CONTAINED
&& route != null
&& hl[i] == route.size() - 2
) {
// get direction we go on the way
ConnectionWithNode c = (ConnectionWithNode) route.elementAt(hl[i]);
routeIsForwardOnWay = (c.wayFromConAt < c.wayToConAt);
pathIndexOfNewSeg = (routeIsForwardOnWay ? c.wayToConAt - 1 : c.wayToConAt);
//System.out.println ("waytoconat: " + c.wayToConAt + " wayfromconat: " + c.wayFromConAt + " i: " + i);
if (
i == pathIndexOfNewSeg
&& !dividedFinalDone
) {
pc.getP().forward(RouteInstructions.getClosestPointOnDestWay(), closestDestP);
originalFinalRouteSegX = xPoints[i + 1];
originalFinalRouteSegY = yPoints[i + 1];
xPoints[i + 1] = closestDestP.x;
yPoints[i + 1] = closestDestP.y;
if (routeIsForwardOnWay) {
;
} else {
hl[i] = PATHSEG_DO_NOT_HIGHLIGHT;
wDraw = w;
}
//pc.g.setColor(0x00ff00);
//pc.g.drawString("closest:" + i, closestDestP.x, closestDestP.y, Graphics.TOP | Graphics.LEFT);
//System.out.println("Insert closest point at " + (i + 1) );
dividedFinalRouteSeg = true;
}
} else {
dividedFinalRouteSeg = false;
}
if (hl[i] >= 0
// if this is the closest segment of the closest connection
&& RouteInstructions.routePathConnection == hl[i]
&& i == RouteInstructions.pathIdxInRoutePathConnection - 1
&& !dividedSeg
) {
IntPoint centerP = new IntPoint();
// this is a divided seg (partly prior route line, partly current route line)
dividedSeg = true;
centerP=pc.getP().getImageCenter();
/** centerP is now provided by Projection implementation */
// pc.getP().forward(
// (short)(MoreMath.FIXPT_MULT * (pc.center.radlat - t.centerLat)),
// (short)(MoreMath.FIXPT_MULT * (pc.center.radlon - t.centerLon)), centerP, t);
// get point dividing the seg
closestP = MoreMath.closestPointOnLine(xPoints[i], yPoints[i], xPoints[i + 1], yPoints[i + 1], centerP.x, centerP.y);
// remember original next point
originalX = xPoints[i + 1];
originalY = yPoints[i + 1];
// replace next point with closest point
xPoints[i + 1] = closestP.x;
yPoints[i + 1] = closestP.y;
// remember width for drawing the closest point
wClosest = wDraw;
// get direction we go on the way
ConnectionWithNode c = (ConnectionWithNode) route.elementAt(hl[i]);
dividedHighlight = (c.wayFromConAt > c.wayToConAt);
// fix dstToRoutePath on way part of divided final route seg for off route display
if ( (dividedFinalDone || dividedFinalRouteSeg)
&&closestP.equals(closestDestP)
) {
pc.squareDstToRoutePath = MoreMath.ptSegDistSq( closestDestP.x, closestDestP.y,
closestDestP.x, closestDestP.y,
centerP.x, centerP.y
);
}
} else {
dividedSeg = false;
}
// if (hl[i] >= 0) {
// pc.g.setColor(0xffff80);
// pc.g.drawString("i:" + i, xPoints[i], yPoints[i],Graphics.TOP | Graphics.LEFT);
// }
// Get the four outer points of the wDraw-wide waysegment
if (ortho){
getParLines(xPoints, yPoints, i , wDraw, l1b, l2b, l1e, l2e);
} else {
pc.getP().getParLines(xPoints, yPoints, i , wDraw, l1b, l2b, l1e, l2e);
}
if (hl[i] != PATHSEG_DO_NOT_DRAW) {
// if (mode == DRAW_AREA) {
setColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
int xbcentre = (l2b.x + l1b.x) / 2;
int xecentre = (l2e.x + l1e.x) / 2;
int ybcentre = (l2b.y + l1b.y) / 2;
int yecentre = (l2e.y + l1e.y) / 2;
int xbdiameter = Math.abs(l2b.x - l1b.x);
int xediameter = Math.abs(l2e.x - l1e.x);
int ybdiameter = Math.abs(l2b.y - l1b.y);
int yediameter = Math.abs(l2e.y - l1e.y);
// FIXME we would need rotated ellipsis for clean rounded endings,
// but lacking that we can apply some heuristics
if (xbdiameter/3 > ybdiameter) {
ybdiameter = xbdiameter/3;
}
if (ybdiameter/3 > xbdiameter) {
xbdiameter = ybdiameter/3;
}
if (xediameter/3 > yediameter) {
yediameter = xediameter/3;
}
if (yediameter/3 > xediameter) {
xediameter = yediameter/3;
}
// when this is not render as lines (for the non-highlighted part of the way) or it is a highlighted part, draw as area
if (wOriginal != 0 || hl[i] >= 0) {
pc.g.fillTriangle(l2b.x, l2b.y, l1b.x, l1b.y, l1e.x, l1e.y);
pc.g.fillTriangle(l1e.x, l1e.y, l2e.x, l2e.y, l2b.x, l2b.y);
if (i == 0) { // if this is the first segment, draw the lines
// draw circular endings
if (Configuration.getCfgBitState(Configuration.CFGBIT_ROUND_WAY_ENDS) && wDraw > 2) {
if (ortho) {
circleWayEnd(pc, xbcentre, ybcentre, wDraw);
circleWayEnd(pc, xecentre, yecentre, wDraw);
} else {
// ellipse is close, but rotation is missing
// FIXME fix the bad appearance for eagle projection
pc.g.fillArc(xbcentre - xbdiameter/2, ybcentre - ybdiameter/2, xbdiameter, ybdiameter, 0, 360);
pc.g.fillArc(xecentre - xediameter/2, yecentre - yediameter/2, xediameter, yediameter, 0, 360);
}
}
setBorderColor(pc, wayDesc,(hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (! Configuration.getCfgBitState(Configuration.CFGBIT_NOSTREETBORDERS) || isCurrentRoutePath(pc, i)) {
pc.g.drawLine(l2b.x, l2b.y, l2e.x, l2e.y);
pc.g.drawLine(l1b.x, l1b.y, l1e.x, l1e.y);
}
}
// Now look at the turns(corners) of the waysegment and fill them if necessary.
// We always look back to the turn between current and previous waysegment.
if (i > 0) {
// as we look back, there is no turn at the first segment
turn = getVectorTurn(xPoints[i - 1], yPoints[i - 1], xPoints[i],
yPoints[i], xPoints[i + 1], yPoints[i + 1] );
if (turn < 0 ) {
// turn right
intersectionPoint(l4b, l4e, l2b, l2e, intersecP, 1);
setColor(pc, wayDesc,(hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
// Fills the gap of the corner with a small triangle
pc.g.fillTriangle(xPoints[i], yPoints[i] , l3e.x, l3e.y, l1b.x,l1b.y);
if (Configuration.getCfgBitState(Configuration.CFGBIT_ROUND_WAY_ENDS) && wDraw > 2) {
if (ortho) {
circleWayEnd(pc, xbcentre, ybcentre, wDraw);
circleWayEnd(pc, xecentre, yecentre, wDraw
);
} else {
// ellipse is close, but rotation is missing
// FIXME fix the bad appearance for eagle projection
pc.g.fillArc(xbcentre - xbdiameter/2, ybcentre - ybdiameter/2, xbdiameter, ybdiameter, 0, 360);
pc.g.fillArc(xecentre - xediameter/2, yecentre - yediameter/2, xediameter, yediameter, 0, 360);
}
}
setBorderColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (! Configuration.getCfgBitState(Configuration.CFGBIT_NOSTREETBORDERS) || isCurrentRoutePath(pc, i)) {
if (highlight == HIGHLIGHT_NONE) {
//paint the inner turn border to the intersection point between old and current waysegment
pc.g.drawLine(intersecP.x, intersecP.y, l2e.x, l2e.y);
} else {
//painting full border of the inner turn while routing
pc.g.drawLine(l2b.x, l2b.y, l2e.x, l2e.y);
}
// paint the full outer turn border
pc.g.drawLine(l1b.x, l1b.y, l1e.x, l1e.y);
// paint the full outer turn border
pc.g.drawLine(l1b.x, l1b.y, l3e.x, l3e.y);
}
}
else if (turn > 0 ) {
// turn left
intersectionPoint(l3b,l3e,l1b,l1e,intersecP,1);
setColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
// Fills the gap of the corner with a small triangle
pc.g.fillTriangle(xPoints[i], yPoints[i] , l4e.x, l4e.y, l2b.x,l2b.y);
if (Configuration.getCfgBitState(Configuration.CFGBIT_ROUND_WAY_ENDS) && wDraw > 2) {
if (ortho) {
circleWayEnd(pc, xbcentre, ybcentre, wDraw);
circleWayEnd(pc, xecentre, yecentre, wDraw);
} else {
// ellipse is close, but rotation is missing
// FIXME fix the bad appearance for eagle projection
pc.g.fillArc(xbcentre - xbdiameter/2, ybcentre - ybdiameter/2, xbdiameter, ybdiameter, 0, 360);
pc.g.fillArc(xecentre - xediameter/2, yecentre - yediameter/2, xediameter, yediameter, 0, 360);
}
}
setBorderColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (! Configuration.getCfgBitState(Configuration.CFGBIT_NOSTREETBORDERS) || isCurrentRoutePath(pc, i)) {
if (highlight == HIGHLIGHT_NONE) {
//see comments above
pc.g.drawLine(intersecP.x, intersecP.y, l1e.x, l1e.y);
} else {
pc.g.drawLine(l1b.x, l1b.y, l1e.x, l1e.y);
}
pc.g.drawLine(l2b.x, l2b.y, l2e.x, l2e.y);
//corner
pc.g.drawLine(l2b.x, l2b.y, l4e.x, l4e.y);
}
}
else {
//no turn, way is straight
setColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (Configuration.getCfgBitState(Configuration.CFGBIT_ROUND_WAY_ENDS) && wDraw > 2) {
if (ortho) {
circleWayEnd(pc, xbcentre, ybcentre, wDraw);
circleWayEnd(pc, xecentre, yecentre, wDraw);
} else {
// ellipse is close, but rotation is missing
// FIXME fix the bad appearance for eagle projection
pc.g.fillArc(xbcentre - xbdiameter/2, ybcentre - ybdiameter/2, xbdiameter, ybdiameter, 0, 360);
pc.g.fillArc(xecentre - xediameter/2, yecentre - yediameter/2, xediameter, yediameter, 0, 360);
}
}
setBorderColor(pc, wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
if (! Configuration.getCfgBitState(Configuration.CFGBIT_NOSTREETBORDERS) || isCurrentRoutePath(pc, i)) {
pc.g.drawLine(l2b.x, l2b.y, l2e.x, l2e.y);
// paint the full outer turn border
pc.g.drawLine(l1b.x, l1b.y, l1e.x, l1e.y);
}
}
}
} else {
// Draw streets as lines (only 1px wide)
setColor(pc,wayDesc, (hl[i] >= 0),
(isCurrentRoutePath(pc, i) || dividedHighlight),
(highlight == HIGHLIGHT_DEST));
pc.g.drawLine(xPoints[i], yPoints[i], xPoints[i + 1], yPoints[i + 1]);
}
if (isBridge()) {
waySegment.drawBridge(pc, xPoints, yPoints, i, count - 1, w,
l1b, l1e, l2b, l2e);
}
if (isTunnel()) {
waySegment.drawTunnel(pc, xPoints, yPoints, i, count - 1, w,
l1b, l1e, l2b, l2e);
}
if (isTollRoad()) {
waySegment.drawTollRoad(pc, xPoints, yPoints, i, count - 1, w,
l1b, l1e, l2b, l2e);
}
if (isDamaged()) {
waySegment.drawDamage(pc, xPoints, yPoints, i, count - 1, w,
l1b, l1e, l2b, l2e);
}
}
//Save the way-corners for the next loop to fill segment-gaps
l3b.set(l1b);
l4b.set(l2b);
l3e.set(l1e);
l4e.set(l2e);
if (dividedSeg || dividedFinalRouteSeg) {
// if this is a divided seg, in the next step draw the second part
i--;
}
}
if (isOneway()) {
// Loop through all waysegments for painting the OnewayArrows as overlay
// TODO: Maybe, we can integrate this one day in the main loop. Currently, we have troubles
// with "not completely fitting arrows" getting overpainted by the next waysegment.
paintPathOnewayArrows(count, wayDesc, pc);
}
//now as we painted all ways, do the things we should only do once
if (wClosest != 0) {
// if we got a closest seg, draw closest point to the center in it
RouteInstructions.drawRouteDot(pc.g, closestP, wClosest);
}
if (nameAsForArea()) {
paintAreaName(pc,t);
}
}
|
diff --git a/src/com/aragaer/jtt/core/Calculator.java b/src/com/aragaer/jtt/core/Calculator.java
index 3786c7c..c63354e 100644
--- a/src/com/aragaer/jtt/core/Calculator.java
+++ b/src/com/aragaer/jtt/core/Calculator.java
@@ -1,163 +1,163 @@
package com.aragaer.jtt.core;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import java.util.Map;
import java.util.HashMap;
import java.util.TimeZone;
import com.luckycatlabs.sunrisesunset.SunriseSunsetCalculator;
import com.luckycatlabs.sunrisesunset.dto.Location;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.util.Log;
public class Calculator extends ContentProvider {
public static final String AUTHORITY = "com.aragaer.jtt.provider.calculator";
public static final Uri TRANSITIONS = Uri.parse("content://" + AUTHORITY + "/transitions"),
LOCATION = Uri.parse("content://" + AUTHORITY + "/location");
private final Map<Long, long[]> cache = new HashMap<Long, long[]>();
private static final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
private static final int TR = 1,
LOC = 2;
static {
matcher.addURI(AUTHORITY, "transitions/#", TR);
matcher.addURI(AUTHORITY, "location", LOC);
}
private SunriseSunsetCalculator calculator;
@Override
public boolean onCreate() {
return true;
}
private static final String PROJECTION_TR[] = { "prev", "start", "end", "next", "is_day" };
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
final int action = matcher.match(uri);
if (action != TR)
throw new IllegalArgumentException("Unsupported uri for query: " + uri);
if (calculator == null)
throw new IllegalStateException("Location not set");
final long now = ContentUris.parseId(uri);
long jdn = longToJDN(now);
/* fill 4 transitions at once */
final long tr[] = new long[] {
getTrForJDN(jdn - 1)[1],
getTrForJDN(jdn)[0],
getTrForJDN(jdn)[1],
getTrForJDN(jdn + 1)[0]
};
boolean is_day = true;
// if tr2 is before now
while (now >= tr[2]) {
for (int i = 0; i < 3; i++)
tr[i] = tr[i + 1];
if (is_day)
- tr[3] = getTrForJDN(jdn)[1];
+ tr[3] = getTrForJDN(jdn + 1)[1];
else {
jdn++;
- tr[3] = getTrForJDN(jdn)[0];
+ tr[3] = getTrForJDN(jdn + 1)[0];
}
is_day = !is_day;
}
// (else) if tr1 is after now
while (now < tr[1]) {
for (int i = 0; i < 3; i++)
tr[i + 1] = tr[i];
if (is_day)
- tr[0] = getTrForJDN(jdn)[0];
+ tr[0] = getTrForJDN(jdn - 1)[0];
else {
jdn--;
- tr[0] = getTrForJDN(jdn)[1];
+ tr[0] = getTrForJDN(jdn - 1)[1];
}
is_day = !is_day;
}
final MatrixCursor c = new MatrixCursor(PROJECTION_TR, 1);
c.addRow(new Object[] {tr[0], tr[1], tr[2], tr[3], is_day ? 1 : 0});
return c;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
public String getType(Uri uri) {
return null;
}
public Uri insert(Uri uri, ContentValues values) {
return null;
}
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
if (matcher.match(uri) != LOC)
throw new IllegalArgumentException("Unsupported uri for update: " + uri);
calculator = new SunriseSunsetCalculator(
new Location(
values.getAsFloat("lat"),
values.getAsFloat("lon")),
TimeZone.getDefault());
cache.clear();
Log.d("PROVIDER", "Location updated");
return 0;
}
/* Calculate a total of 4 transitions, tr[1] <= now < tr[2]. Return true if it is day now */
public static boolean getSurroundingTransitions(final Context context, final long now, final long tr[]) {
final Cursor c = context.getContentResolver()
.query(ContentUris.withAppendedId(TRANSITIONS, now), null, null, null, null);
c.moveToFirst();
for (int i = 0; i < 4; i++)
tr[i] = c.getLong(i);
final boolean is_day = c.getInt(4) == 1;
c.close();
return is_day;
}
public static final long ms_per_day = TimeUnit.SECONDS.toMillis(60 * 60 * 24);
private static long longToJDN(long time) {
return (long) Math.floor(longToJD(time));
}
private static double longToJD(long time) {
return time / ((double) ms_per_day) + 2440587.5;
}
private static long JDToLong(final double jd) {
return Math.round((jd - 2440587.5) * ms_per_day);
}
private long[] getTrForJDN(final long jdn) {
long[] result = cache.get(jdn);
if (result == null) {
final Calendar date = Calendar.getInstance();
date.setTimeInMillis(JDToLong(jdn));
result = new long[] { calculator.getOfficialSunriseForDate(date),
calculator.getOfficialSunsetForDate(date) };
cache.put(jdn, result);
}
return result;
}
}
| false | true | public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
final int action = matcher.match(uri);
if (action != TR)
throw new IllegalArgumentException("Unsupported uri for query: " + uri);
if (calculator == null)
throw new IllegalStateException("Location not set");
final long now = ContentUris.parseId(uri);
long jdn = longToJDN(now);
/* fill 4 transitions at once */
final long tr[] = new long[] {
getTrForJDN(jdn - 1)[1],
getTrForJDN(jdn)[0],
getTrForJDN(jdn)[1],
getTrForJDN(jdn + 1)[0]
};
boolean is_day = true;
// if tr2 is before now
while (now >= tr[2]) {
for (int i = 0; i < 3; i++)
tr[i] = tr[i + 1];
if (is_day)
tr[3] = getTrForJDN(jdn)[1];
else {
jdn++;
tr[3] = getTrForJDN(jdn)[0];
}
is_day = !is_day;
}
// (else) if tr1 is after now
while (now < tr[1]) {
for (int i = 0; i < 3; i++)
tr[i + 1] = tr[i];
if (is_day)
tr[0] = getTrForJDN(jdn)[0];
else {
jdn--;
tr[0] = getTrForJDN(jdn)[1];
}
is_day = !is_day;
}
final MatrixCursor c = new MatrixCursor(PROJECTION_TR, 1);
c.addRow(new Object[] {tr[0], tr[1], tr[2], tr[3], is_day ? 1 : 0});
return c;
}
| public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
final int action = matcher.match(uri);
if (action != TR)
throw new IllegalArgumentException("Unsupported uri for query: " + uri);
if (calculator == null)
throw new IllegalStateException("Location not set");
final long now = ContentUris.parseId(uri);
long jdn = longToJDN(now);
/* fill 4 transitions at once */
final long tr[] = new long[] {
getTrForJDN(jdn - 1)[1],
getTrForJDN(jdn)[0],
getTrForJDN(jdn)[1],
getTrForJDN(jdn + 1)[0]
};
boolean is_day = true;
// if tr2 is before now
while (now >= tr[2]) {
for (int i = 0; i < 3; i++)
tr[i] = tr[i + 1];
if (is_day)
tr[3] = getTrForJDN(jdn + 1)[1];
else {
jdn++;
tr[3] = getTrForJDN(jdn + 1)[0];
}
is_day = !is_day;
}
// (else) if tr1 is after now
while (now < tr[1]) {
for (int i = 0; i < 3; i++)
tr[i + 1] = tr[i];
if (is_day)
tr[0] = getTrForJDN(jdn - 1)[0];
else {
jdn--;
tr[0] = getTrForJDN(jdn - 1)[1];
}
is_day = !is_day;
}
final MatrixCursor c = new MatrixCursor(PROJECTION_TR, 1);
c.addRow(new Object[] {tr[0], tr[1], tr[2], tr[3], is_day ? 1 : 0});
return c;
}
|
diff --git a/GhostBuster/src/org/bonsaimind/bukkitplugins/ghostbuster/Plugin.java b/GhostBuster/src/org/bonsaimind/bukkitplugins/ghostbuster/Plugin.java
index 7d095bd..ce5e5ab 100644
--- a/GhostBuster/src/org/bonsaimind/bukkitplugins/ghostbuster/Plugin.java
+++ b/GhostBuster/src/org/bonsaimind/bukkitplugins/ghostbuster/Plugin.java
@@ -1,205 +1,205 @@
/*
* This file is part of GhostBuster.
*
* GhostBuster is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GhostBuster 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 GhostBuster. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Author: Robert 'Bobby' Zenz
* Website: http://www.bonsaimind.org
* GitHub: https://github.com/RobertZenz/org.bonsaimind.bukkitplugins/tree/master/Plugin
* E-Mail: [email protected]
*/
package org.bonsaimind.bukkitplugins.ghostbuster;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event.Type;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
/**
*
* @author Robert 'Bobby' Zenz
*/
public class Plugin extends JavaPlugin {
private Server server = null;
private BukkitScheduler scheduler = null;
private PlayerLoginListener playerListener = new PlayerLoginListener(this);
private EntityDeathListener entityListener = new EntityDeathListener(this);
private Winston winston;
public void onDisable() {
winston.save();
winston = null;
playerListener = null;
entityListener = null;
server = null;
}
public void onEnable() {
server = getServer();
scheduler = server.getScheduler();
PluginManager pm = server.getPluginManager();
pm.registerEvent(Type.PLAYER_LOGIN, playerListener, Priority.Highest, this);
pm.registerEvent(Type.ENTITY_DEATH, entityListener, Priority.Monitor, this);
PluginDescriptionFile pdfFile = this.getDescription();
System.out.println(pdfFile.getName() + " " + pdfFile.getVersion() + " is enabled.");
winston = new Winston("./plugins/GhostBuster/");
winston.load();
setCommand();
}
protected void banPlayer(Player player) {
if (!winston.isExcepted(player.getName())) {
if (!winston.getFreeSlotsMode() || server.getOnlinePlayers().length >= server.getMaxPlayers()) {
// Now ban the bastard!
winston.banPlayer(player.getName());
// Now kick the player
final Player finalizedPlayer = player;
scheduler.scheduleAsyncDelayedTask(this, new Runnable() {
public void run() {
finalizedPlayer.kickPlayer(prepareMessage(winston.getDeathMessage(), winston.getBanExpiration(finalizedPlayer.getName())));
}
}, 4);
}
}
}
protected void checkPlayer(PlayerLoginEvent event) {
// Check if the player is allowed to join
if (winston.isBanned(event.getPlayer().getName())) {
// Nope, it's not...
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, prepareMessage(winston.getStillDeadMessage(), winston.getBanExpiration(event.getPlayer().getName())));
}
}
/**
* Replace %h and %m.
* @param message The message.
* @param timeLeft Time left, in minutes!
* @return
*/
private String prepareMessage(String message, long timeLeft) {
message = message.replace("%h", Long.toString(timeLeft / 60));
message = message.replace("%m", Long.toString(timeLeft % 60));
return message;
}
private void setCommand() {
getCommand("ghostbuster").setExecutor(new CommandExecutor() {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!sender.isOp()) {
sender.sendMessage("I'm sorry, Dave. I'm afraid I can't do that.");
return true;
}
if (args.length == 0) {
return false;
}
for (int idx = 0; idx < args.length; idx++) {
String arg = args[idx];
if (arg.equalsIgnoreCase("ban")) {
- if (idx >= args.length) {
+ if (idx >= args.length - 1) {
return false;
}
if (winston.banPlayer(args[idx + 1])) {
sender.sendMessage("Done.");
} else {
sender.sendMessage("That player is on the exception list.");
}
} else if (arg.equalsIgnoreCase("except")) {
- if (idx >= args.length) {
+ if (idx >= args.length - 1) {
return false;
}
if (winston.addException(args[idx + 1])) {
sender.sendMessage("Done.");
} else {
sender.sendMessage("That player is already on the exception list.");
}
} else if (arg.equalsIgnoreCase("info")) {
- if (idx >= args.length) {
+ if (idx >= args.length - 1) {
return false;
}
if (winston.isExcepted(args[idx + 1])) {
sender.sendMessage("That player is on the exception list.");
} else {
long expires = winston.getBanExpiration(args[idx + 1]);
if (expires > 0) {
sender.sendMessage(prepareMessage("Banned for another %h hours and %m minutes.", expires));
} else {
sender.sendMessage("That player is not banned.");
}
}
} else if (arg.equalsIgnoreCase("reload")) {
winston.reload();
sender.sendMessage("Done.");
} else if (arg.equalsIgnoreCase("save")) {
winston.save();
sender.sendMessage("Done.");
} else if (arg.equalsIgnoreCase("unban")) {
- if (idx >= args.length) {
+ if (idx >= args.length - 1) {
return false;
}
if (winston.unbanPlayer(args[idx + 1])) {
sender.sendMessage("Done.");
} else {
sender.sendMessage("That player is not banned.");
}
} else if (arg.equalsIgnoreCase("unban_all")) {
winston.unbanAll();
sender.sendMessage("Done.");
} else if (arg.equalsIgnoreCase("unexcept")) {
- if (idx >= args.length) {
+ if (idx >= args.length - 1) {
return false;
}
if (winston.removeException(args[idx + 1])) {
sender.sendMessage("Done.");
} else {
sender.sendMessage("That player is not on the exception list.");
}
}
}
return true;
}
});
}
}
| false | true | private void setCommand() {
getCommand("ghostbuster").setExecutor(new CommandExecutor() {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!sender.isOp()) {
sender.sendMessage("I'm sorry, Dave. I'm afraid I can't do that.");
return true;
}
if (args.length == 0) {
return false;
}
for (int idx = 0; idx < args.length; idx++) {
String arg = args[idx];
if (arg.equalsIgnoreCase("ban")) {
if (idx >= args.length) {
return false;
}
if (winston.banPlayer(args[idx + 1])) {
sender.sendMessage("Done.");
} else {
sender.sendMessage("That player is on the exception list.");
}
} else if (arg.equalsIgnoreCase("except")) {
if (idx >= args.length) {
return false;
}
if (winston.addException(args[idx + 1])) {
sender.sendMessage("Done.");
} else {
sender.sendMessage("That player is already on the exception list.");
}
} else if (arg.equalsIgnoreCase("info")) {
if (idx >= args.length) {
return false;
}
if (winston.isExcepted(args[idx + 1])) {
sender.sendMessage("That player is on the exception list.");
} else {
long expires = winston.getBanExpiration(args[idx + 1]);
if (expires > 0) {
sender.sendMessage(prepareMessage("Banned for another %h hours and %m minutes.", expires));
} else {
sender.sendMessage("That player is not banned.");
}
}
} else if (arg.equalsIgnoreCase("reload")) {
winston.reload();
sender.sendMessage("Done.");
} else if (arg.equalsIgnoreCase("save")) {
winston.save();
sender.sendMessage("Done.");
} else if (arg.equalsIgnoreCase("unban")) {
if (idx >= args.length) {
return false;
}
if (winston.unbanPlayer(args[idx + 1])) {
sender.sendMessage("Done.");
} else {
sender.sendMessage("That player is not banned.");
}
} else if (arg.equalsIgnoreCase("unban_all")) {
winston.unbanAll();
sender.sendMessage("Done.");
} else if (arg.equalsIgnoreCase("unexcept")) {
if (idx >= args.length) {
return false;
}
if (winston.removeException(args[idx + 1])) {
sender.sendMessage("Done.");
} else {
sender.sendMessage("That player is not on the exception list.");
}
}
}
return true;
}
});
}
| private void setCommand() {
getCommand("ghostbuster").setExecutor(new CommandExecutor() {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!sender.isOp()) {
sender.sendMessage("I'm sorry, Dave. I'm afraid I can't do that.");
return true;
}
if (args.length == 0) {
return false;
}
for (int idx = 0; idx < args.length; idx++) {
String arg = args[idx];
if (arg.equalsIgnoreCase("ban")) {
if (idx >= args.length - 1) {
return false;
}
if (winston.banPlayer(args[idx + 1])) {
sender.sendMessage("Done.");
} else {
sender.sendMessage("That player is on the exception list.");
}
} else if (arg.equalsIgnoreCase("except")) {
if (idx >= args.length - 1) {
return false;
}
if (winston.addException(args[idx + 1])) {
sender.sendMessage("Done.");
} else {
sender.sendMessage("That player is already on the exception list.");
}
} else if (arg.equalsIgnoreCase("info")) {
if (idx >= args.length - 1) {
return false;
}
if (winston.isExcepted(args[idx + 1])) {
sender.sendMessage("That player is on the exception list.");
} else {
long expires = winston.getBanExpiration(args[idx + 1]);
if (expires > 0) {
sender.sendMessage(prepareMessage("Banned for another %h hours and %m minutes.", expires));
} else {
sender.sendMessage("That player is not banned.");
}
}
} else if (arg.equalsIgnoreCase("reload")) {
winston.reload();
sender.sendMessage("Done.");
} else if (arg.equalsIgnoreCase("save")) {
winston.save();
sender.sendMessage("Done.");
} else if (arg.equalsIgnoreCase("unban")) {
if (idx >= args.length - 1) {
return false;
}
if (winston.unbanPlayer(args[idx + 1])) {
sender.sendMessage("Done.");
} else {
sender.sendMessage("That player is not banned.");
}
} else if (arg.equalsIgnoreCase("unban_all")) {
winston.unbanAll();
sender.sendMessage("Done.");
} else if (arg.equalsIgnoreCase("unexcept")) {
if (idx >= args.length - 1) {
return false;
}
if (winston.removeException(args[idx + 1])) {
sender.sendMessage("Done.");
} else {
sender.sendMessage("That player is not on the exception list.");
}
}
}
return true;
}
});
}
|
diff --git a/drools-planner-examples/src/main/java/org/drools/planner/examples/tsp/solver/solution/initializer/TspStartingSolutionInitializer.java b/drools-planner-examples/src/main/java/org/drools/planner/examples/tsp/solver/solution/initializer/TspStartingSolutionInitializer.java
index 641d2bde..596b8e61 100644
--- a/drools-planner-examples/src/main/java/org/drools/planner/examples/tsp/solver/solution/initializer/TspStartingSolutionInitializer.java
+++ b/drools-planner-examples/src/main/java/org/drools/planner/examples/tsp/solver/solution/initializer/TspStartingSolutionInitializer.java
@@ -1,141 +1,142 @@
/*
* Copyright 2011 JBoss 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 org.drools.planner.examples.tsp.solver.solution.initializer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.drools.FactHandle;
import org.drools.WorkingMemory;
import org.drools.planner.core.score.DefaultSimpleScore;
import org.drools.planner.core.score.Score;
import org.drools.planner.core.solution.initializer.AbstractStartingSolutionInitializer;
import org.drools.planner.core.solver.AbstractSolverScope;
import org.drools.planner.examples.common.domain.PersistableIdComparator;
import org.drools.planner.examples.nurserostering.domain.Assignment;
import org.drools.planner.examples.nurserostering.domain.Employee;
import org.drools.planner.examples.nurserostering.domain.NurseRoster;
import org.drools.planner.examples.nurserostering.domain.Shift;
import org.drools.planner.examples.nurserostering.domain.ShiftDate;
import org.drools.planner.examples.tsp.domain.City;
import org.drools.planner.examples.tsp.domain.CityAssignment;
import org.drools.planner.examples.tsp.domain.TravelingSalesmanTour;
import org.drools.planner.examples.tsp.solver.move.TspMoveHelper;
public class TspStartingSolutionInitializer extends AbstractStartingSolutionInitializer {
@Override
public boolean isSolutionInitialized(AbstractSolverScope abstractSolverScope) {
TravelingSalesmanTour travelingSalesmanTour = (TravelingSalesmanTour) abstractSolverScope.getWorkingSolution();
return travelingSalesmanTour.isInitialized();
}
public void initializeSolution(AbstractSolverScope abstractSolverScope) {
TravelingSalesmanTour travelingSalesmanTour = (TravelingSalesmanTour) abstractSolverScope.getWorkingSolution();
initializeCityAssignmentList(abstractSolverScope, travelingSalesmanTour);
}
private void initializeCityAssignmentList(AbstractSolverScope abstractSolverScope,
TravelingSalesmanTour travelingSalesmanTour) {
City startCity = travelingSalesmanTour.getStartCity();
WorkingMemory workingMemory = abstractSolverScope.getWorkingMemory();
List<CityAssignment> cityAssignmentList = createCityAssignmentList(travelingSalesmanTour);
List<CityAssignment> assignedCityAssignmentList = null;
for (CityAssignment cityAssignment : cityAssignmentList) {
FactHandle cityAssignmentHandle = null;
if (assignedCityAssignmentList == null) {
assignedCityAssignmentList = new ArrayList<CityAssignment>(cityAssignmentList.size());
cityAssignment.setNextCityAssignment(cityAssignment);
cityAssignment.setPreviousCityAssignment(cityAssignment);
cityAssignmentHandle = workingMemory.insert(cityAssignment);
} else {
Score bestScore = DefaultSimpleScore.valueOf(Integer.MIN_VALUE);
CityAssignment bestAfterCityAssignment = null;
FactHandle bestAfterCityAssignmentFactHandle = null;
CityAssignment bestBeforeCityAssignment = null;
FactHandle bestBeforeCityAssignmentFactHandle = null;
for (CityAssignment afterCityAssignment : assignedCityAssignmentList) {
CityAssignment beforeCityAssignment = afterCityAssignment.getNextCityAssignment();
FactHandle afterCityAssignmentFactHandle = workingMemory.getFactHandle(afterCityAssignment);
FactHandle beforeCityAssignmentFactHandle = workingMemory.getFactHandle(beforeCityAssignment);
// Do changes
afterCityAssignment.setNextCityAssignment(cityAssignment);
cityAssignment.setPreviousCityAssignment(afterCityAssignment);
cityAssignment.setNextCityAssignment(beforeCityAssignment);
beforeCityAssignment.setPreviousCityAssignment(cityAssignment);
if (cityAssignmentHandle == null) {
cityAssignmentHandle = workingMemory.insert(cityAssignment);
} else {
workingMemory.update(cityAssignmentHandle, cityAssignment);
}
workingMemory.update(afterCityAssignmentFactHandle, afterCityAssignment);
workingMemory.update(beforeCityAssignmentFactHandle, beforeCityAssignment);
// Calculate score
Score score = abstractSolverScope.calculateScoreFromWorkingMemory();
if (score.compareTo(bestScore) > 0) {
bestScore = score;
bestAfterCityAssignment = afterCityAssignment;
bestAfterCityAssignmentFactHandle = afterCityAssignmentFactHandle;
bestBeforeCityAssignment = beforeCityAssignment;
bestBeforeCityAssignmentFactHandle = beforeCityAssignmentFactHandle;
}
// Undo changes
afterCityAssignment.setNextCityAssignment(beforeCityAssignment);
beforeCityAssignment.setPreviousCityAssignment(afterCityAssignment);
workingMemory.update(afterCityAssignmentFactHandle, afterCityAssignment);
workingMemory.update(beforeCityAssignmentFactHandle, beforeCityAssignment);
}
if (bestAfterCityAssignment == null) {
throw new IllegalStateException("The bestAfterCityAssignment (" + bestAfterCityAssignment
+ ") cannot be null.");
}
bestAfterCityAssignment.setNextCityAssignment(cityAssignment);
cityAssignment.setPreviousCityAssignment(bestAfterCityAssignment);
cityAssignment.setNextCityAssignment(bestBeforeCityAssignment);
bestBeforeCityAssignment.setPreviousCityAssignment(cityAssignment);
workingMemory.update(cityAssignmentHandle, cityAssignment);
workingMemory.update(bestAfterCityAssignmentFactHandle, bestAfterCityAssignment);
workingMemory.update(bestBeforeCityAssignmentFactHandle, bestBeforeCityAssignment);
}
+ assignedCityAssignmentList.add(cityAssignment);
if (cityAssignment.getCity() == startCity) {
travelingSalesmanTour.setStartCityAssignment(cityAssignment);
}
logger.debug(" CityAssignment ({}) initialized for starting solution.", cityAssignment);
}
Collections.sort(cityAssignmentList, new PersistableIdComparator());
travelingSalesmanTour.setCityAssignmentList(cityAssignmentList);
}
public List<CityAssignment> createCityAssignmentList(TravelingSalesmanTour travelingSalesmanTour) {
List<City> cityList = travelingSalesmanTour.getCityList();
// TODO weight: create by city on distance from the center ascending
List<CityAssignment> cityAssignmentList = new ArrayList<CityAssignment>(cityList.size());
int cityAssignmentId = 0;
for (City city : cityList) {
CityAssignment cityAssignment = new CityAssignment();
cityAssignment.setId((long) cityAssignmentId);
cityAssignment.setCity(city);
cityAssignmentList.add(cityAssignment);
cityAssignmentId++;
}
return cityAssignmentList;
}
}
| true | true | private void initializeCityAssignmentList(AbstractSolverScope abstractSolverScope,
TravelingSalesmanTour travelingSalesmanTour) {
City startCity = travelingSalesmanTour.getStartCity();
WorkingMemory workingMemory = abstractSolverScope.getWorkingMemory();
List<CityAssignment> cityAssignmentList = createCityAssignmentList(travelingSalesmanTour);
List<CityAssignment> assignedCityAssignmentList = null;
for (CityAssignment cityAssignment : cityAssignmentList) {
FactHandle cityAssignmentHandle = null;
if (assignedCityAssignmentList == null) {
assignedCityAssignmentList = new ArrayList<CityAssignment>(cityAssignmentList.size());
cityAssignment.setNextCityAssignment(cityAssignment);
cityAssignment.setPreviousCityAssignment(cityAssignment);
cityAssignmentHandle = workingMemory.insert(cityAssignment);
} else {
Score bestScore = DefaultSimpleScore.valueOf(Integer.MIN_VALUE);
CityAssignment bestAfterCityAssignment = null;
FactHandle bestAfterCityAssignmentFactHandle = null;
CityAssignment bestBeforeCityAssignment = null;
FactHandle bestBeforeCityAssignmentFactHandle = null;
for (CityAssignment afterCityAssignment : assignedCityAssignmentList) {
CityAssignment beforeCityAssignment = afterCityAssignment.getNextCityAssignment();
FactHandle afterCityAssignmentFactHandle = workingMemory.getFactHandle(afterCityAssignment);
FactHandle beforeCityAssignmentFactHandle = workingMemory.getFactHandle(beforeCityAssignment);
// Do changes
afterCityAssignment.setNextCityAssignment(cityAssignment);
cityAssignment.setPreviousCityAssignment(afterCityAssignment);
cityAssignment.setNextCityAssignment(beforeCityAssignment);
beforeCityAssignment.setPreviousCityAssignment(cityAssignment);
if (cityAssignmentHandle == null) {
cityAssignmentHandle = workingMemory.insert(cityAssignment);
} else {
workingMemory.update(cityAssignmentHandle, cityAssignment);
}
workingMemory.update(afterCityAssignmentFactHandle, afterCityAssignment);
workingMemory.update(beforeCityAssignmentFactHandle, beforeCityAssignment);
// Calculate score
Score score = abstractSolverScope.calculateScoreFromWorkingMemory();
if (score.compareTo(bestScore) > 0) {
bestScore = score;
bestAfterCityAssignment = afterCityAssignment;
bestAfterCityAssignmentFactHandle = afterCityAssignmentFactHandle;
bestBeforeCityAssignment = beforeCityAssignment;
bestBeforeCityAssignmentFactHandle = beforeCityAssignmentFactHandle;
}
// Undo changes
afterCityAssignment.setNextCityAssignment(beforeCityAssignment);
beforeCityAssignment.setPreviousCityAssignment(afterCityAssignment);
workingMemory.update(afterCityAssignmentFactHandle, afterCityAssignment);
workingMemory.update(beforeCityAssignmentFactHandle, beforeCityAssignment);
}
if (bestAfterCityAssignment == null) {
throw new IllegalStateException("The bestAfterCityAssignment (" + bestAfterCityAssignment
+ ") cannot be null.");
}
bestAfterCityAssignment.setNextCityAssignment(cityAssignment);
cityAssignment.setPreviousCityAssignment(bestAfterCityAssignment);
cityAssignment.setNextCityAssignment(bestBeforeCityAssignment);
bestBeforeCityAssignment.setPreviousCityAssignment(cityAssignment);
workingMemory.update(cityAssignmentHandle, cityAssignment);
workingMemory.update(bestAfterCityAssignmentFactHandle, bestAfterCityAssignment);
workingMemory.update(bestBeforeCityAssignmentFactHandle, bestBeforeCityAssignment);
}
if (cityAssignment.getCity() == startCity) {
travelingSalesmanTour.setStartCityAssignment(cityAssignment);
}
logger.debug(" CityAssignment ({}) initialized for starting solution.", cityAssignment);
}
Collections.sort(cityAssignmentList, new PersistableIdComparator());
travelingSalesmanTour.setCityAssignmentList(cityAssignmentList);
}
| private void initializeCityAssignmentList(AbstractSolverScope abstractSolverScope,
TravelingSalesmanTour travelingSalesmanTour) {
City startCity = travelingSalesmanTour.getStartCity();
WorkingMemory workingMemory = abstractSolverScope.getWorkingMemory();
List<CityAssignment> cityAssignmentList = createCityAssignmentList(travelingSalesmanTour);
List<CityAssignment> assignedCityAssignmentList = null;
for (CityAssignment cityAssignment : cityAssignmentList) {
FactHandle cityAssignmentHandle = null;
if (assignedCityAssignmentList == null) {
assignedCityAssignmentList = new ArrayList<CityAssignment>(cityAssignmentList.size());
cityAssignment.setNextCityAssignment(cityAssignment);
cityAssignment.setPreviousCityAssignment(cityAssignment);
cityAssignmentHandle = workingMemory.insert(cityAssignment);
} else {
Score bestScore = DefaultSimpleScore.valueOf(Integer.MIN_VALUE);
CityAssignment bestAfterCityAssignment = null;
FactHandle bestAfterCityAssignmentFactHandle = null;
CityAssignment bestBeforeCityAssignment = null;
FactHandle bestBeforeCityAssignmentFactHandle = null;
for (CityAssignment afterCityAssignment : assignedCityAssignmentList) {
CityAssignment beforeCityAssignment = afterCityAssignment.getNextCityAssignment();
FactHandle afterCityAssignmentFactHandle = workingMemory.getFactHandle(afterCityAssignment);
FactHandle beforeCityAssignmentFactHandle = workingMemory.getFactHandle(beforeCityAssignment);
// Do changes
afterCityAssignment.setNextCityAssignment(cityAssignment);
cityAssignment.setPreviousCityAssignment(afterCityAssignment);
cityAssignment.setNextCityAssignment(beforeCityAssignment);
beforeCityAssignment.setPreviousCityAssignment(cityAssignment);
if (cityAssignmentHandle == null) {
cityAssignmentHandle = workingMemory.insert(cityAssignment);
} else {
workingMemory.update(cityAssignmentHandle, cityAssignment);
}
workingMemory.update(afterCityAssignmentFactHandle, afterCityAssignment);
workingMemory.update(beforeCityAssignmentFactHandle, beforeCityAssignment);
// Calculate score
Score score = abstractSolverScope.calculateScoreFromWorkingMemory();
if (score.compareTo(bestScore) > 0) {
bestScore = score;
bestAfterCityAssignment = afterCityAssignment;
bestAfterCityAssignmentFactHandle = afterCityAssignmentFactHandle;
bestBeforeCityAssignment = beforeCityAssignment;
bestBeforeCityAssignmentFactHandle = beforeCityAssignmentFactHandle;
}
// Undo changes
afterCityAssignment.setNextCityAssignment(beforeCityAssignment);
beforeCityAssignment.setPreviousCityAssignment(afterCityAssignment);
workingMemory.update(afterCityAssignmentFactHandle, afterCityAssignment);
workingMemory.update(beforeCityAssignmentFactHandle, beforeCityAssignment);
}
if (bestAfterCityAssignment == null) {
throw new IllegalStateException("The bestAfterCityAssignment (" + bestAfterCityAssignment
+ ") cannot be null.");
}
bestAfterCityAssignment.setNextCityAssignment(cityAssignment);
cityAssignment.setPreviousCityAssignment(bestAfterCityAssignment);
cityAssignment.setNextCityAssignment(bestBeforeCityAssignment);
bestBeforeCityAssignment.setPreviousCityAssignment(cityAssignment);
workingMemory.update(cityAssignmentHandle, cityAssignment);
workingMemory.update(bestAfterCityAssignmentFactHandle, bestAfterCityAssignment);
workingMemory.update(bestBeforeCityAssignmentFactHandle, bestBeforeCityAssignment);
}
assignedCityAssignmentList.add(cityAssignment);
if (cityAssignment.getCity() == startCity) {
travelingSalesmanTour.setStartCityAssignment(cityAssignment);
}
logger.debug(" CityAssignment ({}) initialized for starting solution.", cityAssignment);
}
Collections.sort(cityAssignmentList, new PersistableIdComparator());
travelingSalesmanTour.setCityAssignmentList(cityAssignmentList);
}
|
diff --git a/src/peergroup/ThriftServerWorker.java b/src/peergroup/ThriftServerWorker.java
index 711e0f0..9cbc25f 100644
--- a/src/peergroup/ThriftServerWorker.java
+++ b/src/peergroup/ThriftServerWorker.java
@@ -1,58 +1,58 @@
/*
* Peergroup - ThriftServerWorker.java
*
* Peergroup is a P2P Shared Storage System using XMPP for data- and
* participantmanagement and Apache Thrift for direct data-
* exchange between users.
*
* Author : Nicolas Inden
* Contact: [email protected]
*
* License: Not for public distribution!
*/
package peergroup;
import java.util.*;
import org.apache.thrift.server.*;
import org.apache.thrift.transport.*;
/**
* This thread listens for thrift requests and processes them.
*
* @author Nicolas Inden
*/
public class ThriftServerWorker extends Thread {
private TServerSocket serverTransport;
private DataTransfer.Processor processor;
private TServer server;
public ThriftServerWorker(){
}
/**
* The run() method
*/
public void run(){
this.setName("THRIFT-Server Thread");
try{
- this.serverTransport = new TServerSocket(port);
+ this.serverTransport = new TServerSocket(Constants.p2pPort);
this.processor = new DataTransfer.Processor(new ThriftDataHandler());
this.server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor));
Constants.log.addMsg("Starting thrift handler on port " + Constants.p2pPort);
this.server.serve();
}catch(TTransportException e){
Constants.log.addMsg("Thrift server error: " + e);
}
Constants.log.addMsg("Thrift-Server-Thread interrupted. Closing...",4);
}
public void stopThriftWorker(){
this.server.stop();
this.interrupt();
}
}
| true | true | public void run(){
this.setName("THRIFT-Server Thread");
try{
this.serverTransport = new TServerSocket(port);
this.processor = new DataTransfer.Processor(new ThriftDataHandler());
this.server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor));
Constants.log.addMsg("Starting thrift handler on port " + Constants.p2pPort);
this.server.serve();
}catch(TTransportException e){
Constants.log.addMsg("Thrift server error: " + e);
}
Constants.log.addMsg("Thrift-Server-Thread interrupted. Closing...",4);
}
| public void run(){
this.setName("THRIFT-Server Thread");
try{
this.serverTransport = new TServerSocket(Constants.p2pPort);
this.processor = new DataTransfer.Processor(new ThriftDataHandler());
this.server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor));
Constants.log.addMsg("Starting thrift handler on port " + Constants.p2pPort);
this.server.serve();
}catch(TTransportException e){
Constants.log.addMsg("Thrift server error: " + e);
}
Constants.log.addMsg("Thrift-Server-Thread interrupted. Closing...",4);
}
|
diff --git a/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/mutable/mysql/impl/MySQLForeignKeyMetaDataBuilderImpl.java b/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/mutable/mysql/impl/MySQLForeignKeyMetaDataBuilderImpl.java
index 833c704..4552820 100644
--- a/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/mutable/mysql/impl/MySQLForeignKeyMetaDataBuilderImpl.java
+++ b/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/mutable/mysql/impl/MySQLForeignKeyMetaDataBuilderImpl.java
@@ -1,149 +1,150 @@
package net.madz.db.core.meta.mutable.mysql.impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.madz.db.core.meta.immutable.ForeignKeyEntry;
import net.madz.db.core.meta.immutable.IndexEntry;
import net.madz.db.core.meta.immutable.mysql.MySQLColumnMetaData;
import net.madz.db.core.meta.immutable.mysql.MySQLForeignKeyMetaData;
import net.madz.db.core.meta.immutable.mysql.MySQLIndexMetaData;
import net.madz.db.core.meta.immutable.mysql.MySQLSchemaMetaData;
import net.madz.db.core.meta.immutable.mysql.MySQLTableMetaData;
import net.madz.db.core.meta.immutable.mysql.impl.MySQLForeignKeyMetaDataImpl;
import net.madz.db.core.meta.immutable.types.CascadeRule;
import net.madz.db.core.meta.mutable.impl.BaseForeignKeyMetaDataBuilder;
import net.madz.db.core.meta.mutable.mysql.MySQLColumnMetaDataBuilder;
import net.madz.db.core.meta.mutable.mysql.MySQLForeignKeyMetaDataBuilder;
import net.madz.db.core.meta.mutable.mysql.MySQLIndexMetaDataBuilder;
import net.madz.db.core.meta.mutable.mysql.MySQLSchemaMetaDataBuilder;
import net.madz.db.core.meta.mutable.mysql.MySQLTableMetaDataBuilder;
import net.madz.db.utils.MessageConsts;
import net.madz.db.utils.ResourceManagementUtils;
public class MySQLForeignKeyMetaDataBuilderImpl
extends
BaseForeignKeyMetaDataBuilder<MySQLSchemaMetaDataBuilder, MySQLTableMetaDataBuilder, MySQLColumnMetaDataBuilder, MySQLForeignKeyMetaDataBuilder, MySQLIndexMetaDataBuilder, MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>
implements MySQLForeignKeyMetaDataBuilder {
public MySQLForeignKeyMetaDataBuilderImpl(MySQLTableMetaDataBuilder table, String name) {
this.fkTable = table;
this.foreignKeyPath = table.getTablePath().append(name);
}
@Override
public MySQLForeignKeyMetaDataBuilder build(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = null;
try {
rs = stmt.executeQuery("SELECT * FROM referential_constraints WHERE constraint_schema='" + this.fkTable.getTablePath().getParent().getName()
+ "' AND constraint_name='" + this.foreignKeyPath.getName() + "';");
while ( rs.next() ) {
this.updateRule = CascadeRule.getRule(rs.getString("update_rule"));
this.deleteRule = CascadeRule.getRule(rs.getString("delete_rule"));
// [ToDo] [Tracy] about how to get pkTable
// Below code suppose the referenced table is in the same
// schema,
// but actually, the referenced table could be in another
// schema.
this.pkTable = this.fkTable.getSchema().getTableBuilder(rs.getString("referenced_table_name"));
// Note: some times unique_constraint_name is null
this.pkIndex = this.pkTable.getIndexBuilder(rs.getString("unique_constraint_name"));
this.fkIndex = this.fkTable.getIndexBuilder(rs.getString("constraint_name"));
}
} finally {
ResourceManagementUtils.closeResultSet(rs);
}
try {
rs = stmt.executeQuery("SELECT * FROM key_column_usage WHERE constraint_schema='" + this.fkTable.getSchema().getSchemaPath().getName()
- + "' AND constraint_name = '" + this.foreignKeyPath.getName() + "' AND referenced_table_name IS NOT NULL AND referenced_column_name IS NOT NULL;");
+ + "' AND constraint_name = '" + this.foreignKeyPath.getName()
+ + "' AND referenced_table_name IS NOT NULL AND referenced_column_name IS NOT NULL;");
while ( rs.next() ) {
final String columnName = rs.getString("column_name");
final String referencedColumnName = rs.getString("referenced_column_name");
final MySQLColumnMetaData fkColumn = this.fkTable.getColumnBuilder(columnName);
final MySQLColumnMetaData pkColumn = this.pkTable.getColumnBuilder(referencedColumnName);
final Short seq = rs.getShort("ordinal_position");
final BaseForeignKeyMetaDataBuilder<MySQLSchemaMetaDataBuilder, MySQLTableMetaDataBuilder, MySQLColumnMetaDataBuilder, MySQLForeignKeyMetaDataBuilder, MySQLIndexMetaDataBuilder, MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>.Entry entry = new BaseForeignKeyMetaDataBuilder.Entry(
fkColumn, pkColumn, this, seq);
final MySQLColumnMetaDataBuilder columnBuilder = this.fkTable.getColumnBuilder(columnName);
columnBuilder.appendForeignKeyEntry(entry);
this.addEntry(entry);
}
} finally {
ResourceManagementUtils.closeResultSet(rs);
}
// Handle the situation that fkIndex is null, which will be happend when
// creating fk without a constraint name. The name of index
// auto-generated doesn't match the constraint name.
if ( null == this.fkIndex ) {
final Map<Short, MySQLColumnMetaData> fkColumns = new HashMap<Short, MySQLColumnMetaData>();
List<ForeignKeyEntry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> fkEntrySet = this.entryList;
for ( ForeignKeyEntry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : fkEntrySet ) {
fkColumns.put(entry.getSeq(), entry.getForeignKeyColumn());
}
Collection<MySQLIndexMetaDataBuilder> indexSet = this.fkTable.getIndexBuilderSet();
Map<Short, MySQLColumnMetaData> indexColumns = null;
for ( MySQLIndexMetaDataBuilder index : indexSet ) {
indexColumns = new HashMap<Short, MySQLColumnMetaData>();
final Collection<IndexEntry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> entrySet = index
.getEntrySet();
for ( IndexEntry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : entrySet ) {
indexColumns.put(entry.getPosition(), entry.getColumn());
}
// if ( fkColumns.size() != indexColumns.size() ) {
// continue;
// }
boolean matched = true;
for ( Short key : fkColumns.keySet() ) {
MySQLColumnMetaData pkColumn = fkColumns.get(key);
MySQLColumnMetaData indexColumn = indexColumns.get(key);
if ( !pkColumn.getColumnPath().equals(indexColumn.getColumnPath()) ) {
matched = false;
break;
}
}
- if ( matched && !index.getIndexName().equalsIgnoreCase("PRIMARY") ) {
+ if ( matched ) {
this.fkIndex = this.fkTable.getIndexBuilder(index.getIndexName());
break;
}
}
// if (null == this.fkIndex) {
// throw new
// IllegalStateException(MessageConsts.FK_INDEX_SHOULD_NOT_BE_NULL);
// }
}
return this;
}
@Override
public MySQLForeignKeyMetaData createMetaData() {
this.constructedMetaData = new MySQLForeignKeyMetaDataImpl(this.fkTable.getMetaData(), this);
return constructedMetaData;
}
@Override
public String getForeignKeyIndexName() {
return fkIndex.getIndexName();
}
@Override
public String getForeignKeyTableName() {
return fkTable.getTableName();
}
@Override
public String getPrimaryKeyIndexName() {
return pkIndex.getIndexName();
}
@Override
public String getPrimaryKeyTableName() {
return pkTable.getTableName();
}
}
| false | true | public MySQLForeignKeyMetaDataBuilder build(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = null;
try {
rs = stmt.executeQuery("SELECT * FROM referential_constraints WHERE constraint_schema='" + this.fkTable.getTablePath().getParent().getName()
+ "' AND constraint_name='" + this.foreignKeyPath.getName() + "';");
while ( rs.next() ) {
this.updateRule = CascadeRule.getRule(rs.getString("update_rule"));
this.deleteRule = CascadeRule.getRule(rs.getString("delete_rule"));
// [ToDo] [Tracy] about how to get pkTable
// Below code suppose the referenced table is in the same
// schema,
// but actually, the referenced table could be in another
// schema.
this.pkTable = this.fkTable.getSchema().getTableBuilder(rs.getString("referenced_table_name"));
// Note: some times unique_constraint_name is null
this.pkIndex = this.pkTable.getIndexBuilder(rs.getString("unique_constraint_name"));
this.fkIndex = this.fkTable.getIndexBuilder(rs.getString("constraint_name"));
}
} finally {
ResourceManagementUtils.closeResultSet(rs);
}
try {
rs = stmt.executeQuery("SELECT * FROM key_column_usage WHERE constraint_schema='" + this.fkTable.getSchema().getSchemaPath().getName()
+ "' AND constraint_name = '" + this.foreignKeyPath.getName() + "' AND referenced_table_name IS NOT NULL AND referenced_column_name IS NOT NULL;");
while ( rs.next() ) {
final String columnName = rs.getString("column_name");
final String referencedColumnName = rs.getString("referenced_column_name");
final MySQLColumnMetaData fkColumn = this.fkTable.getColumnBuilder(columnName);
final MySQLColumnMetaData pkColumn = this.pkTable.getColumnBuilder(referencedColumnName);
final Short seq = rs.getShort("ordinal_position");
final BaseForeignKeyMetaDataBuilder<MySQLSchemaMetaDataBuilder, MySQLTableMetaDataBuilder, MySQLColumnMetaDataBuilder, MySQLForeignKeyMetaDataBuilder, MySQLIndexMetaDataBuilder, MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>.Entry entry = new BaseForeignKeyMetaDataBuilder.Entry(
fkColumn, pkColumn, this, seq);
final MySQLColumnMetaDataBuilder columnBuilder = this.fkTable.getColumnBuilder(columnName);
columnBuilder.appendForeignKeyEntry(entry);
this.addEntry(entry);
}
} finally {
ResourceManagementUtils.closeResultSet(rs);
}
// Handle the situation that fkIndex is null, which will be happend when
// creating fk without a constraint name. The name of index
// auto-generated doesn't match the constraint name.
if ( null == this.fkIndex ) {
final Map<Short, MySQLColumnMetaData> fkColumns = new HashMap<Short, MySQLColumnMetaData>();
List<ForeignKeyEntry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> fkEntrySet = this.entryList;
for ( ForeignKeyEntry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : fkEntrySet ) {
fkColumns.put(entry.getSeq(), entry.getForeignKeyColumn());
}
Collection<MySQLIndexMetaDataBuilder> indexSet = this.fkTable.getIndexBuilderSet();
Map<Short, MySQLColumnMetaData> indexColumns = null;
for ( MySQLIndexMetaDataBuilder index : indexSet ) {
indexColumns = new HashMap<Short, MySQLColumnMetaData>();
final Collection<IndexEntry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> entrySet = index
.getEntrySet();
for ( IndexEntry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : entrySet ) {
indexColumns.put(entry.getPosition(), entry.getColumn());
}
// if ( fkColumns.size() != indexColumns.size() ) {
// continue;
// }
boolean matched = true;
for ( Short key : fkColumns.keySet() ) {
MySQLColumnMetaData pkColumn = fkColumns.get(key);
MySQLColumnMetaData indexColumn = indexColumns.get(key);
if ( !pkColumn.getColumnPath().equals(indexColumn.getColumnPath()) ) {
matched = false;
break;
}
}
if ( matched && !index.getIndexName().equalsIgnoreCase("PRIMARY") ) {
this.fkIndex = this.fkTable.getIndexBuilder(index.getIndexName());
break;
}
}
// if (null == this.fkIndex) {
// throw new
// IllegalStateException(MessageConsts.FK_INDEX_SHOULD_NOT_BE_NULL);
// }
}
return this;
}
| public MySQLForeignKeyMetaDataBuilder build(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = null;
try {
rs = stmt.executeQuery("SELECT * FROM referential_constraints WHERE constraint_schema='" + this.fkTable.getTablePath().getParent().getName()
+ "' AND constraint_name='" + this.foreignKeyPath.getName() + "';");
while ( rs.next() ) {
this.updateRule = CascadeRule.getRule(rs.getString("update_rule"));
this.deleteRule = CascadeRule.getRule(rs.getString("delete_rule"));
// [ToDo] [Tracy] about how to get pkTable
// Below code suppose the referenced table is in the same
// schema,
// but actually, the referenced table could be in another
// schema.
this.pkTable = this.fkTable.getSchema().getTableBuilder(rs.getString("referenced_table_name"));
// Note: some times unique_constraint_name is null
this.pkIndex = this.pkTable.getIndexBuilder(rs.getString("unique_constraint_name"));
this.fkIndex = this.fkTable.getIndexBuilder(rs.getString("constraint_name"));
}
} finally {
ResourceManagementUtils.closeResultSet(rs);
}
try {
rs = stmt.executeQuery("SELECT * FROM key_column_usage WHERE constraint_schema='" + this.fkTable.getSchema().getSchemaPath().getName()
+ "' AND constraint_name = '" + this.foreignKeyPath.getName()
+ "' AND referenced_table_name IS NOT NULL AND referenced_column_name IS NOT NULL;");
while ( rs.next() ) {
final String columnName = rs.getString("column_name");
final String referencedColumnName = rs.getString("referenced_column_name");
final MySQLColumnMetaData fkColumn = this.fkTable.getColumnBuilder(columnName);
final MySQLColumnMetaData pkColumn = this.pkTable.getColumnBuilder(referencedColumnName);
final Short seq = rs.getShort("ordinal_position");
final BaseForeignKeyMetaDataBuilder<MySQLSchemaMetaDataBuilder, MySQLTableMetaDataBuilder, MySQLColumnMetaDataBuilder, MySQLForeignKeyMetaDataBuilder, MySQLIndexMetaDataBuilder, MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>.Entry entry = new BaseForeignKeyMetaDataBuilder.Entry(
fkColumn, pkColumn, this, seq);
final MySQLColumnMetaDataBuilder columnBuilder = this.fkTable.getColumnBuilder(columnName);
columnBuilder.appendForeignKeyEntry(entry);
this.addEntry(entry);
}
} finally {
ResourceManagementUtils.closeResultSet(rs);
}
// Handle the situation that fkIndex is null, which will be happend when
// creating fk without a constraint name. The name of index
// auto-generated doesn't match the constraint name.
if ( null == this.fkIndex ) {
final Map<Short, MySQLColumnMetaData> fkColumns = new HashMap<Short, MySQLColumnMetaData>();
List<ForeignKeyEntry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> fkEntrySet = this.entryList;
for ( ForeignKeyEntry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : fkEntrySet ) {
fkColumns.put(entry.getSeq(), entry.getForeignKeyColumn());
}
Collection<MySQLIndexMetaDataBuilder> indexSet = this.fkTable.getIndexBuilderSet();
Map<Short, MySQLColumnMetaData> indexColumns = null;
for ( MySQLIndexMetaDataBuilder index : indexSet ) {
indexColumns = new HashMap<Short, MySQLColumnMetaData>();
final Collection<IndexEntry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData>> entrySet = index
.getEntrySet();
for ( IndexEntry<MySQLSchemaMetaData, MySQLTableMetaData, MySQLColumnMetaData, MySQLForeignKeyMetaData, MySQLIndexMetaData> entry : entrySet ) {
indexColumns.put(entry.getPosition(), entry.getColumn());
}
// if ( fkColumns.size() != indexColumns.size() ) {
// continue;
// }
boolean matched = true;
for ( Short key : fkColumns.keySet() ) {
MySQLColumnMetaData pkColumn = fkColumns.get(key);
MySQLColumnMetaData indexColumn = indexColumns.get(key);
if ( !pkColumn.getColumnPath().equals(indexColumn.getColumnPath()) ) {
matched = false;
break;
}
}
if ( matched ) {
this.fkIndex = this.fkTable.getIndexBuilder(index.getIndexName());
break;
}
}
// if (null == this.fkIndex) {
// throw new
// IllegalStateException(MessageConsts.FK_INDEX_SHOULD_NOT_BE_NULL);
// }
}
return this;
}
|
diff --git a/client/ChatClient.java b/client/ChatClient.java
index 7bbefe0..360ea2b 100644
--- a/client/ChatClient.java
+++ b/client/ChatClient.java
@@ -1,175 +1,175 @@
package client;
import shared.*;
import java.util.*;
import java.io.*;
import java.net.*;
public class ChatClient {
/** client socket */
Socket socket;
/** cmd line input */
Scanner stdIn;
/** socket reader */
BufferedReader input;
/** socket writer */
PrintWriter output;
private UUID id;
public String username;
/**
* Constructor
*/
public ChatClient(final String host, final int port, String username) {
try {
socket = new Socket(host, port);
stdIn = new Scanner(System.in);
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream(), true);
id = UUID.randomUUID();
send(id.toString()+ ":"+username);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
/**
* User Input
*/
public String userInput(String prompt) {
if (prompt != null) {
prompt.trim();
System.out.print(prompt + " ");
}
return stdIn.nextLine();
}
/**
* Send
*/
public void send(String message) throws IOException{
output.println(message);
}
public void send(ClientMessage message) throws IOException {
send(message.toString());
}
/**
* receive
*/
public String receive() throws IOException {
return input.readLine();
}
public UUID getID() {
return id;
}
/**
* Main
*/
public static void main(String[] args) {
// new client
System.out.println("Enter server ip: ");
Scanner scanner = new Scanner(System.in);
String ip = scanner.nextLine();
System.out.println("Enter a username: ");
String username = scanner.nextLine();
ChatClient client = new ChatClient(ip, 8080, username);
Thread listen = new Thread(new ClientListener(client));
Thread speak = new Thread(new ClientSpeaker(client));
listen.start();
speak.start();
}
}
/**
* Client Listener
*/
class ClientListener implements Runnable {
ChatClient client;
public ClientListener(ChatClient client) {
this.client = client;
}
public void run() {
while (true) {
try {
String rawMessage = client.receive();
if (rawMessage == null) break;
ClientMessage message = ClientMessage.fromString(rawMessage);
if (message.action == ServerAction.list) {
System.out.println("Users: ");
- String names = message.text.split(".");
+ String[] names = message.text.split(".");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
} else {
System.out.println(message.text);
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("Disconnected...");
System.exit(0);
}
}
/**
* Client Speaker
*/
class ClientSpeaker implements Runnable {
ChatClient client;
public ClientSpeaker(ChatClient client) {
this.client = client;
}
public void run() {
while (true) {
try {
String input = client.userInput(null);
ClientMessage message = InputParser.parse(client, input);
if (message != null) {
client.send(message);
} else {
System.out.println("Invalid input");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| true | true | public void run() {
while (true) {
try {
String rawMessage = client.receive();
if (rawMessage == null) break;
ClientMessage message = ClientMessage.fromString(rawMessage);
if (message.action == ServerAction.list) {
System.out.println("Users: ");
String names = message.text.split(".");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
} else {
System.out.println(message.text);
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("Disconnected...");
System.exit(0);
}
| public void run() {
while (true) {
try {
String rawMessage = client.receive();
if (rawMessage == null) break;
ClientMessage message = ClientMessage.fromString(rawMessage);
if (message.action == ServerAction.list) {
System.out.println("Users: ");
String[] names = message.text.split(".");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
} else {
System.out.println(message.text);
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("Disconnected...");
System.exit(0);
}
|
diff --git a/common/java/swing/org/crosswire/common/swing/plaf/WindowsLFCustoms.java b/common/java/swing/org/crosswire/common/swing/plaf/WindowsLFCustoms.java
index ac519a97..26ed0f7e 100644
--- a/common/java/swing/org/crosswire/common/swing/plaf/WindowsLFCustoms.java
+++ b/common/java/swing/org/crosswire/common/swing/plaf/WindowsLFCustoms.java
@@ -1,76 +1,83 @@
/**
* Distribution License:
* JSword is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License, version 2.1 as published by
* the Free Software Foundation. This program is distributed in the hope
* that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The License is available on the internet at:
* http://www.gnu.org/copyleft/lgpl.html
* or by writing to:
* Free Software Foundation, Inc.
* 59 Temple Place - Suite 330
* Boston, MA 02111-1307, USA
*
* Copyright: 2005
* The copyright to this program is held by it's authors.
*
* ID: $Id$
*/
package org.crosswire.common.swing.plaf;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
/**
* Customizations to Windows LF for tabs.
*
* @see gnu.lgpl.License for license details.
* The copyright to this program is held by it's authors.
* @author Willie Thean [williethean at yahoo dot com]
*/
public class WindowsLFCustoms extends AbstractLFCustoms
{
/**
* Default constructor.
*/
public WindowsLFCustoms()
{
super();
}
/**
* Install Windows platform specific UI defaults.
*/
protected void initPlatformUIDefaults()
{
Border tabbedPanePanelBorder = null;
Color standardBorderColor = null;
Object windowsScrollPaneborder = UIManager.get("ScrollPane.border"); //$NON-NLS-1$
if (windowsScrollPaneborder != null)
{
- standardBorderColor = ((LineBorder) windowsScrollPaneborder).getLineColor();
- tabbedPanePanelBorder = new LineBorder(standardBorderColor);
+ if (windowsScrollPaneborder instanceof LineBorder)
+ {
+ standardBorderColor = ((LineBorder) windowsScrollPaneborder).getLineColor();
+ tabbedPanePanelBorder = new LineBorder(standardBorderColor);
+ }
+ else
+ {
+ tabbedPanePanelBorder = BorderFactory.createEmptyBorder(1, 1, 1, 1);
+ }
}
Border panelSelectBorder = BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(1, 1, 0, 1, standardBorderColor),
BorderFactory.createEmptyBorder(5, 5, 5, 5));
Object[] windowsUIDefaults = new Object[]
{
"BibleViewPane.TabbedPaneUI", WindowsBorderlessTabbedPaneUI.createUI(null), //$NON-NLS-1$
"TabbedPanePanel.border", tabbedPanePanelBorder, //$NON-NLS-1$
"StandardBorder.color", standardBorderColor, //$NON-NLS-1$
"SelectPanel.border", panelSelectBorder //$NON-NLS-1$
};
UIManager.getDefaults().putDefaults(windowsUIDefaults);
}
}
| true | true | protected void initPlatformUIDefaults()
{
Border tabbedPanePanelBorder = null;
Color standardBorderColor = null;
Object windowsScrollPaneborder = UIManager.get("ScrollPane.border"); //$NON-NLS-1$
if (windowsScrollPaneborder != null)
{
standardBorderColor = ((LineBorder) windowsScrollPaneborder).getLineColor();
tabbedPanePanelBorder = new LineBorder(standardBorderColor);
}
Border panelSelectBorder = BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(1, 1, 0, 1, standardBorderColor),
BorderFactory.createEmptyBorder(5, 5, 5, 5));
Object[] windowsUIDefaults = new Object[]
{
"BibleViewPane.TabbedPaneUI", WindowsBorderlessTabbedPaneUI.createUI(null), //$NON-NLS-1$
"TabbedPanePanel.border", tabbedPanePanelBorder, //$NON-NLS-1$
"StandardBorder.color", standardBorderColor, //$NON-NLS-1$
"SelectPanel.border", panelSelectBorder //$NON-NLS-1$
};
UIManager.getDefaults().putDefaults(windowsUIDefaults);
}
| protected void initPlatformUIDefaults()
{
Border tabbedPanePanelBorder = null;
Color standardBorderColor = null;
Object windowsScrollPaneborder = UIManager.get("ScrollPane.border"); //$NON-NLS-1$
if (windowsScrollPaneborder != null)
{
if (windowsScrollPaneborder instanceof LineBorder)
{
standardBorderColor = ((LineBorder) windowsScrollPaneborder).getLineColor();
tabbedPanePanelBorder = new LineBorder(standardBorderColor);
}
else
{
tabbedPanePanelBorder = BorderFactory.createEmptyBorder(1, 1, 1, 1);
}
}
Border panelSelectBorder = BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(1, 1, 0, 1, standardBorderColor),
BorderFactory.createEmptyBorder(5, 5, 5, 5));
Object[] windowsUIDefaults = new Object[]
{
"BibleViewPane.TabbedPaneUI", WindowsBorderlessTabbedPaneUI.createUI(null), //$NON-NLS-1$
"TabbedPanePanel.border", tabbedPanePanelBorder, //$NON-NLS-1$
"StandardBorder.color", standardBorderColor, //$NON-NLS-1$
"SelectPanel.border", panelSelectBorder //$NON-NLS-1$
};
UIManager.getDefaults().putDefaults(windowsUIDefaults);
}
|
diff --git a/src/main/org/codehaus/groovy/reflection/stdclasses/ArrayCachedClass.java b/src/main/org/codehaus/groovy/reflection/stdclasses/ArrayCachedClass.java
index f083bda46..46cb98463 100644
--- a/src/main/org/codehaus/groovy/reflection/stdclasses/ArrayCachedClass.java
+++ b/src/main/org/codehaus/groovy/reflection/stdclasses/ArrayCachedClass.java
@@ -1,74 +1,54 @@
/*
* Copyright 2003-2007 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.reflection.stdclasses;
import groovy.lang.GString;
import org.codehaus.groovy.reflection.CachedClass;
import org.codehaus.groovy.reflection.ClassInfo;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
import java.math.BigDecimal;
/**
* @author Alex.Tkachman
*/
public class ArrayCachedClass extends CachedClass {
public ArrayCachedClass(Class klazz, ClassInfo classInfo) {
super(klazz, classInfo);
}
public Object coerceArgument(Object argument) {
Class argumentClass = argument.getClass();
if (argumentClass.getName().charAt(0) != '[') return argument;
Class argumentComponent = argumentClass.getComponentType();
Class paramComponent = getTheClass().getComponentType();
if (paramComponent.isPrimitive()) {
- if (paramComponent == boolean.class && argumentClass == Boolean[].class) {
- argument = DefaultTypeTransformation.convertToBooleanArray(argument);
- } else if (paramComponent == byte.class && argumentClass == Byte[].class) {
- argument = DefaultTypeTransformation.convertToByteArray(argument);
- } else if (paramComponent == char.class && argumentClass == Character[].class) {
- argument = DefaultTypeTransformation.convertToCharArray(argument);
- } else if (paramComponent == short.class && argumentClass == Short[].class) {
- argument = DefaultTypeTransformation.convertToShortArray(argument);
- } else if (paramComponent == int.class && argumentClass == Integer[].class) {
- argument = DefaultTypeTransformation.convertToIntArray(argument);
- } else if (paramComponent == long.class &&
- (argumentClass == Long[].class || argumentClass == Integer[].class)) {
- argument = DefaultTypeTransformation.convertToLongArray(argument);
- } else if (paramComponent == float.class &&
- (argumentClass == Float[].class || argumentClass == Integer[].class)) {
- argument = DefaultTypeTransformation.convertToFloatArray(argument);
- } else if (paramComponent == double.class &&
- (argumentClass == Double[].class || argumentClass == Float[].class
- || BigDecimal[].class.isAssignableFrom(argumentClass))) {
- argument = DefaultTypeTransformation.convertToDoubleArray(argument);
- }
+ argument = DefaultTypeTransformation.convertToPrimitiveArray(argument, paramComponent);
} else if (paramComponent == String.class && argument instanceof GString[]) {
GString[] strings = (GString[]) argument;
String[] ret = new String[strings.length];
for (int i = 0; i < strings.length; i++) {
ret[i] = strings[i].toString();
}
argument = ret;
} else if (paramComponent==Object.class && argumentComponent.isPrimitive()){
argument = DefaultTypeTransformation.primitiveArrayBox(argument);
}
return argument;
}
}
| true | true | public Object coerceArgument(Object argument) {
Class argumentClass = argument.getClass();
if (argumentClass.getName().charAt(0) != '[') return argument;
Class argumentComponent = argumentClass.getComponentType();
Class paramComponent = getTheClass().getComponentType();
if (paramComponent.isPrimitive()) {
if (paramComponent == boolean.class && argumentClass == Boolean[].class) {
argument = DefaultTypeTransformation.convertToBooleanArray(argument);
} else if (paramComponent == byte.class && argumentClass == Byte[].class) {
argument = DefaultTypeTransformation.convertToByteArray(argument);
} else if (paramComponent == char.class && argumentClass == Character[].class) {
argument = DefaultTypeTransformation.convertToCharArray(argument);
} else if (paramComponent == short.class && argumentClass == Short[].class) {
argument = DefaultTypeTransformation.convertToShortArray(argument);
} else if (paramComponent == int.class && argumentClass == Integer[].class) {
argument = DefaultTypeTransformation.convertToIntArray(argument);
} else if (paramComponent == long.class &&
(argumentClass == Long[].class || argumentClass == Integer[].class)) {
argument = DefaultTypeTransformation.convertToLongArray(argument);
} else if (paramComponent == float.class &&
(argumentClass == Float[].class || argumentClass == Integer[].class)) {
argument = DefaultTypeTransformation.convertToFloatArray(argument);
} else if (paramComponent == double.class &&
(argumentClass == Double[].class || argumentClass == Float[].class
|| BigDecimal[].class.isAssignableFrom(argumentClass))) {
argument = DefaultTypeTransformation.convertToDoubleArray(argument);
}
} else if (paramComponent == String.class && argument instanceof GString[]) {
GString[] strings = (GString[]) argument;
String[] ret = new String[strings.length];
for (int i = 0; i < strings.length; i++) {
ret[i] = strings[i].toString();
}
argument = ret;
} else if (paramComponent==Object.class && argumentComponent.isPrimitive()){
argument = DefaultTypeTransformation.primitiveArrayBox(argument);
}
return argument;
}
| public Object coerceArgument(Object argument) {
Class argumentClass = argument.getClass();
if (argumentClass.getName().charAt(0) != '[') return argument;
Class argumentComponent = argumentClass.getComponentType();
Class paramComponent = getTheClass().getComponentType();
if (paramComponent.isPrimitive()) {
argument = DefaultTypeTransformation.convertToPrimitiveArray(argument, paramComponent);
} else if (paramComponent == String.class && argument instanceof GString[]) {
GString[] strings = (GString[]) argument;
String[] ret = new String[strings.length];
for (int i = 0; i < strings.length; i++) {
ret[i] = strings[i].toString();
}
argument = ret;
} else if (paramComponent==Object.class && argumentComponent.isPrimitive()){
argument = DefaultTypeTransformation.primitiveArrayBox(argument);
}
return argument;
}
|
diff --git a/command/src/main/java/fr/aumgn/bukkitutils/command/args/CommandArgsParser.java b/command/src/main/java/fr/aumgn/bukkitutils/command/args/CommandArgsParser.java
index 00a2bfe..ec53bf8 100644
--- a/command/src/main/java/fr/aumgn/bukkitutils/command/args/CommandArgsParser.java
+++ b/command/src/main/java/fr/aumgn/bukkitutils/command/args/CommandArgsParser.java
@@ -1,130 +1,134 @@
package fr.aumgn.bukkitutils.command.args;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import fr.aumgn.bukkitutils.command.exception.CommandUsageError;
import fr.aumgn.bukkitutils.command.messages.Messages;
public class CommandArgsParser {
private Messages messages;
private String[] args;
private Set<Character> flags;
private Map<Character, String> argsFlags;
public CommandArgsParser(Messages messages, String[] tokens) {
this.messages = messages;
parse(tokens);
}
private void parse(String[] tokens) {
flags = new HashSet<Character>();
argsFlags = new HashMap<Character, String>();
ArrayList<String> argsList = new ArrayList<String>();
boolean quoted = false;
StringBuilder current = null;
for (String token : tokens) {
if (quoted) {
if (!token.isEmpty()
&& token.charAt(token.length() - 1) == '\"') {
current.append(" ");
current.append(token.substring(0, token.length() - 1));
argsList.add(current.toString());
quoted = false;
} else {
current.append(" ");
current.append(token);
}
} else {
if (token.isEmpty()) {
continue;
}
if (token.charAt(0) == '"') {
- quoted = true;
- current = new StringBuilder();
- current.append(token.substring(1));
+ if (token.charAt(token.length() - 1) == '\"') {
+ argsList.add(token.substring(1, token.length() - 1));
+ } else {
+ quoted = true;
+ current = new StringBuilder();
+ current.append(token.substring(1));
+ }
} else if (token.charAt(0) == '-' && token.length() > 1
&& Character.isLetter(token.charAt(1))) {
parseFlags(token.substring(1));
} else {
argsList.add(token);
}
}
}
if (quoted) {
throw new CommandUsageError(
messages.missingEndingQuote(current.toString()));
}
args = argsList.toArray(new String[argsList.size()]);
}
private void parseFlags(String flagsString) {
int equal = flagsString.indexOf("=");
if (equal == -1) {
parseRegularFlags(flagsString);
return;
}
if (equal > 1) {
parseRegularFlags(flagsString.substring(0, equal -1));
}
argsFlags.put(
flagsString.charAt(equal - 1),
flagsString.substring(equal + 1));
}
private void parseRegularFlags(String flagsString) {
for (char flag : flagsString.toCharArray()) {
flags.add(flag);
}
}
public void validate(Set<Character> allowedFlags,
Set<Character> allowedArgsFlags, int min, int max) {
StringBuilder invalidFlags = new StringBuilder();
for (char flag : flags) {
if (!allowedFlags.contains(flag)) {
invalidFlags.append(flag);
}
}
for (char flag : argsFlags.keySet()) {
if (!allowedArgsFlags.contains(flag)) {
invalidFlags.append(flag);
}
}
if (invalidFlags.length() > 0) {
throw new CommandUsageError(messages.invalidFlag(invalidFlags.toString()));
}
if (args.length < min) {
throw new CommandUsageError(messages.missingArguments(args.length, min));
}
if (max != -1 && args.length > max) {
throw new CommandUsageError(messages.tooManyArguments(args.length, max));
}
}
public Set<Character> getFlags() {
return flags;
}
public Map<Character, String> getArgsFlags() {
return argsFlags;
}
public String[] getArgs() {
return args;
}
}
| true | true | private void parse(String[] tokens) {
flags = new HashSet<Character>();
argsFlags = new HashMap<Character, String>();
ArrayList<String> argsList = new ArrayList<String>();
boolean quoted = false;
StringBuilder current = null;
for (String token : tokens) {
if (quoted) {
if (!token.isEmpty()
&& token.charAt(token.length() - 1) == '\"') {
current.append(" ");
current.append(token.substring(0, token.length() - 1));
argsList.add(current.toString());
quoted = false;
} else {
current.append(" ");
current.append(token);
}
} else {
if (token.isEmpty()) {
continue;
}
if (token.charAt(0) == '"') {
quoted = true;
current = new StringBuilder();
current.append(token.substring(1));
} else if (token.charAt(0) == '-' && token.length() > 1
&& Character.isLetter(token.charAt(1))) {
parseFlags(token.substring(1));
} else {
argsList.add(token);
}
}
}
if (quoted) {
throw new CommandUsageError(
messages.missingEndingQuote(current.toString()));
}
args = argsList.toArray(new String[argsList.size()]);
}
| private void parse(String[] tokens) {
flags = new HashSet<Character>();
argsFlags = new HashMap<Character, String>();
ArrayList<String> argsList = new ArrayList<String>();
boolean quoted = false;
StringBuilder current = null;
for (String token : tokens) {
if (quoted) {
if (!token.isEmpty()
&& token.charAt(token.length() - 1) == '\"') {
current.append(" ");
current.append(token.substring(0, token.length() - 1));
argsList.add(current.toString());
quoted = false;
} else {
current.append(" ");
current.append(token);
}
} else {
if (token.isEmpty()) {
continue;
}
if (token.charAt(0) == '"') {
if (token.charAt(token.length() - 1) == '\"') {
argsList.add(token.substring(1, token.length() - 1));
} else {
quoted = true;
current = new StringBuilder();
current.append(token.substring(1));
}
} else if (token.charAt(0) == '-' && token.length() > 1
&& Character.isLetter(token.charAt(1))) {
parseFlags(token.substring(1));
} else {
argsList.add(token);
}
}
}
if (quoted) {
throw new CommandUsageError(
messages.missingEndingQuote(current.toString()));
}
args = argsList.toArray(new String[argsList.size()]);
}
|
diff --git a/org.eclipse.mylyn.commons.net/src/org/eclipse/mylyn/commons/net/WebUtil.java b/org.eclipse.mylyn.commons.net/src/org/eclipse/mylyn/commons/net/WebUtil.java
index ffaf6ec5..1749350e 100644
--- a/org.eclipse.mylyn.commons.net/src/org/eclipse/mylyn/commons/net/WebUtil.java
+++ b/org.eclipse.mylyn.commons.net/src/org/eclipse/mylyn/commons/net/WebUtil.java
@@ -1,594 +1,597 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.mylyn.commons.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.text.ParseException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.swing.text.html.HTML.Tag;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.DefaultHttpParams;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.lang.StringEscapeUtils;
import org.eclipse.core.net.proxy.IProxyData;
import org.eclipse.core.net.proxy.IProxyService;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.mylyn.commons.net.HtmlStreamTokenizer.Token;
import org.eclipse.mylyn.internal.commons.net.AuthenticatedProxy;
import org.eclipse.mylyn.internal.commons.net.CloneableHostConfiguration;
import org.eclipse.mylyn.internal.commons.net.CommonsNetPlugin;
import org.eclipse.mylyn.internal.commons.net.PollingInputStream;
import org.eclipse.mylyn.internal.commons.net.PollingProtocolSocketFactory;
import org.eclipse.mylyn.internal.commons.net.PollingSslProtocolSocketFactory;
import org.eclipse.mylyn.internal.commons.net.TimeoutInputStream;
/**
* @author Mik Kersten
* @author Steffen Pingel
* @author Rob Elves
* @since 3.0
*/
public class WebUtil {
/**
* like Mylyn/2.1.0 (Rally Connector 1.0) Eclipse/3.3.0 (JBuilder 2007) HttpClient/3.0.1 Java/1.5.0_11 (Sun)
* Linux/2.6.20-16-lowlatency (i386; en)
*/
private static final String USER_AGENT;
private static final int CONNNECT_TIMEOUT = 60000;
private static final int SOCKET_TIMEOUT = 60000;
private static final int POLL_TIMEOUT = 1000;
private static final int POLL_ATTEMPTS = SOCKET_TIMEOUT / POLL_TIMEOUT;
private static final int HTTP_PORT = 80;
private static final int HTTPS_PORT = 443;
private static final long POLL_INTERVAL = 1000;
private static final String USER_AGENT_PREFIX;
private static final String USER_AGENT_POSTFIX;
private static final int BUFFER_SIZE = 1024;
/**
* Do not block.
*/
private static final long CLOSE_TIMEOUT = -1;
static {
initCommonsLoggingSettings();
StringBuilder sb = new StringBuilder();
sb.append("Mylyn");
sb.append(getBundleVersion(CommonsNetPlugin.getDefault()));
USER_AGENT_PREFIX = sb.toString();
sb.setLength(0);
if (System.getProperty("org.osgi.framework.vendor") != null) {
sb.append(" ");
sb.append(System.getProperty("org.osgi.framework.vendor"));
sb.append(stripQualifier(System.getProperty("osgi.framework.version")));
if (System.getProperty("eclipse.product") != null) {
sb.append(" (");
sb.append(System.getProperty("eclipse.product"));
sb.append(")");
}
}
sb.append(" ");
sb.append(DefaultHttpParams.getDefaultParams().getParameter(HttpMethodParams.USER_AGENT).toString().split("-")[1]);
sb.append(" Java/");
sb.append(System.getProperty("java.version"));
sb.append(" (");
sb.append(System.getProperty("java.vendor").split(" ")[0]);
sb.append(") ");
sb.append(System.getProperty("os.name"));
sb.append("/");
sb.append(System.getProperty("os.version"));
sb.append(" (");
sb.append(System.getProperty("os.arch"));
if (System.getProperty("osgi.nl") != null) {
sb.append("; ");
sb.append(System.getProperty("osgi.nl"));
}
sb.append(")");
USER_AGENT_POSTFIX = sb.toString();
USER_AGENT = USER_AGENT_PREFIX + USER_AGENT_POSTFIX;
}
/**
* @since 3.0
*/
public static void configureHttpClient(HttpClient client, String userAgent) {
client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
client.getParams().setParameter(HttpMethodParams.USER_AGENT, getUserAgent(userAgent));
// API REVIEW consider setting this as the default
//client.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
configureHttpClientConnectionManager(client);
}
private static void configureHttpClientConnectionManager(HttpClient client) {
client.getHttpConnectionManager().getParams().setSoTimeout(WebUtil.SOCKET_TIMEOUT);
client.getHttpConnectionManager().getParams().setConnectionTimeout(WebUtil.CONNNECT_TIMEOUT);
}
private static void configureHttpClientProxy(HttpClient client, HostConfiguration hostConfiguration,
AbstractWebLocation location) {
String host = WebUtil.getHost(location.getUrl());
Proxy proxy;
if (WebUtil.isRepositoryHttps(location.getUrl())) {
proxy = location.getProxyForHost(host, IProxyData.HTTP_PROXY_TYPE);
} else {
proxy = location.getProxyForHost(host, IProxyData.HTTPS_PROXY_TYPE);
}
if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
InetSocketAddress address = (InetSocketAddress) proxy.address();
hostConfiguration.setProxy(address.getHostName(), address.getPort());
if (proxy instanceof AuthenticatedProxy) {
AuthenticatedProxy authProxy = (AuthenticatedProxy) proxy;
Credentials credentials = getCredentials(authProxy.getUserName(), authProxy.getPassword(),
address.getAddress());
AuthScope proxyAuthScope = new AuthScope(address.getHostName(), address.getPort(), AuthScope.ANY_REALM);
client.getState().setProxyCredentials(proxyAuthScope, credentials);
}
} else {
hostConfiguration.setProxyHost(null);
}
}
/**
* @since 3.0
*/
public static void connect(final Socket socket, final InetSocketAddress address, final int timeout,
IProgressMonitor monitor) throws IOException {
if (socket == null) {
throw new IllegalArgumentException();
}
WebRequest<?> executor = new WebRequest<Object>() {
@Override
public void abort() {
try {
socket.close();
} catch (IOException e) {
// ignore
}
}
public Object call() throws Exception {
socket.connect(address, timeout);
return null;
}
};
executeInternal(monitor, executor);
}
/**
* @since 3.0
*/
public static HostConfiguration createHostConfiguration(HttpClient client, AbstractWebLocation location,
IProgressMonitor monitor) {
if (client == null || location == null) {
throw new IllegalArgumentException();
}
String url = location.getUrl();
String host = WebUtil.getHost(url);
int port = WebUtil.getPort(url);
configureHttpClientConnectionManager(client);
HostConfiguration hostConfiguration = new CloneableHostConfiguration();
configureHttpClientProxy(client, hostConfiguration, location);
AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.HTTP);
if (credentials != null) {
AuthScope authScope = new AuthScope(host, port, AuthScope.ANY_REALM);
client.getState().setCredentials(authScope, getHttpClientCredentials(credentials, host));
}
if (WebUtil.isRepositoryHttps(url)) {
ProtocolSocketFactory socketFactory = new PollingSslProtocolSocketFactory(monitor);
Protocol protocol = new Protocol("https", socketFactory, port);
hostConfiguration.setHost(host, port, protocol);
} else {
ProtocolSocketFactory socketFactory = new PollingProtocolSocketFactory(monitor);
Protocol protocol = new Protocol("http", socketFactory, port);
hostConfiguration.setHost(host, port, protocol);
}
return hostConfiguration;
}
/**
* @since 3.0
*/
public static int execute(final HttpClient client, final HostConfiguration hostConfiguration,
final HttpMethod method, IProgressMonitor monitor) throws IOException {
if (client == null || method == null) {
throw new IllegalArgumentException();
}
monitor = Policy.monitorFor(monitor);
WebRequest<Integer> executor = new WebRequest<Integer>() {
@Override
public void abort() {
method.abort();
}
public Integer call() throws Exception {
return client.executeMethod(hostConfiguration, method);
}
};
return executeInternal(monitor, executor);
}
/**
* @since 3.0
*/
public static <T> T execute(IProgressMonitor monitor, WebRequest<T> request) throws Throwable {
monitor = Policy.monitorFor(monitor);
Future<T> future = CommonsNetPlugin.getExecutorService().submit(request);
while (true) {
if (monitor.isCanceled()) {
if (!future.cancel(false)) {
request.abort();
}
// wait for executor to finish
try {
if (!future.isCancelled()) {
future.get();
}
} catch (InterruptedException e) {
// ignore
} catch (ExecutionException e) {
// ignore
}
throw new OperationCanceledException();
}
try {
return future.get(POLL_INTERVAL, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
throw e.getCause();
} catch (TimeoutException ignored) {
}
}
}
@SuppressWarnings("unchecked")
private static <T> T executeInternal(IProgressMonitor monitor, WebRequest<?> request) throws IOException {
try {
return (T) execute(monitor, request);
} catch (IOException e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Error e) {
throw e;
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
private static String getBundleVersion(Plugin plugin) {
if (null == plugin) {
return "";
}
Object bundleVersion = plugin.getBundle().getHeaders().get("Bundle-Version");
if (null == bundleVersion) {
return "";
}
return stripQualifier((String) bundleVersion);
}
/**
* @since 3.0
*/
public static int getConnectionTimeout() {
return CONNNECT_TIMEOUT;
}
static Credentials getCredentials(final String username, final String password, final InetAddress address) {
int i = username.indexOf("\\");
if (i > 0 && i < username.length() - 1 && address != null) {
return new NTCredentials(username.substring(i + 1), password, address.getHostName(), username.substring(0,
i));
} else {
return new UsernamePasswordCredentials(username, password);
}
}
/**
* @since 3.0
*/
public static String getHost(String repositoryUrl) {
String result = repositoryUrl;
int colonSlashSlash = repositoryUrl.indexOf("://");
if (colonSlashSlash >= 0) {
result = repositoryUrl.substring(colonSlashSlash + 3);
}
int colonPort = result.indexOf(':');
int requestPath = result.indexOf('/');
int substringEnd;
// minimum positive, or string length
if (colonPort > 0 && requestPath > 0) {
substringEnd = Math.min(colonPort, requestPath);
} else if (colonPort > 0) {
substringEnd = colonPort;
} else if (requestPath > 0) {
substringEnd = requestPath;
} else {
substringEnd = result.length();
}
return result.substring(0, substringEnd);
}
/**
* @since 2.2
*/
public static Credentials getHttpClientCredentials(AuthenticationCredentials credentials, String host) {
String username = credentials.getUserName();
String password = credentials.getPassword();
int i = username.indexOf("\\");
if (i > 0 && i < username.length() - 1 && host != null) {
return new NTCredentials(username.substring(i + 1), password, host, username.substring(0, i));
} else {
return new UsernamePasswordCredentials(username, password);
}
}
/**
* @since 2.0
*/
public static int getPort(String repositoryUrl) {
int colonSlashSlash = repositoryUrl.indexOf("://");
int firstSlash = repositoryUrl.indexOf("/", colonSlashSlash + 3);
int colonPort = repositoryUrl.indexOf(':', colonSlashSlash + 1);
if (firstSlash == -1) {
firstSlash = repositoryUrl.length();
}
if (colonPort < 0 || colonPort > firstSlash) {
return isRepositoryHttps(repositoryUrl) ? HTTPS_PORT : HTTP_PORT;
}
int requestPath = repositoryUrl.indexOf('/', colonPort + 1);
int end = requestPath < 0 ? repositoryUrl.length() : requestPath;
String port = repositoryUrl.substring(colonPort + 1, end);
if (port.length() == 0) {
return isRepositoryHttps(repositoryUrl) ? HTTPS_PORT : HTTP_PORT;
}
return Integer.parseInt(port);
}
/**
* @since 2.0
*/
public static String getRequestPath(String repositoryUrl) {
int colonSlashSlash = repositoryUrl.indexOf("://");
int requestPath = repositoryUrl.indexOf('/', colonSlashSlash + 3);
if (requestPath < 0) {
return "";
} else {
return repositoryUrl.substring(requestPath);
}
}
public static InputStream getResponseBodyAsStream(HttpMethodBase method, IProgressMonitor monitor)
throws IOException {
monitor = Policy.monitorFor(monitor);
return new PollingInputStream(new TimeoutInputStream(method.getResponseBodyAsStream(), BUFFER_SIZE,
SOCKET_TIMEOUT, CLOSE_TIMEOUT), POLL_ATTEMPTS, monitor);
}
/**
* @since 3.0
*/
public static int getSocketTimeout() {
return SOCKET_TIMEOUT;
}
/**
* Returns the title of a web page.
*
* @throws IOException
* if a network occurs
* @return the title; null, if the title could not be determined;
*
* @since 3.0
*/
public static String getTitleFromUrl(AbstractWebLocation location, IProgressMonitor monitor) throws IOException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask("Retrieving " + location.getUrl(), IProgressMonitor.UNKNOWN);
HttpClient client = new HttpClient();
WebUtil.configureHttpClient(client, "");
GetMethod method = new GetMethod(location.getUrl());
try {
HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, monitor);
int result = WebUtil.execute(client, hostConfiguration, method, monitor);
if (result == HttpStatus.SC_OK) {
InputStream in = WebUtil.getResponseBodyAsStream(method, monitor);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(reader, null);
try {
for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) {
if (token.getType() == Token.TAG) {
HtmlTag tag = (HtmlTag) token.getValue();
if (tag.getTagType() == Tag.TITLE) {
- return getText(tokenizer);
+ String text = getText(tokenizer);
+ text = text.replaceAll("\n", "");
+ text = text.replaceAll("\\s+", " ");
+ return text.trim();
}
}
}
} catch (ParseException e) {
throw new IOException("Error reading url");
}
} finally {
in.close();
}
}
} finally {
method.releaseConnection();
}
} finally {
monitor.done();
}
return null;
}
private static String getText(HtmlStreamTokenizer tokenizer) throws IOException, ParseException {
StringBuilder sb = new StringBuilder();
for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) {
if (token.getType() == Token.TEXT) {
sb.append(token.toString());
} else if (token.getType() == Token.COMMENT) {
// ignore
} else {
break;
}
}
return StringEscapeUtils.unescapeHtml(sb.toString());
}
/**
* Returns a user agent string that contains information about the platform and operating system. The
* <code>product</code> parameter allows to additional specify custom text that is inserted into the returned
* string. The exact return value depends on the environment.
*
* <p>
* Examples:
* <ul>
* <li>Headless: <code>Mylyn MyProduct HttpClient/3.1 Java/1.5.0_13 (Sun) Linux/2.6.22-14-generic (i386)</code>
* <li>Eclipse:
* <code>Mylyn/2.2.0 Eclipse/3.4.0 (org.eclipse.sdk.ide) HttpClient/3.1 Java/1.5.0_13 (Sun) Linux/2.6.22-14-generic (i386; en_CA)</code>
*
* @param product
* an identifier that is inserted into the returned user agent string
* @return a user agent string
* @since 2.3
*/
public static String getUserAgent(String product) {
if (product != null && product.length() > 0) {
StringBuilder sb = new StringBuilder();
sb.append(USER_AGENT_PREFIX);
sb.append(" ");
sb.append(product);
sb.append(USER_AGENT_POSTFIX);
return sb.toString();
} else {
return USER_AGENT;
}
}
public static void init() {
// initialization is done in the static initializer
}
private static void initCommonsLoggingSettings() {
// remove?
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "off");
System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "off");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "off");
}
private static boolean isRepositoryHttps(String repositoryUrl) {
return repositoryUrl.matches("https.*");
}
private static String stripQualifier(String longVersion) {
if (longVersion == null) {
return "";
}
String parts[] = longVersion.split("\\.");
StringBuilder version = new StringBuilder();
if (parts.length > 0) {
version.append("/");
version.append(parts[0]);
if (parts.length > 1) {
version.append(".");
version.append(parts[1]);
if (parts.length > 2) {
version.append(".");
version.append(parts[2]);
}
}
}
return version.toString();
}
/**
* For standalone applications that want to provide a global proxy service.
*
* @param proxyService
* the proxy service
* @since 3.0
*/
public static void setProxyService(IProxyService proxyService) {
CommonsNetPlugin.setProxyService(proxyService);
}
}
| true | true | public static String getTitleFromUrl(AbstractWebLocation location, IProgressMonitor monitor) throws IOException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask("Retrieving " + location.getUrl(), IProgressMonitor.UNKNOWN);
HttpClient client = new HttpClient();
WebUtil.configureHttpClient(client, "");
GetMethod method = new GetMethod(location.getUrl());
try {
HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, monitor);
int result = WebUtil.execute(client, hostConfiguration, method, monitor);
if (result == HttpStatus.SC_OK) {
InputStream in = WebUtil.getResponseBodyAsStream(method, monitor);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(reader, null);
try {
for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) {
if (token.getType() == Token.TAG) {
HtmlTag tag = (HtmlTag) token.getValue();
if (tag.getTagType() == Tag.TITLE) {
return getText(tokenizer);
}
}
}
} catch (ParseException e) {
throw new IOException("Error reading url");
}
} finally {
in.close();
}
}
} finally {
method.releaseConnection();
}
} finally {
monitor.done();
}
return null;
}
| public static String getTitleFromUrl(AbstractWebLocation location, IProgressMonitor monitor) throws IOException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask("Retrieving " + location.getUrl(), IProgressMonitor.UNKNOWN);
HttpClient client = new HttpClient();
WebUtil.configureHttpClient(client, "");
GetMethod method = new GetMethod(location.getUrl());
try {
HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, monitor);
int result = WebUtil.execute(client, hostConfiguration, method, monitor);
if (result == HttpStatus.SC_OK) {
InputStream in = WebUtil.getResponseBodyAsStream(method, monitor);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(reader, null);
try {
for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) {
if (token.getType() == Token.TAG) {
HtmlTag tag = (HtmlTag) token.getValue();
if (tag.getTagType() == Tag.TITLE) {
String text = getText(tokenizer);
text = text.replaceAll("\n", "");
text = text.replaceAll("\\s+", " ");
return text.trim();
}
}
}
} catch (ParseException e) {
throw new IOException("Error reading url");
}
} finally {
in.close();
}
}
} finally {
method.releaseConnection();
}
} finally {
monitor.done();
}
return null;
}
|
diff --git a/src/programming/calculator/MainActivity.java b/src/programming/calculator/MainActivity.java
index 303f4b0..7f0ece6 100644
--- a/src/programming/calculator/MainActivity.java
+++ b/src/programming/calculator/MainActivity.java
@@ -1,1498 +1,1498 @@
/********************************************************************************
*******************************PROJECT INFORMATION*******************************
Project: Programming Calculator
Author: Taylor Carrington
Created: August 3, 2013
Repository: https://github.com/tcarrington/android-calculator
Description: Programming Calculator - Do calculations and convert numbers in binary, octal, decimal, hexadecimal.
Notes: This is my first Java and Android project. Lots of mistakes but learning lots! : )
Goal: Post on Google Play!
********************************************************************************/
package programming.calculator;
import java.util.Locale;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int INT_MAX = 2147483647;
int INT_MIN = -2147483648;
//global variables
String operand1;
String operation;
String operand2;
String displayValue;
String holdRecentEqualOperand;
boolean recentEqualFlag = false;
boolean divZeroFlag = false;
int currentBase;
int currentBaseStr;
//cannot switch on string, using numbers
/*
* 1: "+"
* 2: "-"
* 3: "*"
* 4: "/"
* 5: "%"
*/
int previousOperation;
//start of main code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//calculate metrics
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
TextView display_main = (TextView) findViewById(R.id.display_main);
TextView display_secondary = (TextView) findViewById(R.id.display_secondary);
TextView display_operation = (TextView) findViewById(R.id.display_operation);
TextView delete_button = (TextView) findViewById(R.id.delete_button);
Button bin_select = (Button) findViewById(R.id.bin_select);
Button oct_select = (Button) findViewById(R.id.oct_select);
Button dec_select = (Button) findViewById(R.id.dec_select);
Button hex_select = (Button) findViewById(R.id.hex_select);
Button d_button = (Button) findViewById(R.id.d_button);
Button e_button = (Button) findViewById(R.id.e_button);
Button f_button = (Button) findViewById(R.id.f_button);
Button clear_button = (Button) findViewById(R.id.clear_button);
Button a_button = (Button) findViewById(R.id.a_button);
Button b_button = (Button) findViewById(R.id.b_button);
Button c_button = (Button) findViewById(R.id.c_button);
Button div_button = (Button) findViewById(R.id.div_button);
Button button_7 = (Button) findViewById(R.id.button_7);
Button button_8 = (Button) findViewById(R.id.button_8);
Button button_9 = (Button) findViewById(R.id.button_9);
Button mult_button = (Button) findViewById(R.id.mult_button);
Button button_4 = (Button) findViewById(R.id.button_4);
Button button_5 = (Button) findViewById(R.id.button_5);
Button button_6 = (Button) findViewById(R.id.button_6);
Button sub_button = (Button) findViewById(R.id.sub_button);
Button button_1 = (Button) findViewById(R.id.button_1);
Button button_2 = (Button) findViewById(R.id.button_2);
Button button_3 = (Button) findViewById(R.id.button_3);
Button add_button = (Button) findViewById(R.id.add_button);
Button button_0 = (Button) findViewById(R.id.button_0);
Button plusminus_button = (Button) findViewById(R.id.plusminus_button);
Button equal_button = (Button) findViewById(R.id.equal_button);
Button mod_button = (Button) findViewById(R.id.mod_button);
//width formatting
display_operation.setWidth((width/4)-16);
display_secondary.setWidth(((width*3)/4)-16);
display_main.setWidth(((width*3)/4)-16);
delete_button.setWidth((width/4)-16);
bin_select.setWidth((width/4)-16);
oct_select.setWidth((width/4)-16);
dec_select.setWidth((width/4)-16);
hex_select.setWidth((width/4)-16);
d_button.setWidth((width/4)-16);
e_button.setWidth((width/4)-16);
f_button.setWidth((width/4)-16);
clear_button.setWidth((width/4)-16);
a_button.setWidth((width/4)-16);
b_button.setWidth((width/4)-16);
c_button.setWidth((width/4)-16);
div_button.setWidth((width/4)-16);
button_7.setWidth((width/4)-16);
button_8.setWidth((width/4)-16);
button_9.setWidth((width/4)-16);
mult_button.setWidth((width/4)-16);
button_4.setWidth((width/4)-16);
button_5.setWidth((width/4)-16);
button_6.setWidth((width/4)-16);
sub_button.setWidth((width/4)-16);
button_1.setWidth((width/4)-16);
button_2.setWidth((width/4)-16);
button_3.setWidth((width/4)-16);
add_button.setWidth((width/4)-16);
mult_button.setWidth((width/4)-16);
button_0.setWidth((width/4)-16);
plusminus_button.setWidth((width/4)-16);
equal_button.setWidth((width/4)-16);
mod_button.setWidth((width/4)-16);
//height formatting
display_operation.setHeight((height/9)-16);
display_secondary.setHeight((height/9)-16);
display_main.setHeight((height/9)-16);
delete_button.setHeight((height/9)-16);
bin_select.setHeight((height/9)-16);
oct_select.setHeight((height/9)-16);
dec_select.setHeight((height/9)-16);
hex_select.setHeight((height/9)-16);
d_button.setHeight((height/9)-16);
e_button.setHeight((height/9)-16);
f_button.setHeight((height/9)-16);
clear_button.setHeight((height/9)-16);
a_button.setHeight((height/9)-16);
b_button.setHeight((height/9)-16);
c_button.setHeight((height/9)-16);
div_button.setHeight((height/9)-16);
button_7.setHeight((height/9)-16);
button_8.setHeight((height/9)-16);
button_9.setHeight((height/9)-16);
mult_button.setHeight((height/9)-16);
button_4.setHeight((height/9)-16);
button_5.setHeight((height/9)-16);
button_6.setHeight((height/9)-16);
sub_button.setHeight((height/9)-16);
button_1.setHeight((height/9)-16);
button_2.setHeight((height/9)-16);
button_3.setHeight((height/9)-16);
add_button.setHeight((height/9)-16);
mult_button.setHeight((height/9)-16);
button_0.setHeight((height/9)-16);
plusminus_button.setHeight((height/9)-16);
equal_button.setHeight((height/9)-16);
mod_button.setHeight((height/9)-16);
//set defaults for base select buttons
f_button.setEnabled(false);
e_button.setEnabled(false);
d_button.setEnabled(false);
c_button.setEnabled(false);
b_button.setEnabled(false);
a_button.setEnabled(false);
button_9.setEnabled(true);
button_8.setEnabled(true);
button_7.setEnabled(true);
button_6.setEnabled(true);
button_5.setEnabled(true);
button_4.setEnabled(true);
button_3.setEnabled(true);
button_2.setEnabled(true);
button_1.setEnabled(true);
button_0.setEnabled(true);
plusminus_button.setEnabled(true);
bin_select.setTextColor(Color.parseColor("#FFFFFF"));
oct_select.setTextColor(Color.parseColor("#FFFFFF"));
dec_select.setTextColor(Color.parseColor("#33B5E5"));
hex_select.setTextColor(Color.parseColor("#FFFFFF"));
((TextView) findViewById(R.id.display_main)).setTextSize(35);
((TextView) findViewById(R.id.display_secondary)).setTextSize(35);
//required assignment for leading zero at onCreate()
operand1 = "0";
operand2 = "0";
displayValue = "0";
operation="";
holdRecentEqualOperand="0";
currentBase = 10;
recentEqualFlag = false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//base conversion
public void bin_select(View view){
//button locking
((Button) findViewById(R.id.d_button)).setEnabled(false);
((Button) findViewById(R.id.e_button)).setEnabled(false);
((Button) findViewById(R.id.f_button)).setEnabled(false);
((Button) findViewById(R.id.a_button)).setEnabled(false);
((Button) findViewById(R.id.b_button)).setEnabled(false);
((Button) findViewById(R.id.c_button)).setEnabled(false);
((Button) findViewById(R.id.button_7)).setEnabled(false);
((Button) findViewById(R.id.button_8)).setEnabled(false);
((Button) findViewById(R.id.button_9)).setEnabled(false);
((Button) findViewById(R.id.button_4)).setEnabled(false);
((Button) findViewById(R.id.button_5)).setEnabled(false);
((Button) findViewById(R.id.button_6)).setEnabled(false);
((Button) findViewById(R.id.button_1)).setEnabled(true);
((Button) findViewById(R.id.button_2)).setEnabled(false);
((Button) findViewById(R.id.button_3)).setEnabled(false);
((Button) findViewById(R.id.button_0)).setEnabled(true);
((Button) findViewById(R.id.bin_select)).setTextColor(Color.parseColor("#33B5E5"));
((Button) findViewById(R.id.oct_select)).setTextColor(Color.parseColor("#FFFFFF"));
((Button) findViewById(R.id.dec_select)).setTextColor(Color.parseColor("#FFFFFF"));
((Button) findViewById(R.id.hex_select)).setTextColor(Color.parseColor("#FFFFFF"));
((TextView) findViewById(R.id.display_main)).setTextSize(13);
((TextView) findViewById(R.id.display_secondary)).setTextSize(13);
//text_display conversion
TextView display_main = (TextView) findViewById(R.id.display_main);
TextView display_secondary = (TextView) findViewById(R.id.display_secondary);
displayValue = Integer.toBinaryString(Long.valueOf(displayValue, currentBase).intValue());
operand1 = Integer.toBinaryString(Long.valueOf(operand1, currentBase).intValue());
operand2 = Integer.toBinaryString(Long.valueOf(operand2, currentBase).intValue());
holdRecentEqualOperand = Integer.toBinaryString(Long.valueOf(holdRecentEqualOperand, currentBase).intValue());
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
if((!operand1.equals("0")) && (!recentEqualFlag)) {
display_secondary.setText(operand1.toUpperCase(Locale.ENGLISH));
}
currentBase = 2;
currentBaseStr = 32;
}
public void oct_select(View view){
//button locking
((Button) findViewById(R.id.d_button)).setEnabled(false);
((Button) findViewById(R.id.e_button)).setEnabled(false);
((Button) findViewById(R.id.f_button)).setEnabled(false);
((Button) findViewById(R.id.a_button)).setEnabled(false);
((Button) findViewById(R.id.b_button)).setEnabled(false);
((Button) findViewById(R.id.c_button)).setEnabled(false);
((Button) findViewById(R.id.button_7)).setEnabled(true);
((Button) findViewById(R.id.button_8)).setEnabled(false);
((Button) findViewById(R.id.button_9)).setEnabled(false);
((Button) findViewById(R.id.button_4)).setEnabled(true);
((Button) findViewById(R.id.button_5)).setEnabled(true);
((Button) findViewById(R.id.button_6)).setEnabled(true);
((Button) findViewById(R.id.button_1)).setEnabled(true);
((Button) findViewById(R.id.button_2)).setEnabled(true);
((Button) findViewById(R.id.button_3)).setEnabled(true);
((Button) findViewById(R.id.button_0)).setEnabled(true);
((Button) findViewById(R.id.bin_select)).setTextColor(Color.parseColor("#FFFFFF"));
((Button) findViewById(R.id.oct_select)).setTextColor(Color.parseColor("#33B5E5"));
((Button) findViewById(R.id.dec_select)).setTextColor(Color.parseColor("#FFFFFF"));
((Button) findViewById(R.id.hex_select)).setTextColor(Color.parseColor("#FFFFFF"));
((TextView) findViewById(R.id.display_main)).setTextSize(35);
((TextView) findViewById(R.id.display_secondary)).setTextSize(35);
//text_display conversion
TextView display_main = (TextView) findViewById(R.id.display_main);
TextView display_secondary = (TextView) findViewById(R.id.display_secondary);
displayValue = Integer.toOctalString(Long.valueOf(displayValue, currentBase).intValue());
operand1 = Integer.toOctalString(Long.valueOf(operand1, currentBase).intValue());
operand2 = Integer.toOctalString(Long.valueOf(operand2, currentBase).intValue());
holdRecentEqualOperand = Integer.toOctalString(Long.valueOf(holdRecentEqualOperand, currentBase).intValue());
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
if((!operand1.equals("0")) && (!recentEqualFlag)) {
display_secondary.setText(operand1.toUpperCase(Locale.ENGLISH));
}
currentBase = 8;
currentBaseStr = 11;
}
public void dec_select(View view){
//button locking
((Button) findViewById(R.id.d_button)).setEnabled(false);
((Button) findViewById(R.id.e_button)).setEnabled(false);
((Button) findViewById(R.id.f_button)).setEnabled(false);
((Button) findViewById(R.id.a_button)).setEnabled(false);
((Button) findViewById(R.id.b_button)).setEnabled(false);
((Button) findViewById(R.id.c_button)).setEnabled(false);
((Button) findViewById(R.id.button_7)).setEnabled(true);
((Button) findViewById(R.id.button_8)).setEnabled(true);
((Button) findViewById(R.id.button_9)).setEnabled(true);
((Button) findViewById(R.id.button_4)).setEnabled(true);
((Button) findViewById(R.id.button_5)).setEnabled(true);
((Button) findViewById(R.id.button_6)).setEnabled(true);
((Button) findViewById(R.id.button_1)).setEnabled(true);
((Button) findViewById(R.id.button_2)).setEnabled(true);
((Button) findViewById(R.id.button_3)).setEnabled(true);
((Button) findViewById(R.id.button_0)).setEnabled(true);
((Button) findViewById(R.id.bin_select)).setTextColor(Color.parseColor("#FFFFFF"));
((Button) findViewById(R.id.oct_select)).setTextColor(Color.parseColor("#FFFFFF"));
((Button) findViewById(R.id.dec_select)).setTextColor(Color.parseColor("#33B5E5"));
((Button) findViewById(R.id.hex_select)).setTextColor(Color.parseColor("#FFFFFF"));
((TextView) findViewById(R.id.display_main)).setTextSize(35);
((TextView) findViewById(R.id.display_secondary)).setTextSize(35);
//text_display conversion
TextView display_main = (TextView) findViewById(R.id.display_main);
TextView display_secondary = (TextView) findViewById(R.id.display_secondary);
displayValue = Integer.toString(Long.valueOf(displayValue, currentBase).intValue());
operand1 = Integer.toString(Long.valueOf(operand1, currentBase).intValue());
operand2 = Integer.toString(Long.valueOf(operand2, currentBase).intValue());
holdRecentEqualOperand = Integer.toString(Long.valueOf(holdRecentEqualOperand, currentBase).intValue());
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
if((!operand1.equals("0")) && (!recentEqualFlag)) {
display_secondary.setText(operand1.toUpperCase(Locale.ENGLISH));
}
currentBase = 10;
}
public void hex_select(View view){
//button locking
((Button) findViewById(R.id.d_button)).setEnabled(true);
((Button) findViewById(R.id.e_button)).setEnabled(true);
((Button) findViewById(R.id.f_button)).setEnabled(true);
((Button) findViewById(R.id.a_button)).setEnabled(true);
((Button) findViewById(R.id.b_button)).setEnabled(true);
((Button) findViewById(R.id.c_button)).setEnabled(true);
((Button) findViewById(R.id.button_7)).setEnabled(true);
((Button) findViewById(R.id.button_8)).setEnabled(true);
((Button) findViewById(R.id.button_9)).setEnabled(true);
((Button) findViewById(R.id.button_4)).setEnabled(true);
((Button) findViewById(R.id.button_5)).setEnabled(true);
((Button) findViewById(R.id.button_6)).setEnabled(true);
((Button) findViewById(R.id.button_1)).setEnabled(true);
((Button) findViewById(R.id.button_2)).setEnabled(true);
((Button) findViewById(R.id.button_3)).setEnabled(true);
((Button) findViewById(R.id.button_0)).setEnabled(true);
((Button) findViewById(R.id.bin_select)).setTextColor(Color.parseColor("#FFFFFF"));
((Button) findViewById(R.id.oct_select)).setTextColor(Color.parseColor("#FFFFFF"));
((Button) findViewById(R.id.dec_select)).setTextColor(Color.parseColor("#FFFFFF"));
((Button) findViewById(R.id.hex_select)).setTextColor(Color.parseColor("#33B5E5"));
((TextView) findViewById(R.id.display_main)).setTextSize(35);
((TextView) findViewById(R.id.display_secondary)).setTextSize(35);
//text_display conversion
TextView display_main = (TextView) findViewById(R.id.display_main);
TextView display_secondary = (TextView) findViewById(R.id.display_secondary);
displayValue = Integer.toHexString(Long.valueOf(displayValue, currentBase).intValue());
operand1 = Integer.toHexString(Long.valueOf(operand1, currentBase).intValue());
operand2 = Integer.toHexString(Long.valueOf(operand2, currentBase).intValue());
holdRecentEqualOperand = Integer.toHexString(Long.valueOf(holdRecentEqualOperand, currentBase).intValue());
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
if((!operand1.equals("0")) && (!recentEqualFlag)) {
display_secondary.setText(operand1.toUpperCase(Locale.ENGLISH));
}
currentBase = 16;
currentBaseStr = 8;
}
//input buttons
public void send_0(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "0";
if(recentEqualFlag) { //reset values if "clr" is not pressed
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 10) {
if((Integer.valueOf(displayValue + buttonValue, currentBase) >= INT_MIN) &&
(Integer.valueOf(displayValue + buttonValue, currentBase) <= INT_MAX))
displayValue += buttonValue;
}
else if((currentBase == 2) || (currentBase == 16)) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
else if(currentBase == 8) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX)) {
if((displayValue.length() == currentBaseStr - 1) && (Integer.valueOf(displayValue.substring(0, 1)) <= 3))
displayValue += buttonValue;
else if(displayValue.length() < (currentBaseStr - 1))
displayValue += buttonValue;
}
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_1(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "1";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 10) {
if((Integer.valueOf(displayValue + buttonValue, currentBase) >= INT_MIN) &&
(Integer.valueOf(displayValue + buttonValue, currentBase) <= INT_MAX))
displayValue += buttonValue;
}
else if((currentBase == 2) || (currentBase == 16)) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
else if(currentBase == 8) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX)) {
if((displayValue.length() == currentBaseStr - 1) && (Integer.valueOf(displayValue.substring(0, 1)) <= 3))
displayValue += buttonValue;
else if(displayValue.length() < (currentBaseStr - 1))
displayValue += buttonValue;
}
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_2(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "2";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 10) {
if((Integer.valueOf(displayValue + buttonValue, currentBase) >= INT_MIN) &&
(Integer.valueOf(displayValue + buttonValue, currentBase) <= INT_MAX))
displayValue += buttonValue;
}
else if(currentBase == 16) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
else if(currentBase == 8) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX)) {
if((displayValue.length() == currentBaseStr - 1) && (Integer.valueOf(displayValue.substring(0, 1)) <= 3))
displayValue += buttonValue;
else if(displayValue.length() < (currentBaseStr - 1))
displayValue += buttonValue;
}
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_3(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "3";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 10) {
if((Integer.valueOf(displayValue + buttonValue, currentBase) >= INT_MIN) &&
(Integer.valueOf(displayValue + buttonValue, currentBase) <= INT_MAX))
displayValue += buttonValue;
}
else if(currentBase == 16) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
else if(currentBase == 8) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX)) {
if((displayValue.length() == currentBaseStr - 1) && (Integer.valueOf(displayValue.substring(0, 1)) <= 3))
displayValue += buttonValue;
else if(displayValue.length() < (currentBaseStr - 1))
displayValue += buttonValue;
}
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_4(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "4";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 10) {
if((Integer.valueOf(displayValue + buttonValue, currentBase) >= INT_MIN) &&
(Integer.valueOf(displayValue + buttonValue, currentBase) <= INT_MAX))
displayValue += buttonValue;
}
else if(currentBase == 16) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
else if(currentBase == 8) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX)) {
if((displayValue.length() == currentBaseStr - 1) && (Integer.valueOf(displayValue.substring(0, 1)) <= 3))
displayValue += buttonValue;
else if(displayValue.length() < (currentBaseStr - 1))
displayValue += buttonValue;
}
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_5(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "5";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 10) {
if((Integer.valueOf(displayValue + buttonValue, currentBase) >= INT_MIN) &&
(Integer.valueOf(displayValue + buttonValue, currentBase) <= INT_MAX))
displayValue += buttonValue;
}
else if(currentBase == 16) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
else if(currentBase == 8) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX)) {
if((displayValue.length() == currentBaseStr - 1) && (Integer.valueOf(displayValue.substring(0, 1)) <= 3))
displayValue += buttonValue;
else if(displayValue.length() < (currentBaseStr - 1))
displayValue += buttonValue;
}
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_6(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "6";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 10) {
if((Integer.valueOf(displayValue + buttonValue, currentBase) >= INT_MIN) &&
(Integer.valueOf(displayValue + buttonValue, currentBase) <= INT_MAX))
displayValue += buttonValue;
}
else if(currentBase == 16) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
else if(currentBase == 8) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX)) {
if((displayValue.length() == currentBaseStr - 1) && (Integer.valueOf(displayValue.substring(0, 1)) <= 3))
displayValue += buttonValue;
else if(displayValue.length() < (currentBaseStr - 1))
displayValue += buttonValue;
}
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_7(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "7";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 10) {
if((Integer.valueOf(displayValue + buttonValue, currentBase) >= INT_MIN) &&
(Integer.valueOf(displayValue + buttonValue, currentBase) <= INT_MAX))
displayValue += buttonValue;
}
else if(currentBase == 16) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
else if(currentBase == 8) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX)) {
if((displayValue.length() == currentBaseStr - 1) && (Integer.valueOf(displayValue.substring(0, 1)) <= 3))
displayValue += buttonValue;
else if(displayValue.length() < (currentBaseStr - 1))
displayValue += buttonValue;
}
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_8(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "8";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 10) {
if((Integer.valueOf(displayValue + buttonValue, currentBase) >= INT_MIN) &&
(Integer.valueOf(displayValue + buttonValue, currentBase) <= INT_MAX))
displayValue += buttonValue;
}
else if(currentBase == 16) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_9(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "9";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 10) {
if((Integer.valueOf(displayValue + buttonValue, currentBase) >= INT_MIN) &&
(Integer.valueOf(displayValue + buttonValue, currentBase) <= INT_MAX))
displayValue += buttonValue;
}
else if(currentBase == 16) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_a(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "A";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 16) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_b(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "B";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 16) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_c(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "C";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 16) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_d(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "D";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 16) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_e(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "E";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 16) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));;
}
public void send_f(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
String buttonValue = "F";
if(recentEqualFlag) {
displayValue = "0";
recentEqualFlag = false;
}
if(displayValue.equals("0"))
displayValue = buttonValue;
else {
try {
if(currentBase == 16) {
if((Long.valueOf(displayValue + buttonValue, currentBase).intValue() >= INT_MIN) &&
(Long.valueOf(displayValue + buttonValue, currentBase).intValue() <= INT_MAX) &&
(displayValue.length() < currentBaseStr))
displayValue += buttonValue;
}
}
catch(Exception e) {}
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
}
//control buttons
public void send_delete(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
if(displayValue.length() > 0) {
displayValue = displayValue.substring(0, displayValue.length() - 1);
if(displayValue.length() == 0){
displayValue = "0";
}
}
operand1 = displayValue;
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
}
public void send_clear(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
TextView display_operation = (TextView) findViewById(R.id.display_operation);
TextView display_secondary = (TextView) findViewById(R.id.display_secondary);
//button unlocking
Button d_button = (Button) findViewById(R.id.d_button);
Button e_button = (Button) findViewById(R.id.e_button);
Button f_button = (Button) findViewById(R.id.f_button);
Button a_button = (Button) findViewById(R.id.a_button);
Button b_button = (Button) findViewById(R.id.b_button);
Button c_button = (Button) findViewById(R.id.c_button);
Button button_7 = (Button) findViewById(R.id.button_7);
Button button_8 = (Button) findViewById(R.id.button_8);
Button button_9 = (Button) findViewById(R.id.button_9);
Button button_4 = (Button) findViewById(R.id.button_4);
Button button_5 = (Button) findViewById(R.id.button_5);
Button button_6 = (Button) findViewById(R.id.button_6);
Button button_1 = (Button) findViewById(R.id.button_1);
Button button_2 = (Button) findViewById(R.id.button_2);
Button button_3 = (Button) findViewById(R.id.button_3);
Button button_0 = (Button) findViewById(R.id.button_0);
Button plusminus_button = (Button) findViewById(R.id.plusminus_button);
Button equal_button = (Button) findViewById(R.id.equal_button);
Button mod_button = (Button) findViewById(R.id.mod_button);
Button div_button = (Button) findViewById(R.id.div_button);
Button mult_button = (Button) findViewById(R.id.mult_button);
Button sub_button = (Button) findViewById(R.id.sub_button);
Button add_button = (Button) findViewById(R.id.add_button);
Button bin_select = (Button) findViewById(R.id.bin_select);
Button oct_select = (Button) findViewById(R.id.oct_select);
Button dec_select = (Button) findViewById(R.id.dec_select);
Button hex_select = (Button) findViewById(R.id.hex_select);
Button delete_button = (Button) findViewById(R.id.delete_button);
plusminus_button.setEnabled(true);
add_button.setEnabled(true);
sub_button.setEnabled(true);
mult_button.setEnabled(true);
div_button.setEnabled(true);
mod_button.setEnabled(true);
equal_button.setEnabled(true);
bin_select.setEnabled(true);
oct_select.setEnabled(true);
dec_select.setEnabled(true);
hex_select.setEnabled(true);
button_1.setEnabled(true);
button_0.setEnabled(true);
delete_button.setEnabled(true);
switch(currentBase) {
case 8:
button_7.setEnabled(true);
button_6.setEnabled(true);
button_5.setEnabled(true);
button_4.setEnabled(true);
button_3.setEnabled(true);
button_2.setEnabled(true);
break;
case 10:
button_9.setEnabled(true);
button_8.setEnabled(true);
button_7.setEnabled(true);
button_6.setEnabled(true);
button_5.setEnabled(true);
button_4.setEnabled(true);
button_3.setEnabled(true);
button_2.setEnabled(true);
break;
case 16:
f_button.setEnabled(true);
e_button.setEnabled(true);
d_button.setEnabled(true);
c_button.setEnabled(true);
b_button.setEnabled(true);
a_button.setEnabled(true);
button_9.setEnabled(true);
button_8.setEnabled(true);
button_7.setEnabled(true);
button_6.setEnabled(true);
button_5.setEnabled(true);
button_4.setEnabled(true);
button_3.setEnabled(true);
button_2.setEnabled(true);
}
displayValue = display_main.getText().toString();
holdRecentEqualOperand = "0";
recentEqualFlag = false;
displayValue = "0";
operand1 = "0";
operand2 = "0";
operation = "";
display_operation.setText("");
display_main.setText(displayValue);
display_secondary.setText("");
}
public void send_plusminus(View view) {
//conversion from hex -> decimal gives inverse values if +/- is pushed on a negative hex value
TextView display_main = (TextView) findViewById(R.id.display_main);
long holdInverse = 0;
if((Long.valueOf(displayValue, currentBase).intValue() > INT_MIN) && (Long.valueOf(displayValue, currentBase).intValue() <= INT_MAX)) {
holdInverse = ~Long.valueOf(displayValue, currentBase).intValue() + 1;
}
else if(Integer.valueOf(displayValue, currentBase) == 0) {
holdInverse = 0;
}
switch (currentBase) {
case 2:
displayValue = Integer.toBinaryString(Long.valueOf(holdInverse).intValue());
break;
case 8:
displayValue = Integer.toOctalString(Long.valueOf(holdInverse).intValue());
break;
case 10:
displayValue = Integer.toString(Long.valueOf(holdInverse).intValue());
break;
case 16:
displayValue = Integer.toHexString(Long.valueOf(holdInverse).intValue());
break;
}
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
}
public void send_equal(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
TextView display_secondary = (TextView) findViewById(R.id.display_secondary);
TextView display_operation = (TextView) findViewById(R.id.display_operation);
//button locking
Button d_button = (Button) findViewById(R.id.d_button);
Button e_button = (Button) findViewById(R.id.e_button);
Button f_button = (Button) findViewById(R.id.f_button);
Button a_button = (Button) findViewById(R.id.a_button);
Button b_button = (Button) findViewById(R.id.b_button);
Button c_button = (Button) findViewById(R.id.c_button);
Button button_7 = (Button) findViewById(R.id.button_7);
Button button_8 = (Button) findViewById(R.id.button_8);
Button button_9 = (Button) findViewById(R.id.button_9);
Button button_4 = (Button) findViewById(R.id.button_4);
Button button_5 = (Button) findViewById(R.id.button_5);
Button button_6 = (Button) findViewById(R.id.button_6);
Button button_1 = (Button) findViewById(R.id.button_1);
Button button_2 = (Button) findViewById(R.id.button_2);
Button button_3 = (Button) findViewById(R.id.button_3);
Button button_0 = (Button) findViewById(R.id.button_0);
Button plusminus_button = (Button) findViewById(R.id.plusminus_button);
Button equal_button = (Button) findViewById(R.id.equal_button);
Button mod_button = (Button) findViewById(R.id.mod_button);
Button div_button = (Button) findViewById(R.id.div_button);
Button mult_button = (Button) findViewById(R.id.mult_button);
Button sub_button = (Button) findViewById(R.id.sub_button);
Button add_button = (Button) findViewById(R.id.add_button);
Button bin_select = (Button) findViewById(R.id.bin_select);
Button oct_select = (Button) findViewById(R.id.oct_select);
Button dec_select = (Button) findViewById(R.id.dec_select);
Button hex_select = (Button) findViewById(R.id.hex_select);
Button delete_button = (Button) findViewById(R.id.delete_button);
if(operation != "")
operand2 = displayValue;
if(recentEqualFlag){
operand2 = holdRecentEqualOperand;
}
long solutionInt = 0;
if(operation == "+") {
solutionInt = Long.valueOf(operand1, currentBase).intValue() + Long.valueOf(operand2, currentBase).intValue();
}
else if(operation == "-") {
solutionInt = Long.valueOf(operand1, currentBase).intValue() - Long.valueOf(operand2, currentBase).intValue();
}
else if(operation == "*") {
solutionInt = Long.valueOf(operand1, currentBase).intValue() * Long.valueOf(operand2, currentBase).intValue();
}
else if(operation == "/") {
if(operand2.equals("0")) {
display_secondary.setText("ERROR:");
display_main.setText("DIV BY ZERO");
display_operation.setText(null);
f_button.setEnabled(false);
e_button.setEnabled(false);
d_button.setEnabled(false);
c_button.setEnabled(false);
b_button.setEnabled(false);
a_button.setEnabled(false);
button_9.setEnabled(false);
button_8.setEnabled(false);
button_7.setEnabled(false);
button_6.setEnabled(false);
button_5.setEnabled(false);
button_4.setEnabled(false);
button_3.setEnabled(false);
button_2.setEnabled(false);
button_1.setEnabled(false);
button_0.setEnabled(false);
plusminus_button.setEnabled(false);
add_button.setEnabled(false);
sub_button.setEnabled(false);
mult_button.setEnabled(false);
div_button.setEnabled(false);
mod_button.setEnabled(false);
equal_button.setEnabled(false);
bin_select.setEnabled(false);
oct_select.setEnabled(false);
dec_select.setEnabled(false);
hex_select.setEnabled(false);
delete_button.setEnabled(false);
divZeroFlag = true;
}
else
solutionInt = Long.valueOf(operand1, currentBase).intValue() / Long.valueOf(operand2, currentBase).intValue();
}
else if(operation == "%") {
- if(operand2 == "0") {
+ if(operand2.equals("0")) {
display_secondary.setText("ERROR:");
display_main.setText("MOD BY ZERO");
display_operation.setText(null);
f_button.setEnabled(false);
e_button.setEnabled(false);
d_button.setEnabled(false);
c_button.setEnabled(false);
b_button.setEnabled(false);
a_button.setEnabled(false);
button_9.setEnabled(false);
button_8.setEnabled(false);
button_7.setEnabled(false);
button_6.setEnabled(false);
button_5.setEnabled(false);
button_4.setEnabled(false);
button_3.setEnabled(false);
button_2.setEnabled(false);
button_1.setEnabled(false);
button_0.setEnabled(false);
plusminus_button.setEnabled(false);
add_button.setEnabled(false);
sub_button.setEnabled(false);
mult_button.setEnabled(false);
div_button.setEnabled(false);
mod_button.setEnabled(false);
equal_button.setEnabled(false);
bin_select.setEnabled(false);
oct_select.setEnabled(false);
dec_select.setEnabled(false);
hex_select.setEnabled(false);
delete_button.setEnabled(false);
divZeroFlag = true;
}
else
solutionInt = Long.valueOf(operand1, currentBase).intValue() % Long.valueOf(operand2, currentBase).intValue();
}
if (operation != ""){
switch (currentBase) {
case 2:
displayValue = Integer.toBinaryString(Long.valueOf(solutionInt).intValue());
break;
case 8:
displayValue = Integer.toOctalString(Long.valueOf(solutionInt).intValue());
break;
case 10:
displayValue = Integer.toString(Long.valueOf(solutionInt).intValue());
break;
case 16:
displayValue = Integer.toHexString(Long.valueOf(solutionInt).intValue());
break;
}
if(!divZeroFlag) {
holdRecentEqualOperand = operand2;
operand1 = displayValue;
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
display_secondary.setText("");
display_operation.setText("");
}
recentEqualFlag = true;
divZeroFlag = false;
}
}
//operations
public void send_add(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
TextView display_operation = (TextView) findViewById(R.id.display_operation);
TextView display_secondary = (TextView) findViewById(R.id.display_secondary);
long solutionInt = 0;
operation = "+";
if(!operand1.equals("0")) {
operand2 = displayValue;
}
else {
operand1 = displayValue;
}
display_secondary.setText(operand1.toUpperCase(Locale.ENGLISH));
if((!operand1.equals("0")) && (!operand2.equals("0")) && !recentEqualFlag) {
switch (previousOperation) {
case 1:
solutionInt = Long.valueOf(operand1, currentBase).intValue() + Long.valueOf(operand2, currentBase).intValue();
break;
case 2:
solutionInt = Long.valueOf(operand1, currentBase).intValue() - Long.valueOf(operand2, currentBase).intValue();
break;
case 3:
solutionInt = Long.valueOf(operand1, currentBase).intValue() * Long.valueOf(operand2, currentBase).intValue();
break;
case 4:
solutionInt = Long.valueOf(operand1, currentBase).intValue() / Long.valueOf(operand2, currentBase).intValue();
break;
case 5:
solutionInt = Long.valueOf(operand1, currentBase).intValue() % Long.valueOf(operand2, currentBase).intValue();
break;
}
switch (currentBase) {
case 2:
displayValue = Integer.toBinaryString(Long.valueOf(solutionInt).intValue());
break;
case 8:
displayValue = Integer.toOctalString(Long.valueOf(solutionInt).intValue());
break;
case 10:
displayValue = Integer.toString(Long.valueOf(solutionInt).intValue());
break;
case 16:
displayValue = Integer.toHexString(Long.valueOf(solutionInt).intValue());
break;
}
display_secondary.setText(displayValue.toUpperCase(Locale.ENGLISH));
operand1 = displayValue;
operand2 = "0";
displayValue = "0";
display_main.setText(displayValue);
display_operation.setText(operation);
}
else {
displayValue = "0";
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
display_operation.setText(operation);
recentEqualFlag = false;
}
previousOperation = 1;
}
public void send_sub(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
TextView display_operation = (TextView) findViewById(R.id.display_operation);
TextView display_secondary = (TextView) findViewById(R.id.display_secondary);
int solutionInt = 0;
operation = "-";
if(!operand1.equals("0")) {
operand2 = display_main.getText().toString();
}
else {
operand1 = display_main.getText().toString();
}
display_secondary.setText(operand1.toUpperCase(Locale.ENGLISH));
if((!operand1.equals("0")) && (!operand2.equals("0")) && !recentEqualFlag) {
switch (previousOperation) {
case 1:
solutionInt = Long.valueOf(operand1, currentBase).intValue() + Long.valueOf(operand2, currentBase).intValue();
break;
case 2:
solutionInt = Long.valueOf(operand1, currentBase).intValue() - Long.valueOf(operand2, currentBase).intValue();
break;
case 3:
solutionInt = Long.valueOf(operand1, currentBase).intValue() * Long.valueOf(operand2, currentBase).intValue();
break;
case 4:
solutionInt = Long.valueOf(operand1, currentBase).intValue() / Long.valueOf(operand2, currentBase).intValue();
break;
case 5:
solutionInt = Long.valueOf(operand1, currentBase).intValue() % Long.valueOf(operand2, currentBase).intValue();
break;
}
switch (currentBase) {
case 2:
displayValue = Integer.toBinaryString(Long.valueOf(solutionInt).intValue());
break;
case 8:
displayValue = Integer.toOctalString(Long.valueOf(solutionInt).intValue());
break;
case 10:
displayValue = Integer.toString(Long.valueOf(solutionInt).intValue());
break;
case 16:
displayValue = Integer.toHexString(Long.valueOf(solutionInt).intValue());
break;
}
display_secondary.setText(displayValue.toUpperCase(Locale.ENGLISH));
operand1 = displayValue;
operand2 = "0";
displayValue = "0";
display_main.setText(displayValue);
display_operation.setText(operation);
}
else {
displayValue = "0";
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
display_operation.setText(operation);
recentEqualFlag = false;
}
previousOperation = 2;
}
public void send_mult(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
TextView display_operation = (TextView) findViewById(R.id.display_operation);
TextView display_secondary = (TextView) findViewById(R.id.display_secondary);
int solutionInt = 0;
operation = "*";
if(!operand1.equals("0")) {
operand2 = displayValue;
}
else {
operand1 = displayValue;
}
display_secondary.setText(operand1.toUpperCase(Locale.ENGLISH));
if((!operand1.equals("0")) && (!operand2.equals("0")) && !recentEqualFlag) {
switch (previousOperation) {
case 1:
solutionInt = Long.valueOf(operand1, currentBase).intValue() + Long.valueOf(operand2, currentBase).intValue();
break;
case 2:
solutionInt = Long.valueOf(operand1, currentBase).intValue() - Long.valueOf(operand2, currentBase).intValue();
break;
case 3:
solutionInt = Long.valueOf(operand1, currentBase).intValue() * Long.valueOf(operand2, currentBase).intValue();
break;
case 4:
solutionInt = Long.valueOf(operand1, currentBase).intValue() / Long.valueOf(operand2, currentBase).intValue();
break;
case 5:
solutionInt = Long.valueOf(operand1, currentBase).intValue() % Long.valueOf(operand2, currentBase).intValue();
break;
}
switch (currentBase) {
case 2:
displayValue = Integer.toBinaryString(Long.valueOf(solutionInt).intValue());
break;
case 8:
displayValue = Integer.toOctalString(Long.valueOf(solutionInt).intValue());
break;
case 10:
displayValue = Integer.toString(Long.valueOf(solutionInt).intValue());
break;
case 16:
displayValue = Integer.toHexString(Long.valueOf(solutionInt).intValue());
break;
}
display_secondary.setText(displayValue.toUpperCase(Locale.ENGLISH));
operand1 = displayValue;
operand2 = "0";
displayValue = "0";
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
display_operation.setText(operation);
}
else {
displayValue = "0";
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
display_operation.setText(operation);
recentEqualFlag = false;
}
previousOperation = 3;
}
public void send_div(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
TextView display_operation = (TextView) findViewById(R.id.display_operation);
TextView display_secondary = (TextView) findViewById(R.id.display_secondary);
int solutionInt = 0;
operation = "/";
if(!operand1.equals("0")) {
operand2 = displayValue;
}
else {
operand1 = displayValue;
}
display_secondary.setText(operand1.toUpperCase(Locale.ENGLISH));
if((!operand1.equals("0")) && (!operand2.equals("0")) && !recentEqualFlag) {
switch (previousOperation) {
case 1:
solutionInt = Long.valueOf(operand1, currentBase).intValue() + Long.valueOf(operand2, currentBase).intValue();
break;
case 2:
solutionInt = Long.valueOf(operand1, currentBase).intValue() - Long.valueOf(operand2, currentBase).intValue();
break;
case 3:
solutionInt = Long.valueOf(operand1, currentBase).intValue() * Long.valueOf(operand2, currentBase).intValue();
break;
case 4:
solutionInt = Long.valueOf(operand1, currentBase).intValue() / Long.valueOf(operand2, currentBase).intValue();
break;
case 5:
solutionInt = Long.valueOf(operand1, currentBase).intValue() % Long.valueOf(operand2, currentBase).intValue();
break;
}
switch (currentBase) {
case 2:
displayValue = Integer.toBinaryString(Long.valueOf(solutionInt).intValue());
break;
case 8:
displayValue = Integer.toOctalString(Long.valueOf(solutionInt).intValue());
break;
case 10:
displayValue = Integer.toString(Long.valueOf(solutionInt).intValue());
break;
case 16:
displayValue = Integer.toHexString(Long.valueOf(solutionInt).intValue());
break;
}
display_secondary.setText(displayValue.toUpperCase(Locale.ENGLISH));
operand1 = displayValue;
operand2 = "0";
displayValue = "0";
display_main.setText(displayValue);
display_operation.setText(operation);
}
else {
displayValue = "0";
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
display_operation.setText(operation);
recentEqualFlag = false;
}
previousOperation = 4;
}
public void send_mod(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
TextView display_operation = (TextView) findViewById(R.id.display_operation);
TextView display_secondary = (TextView) findViewById(R.id.display_secondary);
int solutionInt = 0;
operation = "%";
if(!operand1.equals("0")) {
operand2 = displayValue;
}
else {
operand1 = displayValue;
}
display_secondary.setText(operand1.toUpperCase(Locale.ENGLISH));
if((!operand1.equals("0")) && (!operand2.equals("0")) && !recentEqualFlag) {
switch (previousOperation) {
case 1:
solutionInt = Long.valueOf(operand1, currentBase).intValue() + Long.valueOf(operand2, currentBase).intValue();
break;
case 2:
solutionInt = Long.valueOf(operand1, currentBase).intValue() - Long.valueOf(operand2, currentBase).intValue();
break;
case 3:
solutionInt = Long.valueOf(operand1, currentBase).intValue() * Long.valueOf(operand2, currentBase).intValue();
break;
case 4:
solutionInt = Long.valueOf(operand1, currentBase).intValue() / Long.valueOf(operand2, currentBase).intValue();
break;
case 5:
solutionInt = Long.valueOf(operand1, currentBase).intValue() % Long.valueOf(operand2, currentBase).intValue();
break;
}
switch (currentBase) {
case 2:
displayValue = Integer.toBinaryString(Long.valueOf(solutionInt).intValue());
break;
case 8:
displayValue = Integer.toOctalString(Long.valueOf(solutionInt).intValue());
break;
case 10:
displayValue = Integer.toString(Long.valueOf(solutionInt).intValue());
break;
case 16:
displayValue = Integer.toHexString(Long.valueOf(solutionInt).intValue());
break;
}
display_secondary.setText(displayValue.toUpperCase(Locale.ENGLISH));
operand1 = displayValue;
operand2 = "0";
displayValue = "0";
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
display_operation.setText(operation);
}
else {
displayValue = "0";
display_main.setText(displayValue);
display_operation.setText(operation);
recentEqualFlag = false;
}
previousOperation = 5;
}
}
/****************************************************************
New features list:
Swipe to clear!
More color options
More operations
Bug:
division by zero does not work when switching bases
****************************************************************/
| true | true | public void send_equal(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
TextView display_secondary = (TextView) findViewById(R.id.display_secondary);
TextView display_operation = (TextView) findViewById(R.id.display_operation);
//button locking
Button d_button = (Button) findViewById(R.id.d_button);
Button e_button = (Button) findViewById(R.id.e_button);
Button f_button = (Button) findViewById(R.id.f_button);
Button a_button = (Button) findViewById(R.id.a_button);
Button b_button = (Button) findViewById(R.id.b_button);
Button c_button = (Button) findViewById(R.id.c_button);
Button button_7 = (Button) findViewById(R.id.button_7);
Button button_8 = (Button) findViewById(R.id.button_8);
Button button_9 = (Button) findViewById(R.id.button_9);
Button button_4 = (Button) findViewById(R.id.button_4);
Button button_5 = (Button) findViewById(R.id.button_5);
Button button_6 = (Button) findViewById(R.id.button_6);
Button button_1 = (Button) findViewById(R.id.button_1);
Button button_2 = (Button) findViewById(R.id.button_2);
Button button_3 = (Button) findViewById(R.id.button_3);
Button button_0 = (Button) findViewById(R.id.button_0);
Button plusminus_button = (Button) findViewById(R.id.plusminus_button);
Button equal_button = (Button) findViewById(R.id.equal_button);
Button mod_button = (Button) findViewById(R.id.mod_button);
Button div_button = (Button) findViewById(R.id.div_button);
Button mult_button = (Button) findViewById(R.id.mult_button);
Button sub_button = (Button) findViewById(R.id.sub_button);
Button add_button = (Button) findViewById(R.id.add_button);
Button bin_select = (Button) findViewById(R.id.bin_select);
Button oct_select = (Button) findViewById(R.id.oct_select);
Button dec_select = (Button) findViewById(R.id.dec_select);
Button hex_select = (Button) findViewById(R.id.hex_select);
Button delete_button = (Button) findViewById(R.id.delete_button);
if(operation != "")
operand2 = displayValue;
if(recentEqualFlag){
operand2 = holdRecentEqualOperand;
}
long solutionInt = 0;
if(operation == "+") {
solutionInt = Long.valueOf(operand1, currentBase).intValue() + Long.valueOf(operand2, currentBase).intValue();
}
else if(operation == "-") {
solutionInt = Long.valueOf(operand1, currentBase).intValue() - Long.valueOf(operand2, currentBase).intValue();
}
else if(operation == "*") {
solutionInt = Long.valueOf(operand1, currentBase).intValue() * Long.valueOf(operand2, currentBase).intValue();
}
else if(operation == "/") {
if(operand2.equals("0")) {
display_secondary.setText("ERROR:");
display_main.setText("DIV BY ZERO");
display_operation.setText(null);
f_button.setEnabled(false);
e_button.setEnabled(false);
d_button.setEnabled(false);
c_button.setEnabled(false);
b_button.setEnabled(false);
a_button.setEnabled(false);
button_9.setEnabled(false);
button_8.setEnabled(false);
button_7.setEnabled(false);
button_6.setEnabled(false);
button_5.setEnabled(false);
button_4.setEnabled(false);
button_3.setEnabled(false);
button_2.setEnabled(false);
button_1.setEnabled(false);
button_0.setEnabled(false);
plusminus_button.setEnabled(false);
add_button.setEnabled(false);
sub_button.setEnabled(false);
mult_button.setEnabled(false);
div_button.setEnabled(false);
mod_button.setEnabled(false);
equal_button.setEnabled(false);
bin_select.setEnabled(false);
oct_select.setEnabled(false);
dec_select.setEnabled(false);
hex_select.setEnabled(false);
delete_button.setEnabled(false);
divZeroFlag = true;
}
else
solutionInt = Long.valueOf(operand1, currentBase).intValue() / Long.valueOf(operand2, currentBase).intValue();
}
else if(operation == "%") {
if(operand2 == "0") {
display_secondary.setText("ERROR:");
display_main.setText("MOD BY ZERO");
display_operation.setText(null);
f_button.setEnabled(false);
e_button.setEnabled(false);
d_button.setEnabled(false);
c_button.setEnabled(false);
b_button.setEnabled(false);
a_button.setEnabled(false);
button_9.setEnabled(false);
button_8.setEnabled(false);
button_7.setEnabled(false);
button_6.setEnabled(false);
button_5.setEnabled(false);
button_4.setEnabled(false);
button_3.setEnabled(false);
button_2.setEnabled(false);
button_1.setEnabled(false);
button_0.setEnabled(false);
plusminus_button.setEnabled(false);
add_button.setEnabled(false);
sub_button.setEnabled(false);
mult_button.setEnabled(false);
div_button.setEnabled(false);
mod_button.setEnabled(false);
equal_button.setEnabled(false);
bin_select.setEnabled(false);
oct_select.setEnabled(false);
dec_select.setEnabled(false);
hex_select.setEnabled(false);
delete_button.setEnabled(false);
divZeroFlag = true;
}
else
solutionInt = Long.valueOf(operand1, currentBase).intValue() % Long.valueOf(operand2, currentBase).intValue();
}
if (operation != ""){
switch (currentBase) {
case 2:
displayValue = Integer.toBinaryString(Long.valueOf(solutionInt).intValue());
break;
case 8:
displayValue = Integer.toOctalString(Long.valueOf(solutionInt).intValue());
break;
case 10:
displayValue = Integer.toString(Long.valueOf(solutionInt).intValue());
break;
case 16:
displayValue = Integer.toHexString(Long.valueOf(solutionInt).intValue());
break;
}
if(!divZeroFlag) {
holdRecentEqualOperand = operand2;
operand1 = displayValue;
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
display_secondary.setText("");
display_operation.setText("");
}
recentEqualFlag = true;
divZeroFlag = false;
}
}
| public void send_equal(View view) {
TextView display_main = (TextView) findViewById(R.id.display_main);
TextView display_secondary = (TextView) findViewById(R.id.display_secondary);
TextView display_operation = (TextView) findViewById(R.id.display_operation);
//button locking
Button d_button = (Button) findViewById(R.id.d_button);
Button e_button = (Button) findViewById(R.id.e_button);
Button f_button = (Button) findViewById(R.id.f_button);
Button a_button = (Button) findViewById(R.id.a_button);
Button b_button = (Button) findViewById(R.id.b_button);
Button c_button = (Button) findViewById(R.id.c_button);
Button button_7 = (Button) findViewById(R.id.button_7);
Button button_8 = (Button) findViewById(R.id.button_8);
Button button_9 = (Button) findViewById(R.id.button_9);
Button button_4 = (Button) findViewById(R.id.button_4);
Button button_5 = (Button) findViewById(R.id.button_5);
Button button_6 = (Button) findViewById(R.id.button_6);
Button button_1 = (Button) findViewById(R.id.button_1);
Button button_2 = (Button) findViewById(R.id.button_2);
Button button_3 = (Button) findViewById(R.id.button_3);
Button button_0 = (Button) findViewById(R.id.button_0);
Button plusminus_button = (Button) findViewById(R.id.plusminus_button);
Button equal_button = (Button) findViewById(R.id.equal_button);
Button mod_button = (Button) findViewById(R.id.mod_button);
Button div_button = (Button) findViewById(R.id.div_button);
Button mult_button = (Button) findViewById(R.id.mult_button);
Button sub_button = (Button) findViewById(R.id.sub_button);
Button add_button = (Button) findViewById(R.id.add_button);
Button bin_select = (Button) findViewById(R.id.bin_select);
Button oct_select = (Button) findViewById(R.id.oct_select);
Button dec_select = (Button) findViewById(R.id.dec_select);
Button hex_select = (Button) findViewById(R.id.hex_select);
Button delete_button = (Button) findViewById(R.id.delete_button);
if(operation != "")
operand2 = displayValue;
if(recentEqualFlag){
operand2 = holdRecentEqualOperand;
}
long solutionInt = 0;
if(operation == "+") {
solutionInt = Long.valueOf(operand1, currentBase).intValue() + Long.valueOf(operand2, currentBase).intValue();
}
else if(operation == "-") {
solutionInt = Long.valueOf(operand1, currentBase).intValue() - Long.valueOf(operand2, currentBase).intValue();
}
else if(operation == "*") {
solutionInt = Long.valueOf(operand1, currentBase).intValue() * Long.valueOf(operand2, currentBase).intValue();
}
else if(operation == "/") {
if(operand2.equals("0")) {
display_secondary.setText("ERROR:");
display_main.setText("DIV BY ZERO");
display_operation.setText(null);
f_button.setEnabled(false);
e_button.setEnabled(false);
d_button.setEnabled(false);
c_button.setEnabled(false);
b_button.setEnabled(false);
a_button.setEnabled(false);
button_9.setEnabled(false);
button_8.setEnabled(false);
button_7.setEnabled(false);
button_6.setEnabled(false);
button_5.setEnabled(false);
button_4.setEnabled(false);
button_3.setEnabled(false);
button_2.setEnabled(false);
button_1.setEnabled(false);
button_0.setEnabled(false);
plusminus_button.setEnabled(false);
add_button.setEnabled(false);
sub_button.setEnabled(false);
mult_button.setEnabled(false);
div_button.setEnabled(false);
mod_button.setEnabled(false);
equal_button.setEnabled(false);
bin_select.setEnabled(false);
oct_select.setEnabled(false);
dec_select.setEnabled(false);
hex_select.setEnabled(false);
delete_button.setEnabled(false);
divZeroFlag = true;
}
else
solutionInt = Long.valueOf(operand1, currentBase).intValue() / Long.valueOf(operand2, currentBase).intValue();
}
else if(operation == "%") {
if(operand2.equals("0")) {
display_secondary.setText("ERROR:");
display_main.setText("MOD BY ZERO");
display_operation.setText(null);
f_button.setEnabled(false);
e_button.setEnabled(false);
d_button.setEnabled(false);
c_button.setEnabled(false);
b_button.setEnabled(false);
a_button.setEnabled(false);
button_9.setEnabled(false);
button_8.setEnabled(false);
button_7.setEnabled(false);
button_6.setEnabled(false);
button_5.setEnabled(false);
button_4.setEnabled(false);
button_3.setEnabled(false);
button_2.setEnabled(false);
button_1.setEnabled(false);
button_0.setEnabled(false);
plusminus_button.setEnabled(false);
add_button.setEnabled(false);
sub_button.setEnabled(false);
mult_button.setEnabled(false);
div_button.setEnabled(false);
mod_button.setEnabled(false);
equal_button.setEnabled(false);
bin_select.setEnabled(false);
oct_select.setEnabled(false);
dec_select.setEnabled(false);
hex_select.setEnabled(false);
delete_button.setEnabled(false);
divZeroFlag = true;
}
else
solutionInt = Long.valueOf(operand1, currentBase).intValue() % Long.valueOf(operand2, currentBase).intValue();
}
if (operation != ""){
switch (currentBase) {
case 2:
displayValue = Integer.toBinaryString(Long.valueOf(solutionInt).intValue());
break;
case 8:
displayValue = Integer.toOctalString(Long.valueOf(solutionInt).intValue());
break;
case 10:
displayValue = Integer.toString(Long.valueOf(solutionInt).intValue());
break;
case 16:
displayValue = Integer.toHexString(Long.valueOf(solutionInt).intValue());
break;
}
if(!divZeroFlag) {
holdRecentEqualOperand = operand2;
operand1 = displayValue;
display_main.setText(displayValue.toUpperCase(Locale.ENGLISH));
display_secondary.setText("");
display_operation.setText("");
}
recentEqualFlag = true;
divZeroFlag = false;
}
}
|
diff --git a/A1P3/src/com/group2/finger_occ_demo/Points.java b/A1P3/src/com/group2/finger_occ_demo/Points.java
index 6ac7650..2a7d228 100644
--- a/A1P3/src/com/group2/finger_occ_demo/Points.java
+++ b/A1P3/src/com/group2/finger_occ_demo/Points.java
@@ -1,386 +1,386 @@
package com.group2.finger_occ_demo;
import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.View;
import com.group2.finger_occ_demo.data.Movie;
/**
* Responsible for all shapes on screen. Note order of list is the way of doing
* z-indexing.
*/
public class Points {
private int[] rect_size = {20, 20};
private ArrayList<Square_Shape> squares;
private int radiusPX;// From the center of a shape
private float xStart;
private float yStart;
private float availableWidth;
private float availableHeight;
private int[] xRange;
private int[] yRange;
private int xOffset;
private int yOffset;
public ArrayList<Square_Shape> sqs = new ArrayList<Square_Shape>();
/**
* Responsible for all shapes in a given box. Note order of list is the way of doing
* z-indexing.
*/
public Points(float xStart, float yStart, float screenWidth, float screenHeight, int[] xRange, int[] yRange){
xOffset = 0;
yOffset = 0;
// Get the available width and ranges
this.availableWidth = screenWidth;
this.availableHeight = screenHeight;
this.xStart = xStart;
this.yStart = yStart;
this.xRange = xRange;
this.yRange = yRange;
// Derive rectangle size from screen size so it looks nice (only for now)
rect_size[0] = (int) (this.availableWidth * 0.02);
rect_size[1] = (int) (this.availableWidth * 0.02);
// Also derive radius from screen size, make it 4 times the shapes size
radiusPX = rect_size[0] * 4;
squares = new ArrayList<Square_Shape>();
init_from_data(null);
}
/**
* Currently uses year on x and rating on height. Formula is:
* (n/m) * r = x or y position,
* where n is the maximum graph value for the axis, n is the maximum value
* for the data points i.e. for rating 10, and r is the current value of the point.
* If movies is null the default movie list is loaded.
*/
public void init_from_data(List<Movie> movies){
float x;
float y;
int color = Color.GREEN;
if (movies == null)
movies = canvasApp.data.getMovie();
float heightInc = availableHeight/(yRange[1] - yRange[0]);
float widthInc = availableWidth/(xRange[1] - xRange[0]);
squares = new ArrayList<Square_Shape>();
for (Movie movie : movies){
x = (float) ( (widthInc * movie.getYear1900()) + xOffset + xStart);
y = (float) ( ((availableHeight + yStart) - (heightInc * movie.getRating())) + yOffset);//invert the ratings so 0 is at the bottom
color = getColor(movie.getGenre().get(0));
squares.add(new Square_Shape(movie, x + rect_size[0]/2, y - rect_size[1]/2, rect_size, color));// the minus size centers a shape on a tick line
}
}
public void filter_points(String genre, String rating){
squares.clear();
List<Movie> movies;
if(genre.equals("All") && rating.equals("All")){
movies = canvasApp.data.getMovie();
}
else{
movies = new ArrayList<Movie>();
for(Movie movie : canvasApp.data.getMovie()){
String g = movie.getGenre().get(0);
int r = movie.getRating();
if(genre.equals("All")){
if(r==Integer.valueOf(rating)){
movies.add(movie);
}
}
else if(rating.equals("All")){
if(g.equals(genre)){
movies.add(movie);
}
}
else if(g.equals(genre) && r==Integer.valueOf(rating)){
movies.add(movie);
}
}
}
init_from_data(movies);
}
public void filter_points(String text, String genre, String rating)
{
text = text.trim();
- if(text.length() > 0)
+ if(text.length() > 1)
{
squares.clear();
List<Movie> movies;
movies = new ArrayList<Movie>();
for(Movie movie : canvasApp.data.getMovie()){
String g = movie.getGenre().get(0);
int r = movie.getRating();
if(genre.equals("All") && rating.equals("All")){
if(Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE).matcher(movie.getTitle()).find())
{
movies.add(movie);
}
}
else
if(genre.equals("All")){
if(r==Integer.valueOf(rating) && Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE).matcher(movie.getTitle()).find()){
movies.add(movie);
}
}
else if(rating.equals("All")){
if(g.equals(genre) && Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE).matcher(movie.getTitle()).find()){
movies.add(movie);
}
}
else if(g.equals(genre) && r==Integer.valueOf(rating)){
if(Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE).matcher(movie.getTitle()).find())
{
movies.add(movie);
}
}
}
init_from_data(movies);
}
}
/**
* Draw all shapes visible on the sent canvas. Due to ordering shapes in the same position end up in the
* same place of an array. So can use previous coordinates to determine if shape is drawable. Also sets
* the current shape to drawable.
*/
public void drawShapes(Canvas on){
Square_Shape square;
int[] prevXY = {-1,-1};// should not be on screen, meaning first shape is always drawn
for (int i = 0; i < squares.size(); i++){
square = squares.get(i);
square.setDrawn(false);
if ( !(square.getX() == prevXY[0] && square.getY() == prevXY[1])){
square.draw(on);
prevXY[0] = square.getX();
prevXY[1] = square.getY();
square.setDrawn(true);
}
}
}
/**
* If in any drawn shape on the canvas is under the finger and is the biggest.
*/
public ArrayList<Movie> inShape(int x, int y){
int[] position = {x, y};
ArrayList<Movie> movies = new ArrayList<Movie>();
// See if in any of the shapes, backwards loop because current biggest
// objects are in the end of the array list. Only retrieves object if drawn.
for (int i = squares.size() - 1; i > 0; i--){
//System.out.println(squares.get(i).getMovie().getTitle());
if (squares.get(i).inShape(position) == true){
if(squares.get(i).isDrawn()){
movies.add(squares.get(i).getMovie());
//System.out.println(squares.get(i).getMovie().getTitle());
return movies;
}
else{
//squares.get(i).translate(0, 0 +20);
movies.add(squares.get(i).getMovie());
//System.out.println(squares.get(i).getMovie().getTitle());
}
}
}
return movies;
}
public void inShapeSquares(int x, int y){
int[] position = {x, y};
int xint = 0;
int yint = 0;
//System.out.println("Event: action move");
// See if in any of the shapes, backwards loop because current biggest
// objects are in the end of the array list. Only retrieves object if drawn.
for (int i = squares.size() - 1; i > 0; i--){
//System.out.println(squares.get(i).getMovie().getTitle());
if (squares.get(i).inShape(position) == true){
if(squares.get(i).isDrawn()){
//System.out.println(squares.get(i).getMovie().getTitle());
//sqs.add(squares.get(i));
//System.out.println(squares.get(i).getMovie().getTitle());
}
else{
//System.out.println(squares.get(i).getMovie().getTitle());
squares.get(i).translate(xint, yint -10);
sqs.add(squares.get(i));
//System.out.println(squares.get(i).getMovie().getTitle());
}
}
}
}
/**
* Checks an expands any shapes in the current radius. Does this by specifying and area
* that will need to be redrawn. The biggest objects are put in front.
*/
public void checkRadius(int x, int y, View view){
Square_Shape square;
int largeRadius = (int) (radiusPX * 1.5);
for (int i = 0; i < squares.size(); i++){
square = squares.get(i);
// if a square is double the distance away don't bother calculating it. This is a rough approximation keep in mind.
if ( (square.getX() > x - largeRadius && square.getX() < x + largeRadius) &&
(square.getY() > y - largeRadius && square.getY() < y + largeRadius))
square.checkRadius(x, y, radiusPX);
}
reorderZ();
// invalidate only this rectangle.
view.invalidate(x - largeRadius, y - largeRadius, x + largeRadius, y + largeRadius);
}
/**
* Reorders z-indexing of shapes (list order) by the current size of
* the shape. Greatest elements are last as they are rendered last
* overlapping other elements.
*/
private void reorderZ(){
Collections.sort(squares, new Comparator<Object>(){
public int compare(Object obj1, Object obj2) {
Square_Shape sqr1 = (Square_Shape)obj1;
Square_Shape sqr2 = (Square_Shape)obj2;
return sqr1.getSize() - sqr2.getSize();
}
});
}
/**
* Sets all shapes to the default size
*/
public void goDefaultSize(){
for (int i = 0; i < squares.size(); i++)
squares.get(i).setDefaultSize();
}
/*
* Getters and setters
*/
public void translateSquares(int xOffset, int yOffset, ArrayList<Square_Shape> sqs){
for(Square_Shape sq:sqs)
sq.translate(xOffset, yOffset);
}
public void translate(int xOffset, int yOffset){
this.xOffset = xOffset;
this.yOffset = yOffset;
for (Square_Shape square : squares)
square.translate(xOffset, yOffset);
}
public void resetPosition(){
this.xOffset = 0;
this.yOffset = 0;
for (Square_Shape square : squares)
square.resetPosition();
}
public int getColor(String color){
if(color.equals("Action")){
return Color.WHITE;
}
else if(color.equals("Drama")){
return Color.RED;
}
else if(color.equals("Mystery")){
return Color.BLUE;
}
else if(color.equals("Comedy")){
return Color.MAGENTA;
}
else if(color.equals("Music")){
return Color.YELLOW;
}
else if(color.equals("War")){
return Color.GREEN;
}
else if(color.equals("Sci-Fi")){
return Color.rgb(255, 69, 0);//orange
}
else if(color.equals("Western")){
return Color.rgb(238, 221, 130);
}
else if(color.equals("Horror")){
return Color.rgb(152, 251, 152);
}
else if(color.equals("Family")){
return Color.rgb(160, 32, 240);
}
else if(color.equals("Fantasy")){
return Color.rgb(224, 255, 255);
}
else if(color.equals("Romance")){
return Color.rgb(255, 20, 147);
}
else if(color.equals("Short")){
return Color.GRAY;
}
else if(color.equals("Thriller")){
return Color.rgb(178, 34, 34);
}
return Color.WHITE;
}
}
| true | true | public void filter_points(String text, String genre, String rating)
{
text = text.trim();
if(text.length() > 0)
{
squares.clear();
List<Movie> movies;
movies = new ArrayList<Movie>();
for(Movie movie : canvasApp.data.getMovie()){
String g = movie.getGenre().get(0);
int r = movie.getRating();
if(genre.equals("All") && rating.equals("All")){
if(Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE).matcher(movie.getTitle()).find())
{
movies.add(movie);
}
}
else
if(genre.equals("All")){
if(r==Integer.valueOf(rating) && Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE).matcher(movie.getTitle()).find()){
movies.add(movie);
}
}
else if(rating.equals("All")){
if(g.equals(genre) && Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE).matcher(movie.getTitle()).find()){
movies.add(movie);
}
}
else if(g.equals(genre) && r==Integer.valueOf(rating)){
if(Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE).matcher(movie.getTitle()).find())
{
movies.add(movie);
}
}
}
init_from_data(movies);
}
}
| public void filter_points(String text, String genre, String rating)
{
text = text.trim();
if(text.length() > 1)
{
squares.clear();
List<Movie> movies;
movies = new ArrayList<Movie>();
for(Movie movie : canvasApp.data.getMovie()){
String g = movie.getGenre().get(0);
int r = movie.getRating();
if(genre.equals("All") && rating.equals("All")){
if(Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE).matcher(movie.getTitle()).find())
{
movies.add(movie);
}
}
else
if(genre.equals("All")){
if(r==Integer.valueOf(rating) && Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE).matcher(movie.getTitle()).find()){
movies.add(movie);
}
}
else if(rating.equals("All")){
if(g.equals(genre) && Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE).matcher(movie.getTitle()).find()){
movies.add(movie);
}
}
else if(g.equals(genre) && r==Integer.valueOf(rating)){
if(Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE).matcher(movie.getTitle()).find())
{
movies.add(movie);
}
}
}
init_from_data(movies);
}
}
|
diff --git a/sahi/src/com/redhat/qe/jon/sahi/tests/AlertTest.java b/sahi/src/com/redhat/qe/jon/sahi/tests/AlertTest.java
index bb7b51c7..8fba3f3e 100644
--- a/sahi/src/com/redhat/qe/jon/sahi/tests/AlertTest.java
+++ b/sahi/src/com/redhat/qe/jon/sahi/tests/AlertTest.java
@@ -1,304 +1,304 @@
package com.redhat.qe.jon.sahi.tests;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.testng.annotations.*;
import com.redhat.qe.auto.testng.Assert;
import com.redhat.qe.auto.testng.TestNGUtils;
import com.redhat.qe.jon.sahi.base.ComboBox;
import com.redhat.qe.jon.sahi.base.Common;
import com.redhat.qe.jon.sahi.base.SahiTestScript;
/**
* @author jkandasa (Jeeva Kandasamy)
* Aug 17, 2011
*/
public class AlertTest extends SahiTestScript{
private static Logger _logger = Logger.getLogger(AlertTest.class.getName());
public static String RESOURCE_NAME = "resourceName";
public static String ALERT_NAME = "alertName";
public static String ALERT_DESCRIPTION = "alertDescription";
public static String CONDITION_DROPDOWNS = "conditionDropDowns";
public static String CONDITION_TEXTBOX = "conditionTextbox";
public static String NOTIFICATION_TYPE = "notificationType";
public static String NOTIFICATION_DATA = "notificationData";
public void gotoAlertDefinationPage(String resourceName){
sahiTasks.link("Inventory").click();
String[] resourceType = resourceName.split("=");
if(resourceType.length>1){
sahiTasks.cell(resourceType[0].trim()).click();
sahiTasks.textbox("SearchPatternField").setValue(resourceType[1].trim());
sahiTasks.execute("_sahi._keyPress(_sahi._textbox('SearchPatternField'), 13);");
}else{
sahiTasks.cell("Servers").click();
}
sahiTasks.link(resourceType[1].trim()).click();
sahiTasks.cell("Alerts").click();
sahiTasks.xy(sahiTasks.cell("Definitions"), 3, 3).click();
}
public void selectConditionComboBoxes(String options){
/*String comboBoxIdentifier = "selectItemText";
int indexStartFrom = 3;
String[] optionArray = Common.getCommaToArray(options);
int totalComboBox = sahiTasks.div(comboBoxIdentifier).countSimilar();
_logger.finer("ComboBoxIdentifier Count: "+totalComboBox);
for(int i=0; i<totalComboBox; i++){
_logger.finer("ComboBoxIdentifier Name: "+comboBoxIdentifier+"["+i+"] --> "+sahiTasks.div(comboBoxIdentifier+"["+i+"]").getText());
}
if(optionArray.length > 2){
Wait.waitForElementDivExists(sahiTasks, comboBoxIdentifier+"["+(optionArray.length+indexStartFrom)+"]", 1000*10);
}
for(int i=0;i<optionArray.length;i++){
ComboBox.selectComboBoxDivRow(sahiTasks, comboBoxIdentifier+"["+(i+indexStartFrom)+"]", optionArray[i].trim());
}*/
String[] optionArray = Common.getCommaToArray(options);
for(String option : optionArray){
String[] optionTmp = option.split("-->");
ComboBox.selectComboBoxDivRow(sahiTasks, optionTmp[0].trim(), optionTmp[1].trim());
}
}
private void updateSystemUserNotification(String users){
String[] usersArray = Common.getCommaToArray(users);
for(String user: usersArray){
sahiTasks.byText(user.trim(), "nobr").doubleClick();
}
}
private int getNumberAlert(String alertName){
return sahiTasks.link(alertName).countSimilar();
}
//@Parameters({ "resourceName", "alertName", "alertDescription", "conditionDropDowns", "conditionTextBox", "notificationType", "notificationData" })
//@Test(groups = { "sanity","full","functional" })
public void createAlert(@Optional String resourceName, String alertName, @Optional String alertDescription, String conditionsDropDown, @Optional String conditionTextBox, String notificationType, String notificationData){
//Select Resource to define alert
if(resourceName != null){
gotoAlertDefinationPage(resourceName);
}
//Take current status
int similarAlert = getNumberAlert(alertName);
_logger.finer("pre-status of Alert definition ["+alertName+"]: "+similarAlert +" definition(s)");
//Define new alert name and Description(if any)
sahiTasks.cell("New").click();
sahiTasks.textbox(0).setValue(alertName);
if(alertDescription != null){
sahiTasks.textarea(0).setValue(alertDescription);
}
//Add conditions
sahiTasks.cell("Conditions").click();
sahiTasks.cell("Add").click();
selectConditionComboBoxes(conditionsDropDown);
if(conditionTextBox != null){
if(conditionTextBox.trim().length()>0){
HashMap<String, String> keyValueMap = Common.getKeyValueMap(conditionTextBox);
Set<String> keys = keyValueMap.keySet();
for(String key: keys){
sahiTasks.textbox(key).setValue(keyValueMap.get(key));
}
}
}
sahiTasks.cell("OK").click();
//Add notifications
sahiTasks.cell("Notifications").click();
sahiTasks.cell("Add[1]").click();
//Select Notification type
if(notificationType.equalsIgnoreCase("System Users")){
updateSystemUserNotification(notificationData);
}else{
_logger.log(Level.WARNING, "Undefined notification type: "+notificationType);
}
sahiTasks.cell("OK").click();
sahiTasks.xy(sahiTasks.cell("Save"), 3, 3).click();
sahiTasks.bold("Back to List").click();
//Check Creation Status
Assert.assertEquals(getNumberAlert(alertName)-similarAlert, 1, "Alert Definition: \""+alertName+"\"");
_logger.finer( "\""+alertName+"\" alert definition successfully created!");
}
//@Parameters({ "resourceName", "alertName", "alertDescription", "conditionDropDowns", "conditionTextBox", "notificationType", "notificationData" })
//@Test(groups = { "sanity","full","functional" })
public void checkAlertFired(@Optional String resourceName, String alertName, @Optional String alertDescription, String conditionsDropDown, @Optional String conditionTextBox, String notificationType, String notificationData){
//Select Resource to define alert
if(resourceName != null){
gotoAlertDefinationPage(resourceName);
}
//Take current status
int similarAlert = getNumberAlert(alertName);
_logger.finer("pre-status of Alert definition ["+alertName+"]: "+similarAlert +" definition(s)");
//Define new alert name and Description(if any)
sahiTasks.cell("New").click();
sahiTasks.textbox(0).setValue(alertName);
if(alertDescription != null){
sahiTasks.textarea(0).setValue(alertDescription);
}
//Add conditions
sahiTasks.cell("Conditions").click();
sahiTasks.cell("Add").click();
selectConditionComboBoxes(conditionsDropDown);
if(conditionTextBox != null){
if(conditionTextBox.trim().length()>0){
HashMap<String, String> keyValueMap = Common.getKeyValueMap(conditionTextBox);
Set<String> keys = keyValueMap.keySet();
for(String key: keys){
sahiTasks.textbox(key).setValue(keyValueMap.get(key));
}
}
}
sahiTasks.cell("OK").click();
//Add notifications
sahiTasks.cell("Notifications").click();
sahiTasks.cell("Add[1]").click();
//Select Notification type
if(notificationType.equalsIgnoreCase("System Users")){
updateSystemUserNotification(notificationData);
}else{
_logger.log(Level.WARNING, "Undefined notification type: "+notificationType);
}
sahiTasks.cell("OK").click();
sahiTasks.xy(sahiTasks.cell("Save"), 3, 3).click();
sahiTasks.bold("Back to List").click();
//Check Creation Status
Assert.assertEquals(getNumberAlert(alertName)-similarAlert, 1, "Alert Definition: \""+alertName+"\"");
_logger.finer( "\""+alertName+"\" alert definition successfully created!");
}
@Test (groups="alertTest", dataProvider="alertCreationData")
public void createAlert(Object alertDetail){
HashMap<String, String> alertDetails = (HashMap<String, String>)alertDetail;
createAlert(alertDetails.get(RESOURCE_NAME), alertDetails.get(ALERT_NAME), alertDetails.get(ALERT_DESCRIPTION), alertDetails.get(CONDITION_DROPDOWNS), alertDetails.get(CONDITION_TEXTBOX), alertDetails.get(NOTIFICATION_TYPE), alertDetails.get(NOTIFICATION_DATA));
}
@DataProvider(name="alertCreationData")
public Object[][] getAlertCreationData(){
ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent-Server Clock Difference");
map.put(ALERT_DESCRIPTION, "Generated by automation");
- map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->Agent-Server Clock Difference,< (Less than) --> < (Less than)");
+ map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->Agent-Server Clock Difference[1],< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=5000");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Avg Execution Time Commands Received Successfully");
map.put(ALERT_DESCRIPTION, "Generated by automation");
- map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->Avg Execution Time Commands Received Successfully,< (Less than) --> > (Greater Than)");
+ map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->Avg Execution Time Commands Received Successfully,< (Less than) --> > (Greater Than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=21");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Avg Execution Time Commands Sent Successfully");
map.put(ALERT_DESCRIPTION, "Generated by automation");
- map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->Avg Execution Time Commands Sent Successfully,< (Less than) --> > (Greater Than)");
+ map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->Avg Execution Time Commands Sent Successfully,< (Less than) --> > (Greater Than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=21");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - JVM Active Threads");
map.put(ALERT_DESCRIPTION, "Generated by automation");
- map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->JVM Active Threads,< (Less than) --> > (Greater Than)");
+ map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->JVM Active Threads,< (Less than) --> > (Greater Than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=35");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - JVM Free Memory");
map.put(ALERT_DESCRIPTION, "Generated by automation");
- map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->JVM Free Memory,< (Less than) --> < (Less than)");
+ map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->JVM Free Memory,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=20971520");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent Number Of Active Commands Being Sent");
map.put(ALERT_DESCRIPTION, "Generated by automation");
- map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->Number Of Active Commands Being Sent,< (Less than) --> < (Less than)");
+ map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->Number Of Active Commands Being Sent,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=500");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Number of restarts");
map.put(ALERT_DESCRIPTION, "Generated by automation");
- map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->Number of Agent Restarts,< (Less than) --> < (Less than)");
+ map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->Number of Agent Restarts,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=50");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Number of Commands In Queue");
map.put(ALERT_DESCRIPTION, "Generated by automation");
- map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->Number of Commands In Queue,< (Less than) --> < (Less than)");
+ map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->Number of Commands In Queue,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=500");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Number of Commands Received Successfully");
map.put(ALERT_DESCRIPTION, "Generated by automation");
- map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->Number of Commands Received Successfully,< (Less than) --> < (Less than)");
+ map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->Number of Commands Received Successfully,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=500");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
return TestNGUtils.convertListTo2dArray(data);
}
}
| false | true | public Object[][] getAlertCreationData(){
ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent-Server Clock Difference");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->Agent-Server Clock Difference,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=5000");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Avg Execution Time Commands Received Successfully");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->Avg Execution Time Commands Received Successfully,< (Less than) --> > (Greater Than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=21");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Avg Execution Time Commands Sent Successfully");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->Avg Execution Time Commands Sent Successfully,< (Less than) --> > (Greater Than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=21");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - JVM Active Threads");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->JVM Active Threads,< (Less than) --> > (Greater Than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=35");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - JVM Free Memory");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->JVM Free Memory,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=20971520");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent Number Of Active Commands Being Sent");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->Number Of Active Commands Being Sent,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=500");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Number of restarts");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->Number of Agent Restarts,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=50");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Number of Commands In Queue");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->Number of Commands In Queue,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=500");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Number of Commands Received Successfully");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference[1]-->Number of Commands Received Successfully,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=500");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
return TestNGUtils.convertListTo2dArray(data);
}
| public Object[][] getAlertCreationData(){
ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent-Server Clock Difference");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->Agent-Server Clock Difference[1],< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=5000");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Avg Execution Time Commands Received Successfully");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->Avg Execution Time Commands Received Successfully,< (Less than) --> > (Greater Than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=21");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Avg Execution Time Commands Sent Successfully");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->Avg Execution Time Commands Sent Successfully,< (Less than) --> > (Greater Than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=21");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - JVM Active Threads");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->JVM Active Threads,< (Less than) --> > (Greater Than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=35");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - JVM Free Memory");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->JVM Free Memory,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=20971520");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent Number Of Active Commands Being Sent");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->Number Of Active Commands Being Sent,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=500");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Number of restarts");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->Number of Agent Restarts,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=50");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Number of Commands In Queue");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->Number of Commands In Queue,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=500");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
map.put(RESOURCE_NAME, "Servers=RHQ Agent");
map.put(ALERT_NAME, "RHQ Agent - Number of Commands Received Successfully");
map.put(ALERT_DESCRIPTION, "Generated by automation");
map.put(CONDITION_DROPDOWNS, "Availability Change-->Measurement Absolute Value Threshold,Agent-Server Clock Difference-->Number of Commands Received Successfully,< (Less than) --> < (Less than)");
map.put(CONDITION_TEXTBOX, "metricAbsoluteValue=500");
map.put(NOTIFICATION_TYPE, "System Users");
map.put(NOTIFICATION_DATA, "rhqadmin");
data.add((HashMap<String, String>) map.clone());
map.clear();
return TestNGUtils.convertListTo2dArray(data);
}
|
diff --git a/dspace/src/org/dspace/workflow/WorkflowManager.java b/dspace/src/org/dspace/workflow/WorkflowManager.java
index b67a7721a..a78ad12c9 100644
--- a/dspace/src/org/dspace/workflow/WorkflowManager.java
+++ b/dspace/src/org/dspace/workflow/WorkflowManager.java
@@ -1,935 +1,935 @@
/*
* WorkflowManager
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2001, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.workflow;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.sql.SQLException;
import javax.mail.MessagingException;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.Email;
import org.dspace.core.LogManager;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Collection;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.InstallItem;
import org.dspace.content.WorkspaceItem;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
import org.dspace.handle.HandleManager;
import org.dspace.search.DSIndexer;
import org.dspace.storage.rdbms.DatabaseManager;
import org.dspace.storage.rdbms.TableRow;
import org.dspace.storage.rdbms.TableRowIterator;
//import java.sql.*;
//import org.dspace.core.*;
//import org.dspace.db.*;
//import org.dspace.db.generated.*;
//import org.dspace.util.handles.HandleManager;
//import org.dspace.jsptags.DateTag;
//import org.dspace.servlets.SubmitServlet;
//import org.dspace.util.DSpaceDate;
//import org.dspace.util.email.*;
/*
issues
abort has to go through reject - they should share code
authorization isn't done
should do log4j for email errors
*/
/*
* Notes:
Table definitions:
TABLE PersonalWorkspace
personal_workspace_id INTEGER PRIMARY KEY,
item_id INTEGER REFERENCES Item(item_id),
collection_id INTEGER REFERENCES Collection(collection_id)
TABLE WorkflowItem
workflow_id INTEGER PRIMARY KEY,
item_id INTEGER REFERENCES Item(item_id) UNIQUE,
collection_id INTEGER REFERENCES Collection(collection_id)
state INTEGER -- state of workflow
Determining item status from the database:
When an item has not been submitted yet, it is in the user's
personal workspace (there is a row in PersonalWorkspace pointing
to it.)
When an item is submitted and is somewhere in a workflow, it has
a row in the WorkflowItem table pointing to it. The state of the
workflow can be determined by looking at WorkflowItem.getState()
When a submission is complete, the WorkflowItem pointing to the item
is destroyed and SubmitServlet.insertItem() is called, which hooks
the item up to the archive.
Notification:
When an item enters a state that requires notification, (WFSTATE_REVIEWPOOL,
WFSTATE_ADMINPOOL, WFSTATE_EDITPOOL,) the workflow needs to notify
the appropriate groups that they have a pending task to claim.
Revealing lists of approvers, editors, and reviewers. A method could
be added to do this, but it isn't strictly necessary.
(say public List getStateEPeople( WorkflowItem wi, int state ) could
return people affected by the item's current state.
*/
public class WorkflowManager
{
/** log4j category */
private static Logger log = Logger.getLogger(WorkflowManager.class);
// states to store in WorkflowItem for the GUI to report on
// fits our current set of workflow states (stored in WorkflowItem.state)
public static final int WFSTATE_SUBMIT = 0; // hmm, probably don't need
public static final int WFSTATE_REVIEWPOOL = 1; // waiting for a reviewer to claim it
public static final int WFSTATE_REVIEW = 2; // task - reviewer has claimed it
public static final int WFSTATE_ADMINPOOL = 3; // waiting for an admin to claim it
public static final int WFSTATE_ADMIN = 4; // task - admin has claimed item
public static final int WFSTATE_EDITPOOL = 5; // waiting for an editor to claim it
public static final int WFSTATE_EDIT = 6; // task - editor has claimed the item
public static final int WFSTATE_ARCHIVE = 7; // probably don't need this one either
/** startWorkflow() begins a workflow - in a single transaction
* do away with the PersonalWorkspace entry and turn it into
* a WorkflowItem.
*
* @param c Context
* @param pw The PersonalWorkspace to convert to a workflow item
* @return The resulting workflow item
*/
public static WorkflowItem start(Context c,WorkspaceItem wsi)
throws SQLException, AuthorizeException, IOException
{
// FIXME Check auth
Item myitem = wsi.getItem();
Collection collection = wsi.getCollection();
log.info(LogManager.getHeader(c,
"start_workflow",
"workspace_item_id=" + wsi.getID() +
"item_id=" + myitem.getID() +
"collection_id=" + collection.getID()));
// record the start of the workflow w/provenance message
recordStart(c, myitem);
// create the WorkflowItem
TableRow row = DatabaseManager.create(c, "workflowitem");
row.setColumn( "item_id", myitem.getID() );
row.setColumn( "collection_id", wsi.getCollection().getID() );
WorkflowItem wfi = new WorkflowItem(c, row);
wfi.setMultipleFiles ( wsi.hasMultipleFiles() );
wfi.setMultipleTitles ( wsi.hasMultipleTitles() );
wfi.setPublishedBefore( wsi.isPublishedBefore() );
// remove the WorkspaceItem
wsi.delete();
// now get the worflow started
doState(c, wfi, WFSTATE_REVIEWPOOL, null);
// Return the workflow item
return wfi;
}
/** getOwnedTasks() returns a List of WorkflowItems containing
* the tasks claimed and owned by an EPerson. The GUI displays
* this info on the MyDSpace page.
* @param e The EPerson we want to fetch owned tasks for.
*/
public static List getOwnedTasks(Context c, EPerson e)
throws java.sql.SQLException
{
ArrayList mylist = new ArrayList();
String myquery = "SELECT * FROM WorkflowItem WHERE owner="
+ e.getID();
TableRowIterator tri = DatabaseManager.query( c, "workflowitem", myquery );
while (tri.hasNext())
{
mylist.add( new WorkflowItem( c, tri.next() ) );
}
return mylist;
}
/** getPooledTasks() returns a List of WorkflowItems an EPerson could claim
* (as a reviewer, etc.) for display on a user's MyDSpace page.
* @param e The Eperson we want to fetch the pooled tasks for.
*/
public static List getPooledTasks(Context c, EPerson e)
throws SQLException
{
ArrayList mylist = new ArrayList();
String myquery = "SELECT workflowitem.* FROM workflowitem, TaskListItem"
+ " WHERE tasklistitem.eperson_id=" + e.getID()
+ " AND tasklistitem.workflow_id=workflowitem.workflow_id";
TableRowIterator tri = DatabaseManager.query(c, "tasklistitem", myquery);
while( tri.hasNext() )
{
mylist.add( new WorkflowItem( c, tri.next() ) );
}
return mylist;
}
/** claim() claims a workflow task for an EPerson
* @param wi WorkflowItem to do the claim on
* @param e The EPerson doing the claim
*/
// claim an item and become it's owner
public static void claim(Context c,WorkflowItem wi, EPerson e)
throws SQLException, IOException, AuthorizeException
{
int taskstate = wi.getState();
switch (taskstate)
{
case WFSTATE_REVIEWPOOL:
// authorize DSpaceActions.SUBMIT_REVIEW
doState(c, wi, WFSTATE_REVIEW, e);
break;
case WFSTATE_ADMINPOOL:
// authorize DSpaceActions.SUBMIT_ADMIN
doState(c, wi, WFSTATE_ADMIN, e);
break;
case WFSTATE_EDITPOOL:
// authorize DSpaceActions.SUBMIT_EDIT
doState(c, wi, WFSTATE_EDIT, e);
break;
// if we got here, we weren't pooled... error?
// FIXME - log the error?
}
}
/** approveAction() sends an item forward in the workflow (reviewers, approvers, and
* editors all do an 'approve' to move the item forward)
* if the item arrives at the submit state, then remove the WorkflowItem
* and call SubmitServlet.insertItem() to put it in the archive,
* and email notify the submitter of a successful submission
*
* @param c Context
* @param wi WorkflowItem do do the approval on
* @param e EPerson doing the approval
*/
public static void advance(Context c,WorkflowItem wi, EPerson e)
throws SQLException, IOException, AuthorizeException
{
int taskstate = wi.getState();
switch (taskstate)
{
case WFSTATE_REVIEW:
// authorize DSpaceActions.SUBMIT_REVIEW
// Record provenance
recordApproval(c, wi, e);
doState(c, wi, WFSTATE_ADMINPOOL, e);
break;
case WFSTATE_ADMIN:
// authorize DSpaceActions.SUBMIT_ADMIN
// Record provenance
recordApproval(c, wi, e);
doState(c, wi, WFSTATE_EDITPOOL, e);
break;
case WFSTATE_EDIT:
// authorize DSpaceActions.SUBMIT_EDIT
// We don't record approval for editors, since they can't reject,
// and thus didn't actually make a decision
doState(c, wi, WFSTATE_ARCHIVE, e);
break;
// error handling? shouldn't get here
}
}
/** unclaim() returns an owned task/item to the pool
* @param c Context
* @param wi WorkflowItem to operate on
* @param e EPerson doing the operation
*/
// return task to pool
public static void unclaim(Context c,WorkflowItem wi, EPerson e)
throws SQLException, IOException, AuthorizeException
{
int taskstate = wi.getState();
switch( taskstate )
{
case WFSTATE_REVIEW:
// authorize DSpaceActions.REVIEW
doState(c, wi, WFSTATE_REVIEWPOOL, e);
break;
case WFSTATE_ADMIN:
// authorize DSpaceActions.APPROVE
doState(c, wi, WFSTATE_ADMINPOOL, e);
break;
case WFSTATE_EDIT:
// authorize DSpaceActions.EDIT
doState(c, wi, WFSTATE_EDITPOOL, e);
break;
// error handling? shouldn't get here
// FIXME - what to do with error - log it?
}
}
/** abort() aborts a workflow, completely deleting it (administrator do this)
* (it will basically do a reject from any state - the item
* ends up back in the user's PersonalWorkspace
*
* @param c Context
* @param wi WorkflowItem to operate on
* @param e EPerson doing the operation
*/
// abort workflow - admin to delete all
public static void abort(Context c,WorkflowItem wi, EPerson e)
throws SQLException, AuthorizeException
{
// authorize a DSpaceActions.ABORT
// stop workflow regardless of its state
// do a reject
reject(c, wi, e, "This item's submission has been aborted by an admin.");
}
private static void doState(Context c,WorkflowItem wi, int newstate, EPerson newowner)
throws SQLException, IOException, AuthorizeException
{
Collection mycollection = wi.getCollection();
Group mygroup = null;
wi.setState(newstate);
// wi.update();
switch (newstate)
{
case WFSTATE_REVIEWPOOL:
// any reviewers?
// if so, add them to the tasklist
wi.setOwner( null );
//wi.update();
// get reviewers (group 1 )
mygroup = mycollection.getWorkflowGroup( 1 );
if (mygroup != null )
{
// there were reviewers, change the state
// and add them to the list
createTasks(c, wi, mygroup);
wi.update();
// email notification
notifyGroupOfTask(c, mygroup, wi);
}
else
{
// no reviewers, skip ahead
doState(c, wi, WFSTATE_ADMINPOOL, null);
}
break;
case WFSTATE_REVIEW:
// remove reviewers from tasklist
// assign owner
deleteTasks(c, wi);
wi.setOwner(newowner);
//wi.update();
break;
case WFSTATE_ADMINPOOL:
// clear owner
// any approvers?
// if so, add them to tasklist
// if not, skip to next state
wi.setOwner( null );
//wi.update();
// get approvers (group 2)
mygroup = mycollection.getWorkflowGroup( 2 );
if( mygroup != null )
{
// there were approvers, change the state
// timestamp, and add them to the list
createTasks(c, wi, mygroup );
//wi.update();
// email notification
notifyGroupOfTask(c, mygroup, wi);
}
else
{
// no reviewers, skip ahead
doState(c, wi, WFSTATE_EDITPOOL, null);
}
break;
case WFSTATE_ADMIN:
// remove admins from tasklist
// assign owner
deleteTasks(c, wi);
wi.setOwner(newowner);
//wi.update();
break;
case WFSTATE_EDITPOOL:
// any editors?
// if so, add them to tasklist
wi.setOwner( null );
//wi.update();
mygroup = mycollection.getWorkflowGroup( 3 );
if( mygroup != null )
{
// there were editors, change the state
// timestamp, and add them to the list
createTasks(c, wi, mygroup);
//wi.update();
// email notification
notifyGroupOfTask(c, mygroup, wi);
}
else
{
// no editors, skip ahead
doState(c, wi, WFSTATE_ARCHIVE, newowner);
}
break;
case WFSTATE_EDIT:
// remove editors from tasklist
// assign owner
deleteTasks(c, wi);
wi.setOwner(newowner);
//wi.update();
break;
case WFSTATE_ARCHIVE:
// put in archive in one transaction
// int itemid = wi.getItemId();
// Collection col =
// wi.getCollectionFromCollectionId();
try
{
// notify that it's been archived
//notifyOfArchive( wi );
// remove workflow tasks
deleteTasks(c, wi);
mycollection = wi.getCollection();
Item myitem = archive(c, wi);
// now email notification
notifyOfArchive(c, myitem, mycollection);
// index the item
- DSIndexer.indexItem(c, myitem);
+// DSIndexer.indexItem(c, myitem);
// SubmitServlet.installItem(connection, wi);
// delete workflow - done in installItem
// wi.delete( connection );
// wi = null;
}
catch(IOException e)
{
// indexer causes this
throw e;
}
catch (SQLException e)
{
// problem starting workflow - roll back
// connection.rollback();
throw e;
}
break;
}
if (wi != null) wi.update();
}
/**
* Commit the contained item to the main archive. The item is
* associated with the relevant collection, added to the search index,
* and any other tasks such as assigning dates are performed.
*
* @return the fully archived item.
*/
public static Item archive(Context c, WorkflowItem wfi)
throws SQLException, IOException, AuthorizeException
{
// FIXME: Check auth
Item item = wfi.getItem();
Collection collection = wfi.getCollection();
log.info(LogManager.getHeader(c,
"archive_item",
"workflow_item_id=" + wfi.getID() + "item_id=" + item.getID() +
"collection_id=" + collection.getID()));
InstallItem.installItem(c, wfi);
// Remove workflow item
// wfi.delete(c);
// Log the event
log.info(LogManager.getHeader(
c,
"install_item",
"workflow_id=" + wfi.getID() + ", item_id=" + item.getID() +
"handle=FIXME"));
return item;
}
/**
* notify the submitter that the item is archived
*/
private static void notifyOfArchive(Context c, Item i, Collection coll)
{
try
{
// Get the item handle to email to user
String handle = HandleManager.findHandle(c, i);
// Get title
DCValue titles[] = i.getDC("title", null, Item.ANY);
String title = "Untitled";
if (titles.length > 0) title = titles[0].value;
// Get submitter
EPerson ep = i.getSubmitter();
Email email = ConfigurationManager.getEmail( "submit_archive" );
email.addRecipient( ep.getEmail() );
email.addArgument( title );
email.addArgument( coll.getMetadata("name") );
email.addArgument( handle );
email.send();
}
catch( Exception e )
{
//FIXME: should log this failed attempt at notification
}
}
/**
* Return the workflow item to the workspace of the submitter.
* The workflow item is removed, and a workspace item created.
*
* @param c Context
* @param wfi WorkflowItem to be 'dismantled'
* @return the workspace item
*/
private static WorkspaceItem returnToWorkspace(Context c, WorkflowItem wfi)
throws SQLException, AuthorizeException
{
Item myitem = wfi.getItem();
Collection mycollection = wfi.getCollection();
// FIXME: How should this interact with the workflow system?
// FIXME: Remove license
// FIXME: Provenance statement?
// Remove accession date
myitem.clearDC("date", "accessioned", Item.ANY);
myitem.update();
// Create the new workspace item row
TableRow row = DatabaseManager.create(c, "workspaceitem");
row.setColumn("item_id", myitem.getID());
row.setColumn("collection_id", mycollection.getID());
DatabaseManager.update(c, row);
int wsi_id = row.getIntColumn("workspace_item_id");
WorkspaceItem wi = WorkspaceItem.find(c, wsi_id);
wi.setMultipleFiles(wfi.hasMultipleFiles());
wi.setMultipleTitles(wfi.hasMultipleTitles());
wi.setPublishedBefore(wfi.isPublishedBefore());
wi.update();
log.info(LogManager.getHeader(c,
"return_to_workspace",
"workflow_item_id=" + wfi.getID() + "workspace_item_id=" + wi.getID()));
// Now remove the workflow object manually from the database
DatabaseManager.updateQuery(c,
"DELETE FROM WorkflowItem WHERE workflow_id=" +
wfi.getID() );
//DatabaseManager.delete(c, wfRow);
return wi;
}
/** rejects an item - rejection means undoing
* a submit - WorkspaceItem is created, and the WorkflowItem
* is removed, user is emailed rejection_message.
*
* @param c Context
* @param wi WorkflowItem to operate on
* @param e EPerson doing the operation
* @param rejection_message message to email to user
*/
public static void reject(Context c,WorkflowItem wi, EPerson e, String rejection_message)
throws SQLException, AuthorizeException
{
// authorize a DSpaceActions.REJECT
// stop workflow
deleteTasks(c, wi);
// notify that it's been rejected
notifyOfReject(c, wi, e, rejection_message);
// convert into personal workspace
WorkspaceItem wsi = returnToWorkspace(c, wi);
}
// creates workflow tasklist entries for a workflow
// from a given eperson group
private static void createTasks(Context c, WorkflowItem wi, Group eg)
throws SQLException
{
// get a list of epeople
EPerson [] epa = eg.getMembers();
// create a tasklist entry for each eperson
for( int i=0; i<epa.length; i++ )
{
// can we get away without creating a tasklistitem class?
// do we want to?
TableRow tr = DatabaseManager.create(c, "tasklistitem");
tr.setColumn( "eperson_id", epa[i].getID() );
tr.setColumn( "workflow_id", wi.getID() );
DatabaseManager.update( c, tr );
}
}
// deletes all tasks associated with a workflowitem
private static void deleteTasks(Context c,WorkflowItem wi)
throws SQLException
{
String myrequest = "DELETE FROM TaskListItem WHERE workflow_id="
+ wi.getID();
DatabaseManager.updateQuery( c, myrequest );
}
private static void notifyGroupOfTask(Context c, Group mygroup, WorkflowItem wi)
throws SQLException
{
try
{
// Get the item title
String title = getItemTitle(wi);
// Get the submitter's name
String submitter = getSubmitterName(wi);
// Get the collection
Collection coll = wi.getCollection();
String message = "";
switch (wi.getState())
{
case WFSTATE_REVIEWPOOL:
message = "It requires reviewing.";
break;
case WFSTATE_ADMINPOOL:
message = "The submission must be checked before inclusion in the archive.";
break;
case WFSTATE_EDITPOOL:
message = "The metadata needs to be checked to ensure compliance with the " +
"collection's standards, and edited if necessary.";
break;
}
Email email = ConfigurationManager.getEmail("submit_task");
email.addArgument( title );
email.addArgument( coll.getMetadata("name") );
email.addArgument( submitter );
email.addArgument( message );
email.addArgument( getMyDSpaceLink() );
emailGroup(c, mygroup, email);
}
catch( Exception e )
{
// FIXME: should log failed notification
}
}
/**
* Add the members of a group to the recipeients of an email, and send it
* @param c Context
* @param mygroup Group to get members from
* @param email Email object containing the message
*/
private static void emailGroup(Context c, Group mygroup, Email email )
throws SQLException, MessagingException
{
// send message to each member of the group
EPerson [] epa = mygroup.getMembers();
for( int i = 0; i < epa.length; i++ )
{
email.addRecipient( epa[i].getEmail() );
}
email.send();
}
private static String getMyDSpaceLink()
{
return ConfigurationManager.getProperty( "dspace.url" ) + "mydspace";
}
private static void notifyOfReject(Context c,WorkflowItem wi, EPerson e, String reason)
{
try
{
// Get the item title
String title = getItemTitle(wi);
// Get the collection
Collection coll = wi.getCollection();
// Get rejector's name
String rejector = getEPersonName(e);
Email email = ConfigurationManager.getEmail("submit_reject");
email.addRecipient( getSubmitterEPerson(wi).getEmail() );
email.addArgument( title );
email.addArgument( coll.getMetadata("name") );
email.addArgument( rejector );
email.addArgument( reason );
email.addArgument( getMyDSpaceLink() );
email.send();
}
catch( Exception ex )
{
// FIXME: should log this vital email error
}
}
// FIXME - still needed?
private static EPerson getSubmitterEPerson(WorkflowItem wi)
throws SQLException
{
EPerson e = wi.getSubmitter();
return e;
}
private static String getItemTitle(WorkflowItem wi)
throws SQLException
{
Item myitem = wi.getItem();
DCValue titles[] = myitem.getDC("title", null, Item.ANY);
// only return the first element, or "Untitled"
if( titles.length > 0 )
return titles[0].value;
else
return "Untitled";
}
private static String getSubmitterName(WorkflowItem wi)
throws SQLException
{
EPerson e = wi.getSubmitter();
return getEPersonName( e );
}
private static String getEPersonName(EPerson e)
throws SQLException
{
String submitter = e.getFullName();
submitter = submitter + "(" + e.getEmail() + ")";
return submitter;
}
// Record approval provenance statement
private static void recordApproval(Context c,WorkflowItem wi, EPerson e)
throws SQLException, AuthorizeException
{
Item item = wi.getItem();
// Get user's name + email address
String usersName = getEPersonName( e );
// Get current date
String now = DCDate.getCurrent().toString();
// Here's what happened
String provDescription = "Approved for entry into archive by " + usersName +
" on " + now + " (GMT)";
// add bitstream descriptions (name, size, checksums)
provDescription += InstallItem.getBitstreamProvenanceMessage(item);
// Add to item as a DC field
item.addDC("description", "provenance", null, provDescription);
item.update();
}
// Create workflow start provenance message
private static void recordStart(Context c, Item myitem)
throws SQLException, AuthorizeException
{
// Get non-internal format bitstreams
Bitstream[] bitstreams = myitem.getNonInternalBitstreams();
// get date
DCDate now = DCDate.getCurrent();
// Create provenance description
String provmessage = "";
if( myitem.getSubmitter() != null )
{
provmessage = "Submitted by" +
myitem.getSubmitter().getFullName() + " (" +
myitem.getSubmitter().getEmail() + "). DSpace accession date:" +
now.toString() + "\n Submission has " + bitstreams.length +
" bitstreams:\n";
}
else // null submitter
{
provmessage = "Submitted by unknown (probably automated)" +
" DSpace accession date:" +
now.toString() + "\n Submission has " + bitstreams.length +
" bitstreams:\n";
}
// add sizes and checksums of bitstreams
provmessage += InstallItem.getBitstreamProvenanceMessage(myitem);
// Add message to the DC
myitem.addDC("description", "provenance", "en", provmessage);
myitem.update();
}
}
| true | true | private static void doState(Context c,WorkflowItem wi, int newstate, EPerson newowner)
throws SQLException, IOException, AuthorizeException
{
Collection mycollection = wi.getCollection();
Group mygroup = null;
wi.setState(newstate);
// wi.update();
switch (newstate)
{
case WFSTATE_REVIEWPOOL:
// any reviewers?
// if so, add them to the tasklist
wi.setOwner( null );
//wi.update();
// get reviewers (group 1 )
mygroup = mycollection.getWorkflowGroup( 1 );
if (mygroup != null )
{
// there were reviewers, change the state
// and add them to the list
createTasks(c, wi, mygroup);
wi.update();
// email notification
notifyGroupOfTask(c, mygroup, wi);
}
else
{
// no reviewers, skip ahead
doState(c, wi, WFSTATE_ADMINPOOL, null);
}
break;
case WFSTATE_REVIEW:
// remove reviewers from tasklist
// assign owner
deleteTasks(c, wi);
wi.setOwner(newowner);
//wi.update();
break;
case WFSTATE_ADMINPOOL:
// clear owner
// any approvers?
// if so, add them to tasklist
// if not, skip to next state
wi.setOwner( null );
//wi.update();
// get approvers (group 2)
mygroup = mycollection.getWorkflowGroup( 2 );
if( mygroup != null )
{
// there were approvers, change the state
// timestamp, and add them to the list
createTasks(c, wi, mygroup );
//wi.update();
// email notification
notifyGroupOfTask(c, mygroup, wi);
}
else
{
// no reviewers, skip ahead
doState(c, wi, WFSTATE_EDITPOOL, null);
}
break;
case WFSTATE_ADMIN:
// remove admins from tasklist
// assign owner
deleteTasks(c, wi);
wi.setOwner(newowner);
//wi.update();
break;
case WFSTATE_EDITPOOL:
// any editors?
// if so, add them to tasklist
wi.setOwner( null );
//wi.update();
mygroup = mycollection.getWorkflowGroup( 3 );
if( mygroup != null )
{
// there were editors, change the state
// timestamp, and add them to the list
createTasks(c, wi, mygroup);
//wi.update();
// email notification
notifyGroupOfTask(c, mygroup, wi);
}
else
{
// no editors, skip ahead
doState(c, wi, WFSTATE_ARCHIVE, newowner);
}
break;
case WFSTATE_EDIT:
// remove editors from tasklist
// assign owner
deleteTasks(c, wi);
wi.setOwner(newowner);
//wi.update();
break;
case WFSTATE_ARCHIVE:
// put in archive in one transaction
// int itemid = wi.getItemId();
// Collection col =
// wi.getCollectionFromCollectionId();
try
{
// notify that it's been archived
//notifyOfArchive( wi );
// remove workflow tasks
deleteTasks(c, wi);
mycollection = wi.getCollection();
Item myitem = archive(c, wi);
// now email notification
notifyOfArchive(c, myitem, mycollection);
// index the item
DSIndexer.indexItem(c, myitem);
// SubmitServlet.installItem(connection, wi);
// delete workflow - done in installItem
// wi.delete( connection );
// wi = null;
}
catch(IOException e)
{
// indexer causes this
throw e;
}
catch (SQLException e)
{
// problem starting workflow - roll back
// connection.rollback();
throw e;
}
break;
}
if (wi != null) wi.update();
}
| private static void doState(Context c,WorkflowItem wi, int newstate, EPerson newowner)
throws SQLException, IOException, AuthorizeException
{
Collection mycollection = wi.getCollection();
Group mygroup = null;
wi.setState(newstate);
// wi.update();
switch (newstate)
{
case WFSTATE_REVIEWPOOL:
// any reviewers?
// if so, add them to the tasklist
wi.setOwner( null );
//wi.update();
// get reviewers (group 1 )
mygroup = mycollection.getWorkflowGroup( 1 );
if (mygroup != null )
{
// there were reviewers, change the state
// and add them to the list
createTasks(c, wi, mygroup);
wi.update();
// email notification
notifyGroupOfTask(c, mygroup, wi);
}
else
{
// no reviewers, skip ahead
doState(c, wi, WFSTATE_ADMINPOOL, null);
}
break;
case WFSTATE_REVIEW:
// remove reviewers from tasklist
// assign owner
deleteTasks(c, wi);
wi.setOwner(newowner);
//wi.update();
break;
case WFSTATE_ADMINPOOL:
// clear owner
// any approvers?
// if so, add them to tasklist
// if not, skip to next state
wi.setOwner( null );
//wi.update();
// get approvers (group 2)
mygroup = mycollection.getWorkflowGroup( 2 );
if( mygroup != null )
{
// there were approvers, change the state
// timestamp, and add them to the list
createTasks(c, wi, mygroup );
//wi.update();
// email notification
notifyGroupOfTask(c, mygroup, wi);
}
else
{
// no reviewers, skip ahead
doState(c, wi, WFSTATE_EDITPOOL, null);
}
break;
case WFSTATE_ADMIN:
// remove admins from tasklist
// assign owner
deleteTasks(c, wi);
wi.setOwner(newowner);
//wi.update();
break;
case WFSTATE_EDITPOOL:
// any editors?
// if so, add them to tasklist
wi.setOwner( null );
//wi.update();
mygroup = mycollection.getWorkflowGroup( 3 );
if( mygroup != null )
{
// there were editors, change the state
// timestamp, and add them to the list
createTasks(c, wi, mygroup);
//wi.update();
// email notification
notifyGroupOfTask(c, mygroup, wi);
}
else
{
// no editors, skip ahead
doState(c, wi, WFSTATE_ARCHIVE, newowner);
}
break;
case WFSTATE_EDIT:
// remove editors from tasklist
// assign owner
deleteTasks(c, wi);
wi.setOwner(newowner);
//wi.update();
break;
case WFSTATE_ARCHIVE:
// put in archive in one transaction
// int itemid = wi.getItemId();
// Collection col =
// wi.getCollectionFromCollectionId();
try
{
// notify that it's been archived
//notifyOfArchive( wi );
// remove workflow tasks
deleteTasks(c, wi);
mycollection = wi.getCollection();
Item myitem = archive(c, wi);
// now email notification
notifyOfArchive(c, myitem, mycollection);
// index the item
// DSIndexer.indexItem(c, myitem);
// SubmitServlet.installItem(connection, wi);
// delete workflow - done in installItem
// wi.delete( connection );
// wi = null;
}
catch(IOException e)
{
// indexer causes this
throw e;
}
catch (SQLException e)
{
// problem starting workflow - roll back
// connection.rollback();
throw e;
}
break;
}
if (wi != null) wi.update();
}
|
diff --git a/src/cytoscape/actions/ZoomSelectedAction.java b/src/cytoscape/actions/ZoomSelectedAction.java
index 7d0860401..d36bc9c38 100644
--- a/src/cytoscape/actions/ZoomSelectedAction.java
+++ b/src/cytoscape/actions/ZoomSelectedAction.java
@@ -1,77 +1,82 @@
//-------------------------------------------------------------------------
// $Revision$
// $Date$
// $Author$
//-------------------------------------------------------------------------
package cytoscape.actions;
//-------------------------------------------------------------------------
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import java.awt.geom.Rectangle2D;
import edu.umd.cs.piccolo.util.PBounds;
import edu.umd.cs.piccolo.activities.PTransformActivity;
import java.util.List;
import java.util.Iterator;
import giny.view.*;
import cytoscape.giny.*;
import cytoscape.Cytoscape;
import cytoscape.util.CytoscapeAction;
import cytoscape.view.CyNetworkView;
//-------------------------------------------------------------------------
public class ZoomSelectedAction extends CytoscapeAction {
public ZoomSelectedAction () {
super();
}
public void actionPerformed(ActionEvent e) {
zoomSelected();
}
public static void zoomSelected () {
CyNetworkView view = Cytoscape.getCurrentNetworkView();
List selected_nodes = view.getSelectedNodes();
if ( selected_nodes.size() == 0 ) {return;}
Iterator selected_nodes_iterator = selected_nodes.iterator();
double bigX;
double bigY;
double smallX;
double smallY;
double W;
double H;
NodeView first = ( NodeView )selected_nodes_iterator.next();
bigX = first.getXPosition();
smallX = bigX;
bigY = first.getYPosition();
smallY = bigY;
while ( selected_nodes_iterator.hasNext() ) {
NodeView nv = ( NodeView )selected_nodes_iterator.next();
double x = nv.getXPosition();
double y = nv.getYPosition();
if ( x > bigX ) {
bigX = x;
} else if ( x < smallX ) {
smallX = x;
}
if ( y > bigY ) {
bigY = y;
} else if ( y < smallY ) {
smallY = y;
}
}
- PBounds zoomToBounds = new PBounds( smallX , smallY , ( bigX - smallX + 100 ), ( bigY - smallY + 100 ) );
+ PBounds zoomToBounds;
+ if (selected_nodes.size() == 1) {
+ zoomToBounds = new PBounds( smallX - 100 , smallY - 100 , ( bigX - smallX + 200 ), ( bigY - smallY + 200 ) );
+ } else {
+ zoomToBounds = new PBounds( smallX , smallY , ( bigX - smallX + 100 ), ( bigY - smallY + 100 ) );
+ }
PTransformActivity activity = ( ( PhoebeNetworkView )view).getCanvas().getCamera().animateViewToCenterBounds( zoomToBounds, true, 500 );
}
}
| true | true | public static void zoomSelected () {
CyNetworkView view = Cytoscape.getCurrentNetworkView();
List selected_nodes = view.getSelectedNodes();
if ( selected_nodes.size() == 0 ) {return;}
Iterator selected_nodes_iterator = selected_nodes.iterator();
double bigX;
double bigY;
double smallX;
double smallY;
double W;
double H;
NodeView first = ( NodeView )selected_nodes_iterator.next();
bigX = first.getXPosition();
smallX = bigX;
bigY = first.getYPosition();
smallY = bigY;
while ( selected_nodes_iterator.hasNext() ) {
NodeView nv = ( NodeView )selected_nodes_iterator.next();
double x = nv.getXPosition();
double y = nv.getYPosition();
if ( x > bigX ) {
bigX = x;
} else if ( x < smallX ) {
smallX = x;
}
if ( y > bigY ) {
bigY = y;
} else if ( y < smallY ) {
smallY = y;
}
}
PBounds zoomToBounds = new PBounds( smallX , smallY , ( bigX - smallX + 100 ), ( bigY - smallY + 100 ) );
PTransformActivity activity = ( ( PhoebeNetworkView )view).getCanvas().getCamera().animateViewToCenterBounds( zoomToBounds, true, 500 );
}
| public static void zoomSelected () {
CyNetworkView view = Cytoscape.getCurrentNetworkView();
List selected_nodes = view.getSelectedNodes();
if ( selected_nodes.size() == 0 ) {return;}
Iterator selected_nodes_iterator = selected_nodes.iterator();
double bigX;
double bigY;
double smallX;
double smallY;
double W;
double H;
NodeView first = ( NodeView )selected_nodes_iterator.next();
bigX = first.getXPosition();
smallX = bigX;
bigY = first.getYPosition();
smallY = bigY;
while ( selected_nodes_iterator.hasNext() ) {
NodeView nv = ( NodeView )selected_nodes_iterator.next();
double x = nv.getXPosition();
double y = nv.getYPosition();
if ( x > bigX ) {
bigX = x;
} else if ( x < smallX ) {
smallX = x;
}
if ( y > bigY ) {
bigY = y;
} else if ( y < smallY ) {
smallY = y;
}
}
PBounds zoomToBounds;
if (selected_nodes.size() == 1) {
zoomToBounds = new PBounds( smallX - 100 , smallY - 100 , ( bigX - smallX + 200 ), ( bigY - smallY + 200 ) );
} else {
zoomToBounds = new PBounds( smallX , smallY , ( bigX - smallX + 100 ), ( bigY - smallY + 100 ) );
}
PTransformActivity activity = ( ( PhoebeNetworkView )view).getCanvas().getCamera().animateViewToCenterBounds( zoomToBounds, true, 500 );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.